repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
TiffSequence._parse
def _parse(self): """Get axes and shape from file names.""" if not self.pattern: raise TiffSequence.ParseError('invalid pattern') pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) matches = pattern.findall(os.path.split(self.files[0])[-1]) if not matches:...
python
def _parse(self): """Get axes and shape from file names.""" if not self.pattern: raise TiffSequence.ParseError('invalid pattern') pattern = re.compile(self.pattern, re.IGNORECASE | re.VERBOSE) matches = pattern.findall(os.path.split(self.files[0])[-1]) if not matches:...
[ "def", "_parse", "(", "self", ")", ":", "if", "not", "self", ".", "pattern", ":", "raise", "TiffSequence", ".", "ParseError", "(", "'invalid pattern'", ")", "pattern", "=", "re", ".", "compile", "(", "self", ".", "pattern", ",", "re", ".", "IGNORECASE", ...
Get axes and shape from file names.
[ "Get", "axes", "and", "shape", "from", "file", "names", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5402-L5435
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.open
def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os.path.realpath(self._fi...
python
def open(self): """Open or re-open file.""" if self._fh: return # file is open if isinstance(self._file, pathlib.Path): self._file = str(self._file) if isinstance(self._file, basestring): # file name self._file = os.path.realpath(self._fi...
[ "def", "open", "(", "self", ")", ":", "if", "self", ".", "_fh", ":", "return", "# file is open", "if", "isinstance", "(", "self", ".", "_file", ",", "pathlib", ".", "Path", ")", ":", "self", ".", "_file", "=", "str", "(", "self", ".", "_file", ")",...
Open or re-open file.
[ "Open", "or", "re", "-", "open", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5502-L5570
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read
def read(self, size=-1): """Read 'size' bytes from file, or until EOF is reached.""" if size < 0 and self._offset: size = self._size return self._fh.read(size)
python
def read(self, size=-1): """Read 'size' bytes from file, or until EOF is reached.""" if size < 0 and self._offset: size = self._size return self._fh.read(size)
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "<", "0", "and", "self", ".", "_offset", ":", "size", "=", "self", ".", "_size", "return", "self", ".", "_fh", ".", "read", "(", "size", ")" ]
Read 'size' bytes from file, or until EOF is reached.
[ "Read", "size", "bytes", "from", "file", "or", "until", "EOF", "is", "reached", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5572-L5576
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.memmap_array
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offs...
python
def memmap_array(self, dtype, shape, offset=0, mode='r', order='C'): """Return numpy.memmap of data stored in file.""" if not self.is_file: raise ValueError('Cannot memory-map file without fileno') return numpy.memmap(self._fh, dtype=dtype, mode=mode, offs...
[ "def", "memmap_array", "(", "self", ",", "dtype", ",", "shape", ",", "offset", "=", "0", ",", "mode", "=", "'r'", ",", "order", "=", "'C'", ")", ":", "if", "not", "self", ".", "is_file", ":", "raise", "ValueError", "(", "'Cannot memory-map file without f...
Return numpy.memmap of data stored in file.
[ "Return", "numpy", ".", "memmap", "of", "data", "stored", "in", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5590-L5596
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read_array
def read_array(self, dtype, count=-1, out=None): """Return numpy array from file in native byte order.""" fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes count = size // dtype.itemsize else: ...
python
def read_array(self, dtype, count=-1, out=None): """Return numpy array from file in native byte order.""" fh = self._fh dtype = numpy.dtype(dtype) if count < 0: size = self._size if out is None else out.nbytes count = size // dtype.itemsize else: ...
[ "def", "read_array", "(", "self", ",", "dtype", ",", "count", "=", "-", "1", ",", "out", "=", "None", ")", ":", "fh", "=", "self", ".", "_fh", "dtype", "=", "numpy", ".", "dtype", "(", "dtype", ")", "if", "count", "<", "0", ":", "size", "=", ...
Return numpy array from file in native byte order.
[ "Return", "numpy", "array", "from", "file", "in", "native", "byte", "order", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5598-L5629
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.read_record
def read_record(self, dtype, shape=1, byteorder=None): """Return numpy record from file.""" rec = numpy.rec try: record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) except Exception: dtype = numpy.dtype(dtype) if shape is None: ...
python
def read_record(self, dtype, shape=1, byteorder=None): """Return numpy record from file.""" rec = numpy.rec try: record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder) except Exception: dtype = numpy.dtype(dtype) if shape is None: ...
[ "def", "read_record", "(", "self", ",", "dtype", ",", "shape", "=", "1", ",", "byteorder", "=", "None", ")", ":", "rec", "=", "numpy", ".", "rec", "try", ":", "record", "=", "rec", ".", "fromfile", "(", "self", ".", "_fh", ",", "dtype", ",", "sha...
Return numpy record from file.
[ "Return", "numpy", "record", "from", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5631-L5643
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.write_empty
def write_empty(self, size): """Append size bytes to file. Position must be at end of file.""" if size < 1: return self._fh.seek(size-1, 1) self._fh.write(b'\x00')
python
def write_empty(self, size): """Append size bytes to file. Position must be at end of file.""" if size < 1: return self._fh.seek(size-1, 1) self._fh.write(b'\x00')
[ "def", "write_empty", "(", "self", ",", "size", ")", ":", "if", "size", "<", "1", ":", "return", "self", ".", "_fh", ".", "seek", "(", "size", "-", "1", ",", "1", ")", "self", ".", "_fh", ".", "write", "(", "b'\\x00'", ")" ]
Append size bytes to file. Position must be at end of file.
[ "Append", "size", "bytes", "to", "file", ".", "Position", "must", "be", "at", "end", "of", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5645-L5650
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.write_array
def write_array(self, data): """Write numpy array to binary file.""" try: data.tofile(self._fh) except Exception: # BytesIO self._fh.write(data.tostring())
python
def write_array(self, data): """Write numpy array to binary file.""" try: data.tofile(self._fh) except Exception: # BytesIO self._fh.write(data.tostring())
[ "def", "write_array", "(", "self", ",", "data", ")", ":", "try", ":", "data", ".", "tofile", "(", "self", ".", "_fh", ")", "except", "Exception", ":", "# BytesIO", "self", ".", "_fh", ".", "write", "(", "data", ".", "tostring", "(", ")", ")" ]
Write numpy array to binary file.
[ "Write", "numpy", "array", "to", "binary", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5652-L5658
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.seek
def seek(self, offset, whence=0): """Set file's current position.""" if self._offset: if whence == 0: self._fh.seek(self._offset + offset, whence) return if whence == 2 and self._size > 0: self._fh.seek(self._offset + self._size + o...
python
def seek(self, offset, whence=0): """Set file's current position.""" if self._offset: if whence == 0: self._fh.seek(self._offset + offset, whence) return if whence == 2 and self._size > 0: self._fh.seek(self._offset + self._size + o...
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "if", "self", ".", "_offset", ":", "if", "whence", "==", "0", ":", "self", ".", "_fh", ".", "seek", "(", "self", ".", "_offset", "+", "offset", ",", "whence", ")", "r...
Set file's current position.
[ "Set", "file", "s", "current", "position", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5664-L5673
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
FileHandle.close
def close(self): """Close file.""" if self._close and self._fh: self._fh.close() self._fh = None
python
def close(self): """Close file.""" if self._close and self._fh: self._fh.close() self._fh = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_close", "and", "self", ".", "_fh", ":", "self", ".", "_fh", ".", "close", "(", ")", "self", ".", "_fh", "=", "None" ]
Close file.
[ "Close", "file", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5675-L5679
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.open
def open(self, filehandle): """Re-open file if necessary.""" with self.lock: if filehandle in self.files: self.files[filehandle] += 1 elif filehandle.closed: filehandle.open() self.files[filehandle] = 1 self.past.app...
python
def open(self, filehandle): """Re-open file if necessary.""" with self.lock: if filehandle in self.files: self.files[filehandle] += 1 elif filehandle.closed: filehandle.open() self.files[filehandle] = 1 self.past.app...
[ "def", "open", "(", "self", ",", "filehandle", ")", ":", "with", "self", ".", "lock", ":", "if", "filehandle", "in", "self", ".", "files", ":", "self", ".", "files", "[", "filehandle", "]", "+=", "1", "elif", "filehandle", ".", "closed", ":", "fileha...
Re-open file if necessary.
[ "Re", "-", "open", "file", "if", "necessary", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5749-L5757
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.close
def close(self, filehandle): """Close openend file if no longer used.""" with self.lock: if filehandle in self.files: self.files[filehandle] -= 1 # trim the file cache index = 0 size = len(self.past) while size >...
python
def close(self, filehandle): """Close openend file if no longer used.""" with self.lock: if filehandle in self.files: self.files[filehandle] -= 1 # trim the file cache index = 0 size = len(self.past) while size >...
[ "def", "close", "(", "self", ",", "filehandle", ")", ":", "with", "self", ".", "lock", ":", "if", "filehandle", "in", "self", ".", "files", ":", "self", ".", "files", "[", "filehandle", "]", "-=", "1", "# trim the file cache", "index", "=", "0", "size"...
Close openend file if no longer used.
[ "Close", "openend", "file", "if", "no", "longer", "used", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5759-L5775
nion-software/nionswift-io
nionswift_plugin/TIFF_IO/tifffile.py
OpenFileCache.clear
def clear(self): """Close all opened files if not in use.""" with self.lock: for filehandle, refcount in list(self.files.items()): if refcount == 0: filehandle.close() del self.files[filehandle] del self.past[self.pa...
python
def clear(self): """Close all opened files if not in use.""" with self.lock: for filehandle, refcount in list(self.files.items()): if refcount == 0: filehandle.close() del self.files[filehandle] del self.past[self.pa...
[ "def", "clear", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "for", "filehandle", ",", "refcount", "in", "list", "(", "self", ".", "files", ".", "items", "(", ")", ")", ":", "if", "refcount", "==", "0", ":", "filehandle", ".", "close", ...
Close all opened files if not in use.
[ "Close", "all", "opened", "files", "if", "not", "in", "use", "." ]
train
https://github.com/nion-software/nionswift-io/blob/e9ae37f01faa9332c48b647f93afd5ef2166b155/nionswift_plugin/TIFF_IO/tifffile.py#L5777-L5784
noahmorrison/chevron
chevron/tokenizer.py
grab_literal
def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') return (literal, template) # There...
python
def grab_literal(template, l_del): """Parse a literal from the template""" global _CURRENT_LINE try: # Look for the next tag and move the template to it literal, template = template.split(l_del, 1) _CURRENT_LINE += literal.count('\n') return (literal, template) # There...
[ "def", "grab_literal", "(", "template", ",", "l_del", ")", ":", "global", "_CURRENT_LINE", "try", ":", "# Look for the next tag and move the template to it", "literal", ",", "template", "=", "template", ".", "split", "(", "l_del", ",", "1", ")", "_CURRENT_LINE", "...
Parse a literal from the template
[ "Parse", "a", "literal", "from", "the", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L14-L28
noahmorrison/chevron
chevron/tokenizer.py
l_sa_check
def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find('\n') != -1 or is_standalone: padding = literal.split('\n')[-1] # If all the characters since t...
python
def l_sa_check(template, literal, is_standalone): """Do a preliminary check to see if a tag could be a standalone""" # If there is a newline, or the previous tag was a standalone if literal.find('\n') != -1 or is_standalone: padding = literal.split('\n')[-1] # If all the characters since t...
[ "def", "l_sa_check", "(", "template", ",", "literal", ",", "is_standalone", ")", ":", "# If there is a newline, or the previous tag was a standalone", "if", "literal", ".", "find", "(", "'\\n'", ")", "!=", "-", "1", "or", "is_standalone", ":", "padding", "=", "lit...
Do a preliminary check to see if a tag could be a standalone
[ "Do", "a", "preliminary", "check", "to", "see", "if", "a", "tag", "could", "be", "a", "standalone" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L31-L44
noahmorrison/chevron
chevron/tokenizer.py
r_sa_check
def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template.split('\n', 1) # If the stuff to the right of ...
python
def r_sa_check(template, tag_type, is_standalone): """Do a final checkto see if a tag could be a standalone""" # Check right side if we might be a standalone if is_standalone and tag_type not in ['variable', 'no escape']: on_newline = template.split('\n', 1) # If the stuff to the right of ...
[ "def", "r_sa_check", "(", "template", ",", "tag_type", ",", "is_standalone", ")", ":", "# Check right side if we might be a standalone", "if", "is_standalone", "and", "tag_type", "not", "in", "[", "'variable'", ",", "'no escape'", "]", ":", "on_newline", "=", "templ...
Do a final checkto see if a tag could be a standalone
[ "Do", "a", "final", "checkto", "see", "if", "a", "tag", "could", "be", "a", "standalone" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L47-L62
noahmorrison/chevron
chevron/tokenizer.py
parse_tag
def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { '!': 'comment', '#': 'section', '^': 'inverted section', '/': 'end', '>': 'partial', '=': 'set delimiter?', '{': 'no ...
python
def parse_tag(template, l_del, r_del): """Parse a tag from a template""" global _CURRENT_LINE global _LAST_TAG_LINE tag_types = { '!': 'comment', '#': 'section', '^': 'inverted section', '/': 'end', '>': 'partial', '=': 'set delimiter?', '{': 'no ...
[ "def", "parse_tag", "(", "template", ",", "l_del", ",", "r_del", ")", ":", "global", "_CURRENT_LINE", "global", "_LAST_TAG_LINE", "tag_types", "=", "{", "'!'", ":", "'comment'", ",", "'#'", ":", "'section'", ",", "'^'", ":", "'inverted section'", ",", "'/'",...
Parse a tag from a template
[ "Parse", "a", "tag", "from", "a", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L65-L119
noahmorrison/chevron
chevron/tokenizer.py
tokenize
def tokenize(template, def_ldel='{{', def_rdel='}}'): """Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template...
python
def tokenize(template, def_ldel='{{', def_rdel='}}'): """Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template...
[ "def", "tokenize", "(", "template", ",", "def_ldel", "=", "'{{'", ",", "def_rdel", "=", "'}}'", ")", ":", "global", "_CURRENT_LINE", ",", "_LAST_TAG_LINE", "_CURRENT_LINE", "=", "1", "_LAST_TAG_LINE", "=", "None", "# If the template is a file-like object then read it"...
Tokenize a mustache template Tokenizes a mustache template in a generator fashion, using file-like objects. It also accepts a string containing the template. Arguments: template -- a file-like object, or a string of a mustache template def_ldel -- The default left delimiter ...
[ "Tokenize", "a", "mustache", "template" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/tokenizer.py#L126-L254
noahmorrison/chevron
chevron/main.py
cli_main
def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: return arg def is_dir(arg): ...
python
def cli_main(): """Render mustache templates using json files""" import argparse import os def is_file_or_pipe(arg): if not os.path.exists(arg) or os.path.isdir(arg): parser.error('The file {0} does not exist!'.format(arg)) else: return arg def is_dir(arg): ...
[ "def", "cli_main", "(", ")", ":", "import", "argparse", "import", "os", "def", "is_file_or_pipe", "(", "arg", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "arg", ")", "or", "os", ".", "path", ".", "isdir", "(", "arg", ")", ":", "...
Render mustache templates using json files
[ "Render", "mustache", "templates", "using", "json", "files" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/main.py#L35-L89
noahmorrison/chevron
chevron/renderer.py
_html_escape
def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.replace(char, html_codes[char]) ...
python
def _html_escape(string): """HTML escape all of these " & < >""" html_codes = { '"': '&quot;', '<': '&lt;', '>': '&gt;', } # & must be handled first string = string.replace('&', '&amp;') for char in html_codes: string = string.replace(char, html_codes[char]) ...
[ "def", "_html_escape", "(", "string", ")", ":", "html_codes", "=", "{", "'\"'", ":", "'&quot;'", ",", "'<'", ":", "'&lt;'", ",", "'>'", ":", "'&gt;'", ",", "}", "# & must be handled first", "string", "=", "string", ".", "replace", "(", "'&'", ",", "'&amp...
HTML escape all of these " & < >
[ "HTML", "escape", "all", "of", "these", "&", "<", ">" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L34-L47
noahmorrison/chevron
chevron/renderer.py
_get_key
def _get_key(key, scopes): """Get a key from the current scope""" # If the key is a dot if key == '.': # Then just return the current scope return scopes[0] # Loop through the scopes for scope in scopes: try: # For every dot seperated key for child i...
python
def _get_key(key, scopes): """Get a key from the current scope""" # If the key is a dot if key == '.': # Then just return the current scope return scopes[0] # Loop through the scopes for scope in scopes: try: # For every dot seperated key for child i...
[ "def", "_get_key", "(", "key", ",", "scopes", ")", ":", "# If the key is a dot", "if", "key", "==", "'.'", ":", "# Then just return the current scope", "return", "scopes", "[", "0", "]", "# Loop through the scopes", "for", "scope", "in", "scopes", ":", "try", ":...
Get a key from the current scope
[ "Get", "a", "key", "from", "the", "current", "scope" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L50-L96
noahmorrison/chevron
chevron/renderer.py
_get_partial
def _get_partial(name, partials_dict, partials_path, partials_ext): """Load a partial""" try: # Maybe the partial is in the dictionary return partials_dict[name] except KeyError: # Nope... try: # Maybe it's in the file system path_ext = ('.' + partials...
python
def _get_partial(name, partials_dict, partials_path, partials_ext): """Load a partial""" try: # Maybe the partial is in the dictionary return partials_dict[name] except KeyError: # Nope... try: # Maybe it's in the file system path_ext = ('.' + partials...
[ "def", "_get_partial", "(", "name", ",", "partials_dict", ",", "partials_path", ",", "partials_ext", ")", ":", "try", ":", "# Maybe the partial is in the dictionary", "return", "partials_dict", "[", "name", "]", "except", "KeyError", ":", "# Nope...", "try", ":", ...
Load a partial
[ "Load", "a", "partial" ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L99-L115
noahmorrison/chevron
chevron/renderer.py
render
def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', scopes=None): """Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷...
python
def render(template='', data={}, partials_path='.', partials_ext='mustache', partials_dict={}, padding='', def_ldel='{{', def_rdel='}}', scopes=None): """Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷...
[ "def", "render", "(", "template", "=", "''", ",", "data", "=", "{", "}", ",", "partials_path", "=", "'.'", ",", "partials_ext", "=", "'mustache'", ",", "partials_dict", "=", "{", "}", ",", "padding", "=", "''", ",", "def_ldel", "=", "'{{'", ",", "def...
Render a mustache template. Renders a mustache template with a data scope and partial capability. Given the file structure... ╷ ├─╼ main.py ├─╼ main.ms └─┮ partials └── part.ms then main.py would make the following call: render(open('main.ms', 'r'), {...}, 'partials', 'ms') ...
[ "Render", "a", "mustache", "template", "." ]
train
https://github.com/noahmorrison/chevron/blob/78f1a384eddef16906732d8db66deea6d37049b7/chevron/renderer.py#L124-L367
tapanpandita/pocket
pocket.py
Pocket.bulk_add
def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add '''
python
def bulk_add( self, item_id, ref_id=None, tags=None, time=None, title=None, url=None, wait=True ): ''' Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add '''
[ "def", "bulk_add", "(", "self", ",", "item_id", ",", "ref_id", "=", "None", ",", "tags", "=", "None", ",", "time", "=", "None", ",", "title", "=", "None", ",", "url", "=", "None", ",", "wait", "=", "True", ")", ":" ]
Add a new item to the user's list http://getpocket.com/developer/docs/v3/modify#action_add
[ "Add", "a", "new", "item", "to", "the", "user", "s", "list", "http", ":", "//", "getpocket", ".", "com", "/", "developer", "/", "docs", "/", "v3", "/", "modify#action_add" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L190-L198
tapanpandita/pocket
pocket.py
Pocket.commit
def commit(self): ''' This method executes the bulk query, flushes stored queries and returns the response ''' url = self.api_endpoints['send'] payload = { 'actions': self._bulk_query, } payload.update(self._payload) self._bulk_query =...
python
def commit(self): ''' This method executes the bulk query, flushes stored queries and returns the response ''' url = self.api_endpoints['send'] payload = { 'actions': self._bulk_query, } payload.update(self._payload) self._bulk_query =...
[ "def", "commit", "(", "self", ")", ":", "url", "=", "self", ".", "api_endpoints", "[", "'send'", "]", "payload", "=", "{", "'actions'", ":", "self", ".", "_bulk_query", ",", "}", "payload", ".", "update", "(", "self", ".", "_payload", ")", "self", "....
This method executes the bulk query, flushes stored queries and returns the response
[ "This", "method", "executes", "the", "bulk", "query", "flushes", "stored", "queries", "and", "returns", "the", "response" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L280-L297
tapanpandita/pocket
pocket.py
Pocket.get_request_token
def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/...
python
def get_request_token( cls, consumer_key, redirect_uri='http://example.com/', state=None ): ''' Returns the request token that can be used to fetch the access token ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/...
[ "def", "get_request_token", "(", "cls", ",", "consumer_key", ",", "redirect_uri", "=", "'http://example.com/'", ",", "state", "=", "None", ")", ":", "headers", "=", "{", "'X-Accept'", ":", "'application/json'", ",", "}", "url", "=", "'https://getpocket.com/v3/oaut...
Returns the request token that can be used to fetch the access token
[ "Returns", "the", "request", "token", "that", "can", "be", "used", "to", "fetch", "the", "access", "token" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L300-L319
tapanpandita/pocket
pocket.py
Pocket.get_credentials
def get_credentials(cls, consumer_key, code): ''' Fetches access token from using the request token and consumer key ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/authorize' payload = { 'consumer_k...
python
def get_credentials(cls, consumer_key, code): ''' Fetches access token from using the request token and consumer key ''' headers = { 'X-Accept': 'application/json', } url = 'https://getpocket.com/v3/oauth/authorize' payload = { 'consumer_k...
[ "def", "get_credentials", "(", "cls", ",", "consumer_key", ",", "code", ")", ":", "headers", "=", "{", "'X-Accept'", ":", "'application/json'", ",", "}", "url", "=", "'https://getpocket.com/v3/oauth/authorize'", "payload", "=", "{", "'consumer_key'", ":", "consume...
Fetches access token from using the request token and consumer key
[ "Fetches", "access", "token", "from", "using", "the", "request", "token", "and", "consumer", "key" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L322-L336
tapanpandita/pocket
pocket.py
Pocket.auth
def auth( cls, consumer_key, redirect_uri='http://example.com/', state=None, ): ''' This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication ''' code = cls.get_request_token(consumer_key, redirect_uri, state) aut...
python
def auth( cls, consumer_key, redirect_uri='http://example.com/', state=None, ): ''' This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication ''' code = cls.get_request_token(consumer_key, redirect_uri, state) aut...
[ "def", "auth", "(", "cls", ",", "consumer_key", ",", "redirect_uri", "=", "'http://example.com/'", ",", "state", "=", "None", ",", ")", ":", "code", "=", "cls", ".", "get_request_token", "(", "consumer_key", ",", "redirect_uri", ",", "state", ")", "auth_url"...
This is a test method for verifying if oauth worked http://getpocket.com/developer/docs/authentication
[ "This", "is", "a", "test", "method", "for", "verifying", "if", "oauth", "worked", "http", ":", "//", "getpocket", ".", "com", "/", "developer", "/", "docs", "/", "authentication" ]
train
https://github.com/tapanpandita/pocket/blob/5a144438cc89bfc0ec94db960718ccf1f76468c1/pocket.py#L349-L366
adewes/blitzdb
blitzdb/backends/sql/relations.py
ManyToManyProxy.remove
def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk, ...
python
def remove(self,obj): """ Remove an object from the relation """ relationship_table = self.params['relationship_table'] with self.obj.backend.transaction(implicit = True): condition = and_(relationship_table.c[self.params['related_pk_field_name']] == obj.pk, ...
[ "def", "remove", "(", "self", ",", "obj", ")", ":", "relationship_table", "=", "self", ".", "params", "[", "'relationship_table'", "]", "with", "self", ".", "obj", ".", "backend", ".", "transaction", "(", "implicit", "=", "True", ")", ":", "condition", "...
Remove an object from the relation
[ "Remove", "an", "object", "from", "the", "relation" ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/relations.py#L123-L132
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.begin
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, s...
python
def begin(self): """Start a new transaction.""" if self.in_transaction: # we're already in a transaction... if self._auto_transaction: self._auto_transaction = False return self.commit() self.in_transaction = True for collection, s...
[ "def", "begin", "(", "self", ")", ":", "if", "self", ".", "in_transaction", ":", "# we're already in a transaction...", "if", "self", ".", "_auto_transaction", ":", "self", ".", "_auto_transaction", "=", "False", "return", "self", ".", "commit", "(", ")", "sel...
Start a new transaction.
[ "Start", "a", "new", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L113-L125
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.rollback
def rollback(self, transaction = None): """Roll back a transaction.""" if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_to_rebuild = [] ...
python
def rollback(self, transaction = None): """Roll back a transaction.""" if not self.in_transaction: raise NotInTransaction for collection, store in self.stores.items(): store.rollback() indexes = self.indexes[collection] indexes_to_rebuild = [] ...
[ "def", "rollback", "(", "self", ",", "transaction", "=", "None", ")", ":", "if", "not", "self", ".", "in_transaction", ":", "raise", "NotInTransaction", "for", "collection", ",", "store", "in", "self", ".", "stores", ".", "items", "(", ")", ":", "store",...
Roll back a transaction.
[ "Roll", "back", "a", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L143-L160
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.commit
def commit(self,transaction = None): """Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database i...
python
def commit(self,transaction = None): """Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database i...
[ "def", "commit", "(", "self", ",", "transaction", "=", "None", ")", ":", "for", "collection", "in", "self", ".", "collections", ":", "store", "=", "self", ".", "get_collection_store", "(", "collection", ")", "store", ".", "commit", "(", ")", "indexes", "...
Commit all pending transactions to the database. .. admonition:: Warning This operation can be **expensive** in runtime if a large number of documents (>100.000) is contained in the database, since it will cause all database indexes to be written to disk.
[ "Commit", "all", "pending", "transactions", "to", "the", "database", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L162-L179
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.create_index
def create_index(self, cls_or_collection, params=None, fields=None, ephemeral=False, unique=False): """Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an ...
python
def create_index(self, cls_or_collection, params=None, fields=None, ephemeral=False, unique=False): """Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an ...
[ "def", "create_index", "(", "self", ",", "cls_or_collection", ",", "params", "=", "None", ",", "fields", "=", "None", ",", "ephemeral", "=", "False", ",", "unique", "=", "False", ")", ":", "if", "params", ":", "return", "self", ".", "create_indexes", "("...
Create new index on the given collection/class with given parameters. :param cls_or_collection: The name of the collection or the class for which to create an index :param params: The parameters of the index :param ephemeral: Whether to create a persistent or an ephemera...
[ "Create", "new", "index", "on", "the", "given", "collection", "/", "class", "with", "given", "parameters", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L190-L250
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.get_pk_index
def get_pk_index(self, collection): """Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection """ cls = self.collections[collection] if not cl...
python
def get_pk_index(self, collection): """Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection """ cls = self.collections[collection] if not cl...
[ "def", "get_pk_index", "(", "self", ",", "collection", ")", ":", "cls", "=", "self", ".", "collections", "[", "collection", "]", "if", "not", "cls", ".", "get_pk_name", "(", ")", "in", "self", ".", "indexes", "[", "collection", "]", ":", "self", ".", ...
Return the primary key index for a given collection. :param collection: the collection for which to return the primary index :returns: the primary key index of the given collection
[ "Return", "the", "primary", "key", "index", "for", "a", "given", "collection", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L252-L264
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend.update
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} ...
python
def update(self, obj, set_fields = None, unset_fields = None, update_obj = True): """ We return the result of the save method (updates are not yet implemented here). """ if set_fields: if isinstance(set_fields,(list,tuple)): set_attributes = {} ...
[ "def", "update", "(", "self", ",", "obj", ",", "set_fields", "=", "None", ",", "unset_fields", "=", "None", ",", "update_obj", "=", "True", ")", ":", "if", "set_fields", ":", "if", "isinstance", "(", "set_fields", ",", "(", "list", ",", "tuple", ")", ...
We return the result of the save method (updates are not yet implemented here).
[ "We", "return", "the", "result", "of", "the", "save", "method", "(", "updates", "are", "not", "yet", "implemented", "here", ")", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L427-L456
adewes/blitzdb
blitzdb/backends/file/backend.py
Backend._canonicalize_query
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = tra...
python
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): if isinstance(q, dict): nq = {} for key,value in q.items(): nq[key] = tra...
[ "def", "_canonicalize_query", "(", "self", ",", "query", ")", ":", "def", "transform_query", "(", "q", ")", ":", "if", "isinstance", "(", "q", ",", "dict", ")", ":", "nq", "=", "{", "}", "for", "key", ",", "value", "in", "q", ".", "items", "(", "...
Transform the query dictionary to replace e.g. documents with __ref__ fields.
[ "Transform", "the", "query", "dictionary", "to", "replace", "e", ".", "g", ".", "documents", "with", "__ref__", "fields", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/backend.py#L567-L589
adewes/blitzdb
blitzdb/backends/base.py
Backend.register
def register(self, cls, parameters=None,overwrite = False): """ Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used ...
python
def register(self, cls, parameters=None,overwrite = False): """ Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used ...
[ "def", "register", "(", "self", ",", "cls", ",", "parameters", "=", "None", ",", "overwrite", "=", "False", ")", ":", "if", "cls", "in", "self", ".", "deprecated_classes", "and", "not", "overwrite", ":", "return", "False", "if", "parameters", "is", "None...
Explicitly register a new document class for use in the backend. :param cls: A reference to the class to be defined :param parameters: A dictionary of parameters. Currently, only the `collection` parameter is used to specify the collection in which to store the documen...
[ "Explicitly", "register", "a", "new", "document", "class", "for", "use", "in", "the", "backend", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L101-L163
adewes/blitzdb
blitzdb/backends/base.py
Backend.autoregister
def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = self.get_meta_attributes(cls) return self.register(cls, params)
python
def autoregister(self, cls): """ Autoregister a class that is encountered for the first time. :param cls: The class that should be registered. """ params = self.get_meta_attributes(cls) return self.register(cls, params)
[ "def", "autoregister", "(", "self", ",", "cls", ")", ":", "params", "=", "self", ".", "get_meta_attributes", "(", "cls", ")", "return", "self", ".", "register", "(", "cls", ",", "params", ")" ]
Autoregister a class that is encountered for the first time. :param cls: The class that should be registered.
[ "Autoregister", "a", "class", "that", "is", "encountered", "for", "the", "first", "time", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L180-L188
adewes/blitzdb
blitzdb/backends/base.py
Backend.serialize
def serialize(self, obj, convert_keys_to_str=False, embed_level=0, encoders=None, autosave=True, for_query=False,path = None): """ Serializes a given object, i.e. converts it to a representation that can be stored in the database. ...
python
def serialize(self, obj, convert_keys_to_str=False, embed_level=0, encoders=None, autosave=True, for_query=False,path = None): """ Serializes a given object, i.e. converts it to a representation that can be stored in the database. ...
[ "def", "serialize", "(", "self", ",", "obj", ",", "convert_keys_to_str", "=", "False", ",", "embed_level", "=", "0", ",", "encoders", "=", "None", ",", "autosave", "=", "True", ",", "for_query", "=", "False", ",", "path", "=", "None", ")", ":", "if", ...
Serializes a given object, i.e. converts it to a representation that can be stored in the database. This usually involves replacing all `Document` instances by database references to them. :param obj: The object to serialize. :param convert_keys_to_str: If `True`, converts all dictionary keys t...
[ "Serializes", "a", "given", "object", "i", ".", "e", ".", "converts", "it", "to", "a", "representation", "that", "can", "be", "stored", "in", "the", "database", ".", "This", "usually", "involves", "replacing", "all", "Document", "instances", "by", "database"...
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L190-L300
adewes/blitzdb
blitzdb/backends/base.py
Backend.deserialize
def deserialize(self, obj, encoders=None, embedded=False, create_instance=True): """ Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database a...
python
def deserialize(self, obj, encoders=None, embedded=False, create_instance=True): """ Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database a...
[ "def", "deserialize", "(", "self", ",", "obj", ",", "encoders", "=", "None", ",", "embedded", "=", "False", ",", "create_instance", "=", "True", ")", ":", "if", "not", "encoders", ":", "encoders", "=", "[", "]", "for", "encoder", "in", "encoders", "+",...
Deserializes a given object, i.e. converts references to other (known) `Document` objects by lazy instances of the corresponding class. This allows the automatic fetching of related documents from the database as required. :param obj: The object to be deserialized. :returns: The deserialized o...
[ "Deserializes", "a", "given", "object", "i", ".", "e", ".", "converts", "references", "to", "other", "(", "known", ")", "Document", "objects", "by", "lazy", "instances", "of", "the", "corresponding", "class", ".", "This", "allows", "the", "automatic", "fetch...
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L302-L340
adewes/blitzdb
blitzdb/backends/base.py
Backend.create_instance
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None): """ Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to t...
python
def create_instance(self, collection_or_class, attributes, lazy=False, call_hook=True, deserialize=True, db_loader=None): """ Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to t...
[ "def", "create_instance", "(", "self", ",", "collection_or_class", ",", "attributes", ",", "lazy", "=", "False", ",", "call_hook", "=", "True", ",", "deserialize", "=", "True", ",", "db_loader", "=", "None", ")", ":", "creation_args", "=", "{", "'backend'", ...
Creates an instance of a `Document` class corresponding to the given collection name or class. :param collection_or_class: The name of the collection or a reference to the class for which to create an instance. :param attributes: The attributes of the instance to be created :param lazy: Whether...
[ "Creates", "an", "instance", "of", "a", "Document", "class", "corresponding", "to", "the", "given", "collection", "name", "or", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L342-L380
adewes/blitzdb
blitzdb/backends/base.py
Backend.transaction
def transaction(self,implicit = False): """ This returns a context guard which will automatically open and close a transaction """ class TransactionManager(object): def __init__(self,backend,implicit = False): self.backend = backend self.impl...
python
def transaction(self,implicit = False): """ This returns a context guard which will automatically open and close a transaction """ class TransactionManager(object): def __init__(self,backend,implicit = False): self.backend = backend self.impl...
[ "def", "transaction", "(", "self", ",", "implicit", "=", "False", ")", ":", "class", "TransactionManager", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "backend", ",", "implicit", "=", "False", ")", ":", "self", ".", "backend", "=", "b...
This returns a context guard which will automatically open and close a transaction
[ "This", "returns", "a", "context", "guard", "which", "will", "automatically", "open", "and", "close", "a", "transaction" ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L387-L413
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_collection_for_cls
def get_collection_for_cls(self, cls): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ if cls not in self.classes: if i...
python
def get_collection_for_cls(self, cls): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ if cls not in self.classes: if i...
[ "def", "get_collection_for_cls", "(", "self", ",", "cls", ")", ":", "if", "cls", "not", "in", "self", ".", "classes", ":", "if", "issubclass", "(", "cls", ",", "Document", ")", "and", "cls", "not", "in", "self", ".", "classes", "and", "cls", "not", "...
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class.
[ "Returns", "the", "collection", "name", "for", "a", "given", "document", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L425-L439
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_collection_for_cls_name
def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ for cls in self.classes: ...
python
def get_collection_for_cls_name(self, cls_name): """ Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class. """ for cls in self.classes: ...
[ "def", "get_collection_for_cls_name", "(", "self", ",", "cls_name", ")", ":", "for", "cls", "in", "self", ".", "classes", ":", "if", "cls", ".", "__name__", "==", "cls_name", ":", "return", "self", ".", "classes", "[", "cls", "]", "[", "'collection'", "]...
Returns the collection name for a given document class. :param cls: The document class for which to return the collection name. :returns: The collection name for the given class.
[ "Returns", "the", "collection", "name", "for", "a", "given", "document", "class", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L441-L452
adewes/blitzdb
blitzdb/backends/base.py
Backend.get_cls_for_collection
def get_cls_for_collection(self, collection): """ Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. """ for cls, params in self.cla...
python
def get_cls_for_collection(self, collection): """ Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name. """ for cls, params in self.cla...
[ "def", "get_cls_for_collection", "(", "self", ",", "collection", ")", ":", "for", "cls", ",", "params", "in", "self", ".", "classes", ".", "items", "(", ")", ":", "if", "params", "[", "'collection'", "]", "==", "collection", ":", "return", "cls", "raise"...
Return the class for a given collection name. :param collection: The name of the collection for which to return the class. :returns: A reference to the class for the given collection name.
[ "Return", "the", "class", "for", "a", "given", "collection", "name", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/base.py#L454-L465
adewes/blitzdb
blitzdb/backends/file/index.py
Index.clear
def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
python
def clear(self): """Clear index.""" self._index = defaultdict(list) self._reverse_index = defaultdict(list) self._undefined_keys = {}
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_index", "=", "defaultdict", "(", "list", ")", "self", ".", "_reverse_index", "=", "defaultdict", "(", "list", ")", "self", ".", "_undefined_keys", "=", "{", "}" ]
Clear index.
[ "Clear", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L54-L58
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_value
def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object """ value = attributes if key is None: ...
python
def get_value(self, attributes,key = None): """Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object """ value = attributes if key is None: ...
[ "def", "get_value", "(", "self", ",", "attributes", ",", "key", "=", "None", ")", ":", "value", "=", "attributes", "if", "key", "is", "None", ":", "key", "=", "self", ".", "_splitted_key", "# A splitted key like 'a.b.c' goes into nested properties", "# and the val...
Get value to be indexed from document attributes. :param attributes: Document attributes :type attributes: dict :return: Value to be indexed :rtype: object
[ "Get", "value", "to", "be", "indexed", "from", "document", "attributes", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L74-L97
adewes/blitzdb
blitzdb/backends/file/index.py
Index.save_to_store
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) ...
python
def save_to_store(self): """Save index to store. :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') saved_data = self.save_to_data(in_place=True) data = Serializer.serialize(saved_data) ...
[ "def", "save_to_store", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "AttributeError", "(", "'No datastore defined!'", ")", "saved_data", "=", "self", ".", "save_to_data", "(", "in_place", "=", "True", ")", "data", "=", "Serialize...
Save index to store. :raise AttributeError: If no datastore is defined
[ "Save", "index", "to", "store", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L99-L109
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_all_keys
def get_all_keys(self): """Get all keys indexed. :return: All keys :rtype: list(str) """ all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
python
def get_all_keys(self): """Get all keys indexed. :return: All keys :rtype: list(str) """ all_keys = [] for keys in self._index.values(): all_keys.extend(keys) return all_keys
[ "def", "get_all_keys", "(", "self", ")", ":", "all_keys", "=", "[", "]", "for", "keys", "in", "self", ".", "_index", ".", "values", "(", ")", ":", "all_keys", ".", "extend", "(", "keys", ")", "return", "all_keys" ]
Get all keys indexed. :return: All keys :rtype: list(str)
[ "Get", "all", "keys", "indexed", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L111-L121
adewes/blitzdb
blitzdb/backends/file/index.py
Index.load_from_store
def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') if self._stor...
python
def load_from_store(self): """Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined """ if not self._store: raise AttributeError('No datastore defined!') if self._stor...
[ "def", "load_from_store", "(", "self", ")", ":", "if", "not", "self", ".", "_store", ":", "raise", "AttributeError", "(", "'No datastore defined!'", ")", "if", "self", ".", "_store", ".", "has_blob", "(", "'all_keys'", ")", ":", "data", "=", "Serializer", ...
Load index from store. :return: Whether index was correctly loaded or not :rtype: bool :raise AttributeError: If no datastore is defined
[ "Load", "index", "from", "store", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L132-L152
adewes/blitzdb
blitzdb/backends/file/index.py
Index.sort_keys
def sort_keys(self, keys, order=QuerySet.ASCENDING): """Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted ke...
python
def sort_keys(self, keys, order=QuerySet.ASCENDING): """Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted ke...
[ "def", "sort_keys", "(", "self", ",", "keys", ",", "order", "=", "QuerySet", ".", "ASCENDING", ")", ":", "# to do: check that all reverse index values are unambiguous", "missing_keys", "=", "[", "key", "for", "key", "in", "keys", "if", "not", "len", "(", "self",...
Sort keys. Keys are sorted based on the value they are indexing. :param keys: Keys to be sorted :type keys: list(str) :param order: Order criteri (asending or descending) :type order: int :return: Sorted keys :rtype: list(str) :raise ValueError: If inval...
[ "Sort", "keys", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L154-L191
adewes/blitzdb
blitzdb/backends/file/index.py
Index.save_to_data
def save_to_data(self, in_place=False): """Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list """ if in_place: return [ list(self...
python
def save_to_data(self, in_place=False): """Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list """ if in_place: return [ list(self...
[ "def", "save_to_data", "(", "self", ",", "in_place", "=", "False", ")", ":", "if", "in_place", ":", "return", "[", "list", "(", "self", ".", "_index", ".", "items", "(", ")", ")", ",", "list", "(", "self", ".", "_undefined_keys", ".", "keys", "(", ...
Save index to data structure. :param in_place: Do not copy index value to a new list object :type in_place: bool :return: Index data structure :rtype: list
[ "Save", "index", "to", "data", "structure", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L193-L210
adewes/blitzdb
blitzdb/backends/file/index.py
Index.load_from_data
def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ if with_undefined: defined_values, undefined_values = data else: defined_values = dat...
python
def load_from_data(self, data, with_undefined=False): """Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool """ if with_undefined: defined_values, undefined_values = data else: defined_values = dat...
[ "def", "load_from_data", "(", "self", ",", "data", ",", "with_undefined", "=", "False", ")", ":", "if", "with_undefined", ":", "defined_values", ",", "undefined_values", "=", "data", "else", ":", "defined_values", "=", "data", "undefined_values", "=", "None", ...
Load index structure. :param with_undefined: Load undefined keys as well :type with_undefined: bool
[ "Load", "index", "structure", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L212-L232
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_hash_for
def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str """ if isinstance(value,dict) and '__ref__' in value: return self.get_hash_for(value['__ref__'])...
python
def get_hash_for(self, value): """Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str """ if isinstance(value,dict) and '__ref__' in value: return self.get_hash_for(value['__ref__'])...
[ "def", "get_hash_for", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", "and", "'__ref__'", "in", "value", ":", "return", "self", ".", "get_hash_for", "(", "value", "[", "'__ref__'", "]", ")", "serialized_value", "...
Get hash for a given value. :param value: The value to be indexed :type value: object :return: Hashed value :rtype: str
[ "Get", "hash", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L234-L257
adewes/blitzdb
blitzdb/backends/file/index.py
Index.get_keys_for
def get_keys_for(self, value): """Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str) """ if callable(value): return value(self) hash_value = self.get_has...
python
def get_keys_for(self, value): """Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str) """ if callable(value): return value(self) hash_value = self.get_has...
[ "def", "get_keys_for", "(", "self", ",", "value", ")", ":", "if", "callable", "(", "value", ")", ":", "return", "value", "(", "self", ")", "hash_value", "=", "self", ".", "get_hash_for", "(", "value", ")", "return", "self", ".", "_index", "[", "hash_va...
Get keys for a given value. :param value: The value to look for :type value: object :return: The keys for the given value :rtype: list(str)
[ "Get", "keys", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L259-L271
adewes/blitzdb
blitzdb/backends/file/index.py
Index.add_hashed_value
def add_hashed_value(self, hash_value, store_key): """Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if self._u...
python
def add_hashed_value(self, hash_value, store_key): """Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object """ if self._u...
[ "def", "add_hashed_value", "(", "self", ",", "hash_value", ",", "store_key", ")", ":", "if", "self", ".", "_unique", "and", "hash_value", "in", "self", ".", "_index", ":", "raise", "NonUnique", "(", "'Hash value {} already in index'", ".", "format", "(", "hash...
Add hashed value to the index. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object
[ "Add", "hashed", "value", "to", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L284-L298
adewes/blitzdb
blitzdb/backends/file/index.py
Index.add_key
def add_key(self, attributes, store_key): """Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str """ undefined = False try: ...
python
def add_key(self, attributes, store_key): """Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str """ undefined = False try: ...
[ "def", "add_key", "(", "self", ",", "attributes", ",", "store_key", ")", ":", "undefined", "=", "False", "try", ":", "value", "=", "self", ".", "get_value", "(", "attributes", ")", "except", "(", "KeyError", ",", "IndexError", ")", ":", "undefined", "=",...
Add key to the index. :param attributes: Attributes to be added to the index :type attributes: dict(str) :param store_key: The key for the document in the store :type store_key: str
[ "Add", "key", "to", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L300-L331
adewes/blitzdb
blitzdb/backends/file/index.py
Index.remove_key
def remove_key(self, store_key): """Remove key from the index. :param store_key: The key for the document in the store :type store_key: str """ if store_key in self._undefined_keys: del self._undefined_keys[store_key] if store_key in self._reverse_index: ...
python
def remove_key(self, store_key): """Remove key from the index. :param store_key: The key for the document in the store :type store_key: str """ if store_key in self._undefined_keys: del self._undefined_keys[store_key] if store_key in self._reverse_index: ...
[ "def", "remove_key", "(", "self", ",", "store_key", ")", ":", "if", "store_key", "in", "self", ".", "_undefined_keys", ":", "del", "self", ".", "_undefined_keys", "[", "store_key", "]", "if", "store_key", "in", "self", ".", "_reverse_index", ":", "for", "v...
Remove key from the index. :param store_key: The key for the document in the store :type store_key: str
[ "Remove", "key", "from", "the", "index", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L342-L354
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex._init_cache
def _init_cache(self): """Initialize cache.""" self._add_cache = defaultdict(list) self._reverse_add_cache = defaultdict(list) self._undefined_cache = {} self._remove_cache = {}
python
def _init_cache(self): """Initialize cache.""" self._add_cache = defaultdict(list) self._reverse_add_cache = defaultdict(list) self._undefined_cache = {} self._remove_cache = {}
[ "def", "_init_cache", "(", "self", ")", ":", "self", ".", "_add_cache", "=", "defaultdict", "(", "list", ")", "self", ".", "_reverse_add_cache", "=", "defaultdict", "(", "list", ")", "self", ".", "_undefined_cache", "=", "{", "}", "self", ".", "_remove_cac...
Initialize cache.
[ "Initialize", "cache", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L371-L376
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.commit
def commit(self): """Commit current transaction.""" if (not self._add_cache and not self._remove_cache and not self._undefined_cache): return for store_key, hash_values in self._add_cache.items(): for hash_value in hash_values: ...
python
def commit(self): """Commit current transaction.""" if (not self._add_cache and not self._remove_cache and not self._undefined_cache): return for store_key, hash_values in self._add_cache.items(): for hash_value in hash_values: ...
[ "def", "commit", "(", "self", ")", ":", "if", "(", "not", "self", ".", "_add_cache", "and", "not", "self", ".", "_remove_cache", "and", "not", "self", ".", "_undefined_cache", ")", ":", "return", "for", "store_key", ",", "hash_values", "in", "self", ".",...
Commit current transaction.
[ "Commit", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L386-L405
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.rollback
def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
python
def rollback(self): """Drop changes from current transaction.""" if not self._in_transaction: raise NotInTransaction self._init_cache() self._in_transaction = False
[ "def", "rollback", "(", "self", ")", ":", "if", "not", "self", ".", "_in_transaction", ":", "raise", "NotInTransaction", "self", ".", "_init_cache", "(", ")", "self", ".", "_in_transaction", "=", "False" ]
Drop changes from current transaction.
[ "Drop", "changes", "from", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L407-L412
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.add_hashed_value
def add_hashed_value(self, hash_value, store_key): """Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object ...
python
def add_hashed_value(self, hash_value, store_key): """Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object ...
[ "def", "add_hashed_value", "(", "self", ",", "hash_value", ",", "store_key", ")", ":", "if", "hash_value", "not", "in", "self", ".", "_add_cache", "[", "store_key", "]", ":", "self", ".", "_add_cache", "[", "store_key", "]", ".", "append", "(", "hash_value...
Add hashed value in the context of the current transaction. :param hash_value: The hashed value to be added to the index :type hash_value: str :param store_key: The key for the document in the store :type store_key: object
[ "Add", "hashed", "value", "in", "the", "context", "of", "the", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L424-L440
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.remove_key
def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str """ self._remove_cache[store_key] = True if store_key in self._add_cache: for hash_value in...
python
def remove_key(self, store_key): """Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str """ self._remove_cache[store_key] = True if store_key in self._add_cache: for hash_value in...
[ "def", "remove_key", "(", "self", ",", "store_key", ")", ":", "self", ".", "_remove_cache", "[", "store_key", "]", "=", "True", "if", "store_key", "in", "self", ".", "_add_cache", ":", "for", "hash_value", "in", "self", ".", "_add_cache", "[", "store_key",...
Remove key in the context of the current transaction. :param store_key: The key for the document in the store :type store_key: str
[ "Remove", "key", "in", "the", "context", "of", "the", "current", "transaction", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L442-L455
adewes/blitzdb
blitzdb/backends/file/index.py
TransactionalIndex.get_keys_for
def get_keys_for(self, value, include_uncommitted=False): """Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the gi...
python
def get_keys_for(self, value, include_uncommitted=False): """Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the gi...
[ "def", "get_keys_for", "(", "self", ",", "value", ",", "include_uncommitted", "=", "False", ")", ":", "if", "not", "include_uncommitted", ":", "return", "super", "(", "TransactionalIndex", ",", "self", ")", ".", "get_keys_for", "(", "value", ")", "else", ":"...
Get keys for a given value. :param value: The value to look for :type value: object :param include_uncommitted: Include uncommitted values in results :type include_uncommitted: bool :return: The keys for the given value :rtype: list(str)
[ "Get", "keys", "for", "a", "given", "value", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/index.py#L457-L474
adewes/blitzdb
blitzdb/backends/sql/backend.py
Backend.filter
def filter(self, cls_or_collection, query, raw = False,only = None,include = None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: T...
python
def filter(self, cls_or_collection, query, raw = False,only = None,include = None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: T...
[ "def", "filter", "(", "self", ",", "cls_or_collection", ",", "query", ",", "raw", "=", "False", ",", "only", "=", "None", ",", "include", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls_or_collection", ",", "six", ".", "string_types", ")", ...
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports all query operators that are available in SQLAlchemy and returns a query set ...
[ "Filter", "objects", "from", "the", "database", "that", "correspond", "to", "a", "given", "set", "of", "properties", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/sql/backend.py#L1070-L1404
adewes/blitzdb
blitzdb/backends/mongo/backend.py
Backend._canonicalize_query
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: q = encoder.encode(q,[]) if isinstance(q, dict): ...
python
def _canonicalize_query(self, query): """ Transform the query dictionary to replace e.g. documents with __ref__ fields. """ def transform_query(q): for encoder in self.query_encoders: q = encoder.encode(q,[]) if isinstance(q, dict): ...
[ "def", "_canonicalize_query", "(", "self", ",", "query", ")", ":", "def", "transform_query", "(", "q", ")", ":", "for", "encoder", "in", "self", ".", "query_encoders", ":", "q", "=", "encoder", ".", "encode", "(", "q", ",", "[", "]", ")", "if", "isin...
Transform the query dictionary to replace e.g. documents with __ref__ fields.
[ "Transform", "the", "query", "dictionary", "to", "replace", "e", ".", "g", ".", "documents", "with", "__ref__", "fields", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/mongo/backend.py#L294-L334
adewes/blitzdb
blitzdb/backends/mongo/backend.py
Backend.filter
def filter(self, cls_or_collection, query, raw=False, only=None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function suppo...
python
def filter(self, cls_or_collection, query, raw=False, only=None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function suppo...
[ "def", "filter", "(", "self", ",", "cls_or_collection", ",", "query", ",", "raw", "=", "False", ",", "only", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls_or_collection", ",", "six", ".", "string_types", ")", ":", "collection", "=", "self",...
Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: This function supports most query operators that are available in MongoDB and returns a query...
[ "Filter", "objects", "from", "the", "database", "that", "correspond", "to", "a", "given", "set", "of", "properties", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/mongo/backend.py#L349-L379
adewes/blitzdb
blitzdb/backends/file/queries.py
boolean_operator_query
def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with ...
python
def boolean_operator_query(boolean_operator): """Generate boolean operator checking function.""" def _boolean_operator_query(expressions): """Apply boolean operator to expressions.""" def _apply_boolean_operator(query_function, expressions=expressions): """Return if expressions with ...
[ "def", "boolean_operator_query", "(", "boolean_operator", ")", ":", "def", "_boolean_operator_query", "(", "expressions", ")", ":", "\"\"\"Apply boolean operator to expressions.\"\"\"", "def", "_apply_boolean_operator", "(", "query_function", ",", "expressions", "=", "express...
Generate boolean operator checking function.
[ "Generate", "boolean", "operator", "checking", "function", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L11-L24
adewes/blitzdb
blitzdb/backends/file/queries.py
filter_query
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expressi...
python
def filter_query(key, expression): """Filter documents with a key that satisfies an expression.""" if (isinstance(expression, dict) and len(expression) == 1 and list(expression.keys())[0].startswith('$')): compiled_expression = compile_query(expression) elif callable(expressi...
[ "def", "filter_query", "(", "key", ",", "expression", ")", ":", "if", "(", "isinstance", "(", "expression", ",", "dict", ")", "and", "len", "(", "expression", ")", "==", "1", "and", "list", "(", "expression", ".", "keys", "(", ")", ")", "[", "0", "...
Filter documents with a key that satisfies an expression.
[ "Filter", "documents", "with", "a", "key", "that", "satisfies", "an", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L27-L48
adewes/blitzdb
blitzdb/backends/file/queries.py
not_query
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = e...
python
def not_query(expression): """Apply logical not operator to expression.""" compiled_expression = compile_query(expression) def _not(index, expression=compiled_expression): """Return store key for documents that satisfy expression.""" all_keys = index.get_all_keys() returned_keys = e...
[ "def", "not_query", "(", "expression", ")", ":", "compiled_expression", "=", "compile_query", "(", "expression", ")", "def", "_not", "(", "index", ",", "expression", "=", "compiled_expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"...
Apply logical not operator to expression.
[ "Apply", "logical", "not", "operator", "to", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L51-L61
adewes/blitzdb
blitzdb/backends/file/queries.py
comparison_operator_query
def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for docum...
python
def comparison_operator_query(comparison_operator): """Generate comparison operator checking function.""" def _comparison_operator_query(expression): """Apply binary operator to expression.""" def _apply_comparison_operator(index, expression=expression): """Return store key for docum...
[ "def", "comparison_operator_query", "(", "comparison_operator", ")", ":", "def", "_comparison_operator_query", "(", "expression", ")", ":", "\"\"\"Apply binary operator to expression.\"\"\"", "def", "_apply_comparison_operator", "(", "index", ",", "expression", "=", "expressi...
Generate comparison operator checking function.
[ "Generate", "comparison", "operator", "checking", "function", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L64-L79
adewes/blitzdb
blitzdb/backends/file/queries.py
exists_query
def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ ...
python
def exists_query(expression): """Check that documents have a key that satisfies expression.""" def _exists(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression if ev: return [ ...
[ "def", "exists_query", "(", "expression", ")", ":", "def", "_exists", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expr...
Check that documents have a key that satisfies expression.
[ "Check", "that", "documents", "have", "a", "key", "that", "satisfies", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L82-L97
adewes/blitzdb
blitzdb/backends/file/queries.py
regex_query
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys ...
python
def regex_query(expression): """Apply regular expression to result of expression.""" def _regex(index, expression=expression): """Return store key for documents that satisfy expression.""" pattern = re.compile(expression) return [ store_key for value, store_keys ...
[ "def", "regex_query", "(", "expression", ")", ":", "def", "_regex", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "pattern", "=", "re", ".", "compile", "(", "expression", ")", "re...
Apply regular expression to result of expression.
[ "Apply", "regular", "expression", "to", "result", "of", "expression", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L100-L114
adewes/blitzdb
blitzdb/backends/file/queries.py
all_query
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except T...
python
def all_query(expression): """Match arrays that contain all elements in the query.""" def _all(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) except T...
[ "def", "all_query", "(", "expression", ")", ":", "def", "_all", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression...
Match arrays that contain all elements in the query.
[ "Match", "arrays", "that", "contain", "all", "elements", "in", "the", "query", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L117-L137
adewes/blitzdb
blitzdb/backends/file/queries.py
in_query
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) ...
python
def in_query(expression): """Match any of the values that exist in an array specified in query.""" def _in(index, expression=expression): """Return store key for documents that satisfy expression.""" ev = expression() if callable(expression) else expression try: iter(ev) ...
[ "def", "in_query", "(", "expression", ")", ":", "def", "_in", "(", "index", ",", "expression", "=", "expression", ")", ":", "\"\"\"Return store key for documents that satisfy expression.\"\"\"", "ev", "=", "expression", "(", ")", "if", "callable", "(", "expression",...
Match any of the values that exist in an array specified in query.
[ "Match", "any", "of", "the", "values", "that", "exist", "in", "an", "array", "specified", "in", "query", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L150-L167
adewes/blitzdb
blitzdb/backends/file/queries.py
compile_query
def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {...
python
def compile_query(query): """Compile each expression in query recursively.""" if isinstance(query, dict): expressions = [] for key, value in query.items(): if key.startswith('$'): if key not in query_funcs: raise AttributeError('Invalid operator: {...
[ "def", "compile_query", "(", "query", ")", ":", "if", "isinstance", "(", "query", ",", "dict", ")", ":", "expressions", "=", "[", "]", "for", "key", ",", "value", "in", "query", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'$'...
Compile each expression in query recursively.
[ "Compile", "each", "expression", "in", "query", "recursively", "." ]
train
https://github.com/adewes/blitzdb/blob/4b459e0bcde9e1f6224dd4e3bea74194586864b0/blitzdb/backends/file/queries.py#L169-L189
seantis/suitable
suitable/module_runner.py
ansible_verbosity
def ansible_verbosity(verbosity): """ Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose ...
python
def ansible_verbosity(verbosity): """ Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose ...
[ "def", "ansible_verbosity", "(", "verbosity", ")", ":", "previous", "=", "display", ".", "verbosity", "display", ".", "verbosity", "=", "verbosity", "yield", "display", ".", "verbosity", "=", "previous" ]
Temporarily changes the ansible verbosity. Relies on a single display instance being referenced by the __main__ module. This is setup when suitable is imported, though Ansible could already be imported beforehand, in which case the output might not be as verbose as expected. To be sure, import sui...
[ "Temporarily", "changes", "the", "ansible", "verbosity", ".", "Relies", "on", "a", "single", "display", "instance", "being", "referenced", "by", "the", "__main__", "module", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L32-L46
seantis/suitable
suitable/module_runner.py
environment_variable
def environment_variable(key, value): """ Temporarily overrides an environment variable. """ if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: del os.environ[key] else: os.environ[...
python
def environment_variable(key, value): """ Temporarily overrides an environment variable. """ if key not in os.environ: previous = None else: previous = os.environ[key] os.environ[key] = value yield if previous is None: del os.environ[key] else: os.environ[...
[ "def", "environment_variable", "(", "key", ",", "value", ")", ":", "if", "key", "not", "in", "os", ".", "environ", ":", "previous", "=", "None", "else", ":", "previous", "=", "os", ".", "environ", "[", "key", "]", "os", ".", "environ", "[", "key", ...
Temporarily overrides an environment variable.
[ "Temporarily", "overrides", "an", "environment", "variable", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L50-L65
seantis/suitable
suitable/module_runner.py
host_key_checking
def host_key_checking(enable): """ Temporarily disables host_key_checking, which is set globally. """ def as_string(b): return b and 'True' or 'False' with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)): previous = ansible.constants.HOST_KEY_CHECKING ansible....
python
def host_key_checking(enable): """ Temporarily disables host_key_checking, which is set globally. """ def as_string(b): return b and 'True' or 'False' with environment_variable('ANSIBLE_HOST_KEY_CHECKING', as_string(enable)): previous = ansible.constants.HOST_KEY_CHECKING ansible....
[ "def", "host_key_checking", "(", "enable", ")", ":", "def", "as_string", "(", "b", ")", ":", "return", "b", "and", "'True'", "or", "'False'", "with", "environment_variable", "(", "'ANSIBLE_HOST_KEY_CHECKING'", ",", "as_string", "(", "enable", ")", ")", ":", ...
Temporarily disables host_key_checking, which is set globally.
[ "Temporarily", "disables", "host_key_checking", "which", "is", "set", "globally", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L69-L80
seantis/suitable
suitable/module_runner.py
ModuleRunner.hookup
def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_name, self.execute)
python
def hookup(self, api): """ Hooks this module up to the given api. """ assert not hasattr(api, self.module_name), """ '{}' conflicts with existing attribute """.format(self.module_name) self.api = api setattr(api, self.module_name, self.execute)
[ "def", "hookup", "(", "self", ",", "api", ")", ":", "assert", "not", "hasattr", "(", "api", ",", "self", ".", "module_name", ")", ",", "\"\"\"\n '{}' conflicts with existing attribute\n \"\"\"", ".", "format", "(", "self", ".", "module_name", ")"...
Hooks this module up to the given api.
[ "Hooks", "this", "module", "up", "to", "the", "given", "api", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L119-L128
seantis/suitable
suitable/module_runner.py
ModuleRunner.execute
def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should be hooked up to the api" if set_global_context: set_global_context(self.api.option...
python
def execute(self, *args, **kwargs): """ Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result. """ assert self.is_hooked_up, "the module should be hooked up to the api" if set_global_context: set_global_context(self.api.option...
[ "def", "execute", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "is_hooked_up", ",", "\"the module should be hooked up to the api\"", "if", "set_global_context", ":", "set_global_context", "(", "self", ".", "api", ".", ...
Puts args and kwargs in a way ansible can understand. Calls ansible and interprets the result.
[ "Puts", "args", "and", "kwargs", "in", "a", "way", "ansible", "can", "understand", ".", "Calls", "ansible", "and", "interprets", "the", "result", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L140-L271
seantis/suitable
suitable/module_runner.py
ModuleRunner.ignore_further_calls_to_server
def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
python
def ignore_further_calls_to_server(self, server): """ Takes a server out of the list. """ log.error(u'ignoring further calls to {}'.format(server)) self.api.servers.remove(server)
[ "def", "ignore_further_calls_to_server", "(", "self", ",", "server", ")", ":", "log", ".", "error", "(", "u'ignoring further calls to {}'", ".", "format", "(", "server", ")", ")", "self", ".", "api", ".", "servers", ".", "remove", "(", "server", ")" ]
Takes a server out of the list.
[ "Takes", "a", "server", "out", "of", "the", "list", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L273-L276
seantis/suitable
suitable/module_runner.py
ModuleRunner.evaluate_results
def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) ...
python
def evaluate_results(self, callback): """ prepare the result of runner call for use with RunnerResults. """ for server, result in callback.unreachable.items(): log.error(u'{} could not be reached'.format(server)) log.debug(u'ansible-output =>\n{}'.format(pformat(result))) ...
[ "def", "evaluate_results", "(", "self", ",", "callback", ")", ":", "for", "server", ",", "result", "in", "callback", ".", "unreachable", ".", "items", "(", ")", ":", "log", ".", "error", "(", "u'{} could not be reached'", ".", "format", "(", "server", ")",...
prepare the result of runner call for use with RunnerResults.
[ "prepare", "the", "result", "of", "runner", "call", "for", "use", "with", "RunnerResults", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/module_runner.py#L288-L336
seantis/suitable
suitable/api.py
install_strategy_plugins
def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to...
python
def install_strategy_plugins(directories): """ Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to...
[ "def", "install_strategy_plugins", "(", "directories", ")", ":", "if", "isinstance", "(", "directories", ",", "str", ")", ":", "directories", "=", "directories", ".", "split", "(", "':'", ")", "for", "directory", "in", "directories", ":", "strategy_loader", "....
Loads the given strategy plugins, which is a list of directories, a string with a single directory or a string with multiple directories separated by colon. As these plugins are globally loaded and cached by Ansible we do the same here. We could try to bind those plugins to the Api instance, but that's...
[ "Loads", "the", "given", "strategy", "plugins", "which", "is", "a", "list", "of", "directories", "a", "string", "with", "a", "single", "directory", "or", "a", "string", "with", "multiple", "directories", "separated", "by", "colon", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/api.py#L298-L315
seantis/suitable
suitable/api.py
Api.valid_return_codes
def valid_return_codes(self, *codes): """ Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log') """ ...
python
def valid_return_codes(self, *codes): """ Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log') """ ...
[ "def", "valid_return_codes", "(", "self", ",", "*", "codes", ")", ":", "previous_codes", "=", "self", ".", "_valid_return_codes", "self", ".", "_valid_return_codes", "=", "codes", "yield", "self", ".", "_valid_return_codes", "=", "previous_codes" ]
Sets codes which are considered valid when returned from command modules. The default is (0, ). Should be used as a context:: with api.valid_return_codes(0, 1): api.shell('test -e /tmp/log && rm /tmp/log')
[ "Sets", "codes", "which", "are", "considered", "valid", "when", "returned", "from", "command", "modules", ".", "The", "default", "is", "(", "0", ")", "." ]
train
https://github.com/seantis/suitable/blob/b056afb753f2b89909edfb6e00ec7c55691135ff/suitable/api.py#L280-L295
nielstron/pysyncthru
pysyncthru/__init__.py
construct_url
def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
python
def construct_url(ip_address: str) -> str: """Construct the URL with a given IP address.""" if 'http://' not in ip_address and 'https://' not in ip_address: ip_address = '{}{}'.format('http://', ip_address) if ip_address[-1] == '/': ip_address = ip_address[:-1] return ip_address
[ "def", "construct_url", "(", "ip_address", ":", "str", ")", "->", "str", ":", "if", "'http://'", "not", "in", "ip_address", "and", "'https://'", "not", "in", "ip_address", ":", "ip_address", "=", "'{}{}'", ".", "format", "(", "'http://'", ",", "ip_address", ...
Construct the URL with a given IP address.
[ "Construct", "the", "URL", "with", "a", "given", "IP", "address", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L12-L18
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.update
async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) try: async with self._session.get(url) as response: json_dict = de...
python
async def update(self) -> None: """ Retrieve the data from the printer. Throws ValueError if host does not support SyncThru """ url = '{}{}'.format(self.url, ENDPOINT) try: async with self._session.get(url) as response: json_dict = de...
[ "async", "def", "update", "(", "self", ")", "->", "None", ":", "url", "=", "'{}{}'", ".", "format", "(", "self", ".", "url", ",", "ENDPOINT", ")", "try", ":", "async", "with", "self", ".", "_session", ".", "get", "(", "url", ")", "as", "response", ...
Retrieve the data from the printer. Throws ValueError if host does not support SyncThru
[ "Retrieve", "the", "data", "from", "the", "printer", ".", "Throws", "ValueError", "if", "host", "does", "not", "support", "SyncThru" ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L35-L49
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.model
def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
python
def model(self): """Return the model name of the printer.""" try: return self.data.get('identity').get('model_name') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "model", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'model_name'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_statu...
Return the model name of the printer.
[ "Return", "the", "model", "name", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L66-L71
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.location
def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
python
def location(self): """Return the location of the printer.""" try: return self.data.get('identity').get('location') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "location", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'location'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_stat...
Return the location of the printer.
[ "Return", "the", "location", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L73-L78
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.serial_number
def serial_number(self): """Return the serial number of the printer.""" try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
python
def serial_number(self): """Return the serial number of the printer.""" try: return self.data.get('identity').get('serial_num') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "serial_number", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'serial_num'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "devi...
Return the serial number of the printer.
[ "Return", "the", "serial", "number", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L80-L85
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.hostname
def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
python
def hostname(self): """Return the hostname of the printer.""" try: return self.data.get('identity').get('host_name') except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "hostname", "(", "self", ")", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'identity'", ")", ".", "get", "(", "'host_name'", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "self", ".", "device_sta...
Return the hostname of the printer.
[ "Return", "the", "hostname", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L87-L92
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.device_status
def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
python
def device_status(self): """Return the status of the device as string.""" try: return self.device_status_simple( self.data.get('status').get('status1')) except (KeyError, AttributeError): return self.device_status_simple('')
[ "def", "device_status", "(", "self", ")", ":", "try", ":", "return", "self", ".", "device_status_simple", "(", "self", ".", "data", ".", "get", "(", "'status'", ")", ".", "get", "(", "'status1'", ")", ")", "except", "(", "KeyError", ",", "AttributeError"...
Return the status of the device as string.
[ "Return", "the", "status", "of", "the", "device", "as", "string", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L94-L100
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.capability
def capability(self) -> Dict[str, Any]: """Return the capabilities of the printer.""" try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
python
def capability(self) -> Dict[str, Any]: """Return the capabilities of the printer.""" try: return self.data.get('capability', {}) except (KeyError, AttributeError): return {}
[ "def", "capability", "(", "self", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "try", ":", "return", "self", ".", "data", ".", "get", "(", "'capability'", ",", "{", "}", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "retu...
Return the capabilities of the printer.
[ "Return", "the", "capabilities", "of", "the", "printer", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L102-L107
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.toner_status
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color),...
python
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all toners cartridges.""" toner_status = {} for color in self.COLOR_NAMES: try: toner_stat = self.data.get( '{}_{}'.format(SyncThru.TONER, color),...
[ "def", "toner_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "toner_status", "=", "{", "}", "for", "color", "in", "self", ".", "COLOR_NAMES", ":", "try", ":", "toner_stat", ...
Return the state of all toners cartridges.
[ "Return", "the", "state", "of", "all", "toners", "cartridges", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L116-L129
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.input_tray_status
def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {}) ...
python
def input_tray_status(self, filter_supported: bool = True) -> Dict[int, Any]: """Return the state of all input trays.""" tray_status = {} for i in range(1, 5): try: tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {}) ...
[ "def", "input_tray_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "int", ",", "Any", "]", ":", "tray_status", "=", "{", "}", "for", "i", "in", "range", "(", "1", ",", "5", ")", ":", "try", ":", "t...
Return the state of all input trays.
[ "Return", "the", "state", "of", "all", "input", "trays", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L131-L144
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.output_tray_status
def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_status[i] = { 'nam...
python
def output_tray_status(self) -> Dict[int, Dict[str, str]]: """Return the state of all output trays.""" tray_status = {} try: tray_stat = self.data.get('outputTray', []) for i, stat in enumerate(tray_stat): tray_status[i] = { 'nam...
[ "def", "output_tray_status", "(", "self", ")", "->", "Dict", "[", "int", ",", "Dict", "[", "str", ",", "str", "]", "]", ":", "tray_status", "=", "{", "}", "try", ":", "tray_stat", "=", "self", ".", "data", ".", "get", "(", "'outputTray'", ",", "[",...
Return the state of all output trays.
[ "Return", "the", "state", "of", "all", "output", "trays", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L146-L159
nielstron/pysyncthru
pysyncthru/__init__.py
SyncThru.drum_status
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), ...
python
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]: """Return the state of all drums.""" drum_status = {} for color in self.COLOR_NAMES: try: drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color), ...
[ "def", "drum_status", "(", "self", ",", "filter_supported", ":", "bool", "=", "True", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "drum_status", "=", "{", "}", "for", "color", "in", "self", ".", "COLOR_NAMES", ":", "try", ":", "drum_stat", "...
Return the state of all drums.
[ "Return", "the", "state", "of", "all", "drums", "." ]
train
https://github.com/nielstron/pysyncthru/blob/850a85ba0a74cbd5c408102bb02fd005d8b61ffb/pysyncthru/__init__.py#L161-L174
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
pdb_run
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException try: func(*args, **kwargs) except: # nopep8 type_, value, tb = sys.exc_info() ...
python
def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None: """ Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger. """ # noinspection PyBroadException try: func(*args, **kwargs) except: # nopep8 type_, value, tb = sys.exc_info() ...
[ "def", "pdb_run", "(", "func", ":", "Callable", ",", "*", "args", ":", "Any", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "# noinspection PyBroadException", "try", ":", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except"...
Calls ``func(*args, **kwargs)``; if it raises an exception, break into the ``pdb`` debugger.
[ "Calls", "func", "(", "*", "args", "**", "kwargs", ")", ";", "if", "it", "raises", "an", "exception", "break", "into", "the", "pdb", "debugger", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L48-L59
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
get_class_name_from_frame
def get_class_name_from_frame(fr: FrameType) -> Optional[str]: """ A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It re...
python
def get_class_name_from_frame(fr: FrameType) -> Optional[str]: """ A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It re...
[ "def", "get_class_name_from_frame", "(", "fr", ":", "FrameType", ")", "->", "Optional", "[", "str", "]", ":", "# http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa", "args", ",", "_", ",", "_", ",", "value_dict", ...
A frame contains information about a specific call in the Python call stack; see https://docs.python.org/3/library/inspect.html. If the call was to a member function of a class, this function attempts to read the class's name. It returns ``None`` otherwise.
[ "A", "frame", "contains", "information", "about", "a", "specific", "call", "in", "the", "Python", "call", "stack", ";", "see", "https", ":", "//", "docs", ".", "python", ".", "org", "/", "3", "/", "library", "/", "inspect", ".", "html", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L74-L95
RudolfCardinal/pythonlib
cardinal_pythonlib/debugging.py
get_caller_name
def get_caller_name(back: int = 0) -> str: """ Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) ...
python
def get_caller_name(back: int = 0) -> str: """ Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) ...
[ "def", "get_caller_name", "(", "back", ":", "int", "=", "0", ")", "->", "str", ":", "# http://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback # noqa", "try", ":", "# noinspection PyProtectedMember", "frame", "=", "sys...
Return details about the CALLER OF THE CALLER (plus n calls further back) of this function. So, if your function calls :func:`get_caller_name`, it will return the name of the function that called your function! (Or ``back`` calls further back.) Example: .. code-block:: python from ca...
[ "Return", "details", "about", "the", "CALLER", "OF", "THE", "CALLER", "(", "plus", "n", "calls", "further", "back", ")", "of", "this", "function", "." ]
train
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/debugging.py#L98-L151