_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q264700 | BufferWalker._fill | validation | def _fill(self, size):
"""fills the internal buffer from the source iterator"""
try:
for i in range(size):
self.buffer.append(self.source.next())
except StopIteration:
self.buffer.append((EndOfFile, EndOfFile))
self.len = len(self.buffer) | python | {
"resource": ""
} |
q264701 | BufferWalker.next | validation | def next(self):
"""Advances to and returns the next token or returns EndOfFile"""
self.index += 1
t = self.peek()
if not self.depth:
self._cut()
return t | python | {
"resource": ""
} |
q264702 | main | validation | def main(world_cls, referee_cls, gui_cls, gui_actor_cls, ai_actor_cls,
theater_cls=PygletTheater, default_host=DEFAULT_HOST,
default_port=DEFAULT_PORT, argv=None):
"""
Run a game being developed with the kxg game engine.
Usage:
{exe_name} sandbox [<num_ais>] [-v...]
{exe_name} client [--hos... | python | {
"resource": ""
} |
q264703 | ProcessPool._run_supervisor | validation | def _run_supervisor(self):
"""
Poll the queues that the worker can use to communicate with the
supervisor, until all the workers are done and all the queues are
empty. Handle messages as they appear.
"""
import time
still_supervising = lambda: (
... | python | {
"resource": ""
} |
q264704 | JSONField.field_type | validation | def field_type(self):
"""Return database field type."""
if not self.model:
return 'JSON'
database = self.model._meta.database
if isinstance(database, Proxy):
database = database.obj
if Json and isinstance(database, PostgresqlDatabase):
return '... | python | {
"resource": ""
} |
q264705 | JSONField.python_value | validation | def python_value(self, value):
"""Parse value from database."""
if self.field_type == 'TEXT' and isinstance(value, str):
return self.loads(value)
return value | python | {
"resource": ""
} |
q264706 | AFSAPI.get_fsapi_endpoint | validation | def get_fsapi_endpoint(self):
"""Parse the fsapi endpoint from the device url."""
endpoint = yield from self.__session.get(self.fsapi_device_url, timeout = self.timeout)
text = yield from endpoint.text(encoding='utf-8')
doc = objectify.fromstring(text)
return doc.webfsapi.text | python | {
"resource": ""
} |
q264707 | AFSAPI.create_session | validation | def create_session(self):
"""Create a session on the frontier silicon device."""
req_url = '%s/%s' % (self.__webfsapi, 'CREATE_SESSION')
sid = yield from self.__session.get(req_url, params=dict(pin=self.pin),
timeout = self.timeout)
text = yiel... | python | {
"resource": ""
} |
q264708 | AFSAPI.call | validation | def call(self, path, extra=None):
"""Execute a frontier silicon API call."""
try:
if not self.__webfsapi:
self.__webfsapi = yield from self.get_fsapi_endpoint()
if not self.sid:
self.sid = yield from self.create_session()
if not isins... | python | {
"resource": ""
} |
q264709 | AFSAPI.handle_set | validation | def handle_set(self, item, value):
"""Helper method for setting a value by using the fsapi API."""
doc = yield from self.call('SET/{}'.format(item), dict(value=value))
if doc is None:
return None
return doc.status == 'FS_OK' | python | {
"resource": ""
} |
q264710 | AFSAPI.handle_text | validation | def handle_text(self, item):
"""Helper method for fetching a text value."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return doc.value.c8_array.text or None | python | {
"resource": ""
} |
q264711 | AFSAPI.handle_int | validation | def handle_int(self, item):
"""Helper method for fetching a integer value."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return int(doc.value.u8.text) or None | python | {
"resource": ""
} |
q264712 | AFSAPI.handle_long | validation | def handle_long(self, item):
"""Helper method for fetching a long value. Result is integer."""
doc = yield from self.handle_get(item)
if doc is None:
return None
return int(doc.value.u32.text) or None | python | {
"resource": ""
} |
q264713 | AFSAPI.get_power | validation | def get_power(self):
"""Check if the device is on."""
power = (yield from self.handle_int(self.API.get('power')))
return bool(power) | python | {
"resource": ""
} |
q264714 | AFSAPI.set_power | validation | def set_power(self, value=False):
"""Power on or off the device."""
power = (yield from self.handle_set(
self.API.get('power'), int(value)))
return bool(power) | python | {
"resource": ""
} |
q264715 | AFSAPI.get_modes | validation | def get_modes(self):
"""Get the modes supported by this device."""
if not self.__modes:
self.__modes = yield from self.handle_list(
self.API.get('valid_modes'))
return self.__modes | python | {
"resource": ""
} |
q264716 | AFSAPI.get_volume_steps | validation | def get_volume_steps(self):
"""Read the maximum volume level of the device."""
if not self.__volume_steps:
self.__volume_steps = yield from self.handle_int(
self.API.get('volume_steps'))
return self.__volume_steps | python | {
"resource": ""
} |
q264717 | AFSAPI.get_mute | validation | def get_mute(self):
"""Check if the device is muted."""
mute = (yield from self.handle_int(self.API.get('mute')))
return bool(mute) | python | {
"resource": ""
} |
q264718 | AFSAPI.set_mute | validation | def set_mute(self, value=False):
"""Mute or unmute the device."""
mute = (yield from self.handle_set(self.API.get('mute'), int(value)))
return bool(mute) | python | {
"resource": ""
} |
q264719 | AFSAPI.get_play_status | validation | def get_play_status(self):
"""Get the play status of the device."""
status = yield from self.handle_int(self.API.get('status'))
return self.PLAY_STATES.get(status) | python | {
"resource": ""
} |
q264720 | AFSAPI.get_equalisers | validation | def get_equalisers(self):
"""Get the equaliser modes supported by this device."""
if not self.__equalisers:
self.__equalisers = yield from self.handle_list(
self.API.get('equalisers'))
return self.__equalisers | python | {
"resource": ""
} |
q264721 | AFSAPI.set_sleep | validation | def set_sleep(self, value=False):
"""Set device sleep timer."""
return (yield from self.handle_set(self.API.get('sleep'), int(value))) | python | {
"resource": ""
} |
q264722 | BitAwareByteArray._set_range | validation | def _set_range(self, start, stop, value, value_len):
"""
Assumes that start and stop are already in 'buffer' coordinates. value is a byte iterable.
value_len is fractional.
"""
assert stop >= start and value_len >= 0
range_len = stop - start
if range_len < value_l... | python | {
"resource": ""
} |
q264723 | GenomeVCFLine._parse_genotype | validation | def _parse_genotype(self, vcf_fields):
"""Parse genotype from VCF line data"""
format_col = vcf_fields[8].split(':')
genome_data = vcf_fields[9].split(':')
try:
gt_idx = format_col.index('GT')
except ValueError:
return []
return [int(x) for x in re... | python | {
"resource": ""
} |
q264724 | IRField.toIndex | validation | def toIndex(self, value):
'''
toIndex - An optional method which will return the value prepped for index.
By default, "toStorage" will be called. If you provide "hashIndex=True" on the constructor,
the field will be md5summed for indexing purposes. This is useful for large strings, etc.
'''
if self._isI... | python | {
"resource": ""
} |
q264725 | IRField.copy | validation | def copy(self):
'''
copy - Create a copy of this IRField.
Each subclass should implement this, as you'll need to pass in the args to constructor.
@return <IRField (or subclass)> - Another IRField that has all the same values as this one.
'''
return self.__class__(name=self.name, valueType=self.valueT... | python | {
"resource": ""
} |
q264726 | ForeignLinkData.objHasUnsavedChanges | validation | def objHasUnsavedChanges(self):
'''
objHasUnsavedChanges - Check if any object has unsaved changes, cascading.
'''
if not self.obj:
return False
return self.obj.hasUnsavedChanges(cascadeObjects=True) | python | {
"resource": ""
} |
q264727 | assert_json_type | validation | def assert_json_type(value: JsonValue, expected_type: JsonCheckType) -> None:
"""Check that a value has a certain JSON type.
Raise TypeError if the type does not match.
Supported types: str, int, float, bool, list, dict, and None.
float will match any number, int will only match numbers without
fr... | python | {
"resource": ""
} |
q264728 | composite.load | validation | def load(cls, fh):
"""
Load json or yaml data from file handle.
Args:
fh (file): File handle to load from.
Examlple:
>>> with open('data.json', 'r') as json:
>>> jsdata = composite.load(json)
>>>
>>> with open('data.yml', '... | python | {
"resource": ""
} |
q264729 | composite.from_json | validation | def from_json(cls, fh):
"""
Load json from file handle.
Args:
fh (file): File handle to load from.
Examlple:
>>> with open('data.json', 'r') as json:
>>> data = composite.load(json)
"""
if isinstance(fh, str):
return cl... | python | {
"resource": ""
} |
q264730 | composite.intersection | validation | def intersection(self, other, recursive=True):
"""
Recursively compute intersection of data. For dictionaries, items
for specific keys will be reduced to unique items. For lists, items
will be reduced to unique items. This method is meant to be analogous
to set.intersection for c... | python | {
"resource": ""
} |
q264731 | composite.union | validation | def union(self, other, recursive=True, overwrite=False):
"""
Recursively compute union of data. For dictionaries, items
for specific keys will be combined into a list, depending on the
status of the overwrite= parameter. For lists, items will be appended
and reduced to unique ite... | python | {
"resource": ""
} |
q264732 | composite.append | validation | def append(self, item):
"""
Append to object, if object is list.
"""
if self.meta_type == 'dict':
raise AssertionError('Cannot append to object of `dict` base type!')
if self.meta_type == 'list':
self._list.append(item)
return | python | {
"resource": ""
} |
q264733 | composite.extend | validation | def extend(self, item):
"""
Extend list from object, if object is list.
"""
if self.meta_type == 'dict':
raise AssertionError('Cannot extend to object of `dict` base type!')
if self.meta_type == 'list':
self._list.extend(item)
return | python | {
"resource": ""
} |
q264734 | composite.write_json | validation | def write_json(self, fh, pretty=True):
"""
Write composite object to file handle in JSON format.
Args:
fh (file): File handle to write to.
pretty (bool): Sort keys and indent in output.
"""
sjson = json.JSONEncoder().encode(self.json())
if pretty:... | python | {
"resource": ""
} |
q264735 | filetree.filelist | validation | def filelist(self):
"""
Return list of files in filetree.
"""
if len(self._filelist) == 0:
for item in self._data:
if isinstance(self._data[item], filetree):
self._filelist.extend(self._data[item].filelist())
else:
... | python | {
"resource": ""
} |
q264736 | filetree.prune | validation | def prune(self, regex=r".*"):
"""
Prune leaves of filetree according to specified
regular expression.
Args:
regex (str): Regular expression to use in pruning tree.
"""
return filetree(self.root, ignore=self.ignore, regex=regex) | python | {
"resource": ""
} |
q264737 | Reference.deref | validation | def deref(self, ctx):
"""
Returns the value this reference is pointing to. This method uses 'ctx' to resolve the reference and return
the value this reference references.
If the call was already made, it returns a cached result.
It also makes sure there's no cyclic reference, and... | python | {
"resource": ""
} |
q264738 | IRQueryableList.delete | validation | def delete(self):
'''
delete - Delete all objects in this list.
@return <int> - Number of objects deleted
'''
if len(self) == 0:
return 0
mdl = self.getModel()
return mdl.deleter.deleteMultiple(self) | python | {
"resource": ""
} |
q264739 | IRQueryableList.save | validation | def save(self):
'''
save - Save all objects in this list
'''
if len(self) == 0:
return []
mdl = self.getModel()
return mdl.saver.save(self) | python | {
"resource": ""
} |
q264740 | IRQueryableList.reload | validation | def reload(self):
'''
reload - Reload all objects in this list.
Updates in-place. To just fetch all these objects again, use "refetch"
@return - List (same order as current objects) of either exception (KeyError) if operation failed,
or a dict of fields changed -> (old, new)
'''
if len(self) == 0... | python | {
"resource": ""
} |
q264741 | IRQueryableList.refetch | validation | def refetch(self):
'''
refetch - Fetch a fresh copy of all items in this list.
Returns a new list. To update in-place, use "reload".
@return IRQueryableList<IndexedRedisModel> - List of fetched items
'''
if len(self) == 0:
return IRQueryableList()
mdl = self.getModel()
pks = [item._id for item... | python | {
"resource": ""
} |
q264742 | Blox.render | validation | def render(self, *args, **kwargs):
'''Renders as a str'''
render_to = StringIO()
self.output(render_to, *args, **kwargs)
return render_to.getvalue() | python | {
"resource": ""
} |
q264743 | AbstractTag.start_tag | validation | def start_tag(self):
'''Returns the elements HTML start tag'''
direct_attributes = (attribute.render(self) for attribute in self.render_attributes)
attributes = ()
if hasattr(self, '_attributes'):
attributes = ('{0}="{1}"'.format(key, value)
... | python | {
"resource": ""
} |
q264744 | safe_repr | validation | def safe_repr(obj):
"""Returns a repr of an object and falls back to a minimal representation of type and ID if the call to repr raised
an error.
:param obj: object to safe repr
:returns: repr string or '(type<id> repr error)' string
:rtype: str
"""
try:
obj_repr = repr(obj)
exc... | python | {
"resource": ""
} |
q264745 | match_to_clinvar | validation | def match_to_clinvar(genome_file, clin_file):
"""
Match a genome VCF to variants in the ClinVar VCF file
Acts as a generator, yielding tuples of:
(ClinVarVCFLine, ClinVarAllele, zygosity)
'zygosity' is a string and corresponds to the genome's zygosity for that
ClinVarAllele. It can be either: ... | python | {
"resource": ""
} |
q264746 | Allele.as_dict | validation | def as_dict(self):
"""Return Allele data as dict object."""
self_as_dict = dict()
self_as_dict['sequence'] = self.sequence
if hasattr(self, 'frequency'):
self_as_dict['frequency'] = self.frequency
return self_as_dict | python | {
"resource": ""
} |
q264747 | VCFLine._parse_allele_data | validation | def _parse_allele_data(self):
"""Create list of Alleles from VCF line data"""
return [Allele(sequence=x) for x in
[self.ref_allele] + self.alt_alleles] | python | {
"resource": ""
} |
q264748 | VCFLine._parse_info | validation | def _parse_info(self, info_field):
"""Parse the VCF info field"""
info = dict()
for item in info_field.split(';'):
# Info fields may be "foo=bar" or just "foo".
# For the first case, store key "foo" with value "bar"
# For the second case, store key "foo" with ... | python | {
"resource": ""
} |
q264749 | VCFLine.as_dict | validation | def as_dict(self):
"""Dict representation of parsed VCF data"""
self_as_dict = {'chrom': self.chrom,
'start': self.start,
'ref_allele': self.ref_allele,
'alt_alleles': self.alt_alleles,
'alleles': [x.as_dict(... | python | {
"resource": ""
} |
q264750 | VCFLine.get_pos | validation | def get_pos(vcf_line):
"""
Very lightweight parsing of a vcf line to get position.
Returns a dict containing:
'chrom': index of chromosome (int), indicates sort order
'pos': position on chromosome (int)
"""
if not vcf_line:
return None
vcf_dat... | python | {
"resource": ""
} |
q264751 | IRFieldChain._toStorage | validation | def _toStorage(self, value):
'''
_toStorage - Convert the value to a string representation for storage.
@param value - The value of the item to convert
@return A string value suitable for storing.
'''
for chainedField in self.chainedFields:
value = chainedField.toStorage(value)
return value | python | {
"resource": ""
} |
q264752 | nav_to_vcf_dir | validation | def nav_to_vcf_dir(ftp, build):
"""
Navigate an open ftplib.FTP to appropriate directory for ClinVar VCF files.
Args:
ftp: (type: ftplib.FTP) an open connection to ftp.ncbi.nlm.nih.gov
build: (type: string) genome build, either 'b37' or 'b38'
"""
if build == 'b37':
ftp.cwd... | python | {
"resource": ""
} |
q264753 | ClinVarAllele.as_dict | validation | def as_dict(self, *args, **kwargs):
"""Return ClinVarAllele data as dict object."""
self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)
self_as_dict['hgvs'] = self.hgvs
self_as_dict['clnalleleid'] = self.clnalleleid
self_as_dict['clnsig'] = self.clnsig
self... | python | {
"resource": ""
} |
q264754 | ClinVarVCFLine._parse_frequencies | validation | def _parse_frequencies(self):
"""Parse frequency data in ClinVar VCF"""
frequencies = OrderedDict([
('EXAC', 'Unknown'),
('ESP', 'Unknown'),
('TGP', 'Unknown')])
pref_freq = 'Unknown'
for source in frequencies.keys():
freq_key = 'AF_' + sou... | python | {
"resource": ""
} |
q264755 | ClinVarVCFLine._parse_allele_data | validation | def _parse_allele_data(self):
"""Parse alleles for ClinVar VCF, overrides parent method."""
# Get allele frequencies if they exist.
pref_freq, frequencies = self._parse_frequencies()
info_clnvar_single_tags = ['ALLELEID', 'CLNSIG', 'CLNHGVS']
cln_data = {x.lower(): self.info[x]... | python | {
"resource": ""
} |
q264756 | Factory.add | validation | def add(self, *names):
'''Returns back a class decorator that enables registering Blox to this factory'''
def decorator(blok):
for name in names or (blok.__name__, ):
self[name] = blok
return blok
return decorator | python | {
"resource": ""
} |
q264757 | depricated_name | validation | def depricated_name(newmethod):
"""
Decorator for warning user of depricated functions before use.
Args:
newmethod (str): Name of method to use instead.
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
warnings.simplefilter('always', Deprecatio... | python | {
"resource": ""
} |
q264758 | setDefaultRedisConnectionParams | validation | def setDefaultRedisConnectionParams( connectionParams ):
'''
setDefaultRedisConnectionParams - Sets the default parameters used when connecting to Redis.
This should be the args to redis.Redis in dict (kwargs) form.
@param connectionParams <dict> - A dict of connection parameters.
Common keys are:
... | python | {
"resource": ""
} |
q264759 | clearRedisPools | validation | def clearRedisPools():
'''
clearRedisPools - Disconnect all managed connection pools,
and clear the connectiobn_pool attribute on all stored managed connection pools.
A "managed" connection pool is one where REDIS_CONNECTION_PARAMS does not define the "connection_pool" attribute.
If you define your ... | python | {
"resource": ""
} |
q264760 | getRedisPool | validation | def getRedisPool(params):
'''
getRedisPool - Returns and possibly also creates a Redis connection pool
based on the REDIS_CONNECTION_PARAMS passed in.
The goal of this method is to keep a small connection pool rolling
to each unique Redis instance, otherwise during network issues etc
python-redis will l... | python | {
"resource": ""
} |
q264761 | IndexedRedisModel.pprint | validation | def pprint(self, stream=None):
'''
pprint - Pretty-print a dict representation of this object.
@param stream <file/None> - Either a stream to output, or None to default to sys.stdout
'''
pprint.pprint(self.asDict(includeMeta=True, forStorage=False, strKeys=True), stream=stream) | python | {
"resource": ""
} |
q264762 | IndexedRedisModel.hasUnsavedChanges | validation | def hasUnsavedChanges(self, cascadeObjects=False):
'''
hasUnsavedChanges - Check if any unsaved changes are present in this model, or if it has never been saved.
@param cascadeObjects <bool> default False, if True will check if any foreign linked objects themselves have unsaved changes (recursively).
Other... | python | {
"resource": ""
} |
q264763 | IndexedRedisModel.diff | validation | def diff(firstObj, otherObj, includeMeta=False):
'''
diff - Compare the field values on two IndexedRedisModels.
@param firstObj <IndexedRedisModel instance> - First object (or self)
@param otherObj <IndexedRedisModel instance> - Second object
@param includeMeta <bool> - If meta information (like pk) sh... | python | {
"resource": ""
} |
q264764 | IndexedRedisModel.save | validation | def save(self, cascadeSave=True):
'''
save - Save this object.
Will perform an "insert" if this object had not been saved before,
otherwise will update JUST the fields changed on THIS INSTANCE of the model.
i.e. If you have two processes fetch the same object and change different fields, they wil... | python | {
"resource": ""
} |
q264765 | IndexedRedisModel.hasSameValues | validation | def hasSameValues(self, other, cascadeObject=True):
'''
hasSameValues - Check if this and another model have the same fields and values.
This does NOT include id, so the models can have the same values but be different objects in the database.
@param other <IndexedRedisModel> - Another model
@param cas... | python | {
"resource": ""
} |
q264766 | IndexedRedisModel.copy | validation | def copy(self, copyPrimaryKey=False, copyValues=False):
'''
copy - Copies this object.
@param copyPrimaryKey <bool> default False - If True, any changes to the copy will save over-top the existing entry in Redis.
If False, only the data is copied, and n... | python | {
"resource": ""
} |
q264767 | IndexedRedisModel.saveToExternal | validation | def saveToExternal(self, redisCon):
'''
saveToExternal - Saves this object to a different Redis than that specified by REDIS_CONNECTION_PARAMS on this model.
@param redisCon <dict/redis.Redis> - Either a dict of connection params, a la REDIS_CONNECTION_PARAMS, or an existing Redis connection.
If you are do... | python | {
"resource": ""
} |
q264768 | IndexedRedisModel.reload | validation | def reload(self, cascadeObjects=True):
'''
reload - Reload this object from the database, overriding any local changes and merging in any updates.
@param cascadeObjects <bool> Default True. If True, foreign-linked objects will be reloaded if their values have changed
since last save/fe... | python | {
"resource": ""
} |
q264769 | IndexedRedisModel.copyModel | validation | def copyModel(mdl):
'''
copyModel - Copy this model, and return that copy.
The copied model will have all the same data, but will have a fresh instance of the FIELDS array and all members,
and the INDEXED_FIELDS array.
This is useful for converting, like changing field types or whatever, wh... | python | {
"resource": ""
} |
q264770 | IndexedRedisModel.connectAlt | validation | def connectAlt(cls, redisConnectionParams):
'''
connectAlt - Create a class of this model which will use an alternate connection than the one specified by REDIS_CONNECTION_PARAMS on this model.
@param redisConnectionParams <dict> - Dictionary of arguments to redis.Redis, same as REDIS_CONNECTION_PARAMS.
@r... | python | {
"resource": ""
} |
q264771 | IndexedRedisHelper._get_new_connection | validation | def _get_new_connection(self):
'''
_get_new_connection - Get a new connection
internal
'''
pool = getRedisPool(self.mdl.REDIS_CONNECTION_PARAMS)
return redis.Redis(connection_pool=pool) | python | {
"resource": ""
} |
q264772 | IndexedRedisHelper._get_connection | validation | def _get_connection(self):
'''
_get_connection - Maybe get a new connection, or reuse if passed in.
Will share a connection with a model
internal
'''
if self._connection is None:
self._connection = self._get_new_connection()
return self._connection | python | {
"resource": ""
} |
q264773 | IndexedRedisHelper._add_id_to_keys | validation | def _add_id_to_keys(self, pk, conn=None):
'''
_add_id_to_keys - Adds primary key to table
internal
'''
if conn is None:
conn = self._get_connection()
conn.sadd(self._get_ids_key(), pk) | python | {
"resource": ""
} |
q264774 | IndexedRedisHelper._rem_id_from_keys | validation | def _rem_id_from_keys(self, pk, conn=None):
'''
_rem_id_from_keys - Remove primary key from table
internal
'''
if conn is None:
conn = self._get_connection()
conn.srem(self._get_ids_key(), pk) | python | {
"resource": ""
} |
q264775 | IndexedRedisHelper._add_id_to_index | validation | def _add_id_to_index(self, indexedField, pk, val, conn=None):
'''
_add_id_to_index - Adds an id to an index
internal
'''
if conn is None:
conn = self._get_connection()
conn.sadd(self._get_key_for_index(indexedField, val), pk) | python | {
"resource": ""
} |
q264776 | IndexedRedisHelper._rem_id_from_index | validation | def _rem_id_from_index(self, indexedField, pk, val, conn=None):
'''
_rem_id_from_index - Removes an id from an index
internal
'''
if conn is None:
conn = self._get_connection()
conn.srem(self._get_key_for_index(indexedField, val), pk) | python | {
"resource": ""
} |
q264777 | IndexedRedisHelper._get_key_for_index | validation | def _get_key_for_index(self, indexedField, val):
'''
_get_key_for_index - Returns the key name that would hold the indexes on a value
Internal - does not validate that indexedFields is actually indexed. Trusts you. Don't let it down.
@param indexedField - string of field name
@param val - Value of field
... | python | {
"resource": ""
} |
q264778 | IndexedRedisHelper._compat_rem_str_id_from_index | validation | def _compat_rem_str_id_from_index(self, indexedField, pk, val, conn=None):
'''
_compat_rem_str_id_from_index - Used in compat_convertHashedIndexes to remove the old string repr of a field,
in order to later add the hashed value,
'''
if conn is None:
conn = self._get_connection()
conn.srem(self._compat... | python | {
"resource": ""
} |
q264779 | IndexedRedisHelper._peekNextID | validation | def _peekNextID(self, conn=None):
'''
_peekNextID - Look at, but don't increment the primary key for this model.
Internal.
@return int - next pk
'''
if conn is None:
conn = self._get_connection()
return to_unicode(conn.get(self._get_next_id_key()) or 0) | python | {
"resource": ""
} |
q264780 | IndexedRedisQuery._filter | validation | def _filter(filterObj, **kwargs):
'''
Internal for handling filters; the guts of .filter and .filterInline
'''
for key, value in kwargs.items():
if key.endswith('__ne'):
notFilter = True
key = key[:-4]
else:
notFilter = False
if key not in filterObj.indexedFields:
raise ValueError('Fie... | python | {
"resource": ""
} |
q264781 | IndexedRedisQuery.count | validation | def count(self):
'''
count - gets the number of records matching the filter criteria
Example:
theCount = Model.objects.filter(field1='value').count()
'''
conn = self._get_connection()
numFilters = len(self.filters)
numNotFilters = len(self.notFilters)
if numFilters + numNotFilters == 0:
ret... | python | {
"resource": ""
} |
q264782 | IndexedRedisQuery.exists | validation | def exists(self, pk):
'''
exists - Tests whether a record holding the given primary key exists.
@param pk - Primary key (see getPk method)
Example usage: Waiting for an object to be deleted without fetching the object or running a filter.
This is a very cheap operation.
@return <bool> - True if ob... | python | {
"resource": ""
} |
q264783 | IndexedRedisQuery.getPrimaryKeys | validation | def getPrimaryKeys(self, sortByAge=False):
'''
getPrimaryKeys - Returns all primary keys matching current filterset.
@param sortByAge <bool> - If False, return will be a set and may not be ordered.
If True, return will be a list and is guarenteed to represent objects oldest->newest
@return <set> - A se... | python | {
"resource": ""
} |
q264784 | IndexedRedisQuery.all | validation | def all(self, cascadeFetch=False):
'''
all - Get the underlying objects which match the filter criteria.
Example: objs = Model.objects.filter(field1='value', field2='value2').all()
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched imme... | python | {
"resource": ""
} |
q264785 | IndexedRedisQuery.allOnlyFields | validation | def allOnlyFields(self, fields, cascadeFetch=False):
'''
allOnlyFields - Get the objects which match the filter criteria, only fetching given fields.
@param fields - List of fields to fetch
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetch... | python | {
"resource": ""
} |
q264786 | IndexedRedisQuery.allOnlyIndexedFields | validation | def allOnlyIndexedFields(self):
'''
allOnlyIndexedFields - Get the objects which match the filter criteria, only fetching indexed fields.
@return - Partial objects with only the indexed fields fetched
'''
matchedKeys = self.getPrimaryKeys()
if matchedKeys:
return self.getMultipleOnlyIndexedFields(matc... | python | {
"resource": ""
} |
q264787 | IndexedRedisQuery.random | validation | def random(self, cascadeFetch=False):
'''
Random - Returns a random record in current filterset.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@return - Instance of M... | python | {
"resource": ""
} |
q264788 | IndexedRedisQuery.delete | validation | def delete(self):
'''
delete - Deletes all entries matching the filter criteria
'''
if self.filters or self.notFilters:
return self.mdl.deleter.deleteMultiple(self.allOnlyIndexedFields())
return self.mdl.deleter.destroyModel() | python | {
"resource": ""
} |
q264789 | IndexedRedisQuery.get | validation | def get(self, pk, cascadeFetch=False):
'''
get - Get a single value with the internal primary key.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@param pk - internal ... | python | {
"resource": ""
} |
q264790 | IndexedRedisQuery._doCascadeFetch | validation | def _doCascadeFetch(obj):
'''
_doCascadeFetch - Takes an object and performs a cascading fetch on all foreign links, and all theirs, and so on.
@param obj <IndexedRedisModel> - A fetched model
'''
obj.validateModel()
if not obj.foreignFields:
return
# NOTE: Currently this fetches using one trans... | python | {
"resource": ""
} |
q264791 | IndexedRedisQuery.getMultiple | validation | def getMultiple(self, pks, cascadeFetch=False):
'''
getMultiple - Gets multiple objects with a single atomic operation
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@... | python | {
"resource": ""
} |
q264792 | IndexedRedisQuery.getOnlyFields | validation | def getOnlyFields(self, pk, fields, cascadeFetch=False):
'''
getOnlyFields - Gets only certain fields from a paticular primary key. For working on entire filter set, see allOnlyFields
@param pk <int> - Primary Key
@param fields list<str> - List of fields
@param cascadeFetch <bool> Default False, If Tru... | python | {
"resource": ""
} |
q264793 | IndexedRedisQuery.getMultipleOnlyFields | validation | def getMultipleOnlyFields(self, pks, fields, cascadeFetch=False):
'''
getMultipleOnlyFields - Gets only certain fields from a list of primary keys. For working on entire filter set, see allOnlyFields
@param pks list<str> - Primary Keys
@param fields list<str> - List of fields
@param cascadeFetch <boo... | python | {
"resource": ""
} |
q264794 | IndexedRedisQuery.compat_convertHashedIndexes | validation | def compat_convertHashedIndexes(self, fetchAll=True):
'''
compat_convertHashedIndexes - Reindex fields, used for when you change the propery "hashIndex" on one or more fields.
For each field, this will delete both the hash and unhashed keys to an object,
and then save a hashed or unhashed value, dependin... | python | {
"resource": ""
} |
q264795 | IndexedRedisSave._doSave | validation | def _doSave(self, obj, isInsert, conn, pipeline=None):
'''
_doSave - Internal function to save a single object. Don't call this directly.
Use "save" instead.
If a pipeline is provided, the operations (setting values, updating indexes, etc)
will be queued into that pipeline.
Otherw... | python | {
"resource": ""
} |
q264796 | IndexedRedisSave.compat_convertHashedIndexes | validation | def compat_convertHashedIndexes(self, objs, conn=None):
'''
compat_convertHashedIndexes - Reindex all fields for the provided objects, where the field value is hashed or not.
If the field is unhashable, do not allow.
NOTE: This works one object at a time. It is intended to be used while your application is ... | python | {
"resource": ""
} |
q264797 | IndexedRedisDelete.deleteOne | validation | def deleteOne(self, obj, conn=None):
'''
deleteOne - Delete one object
@param obj - object to delete
@param conn - Connection to reuse, or None
@return - number of items deleted (0 or 1)
'''
if not getattr(obj, '_id', None):
return 0
if conn is None:
conn = self._get_connection()
pipelin... | python | {
"resource": ""
} |
q264798 | IndexedRedisDelete.deleteByPk | validation | def deleteByPk(self, pk):
'''
deleteByPk - Delete object associated with given primary key
'''
obj = self.mdl.objects.getOnlyIndexedFields(pk)
if not obj:
return 0
return self.deleteOne(obj) | python | {
"resource": ""
} |
q264799 | IndexedRedisDelete.deleteMultiple | validation | def deleteMultiple(self, objs):
'''
deleteMultiple - Delete multiple objects
@param objs - List of objects
@return - Number of objects deleted
'''
conn = self._get_connection()
pipeline = conn.pipeline()
numDeleted = 0
for obj in objs:
numDeleted += self.deleteOne(obj, pipeline)
pipeline.... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.