code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
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._file)
self._dir, self._name = os.... | def open(self) | Open or re-open file. | 2.277463 | 2.233571 | 1.019651 |
if size < 0 and self._offset:
size = self._size
return self._fh.read(size) | def read(self, size=-1) | Read 'size' bytes from file, or until EOF is reached. | 5.717069 | 5.038244 | 1.134734 |
if not self.is_file:
raise ValueError('Cannot memory-map file without fileno')
return numpy.memmap(self._fh, dtype=dtype, mode=mode,
offset=self._offset + offset,
shape=shape, order=order) | def memmap_array(self, dtype, shape, offset=0, mode='r', order='C') | Return numpy.memmap of data stored in file. | 3.897835 | 3.576929 | 1.089715 |
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:
size = count * dtype.itemsize
result = numpy.empty(count, dtype) if out is None else out
... | def read_array(self, dtype, count=-1, out=None) | Return numpy array from file in native byte order. | 2.552737 | 2.422119 | 1.053928 |
rec = numpy.rec
try:
record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
except Exception:
dtype = numpy.dtype(dtype)
if shape is None:
shape = self._size // dtype.itemsize
size = product(sequence(shape)) * d... | def read_record(self, dtype, shape=1, byteorder=None) | Return numpy record from file. | 3.123061 | 2.970742 | 1.051273 |
if size < 1:
return
self._fh.seek(size-1, 1)
self._fh.write(b'\x00') | def write_empty(self, size) | Append size bytes to file. Position must be at end of file. | 3.815656 | 3.285383 | 1.161404 |
try:
data.tofile(self._fh)
except Exception:
# BytesIO
self._fh.write(data.tostring()) | def write_array(self, data) | Write numpy array to binary file. | 5.484234 | 5.218659 | 1.05089 |
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 + offset, 0)
return
self._fh.seek(offset, whenc... | def seek(self, offset, whence=0) | Set file's current position. | 2.598712 | 2.545995 | 1.020706 |
if self._close and self._fh:
self._fh.close()
self._fh = None | def close(self) | Close file. | 5.740106 | 4.111598 | 1.396077 |
with self.lock:
if filehandle in self.files:
self.files[filehandle] += 1
elif filehandle.closed:
filehandle.open()
self.files[filehandle] = 1
self.past.append(filehandle) | def open(self, filehandle) | Re-open file if necessary. | 3.174437 | 2.932875 | 1.082364 |
with self.lock:
if filehandle in self.files:
self.files[filehandle] -= 1
# trim the file cache
index = 0
size = len(self.past)
while size > self.size and index < size:
filehandle = self.past[... | def close(self, filehandle) | Close openend file if no longer used. | 2.978636 | 2.935721 | 1.014618 |
with self.lock:
for filehandle, refcount in list(self.files.items()):
if refcount == 0:
filehandle.close()
del self.files[filehandle]
del self.past[self.past.index(filehandle)] | def clear(self) | Close all opened files if not in use. | 4.13164 | 3.611263 | 1.144098 |
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 are no more tags in the template?
except ValueError:
# Then t... | def grab_literal(template, l_del) | Parse a literal from the template | 5.268808 | 5.092509 | 1.034619 |
# 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 the last newline are spaces
if padding.isspace() or padding == '':
# Then the next tag could be a... | def l_sa_check(template, literal, is_standalone) | Do a preliminary check to see if a tag could be a standalone | 5.954224 | 5.373858 | 1.107998 |
# 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 us are spaces we're a standalone
if on_newline[0].isspace() or not on_newline[0]:
return T... | def r_sa_check(template, tag_type, is_standalone) | Do a final checkto see if a tag could be a standalone | 7.345769 | 6.852083 | 1.072049 |
global _CURRENT_LINE
global _LAST_TAG_LINE
tag_types = {
'!': 'comment',
'#': 'section',
'^': 'inverted section',
'/': 'end',
'>': 'partial',
'=': 'set delimiter?',
'{': 'no escape?',
'&': 'no escape'
}
# Get the tag
try:
... | def parse_tag(template, l_del, r_del) | Parse a tag from a template | 4.480719 | 4.437565 | 1.009725 |
global _CURRENT_LINE, _LAST_TAG_LINE
_CURRENT_LINE = 1
_LAST_TAG_LINE = None
# If the template is a file-like object then read it
try:
template = template.read()
except AttributeError:
pass
is_standalone = True
open_sections = []
l_del = def_ldel
r_del = de... | 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_ldel -- The default left delimiter
... | 3.435923 | 3.288873 | 1.044711 |
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):
if not os.path.isdir(arg):
parser.error('The... | def cli_main() | Render mustache templates using json files | 2.306397 | 2.232491 | 1.033105 |
html_codes = {
'"': '"',
'<': '<',
'>': '>',
}
# & must be handled first
string = string.replace('&', '&')
for char in html_codes:
string = string.replace(char, html_codes[char])
return string | def _html_escape(string) | HTML escape all of these " & < > | 2.89276 | 2.76265 | 1.047096 |
# 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 in key.split('.'):
# Move into the scope
... | def _get_key(key, scopes) | Get a key from the current scope | 6.393245 | 6.281297 | 1.017822 |
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_ext if partials_ext else '')
path = partials_path + '/' + name + path_ext
... | def _get_partial(name, partials_dict, partials_path, partials_ext) | Load a partial | 3.413296 | 3.390156 | 1.006826 |
'''
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 | 11.655174 | 3.062513 | 3.805755 |
'''
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 = []
retur... | def commit(self) | This method executes the bulk query, flushes stored queries and
returns the response | 6.585115 | 3.614522 | 1.821849 |
'''
Returns the request token that can be used to fetch the access token
'''
headers = {
'X-Accept': 'application/json',
}
url = 'https://getpocket.com/v3/oauth/request'
payload = {
'consumer_key': consumer_key,
'redirect_uri':... | 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 | 2.907355 | 2.458928 | 1.182367 |
'''
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_key': consumer_key,
'code': code,
... | def get_credentials(cls, consumer_key, code) | Fetches access token from using the request token and consumer key | 3.601539 | 2.740587 | 1.314149 |
'''
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)
auth_url = 'https://getpocket.com/auth/authorize?request_token='\
'%s&redirect_uri=... | 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 | 3.707398 | 2.545503 | 1.45645 |
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,
relationship_table.c[self.params['pk_field_name']] == self.o... | def remove(self,obj) | Remove an object from the relation | 4.110619 | 3.963225 | 1.03719 |
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, store in self.stores.items():
store.... | def begin(self) | Start a new transaction. | 4.378688 | 4.016091 | 1.090286 |
if not self.in_transaction:
raise NotInTransaction
for collection, store in self.stores.items():
store.rollback()
indexes = self.indexes[collection]
indexes_to_rebuild = []
for key, index in indexes.items():
try:
... | def rollback(self, transaction = None) | Roll back a transaction. | 3.313438 | 3.261827 | 1.015823 |
for collection in self.collections:
store = self.get_collection_store(collection)
store.commit()
indexes = self.get_collection_indexes(collection)
for index in indexes.values():
index.commit()
self.in_transaction = False
se... | 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 indexes to be written to disk. | 3.617732 | 4.098842 | 0.882623 |
if params:
return self.create_indexes(cls_or_collection, [params],
ephemeral=ephemeral, unique=unique)
elif fields:
params = []
if len(fields.items()) > 1:
raise ValueError("File backend currently does no... | 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
index
:param params: The parameters of the index
:param ephemeral: Whether to create a persistent or an ephemera... | 3.624902 | 4.346283 | 0.834023 |
cls = self.collections[collection]
if not cls.get_pk_name() in self.indexes[collection]:
self.create_index(cls.get_pk_name(), collection)
return self.indexes[collection][cls.get_pk_name()] | 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 | 3.13221 | 3.692026 | 0.848372 |
if set_fields:
if isinstance(set_fields,(list,tuple)):
set_attributes = {}
for key in set_fields:
try:
set_attributes[key] = get_value(obj,key)
except KeyError:
pass
... | 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). | 2.127872 | 2.070561 | 1.027679 |
def transform_query(q):
if isinstance(q, dict):
nq = {}
for key,value in q.items():
nq[key] = transform_query(value)
return nq
elif isinstance(q, (list,QuerySet,tuple)):
return [transform_quer... | def _canonicalize_query(self, query) | Transform the query dictionary to replace e.g. documents with __ref__ fields. | 2.926321 | 2.633903 | 1.111021 |
if cls in self.deprecated_classes and not overwrite:
return False
if parameters is None:
parameters = {}
if 'collection' in parameters:
collection_name = parameters['collection']
elif hasattr(cls.Meta,'collection'):
collection_na... | 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
to specify the collection in which to store the documen... | 2.243099 | 2.245085 | 0.999116 |
params = self.get_meta_attributes(cls)
return self.register(cls, params) | def autoregister(self, cls) | Autoregister a class that is encountered for the first time.
:param cls: The class that should be registered. | 10.04551 | 12.753761 | 0.787651 |
if not encoders:
encoders = []
for encoder in encoders + self.standard_encoders:
obj = encoder.decode(obj)
if isinstance(obj, dict):
if create_instance and '__collection__' in obj and obj['__collection__'] in self.collections and 'pk' in obj:
... | 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 as required.
:param obj: The object to be deserialized.
:returns: The deserialized o... | 2.468103 | 2.460394 | 1.003133 |
creation_args = {
'backend' : self,
'autoload' : self._autoload_embedded,
'lazy' : lazy,
'db_loader' : db_loader
}
if collection_or_class in self.classes:
cls = collection_or_class
elif collection_or_class in self.coll... | 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 the class for which to create an instance.
:param attributes: The attributes of the instance to be created
:param lazy: Whether... | 2.6278 | 2.783488 | 0.944067 |
class TransactionManager(object):
def __init__(self,backend,implicit = False):
self.backend = backend
self.implicit = implicit
def __enter__(self):
self.within_transaction = True if self.backend.current_transaction else False
... | def transaction(self,implicit = False) | This returns a context guard which will automatically open and close a transaction | 3.281135 | 3.313334 | 0.990282 |
if cls not in self.classes:
if issubclass(cls, Document) and cls not in self.classes and cls not in self.deprecated_classes:
self.autoregister(cls)
else:
raise AttributeError("Unknown object type: %s" % cls.__name__)
collection = self.clas... | 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. | 3.920527 | 4.146174 | 0.945577 |
for cls in self.classes:
if cls.__name__ == cls_name:
return self.classes[cls]['collection']
raise AttributeError("Unknown class name: %s" % 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. | 3.156991 | 3.472488 | 0.909144 |
for cls, params in self.classes.items():
if params['collection'] == collection:
return cls
raise AttributeError("Unknown collection: %s" % 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. | 3.732391 | 4.809323 | 0.776074 |
self._index = defaultdict(list)
self._reverse_index = defaultdict(list)
self._undefined_keys = {} | def clear(self) | Clear index. | 8.746954 | 6.852605 | 1.276442 |
value = attributes
if key is None:
key = self._splitted_key
# A splitted key like 'a.b.c' goes into nested properties
# and the value is retrieved recursively
for i,elem in enumerate(key):
if isinstance(value, (list,tuple)):
#if ... | 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 | 6.067547 | 6.654412 | 0.911808 |
if not self._store:
raise AttributeError('No datastore defined!')
saved_data = self.save_to_data(in_place=True)
data = Serializer.serialize(saved_data)
self._store.store_blob(data, 'all_keys_with_undefined') | def save_to_store(self) | Save index to store.
:raise AttributeError: If no datastore is defined | 9.933956 | 9.032703 | 1.099777 |
all_keys = []
for keys in self._index.values():
all_keys.extend(keys)
return all_keys | def get_all_keys(self) | Get all keys indexed.
:return: All keys
:rtype: list(str) | 4.002194 | 4.064592 | 0.984648 |
if not self._store:
raise AttributeError('No datastore defined!')
if self._store.has_blob('all_keys'):
data = Serializer.deserialize(self._store.get_blob('all_keys'))
self.load_from_data(data)
return True
elif self._store.has_blob('all_key... | 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 | 2.924618 | 2.712218 | 1.078312 |
# to do: check that all reverse index values are unambiguous
missing_keys = [
key
for key in keys
if not len(self._reverse_index[key])
]
keys_and_values = [
(key, self._reverse_index[key][0])
for key in 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 keys
:rtype: list(str)
:raise ValueError: If inval... | 2.662952 | 2.695714 | 0.987847 |
if in_place:
return [
list(self._index.items()),
list(self._undefined_keys.keys())
]
return (
[(key, values[:]) for key, values in self._index.items()],
list(self._undefined_keys.keys()),
) | 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 | 5.311882 | 4.850616 | 1.095094 |
if with_undefined:
defined_values, undefined_values = data
else:
defined_values = data
undefined_values = None
self._index = defaultdict(list, defined_values)
self._reverse_index = defaultdict(list)
for key, values in self._index.items... | def load_from_data(self, data, with_undefined=False) | Load index structure.
:param with_undefined: Load undefined keys as well
:type with_undefined: bool | 2.384053 | 2.385388 | 0.99944 |
if isinstance(value,dict) and '__ref__' in value:
return self.get_hash_for(value['__ref__'])
serialized_value = self._serializer(value)
if isinstance(serialized_value, dict):
# Hash each item and return the hash of all the hashes
return hash(frozenset... | 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 | 2.551425 | 2.623777 | 0.972424 |
if callable(value):
return value(self)
hash_value = self.get_hash_for(value)
return self._index[hash_value][:] | 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) | 5.667768 | 6.047004 | 0.937285 |
if self._unique and hash_value in self._index:
raise NonUnique('Hash value {} already in index'.format(hash_value))
if store_key not in self._index[hash_value]:
self._index[hash_value].append(store_key)
if hash_value not in self._reverse_index[store_key]:
... | 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 | 2.602105 | 2.697266 | 0.964719 |
undefined = False
try:
value = self.get_value(attributes)
except (KeyError, IndexError):
undefined = True
# We remove old values in _reverse_index
self.remove_key(store_key)
if not undefined:
if isinstance(value, (list,tuple))... | 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 | 3.808347 | 4.010432 | 0.94961 |
if store_key in self._undefined_keys:
del self._undefined_keys[store_key]
if store_key in self._reverse_index:
for value in self._reverse_index[store_key]:
self._index[value].remove(store_key)
del self._reverse_index[store_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 | 2.453623 | 2.623866 | 0.935117 |
self._add_cache = defaultdict(list)
self._reverse_add_cache = defaultdict(list)
self._undefined_cache = {}
self._remove_cache = {} | def _init_cache(self) | Initialize cache. | 5.155425 | 4.541929 | 1.135074 |
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:
super(TransactionalIndex, self).add_hashed_val... | def commit(self) | Commit current transaction. | 3.526708 | 3.425101 | 1.029665 |
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | def rollback(self) | Drop changes from current transaction. | 6.34944 | 4.980138 | 1.274953 |
if hash_value not in self._add_cache[store_key]:
self._add_cache[store_key].append(hash_value)
if store_key not in self._reverse_add_cache[hash_value]:
self._reverse_add_cache[hash_value].append(store_key)
if store_key in self._remove_cache:
del self.... | 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 | 2.012249 | 2.147478 | 0.937029 |
self._remove_cache[store_key] = True
if store_key in self._add_cache:
for hash_value in self._add_cache[store_key]:
self._reverse_add_cache[hash_value].remove(store_key)
del self._add_cache[store_key]
if store_key in self._undefined_cache:
... | 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 | 2.571284 | 2.698356 | 0.952907 |
if not include_uncommitted:
return super(TransactionalIndex, self).get_keys_for(value)
else:
keys = super(TransactionalIndex, self).get_keys_for(value)
hash_value = self.get_hash_for(value)
keys += self._reverse_add_cache[hash_value]
r... | 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 given value
:rtype: list(str) | 3.486613 | 3.520928 | 0.990254 |
def transform_query(q):
for encoder in self.query_encoders:
q = encoder.encode(q,[])
if isinstance(q, dict):
nq = {}
for key,value in q.items():
new_key = key
if isinstance(value,dict) an... | def _canonicalize_query(self, query) | Transform the query dictionary to replace e.g. documents with __ref__ fields. | 2.645196 | 2.467616 | 1.071964 |
if not isinstance(cls_or_collection, six.string_types):
collection = self.get_collection_for_cls(cls_or_collection)
cls = cls_or_collection
else:
collection = cls_or_collection
cls = self.get_cls_for_collection(collection)
canonical_quer... | 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 supports most query operators that are available in MongoDB and returns
a query... | 2.633 | 2.673164 | 0.984975 |
def _boolean_operator_query(expressions):
def _apply_boolean_operator(query_function, expressions=expressions):
compiled_expressions = [compile_query(e) for e in expressions]
return reduce(
boolean_operator,
[e(query_function... | def boolean_operator_query(boolean_operator) | Generate boolean operator checking function. | 3.959212 | 3.638266 | 1.088214 |
if (isinstance(expression, dict)
and len(expression) == 1
and list(expression.keys())[0].startswith('$')):
compiled_expression = compile_query(expression)
elif callable(expression):
def _filter(index, expression=expression):
result = [store_key
... | def filter_query(key, expression) | Filter documents with a key that satisfies an expression. | 4.005453 | 3.836348 | 1.04408 |
compiled_expression = compile_query(expression)
def _not(index, expression=compiled_expression):
all_keys = index.get_all_keys()
returned_keys = expression(index)
return [key for key in all_keys if key not in returned_keys]
return _not | def not_query(expression) | Apply logical not operator to expression. | 4.556595 | 4.855876 | 0.938367 |
def _comparison_operator_query(expression):
def _apply_comparison_operator(index, expression=expression):
ev = expression() if callable(expression) else expression
return [
store_key
for value, store_keys
in i... | def comparison_operator_query(comparison_operator) | Generate comparison operator checking function. | 4.622396 | 4.481914 | 1.031344 |
def _exists(index, expression=expression):
ev = expression() if callable(expression) else expression
if ev:
return [
store_key
for store_keys
in index.get_index().values()
for store_key in store_keys
... | def exists_query(expression) | Check that documents have a key that satisfies expression. | 7.195676 | 6.862687 | 1.048522 |
def _regex(index, expression=expression):
pattern = re.compile(expression)
return [
store_key
for value, store_keys
in index.get_index().items()
if (isinstance(value, six.string_types)
and re.match(pattern, value))
... | def regex_query(expression) | Apply regular expression to result of expression. | 4.909632 | 5.290943 | 0.927931 |
def _all(index, expression=expression):
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$all argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
... | def all_query(expression) | Match arrays that contain all elements in the query. | 3.970828 | 4.024819 | 0.986585 |
def _in(index, expression=expression):
ev = expression() if callable(expression) else expression
try:
iter(ev)
except TypeError:
raise AttributeError('$in argument must be an iterable!')
hashed_ev = [index.get_hash_for(v) for v in ev]
sto... | def in_query(expression) | Match any of the values that exist in an array specified in query. | 5.485096 | 5.706033 | 0.96128 |
if isinstance(query, dict):
expressions = []
for key, value in query.items():
if key.startswith('$'):
if key not in query_funcs:
raise AttributeError('Invalid operator: {}'.format(key))
expressions.append(query_funcs[key](value))
... | def compile_query(query) | Compile each expression in query recursively. | 3.139736 | 3.048294 | 1.029998 |
previous = display.verbosity
display.verbosity = verbosity
yield
display.verbosity = previous | 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
as expected.
To be sure, import sui... | 5.857157 | 7.268446 | 0.805833 |
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[key] = previous | def environment_variable(key, value) | Temporarily overrides an environment variable. | 2.245472 | 1.980977 | 1.133517 |
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.constants.HOST_KEY_CHECKING = enable
yield
ansible.constants.HOST_KEY_CHECKING = prev... | def host_key_checking(enable) | Temporarily disables host_key_checking, which is set globally. | 3.399099 | 3.427919 | 0.991593 |
assert not hasattr(api, self.module_name), .format(self.module_name)
self.api = api
setattr(api, self.module_name, self.execute) | def hookup(self, api) | Hooks this module up to the given api. | 5.669986 | 4.99876 | 1.134279 |
assert self.is_hooked_up, "the module should be hooked up to the api"
if set_global_context:
set_global_context(self.api.options)
# legacy key=value pairs shorthand approach
if args:
self.module_args = module_args = self.get_module_args(args, kwargs)
... | def execute(self, *args, **kwargs) | Puts args and kwargs in a way ansible can understand. Calls ansible
and interprets the result. | 5.439109 | 5.376551 | 1.011635 |
log.error(u'ignoring further calls to {}'.format(server))
self.api.servers.remove(server) | def ignore_further_calls_to_server(self, server) | Takes a server out of the list. | 8.246593 | 6.289523 | 1.311163 |
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)))
if self.api.ignore_unreachable:
continue
self.trigger_event(server, 'on... | def evaluate_results(self, callback) | prepare the result of runner call for use with RunnerResults. | 5.536901 | 5.440717 | 1.017679 |
if isinstance(directories, str):
directories = directories.split(':')
for directory in directories:
strategy_loader.add_directory(directory) | 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 bind those plugins to the Api instance, but that's... | 4.480061 | 4.221355 | 1.061285 |
previous_codes = self._valid_return_codes
self._valid_return_codes = codes
yield
self._valid_return_codes = previous_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') | 3.95923 | 3.956208 | 1.000764 |
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)
if ip_address[-1] == '/':
ip_address = ip_address[:-1]
return ip_address | Construct the URL with a given IP address. | null | null | null | |
async def update(self) -> None:
url = '{}{}'.format(self.url, ENDPOINT)
try:
async with self._session.get(url) as response:
json_dict = demjson.decode(await response.text(), strict=False)
except aiohttp.ClientError:
json_dict = {'status':... | Retrieve the data from the printer.
Throws ValueError if host does not support SyncThru | null | null | null | |
def model(self):
try:
return self.data.get('identity').get('model_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the model name of the printer. | null | null | null | |
def location(self):
try:
return self.data.get('identity').get('location')
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the location of the printer. | null | null | null | |
def serial_number(self):
try:
return self.data.get('identity').get('serial_num')
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the serial number of the printer. | null | null | null | |
def hostname(self):
try:
return self.data.get('identity').get('host_name')
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the hostname of the printer. | null | null | null | |
def device_status(self):
try:
return self.device_status_simple(
self.data.get('status').get('status1'))
except (KeyError, AttributeError):
return self.device_status_simple('') | Return the status of the device as string. | null | null | null | |
def capability(self) -> Dict[str, Any]:
try:
return self.data.get('capability', {})
except (KeyError, AttributeError):
return {} | Return the capabilities of the printer. | null | null | null | |
def toner_status(self, filter_supported: bool = True) -> Dict[str, Any]:
toner_status = {}
for color in self.COLOR_NAMES:
try:
toner_stat = self.data.get(
'{}_{}'.format(SyncThru.TONER, color), {})
if filter_supported and to... | Return the state of all toners cartridges. | null | null | null | |
def input_tray_status(self,
filter_supported: bool = True) -> Dict[int, Any]:
tray_status = {}
for i in range(1, 5):
try:
tray_stat = self.data.get('{}{}'.format(SyncThru.TRAY, i), {})
if filter_supported and tray_stat... | Return the state of all input trays. | null | null | null | |
def output_tray_status(self) -> Dict[int, Dict[str, str]]:
tray_status = {}
try:
tray_stat = self.data.get('outputTray', [])
for i, stat in enumerate(tray_stat):
tray_status[i] = {
'name': stat[0],
'capacity... | Return the state of all output trays. | null | null | null | |
def drum_status(self, filter_supported: bool = True) -> Dict[str, Any]:
drum_status = {}
for color in self.COLOR_NAMES:
try:
drum_stat = self.data.get('{}_{}'.format(SyncThru.DRUM, color),
{})
if filter... | Return the state of all drums. | null | null | null | |
# noinspection PyBroadException
try:
func(*args, **kwargs)
except: # nopep8
type_, value, tb = sys.exc_info()
traceback.print_exc()
pdb.post_mortem(tb) | def pdb_run(func: Callable, *args: Any, **kwargs: Any) -> None | Calls ``func(*args, **kwargs)``; if it raises an exception, break into
the ``pdb`` debugger. | 2.517004 | 2.362312 | 1.065483 |
# http://stackoverflow.com/questions/2203424/python-how-to-retrieve-class-information-from-a-frame-object # noqa
args, _, _, value_dict = inspect.getargvalues(fr)
# we check the first parameter for the frame function is named 'self'
if len(args) and args[0] == 'self':
# in that case, 'self... | 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 returns ``None`` otherwise. | 3.796288 | 3.915978 | 0.969436 |
# http://stackoverflow.com/questions/5067604/determine-function-name-from-within-that-function-without-using-traceback # noqa
try:
# noinspection PyProtectedMember
frame = sys._getframe(back + 2)
except ValueError:
# Stack isn't deep enough.
return '?'
function_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.)
Example:
.. code-block:: python
from ca... | 3.279133 | 3.478657 | 0.942643 |
r
# "0 back" is debug_callers, so "1 back" its caller
# https://docs.python.org/3/library/inspect.html
callers = [] # type: List[str]
frameinfolist = inspect.stack() # type: List[FrameInfo] # noqa
frameinfolist = frameinfolist[start_back:]
for frameinfo in frameinfolist:
frame = f... | def get_caller_stack_info(start_back: int = 1) -> List[str] | r"""
Retrieves a textual representation of the call stack.
Args:
start_back: number of calls back in the frame stack (starting
from the frame stack as seen by :func:`get_caller_stack_info`)
to begin with
Returns:
list of descriptions
Example:
.. code-block... | 3.325642 | 3.11511 | 1.067584 |
msgs = ["For {o!r}:".format(o=obj)]
for attrname in dir(obj):
attribute = getattr(obj, attrname)
msgs.append("- {an!r}: {at!r}, of type {t!r}".format(
an=attrname, at=attribute, t=type(attribute)))
log.log(log_level, "{}", "\n".join(msgs)) | def debug_object(obj, log_level: int = logging.DEBUG) -> None | Sends details about a Python to the log, specifically its ``repr()``
representation, and all of its attributes with their name, value, and type.
Args:
obj: object to debug
log_level: log level to use; default is ``logging.DEBUG`` | 3.87942 | 3.789128 | 1.023829 |
if value is None:
return value
return json_decode(value) | def from_db_value(self, value, expression, connection, context) | "Called in all circumstances when the data is loaded from the
database, including in aggregates and values() calls." | 6.172216 | 4.586239 | 1.345812 |
if value is None:
return value
if not isinstance(value, str):
return value
try:
return json_decode(value)
except Exception as err:
raise ValidationError(repr(err)) | def to_python(self, value) | "Called during deserialization and during the clean() method used
from forms.... [s]hould deal gracefully with... (*) an instance of
the correct type; (*) a string; (*) None (if the field allows
null=True)."
"For ``to_python()``, if anything goes wrong during value conversion,
y... | 3.153256 | 2.884879 | 1.093029 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.