INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Register a model in self. | def register(self, model):
"""Register a model in self."""
self.models[model._meta.table_name] = model
model._meta.database = self.database
return model |
Manage a database connection. | async def manage(self):
"""Manage a database connection."""
cm = _ContextManager(self.database)
if isinstance(self.database.obj, AIODatabase):
cm.connection = await self.database.async_connect()
else:
cm.connection = self.database.connect()
return cm |
Write your migrations here. | def migrate(migrator, database, **kwargs):
""" Write your migrations here.
> Model = migrator.orm['name']
> migrator.sql(sql)
> migrator.create_table(Model)
> migrator.drop_table(Model, cascade=True)
> migrator.add_columns(Model, **fields)
> migrator.change_columns(Model, **fields)
> m... |
Runs a series of parsers in sequence passing the result of each parser to the next. The result of the last parser is returned. | def chain(*args):
"""Runs a series of parsers in sequence passing the result of each parser to the next.
The result of the last parser is returned.
"""
def chain_block(*args, **kwargs):
v = args[0](*args, **kwargs)
for p in args[1:]:
v = p(v)
return v
return chain... |
Returns the current token if is found in the collection provided. Fails otherwise. | def one_of(these):
"""Returns the current token if is found in the collection provided.
Fails otherwise.
"""
ch = peek()
try:
if (ch is EndOfFile) or (ch not in these):
fail(list(these))
except TypeError:
if ch != these:
fail([these])
next()
r... |
Returns the current token if it is not found in the collection provided. The negative of one_of. | def not_one_of(these):
"""Returns the current token if it is not found in the collection provided.
The negative of one_of.
"""
ch = peek()
desc = "not_one_of" + repr(these)
try:
if (ch is EndOfFile) or (ch in these):
fail([desc])
except TypeError:
if ch != t... |
Returns the current token if it satisfies the guard function provided. Fails otherwise. This is the a generalisation of one_of. | def satisfies(guard):
"""Returns the current token if it satisfies the guard function provided.
Fails otherwise.
This is the a generalisation of one_of.
"""
i = peek()
if (i is EndOfFile) or (not guard(i)):
fail(["<satisfies predicate " + _fun_to_str(guard) + ">"])
next()
re... |
Succeeds if the given parser cannot consume input | def not_followed_by(parser):
"""Succeeds if the given parser cannot consume input"""
@tri
def not_followed_by_block():
failed = object()
result = optional(tri(parser), failed)
if result != failed:
fail(["not " + _fun_to_str(parser)])
choice(not_followed_by_block) |
Applies the parser to input zero or more times. Returns a list of parser results. | def many(parser):
"""Applies the parser to input zero or more times.
Returns a list of parser results.
"""
results = []
terminate = object()
while local_ps.value:
result = optional(parser, terminate)
if result == terminate:
break
results.append(result)
... |
Consumes as many of these as it can until it term is encountered. Returns a tuple of the list of these results and the term result | def many_until(these, term):
"""Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result
"""
results = []
while True:
stop, result = choice(_tag(True, term),
_tag(False, these))
... |
Like many_until but must consume at least one of these. | def many_until1(these, term):
"""Like many_until but must consume at least one of these.
"""
first = [these()]
these_results, term_result = many_until(these, term)
return (first + these_results, term_result) |
Like sep but must consume at least one of parser. | def sep1(parser, separator):
"""Like sep but must consume at least one of parser.
"""
first = [parser()]
def inner():
separator()
return parser()
return first + many(tri(inner)) |
Iterates over string matching input to the items provided. The most obvious usage of this is to accept an entire string of characters However this is function is more general than that. It takes an iterable and for each item it tries one_of for that set. For example string ( [ aA bB cC ] ) will accept abc in either cas... | def string(string):
"""Iterates over string, matching input to the items provided.
The most obvious usage of this is to accept an entire string of characters,
However this is function is more general than that. It takes an iterable
and for each item, it tries one_of for that set. For example,
... |
Runs a series of parsers in sequence optionally storing results in a returned dictionary. For example: seq ( whitespace ( phone digits ) whitespace ( name remaining )) | def seq(*sequence):
"""Runs a series of parsers in sequence optionally storing results in a returned dictionary.
For example:
seq(whitespace, ('phone', digits), whitespace, ('name', remaining))
"""
results = {}
for p in sequence:
if callable(p):
p()
continue... |
fills the internal buffer from the source iterator | 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) |
Advances to and returns the next token or returns EndOfFile | 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 |
Returns the current ( token position ) or ( EndOfFile EndOfFile ) | def current(self):
"""Returns the current (token, position) or (EndOfFile, EndOfFile)"""
if self.index >= self.len:
self._fill((self.index - self.len) + 1)
return self.index < self.len and self.buffer[self.index] or (EndOfFile, EndOfFile) |
Run a game being developed with the kxg game engine. | 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... |
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. | 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: (
... |
Return database field type. | 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 '... |
Parse value from database. | def python_value(self, value):
"""Parse value from database."""
if self.field_type == 'TEXT' and isinstance(value, str):
return self.loads(value)
return value |
Parse the fsapi endpoint from the device url. | 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 |
Create a session on the frontier silicon device. | 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... |
Execute a frontier silicon API call. | 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... |
Helper method for setting a value by using the fsapi API. | 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' |
Helper method for fetching a text value. | 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 |
Helper method for fetching a integer value. | 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 |
Helper method for fetching a long value. Result is integer. | 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 |
Helper method for fetching a list ( map ) value. | def handle_list(self, item):
"""Helper method for fetching a list(map) value."""
doc = yield from self.call('LIST_GET_NEXT/'+item+'/-1', dict(
maxItems=100,
))
if doc is None:
return []
if not doc.status == 'FS_OK':
return []
ret = l... |
Check if the device is on. | def get_power(self):
"""Check if the device is on."""
power = (yield from self.handle_int(self.API.get('power')))
return bool(power) |
Power on or off the device. | 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) |
Get the modes supported by this device. | 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 |
Get the label list of the supported modes. | def get_mode_list(self):
"""Get the label list of the supported modes."""
self.__modes = yield from self.get_modes()
return (yield from self.collect_labels(self.__modes)) |
Get the currently active mode on the device ( DAB FM Spotify ). | def get_mode(self):
"""Get the currently active mode on the device (DAB, FM, Spotify)."""
mode = None
int_mode = (yield from self.handle_long(self.API.get('mode')))
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['band'] == int_mode:
... |
Set the currently active mode on the device ( DAB FM Spotify ). | def set_mode(self, value):
"""Set the currently active mode on the device (DAB, FM, Spotify)."""
mode = -1
modes = yield from self.get_modes()
for temp_mode in modes:
if temp_mode['label'] == value:
mode = temp_mode['band']
return (yield from self.han... |
Read the maximum volume level of the device. | 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 |
Check if the device is muted. | def get_mute(self):
"""Check if the device is muted."""
mute = (yield from self.handle_int(self.API.get('mute')))
return bool(mute) |
Mute or unmute the device. | 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) |
Get the play status of the device. | 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) |
Get the equaliser modes supported by this device. | 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 |
Get the label list of the supported modes. | def get_equaliser_list(self):
"""Get the label list of the supported modes."""
self.__equalisers = yield from self.get_equalisers()
return (yield from self.collect_labels(self.__equalisers)) |
Set device sleep timer. | def set_sleep(self, value=False):
"""Set device sleep timer."""
return (yield from self.handle_set(self.API.get('sleep'), int(value))) |
Assumes that start and stop are already in buffer coordinates. value is a byte iterable. value_len is fractional. | 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... |
Parse genotype from VCF line data | 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... |
setDefaultIREncoding - Sets the default encoding used by IndexedRedis. This will be the default encoding used for field data. You can override this on a per - field basis by using an IRField ( such as IRUnicodeField or IRRawField ) | def setDefaultIREncoding(encoding):
'''
setDefaultIREncoding - Sets the default encoding used by IndexedRedis.
This will be the default encoding used for field data. You can override this on a
per-field basis by using an IRField (such as IRUnicodeField or IRRawField)
@param encoding - An encoding (like ut... |
toIndex - An optional method which will return the value prepped for index. | 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... |
_getReprProperties - Get the properties of this field to display in repr (). | def _getReprProperties(self):
'''
_getReprProperties - Get the properties of this field to display in repr().
These should be in the form of $propertyName=$propertyRepr
The default IRField implementation handles just the "hashIndex" property.
defaultValue is part of "__repr__" impl. You should just ... |
copy - Create a copy of this IRField. | 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... |
getObj - Fetch ( if not fetched ) and return the obj associated with this data. | def getObj(self):
'''
getObj - Fetch (if not fetched) and return the obj associated with this data.
'''
if self.obj is None:
if not self.pk:
return None
self.obj = self.foreignModel.objects.get(self.pk)
return self.obj |
getPk - Resolve any absent pk s off the obj s ( like if an obj has been saved ) and return the pk. | def getPk(self):
'''
getPk - Resolve any absent pk's off the obj's (like if an obj has been saved), and return the pk.
'''
if not self.pk and self.obj:
if self.obj._id:
self.pk = self.obj._id
return self.pk |
objHasUnsavedChanges - Check if any object has unsaved changes cascading. | def objHasUnsavedChanges(self):
'''
objHasUnsavedChanges - Check if any object has unsaved changes, cascading.
'''
if not self.obj:
return False
return self.obj.hasUnsavedChanges(cascadeObjects=True) |
getPk - | def getPk(self):
'''
getPk - @see ForeignLinkData.getPk
'''
if not self.pk or None in self.pk:
for i in range( len(self.pk) ):
if self.pk[i]:
continue
if self.obj[i] and self.obj[i]._id:
self.pk[i] = self.obj[i]._id
return self.pk |
getObj - @see ForeignLinkData. getObj | def getObj(self):
'''
getObj - @see ForeignLinkData.getObj
Except this always returns a list
'''
if self.obj:
needPks = [ (i, self.pk[i]) for i in range(len(self.obj)) if self.obj[i] is None]
if not needPks:
return self.obj
fetched = list(self.foreignModel.objects.getMultiple([needPk[1] for... |
isFetched - | def isFetched(self):
'''
isFetched - @see ForeignLinkData.isFetched
'''
if not self.obj:
return False
if not self.pk or None in self.obj:
return False
return not bool(self.obj is None) |
objHasUnsavedChanges - @see ForeignLinkData. objHasUnsavedChanges | def objHasUnsavedChanges(self):
'''
objHasUnsavedChanges - @see ForeignLinkData.objHasUnsavedChanges
True if ANY object has unsaved changes.
'''
if not self.obj:
return False
for thisObj in self.obj:
if not thisObj:
continue
if thisObj.hasUnsavedChanges(cascadeObjects=True):
return True... |
Check that a value has a certain JSON type. | 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... |
Get a JSON value by path optionally checking its type. | def json_get(json: JsonValue, path: str, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
>>> j = {"foo": {"num": 3.4, "s": "Text"}, "arr": [10, 20, 30]}
>>> json_get(j, "/foo/num")
3.4
>>> json_get(j, "/arr[1]")
20
Raise ValueError if the path i... |
Get a JSON value by path optionally checking its type. | def json_get_default(json: JsonValue, path: str,
default: Any, expected_type: Any = ANY) -> Any:
"""Get a JSON value by path, optionally checking its type.
This works exactly like json_get(), but instead of raising
ValueError or IndexError when a path part is not found, return
the ... |
Load json or yaml data from file handle. | 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', '... |
Load json from file handle. | 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... |
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 composite objects. | 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... |
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 items. This method is meant to be analogous to set. union for composite objects. | 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... |
Update internal dictionary object. This is meant to be an analog for dict. update (). | def update(self, other):
"""
Update internal dictionary object. This is meant to be an
analog for dict.update().
"""
if self.meta_type == 'list':
raise AssertionError('Cannot update object of `list` base type!')
elif self.meta_type == 'dict':
self.... |
Return keys for object if they are available. | def items(self):
"""
Return keys for object, if they are available.
"""
if self.meta_type == 'list':
return self._list
elif self.meta_type == 'dict':
return self._dict.items() |
Return keys for object if they are available. | def values(self):
"""
Return keys for object, if they are available.
"""
if self.meta_type == 'list':
return self._list
elif self.meta_type == 'dict':
return self._dict.values() |
Append to object if object is list. | 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 |
Extend list from object if object is list. | 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 |
Return JSON representation of object. | def json(self):
"""
Return JSON representation of object.
"""
if self.meta_type == 'list':
ret = []
for dat in self._list:
if not isinstance(dat, composite):
ret.append(dat)
else:
ret.append(d... |
Write composite object to file handle in JSON format. | 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:... |
API niceness defaulting to composite. write_json (). | def write(self, fh, pretty=True):
"""
API niceness defaulting to composite.write_json().
"""
return self.write_json(fh, pretty=pretty) |
Return JSON representation of object. | def json(self):
"""
Return JSON representation of object.
"""
data = {}
for item in self._data:
if isinstance(self._data[item], filetree):
data[item] = self._data[item].json()
else:
data[item] = self._data[item]
retu... |
Return list of files in filetree. | 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:
... |
Prune leaves of filetree according to specified regular expression. | 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) |
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 if so raises CyclicReferenceError. | 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... |
getModel - get the IndexedRedisModel associated with this list. If one was not provided in constructor it will be inferred from the first item in the list ( if present ) | def getModel(self):
'''
getModel - get the IndexedRedisModel associated with this list. If one was not provided in constructor,
it will be inferred from the first item in the list (if present)
@return <None/IndexedRedisModel> - None if none could be found, otherwise the IndexedRedisModel type of the ite... |
delete - Delete all objects in this list. | 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) |
save - Save all objects in this list | def save(self):
'''
save - Save all objects in this list
'''
if len(self) == 0:
return []
mdl = self.getModel()
return mdl.saver.save(self) |
reload - Reload all objects in this list. Updates in - place. To just fetch all these objects again use refetch | 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... |
refetch - Fetch a fresh copy of all items in this list. Returns a new list. To update in - place use reload. | 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... |
A function which can generate a hash of a one - level dict containing strings ( like REDIS_CONNECTION_PARAMS ) | def hashDictOneLevel(myDict):
'''
A function which can generate a hash of a one-level
dict containing strings (like REDIS_CONNECTION_PARAMS)
@param myDict <dict> - Dict with string keys and values
@return <long> - Hash of myDict
'''
keys = [str(x) for x in myDict.keys()]
keys.sort()
lst = []
for key... |
Outputs to a stream ( like a file or request ) | def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
for blok in self:
blok.output(to, *args, **kwargs)
return self |
Renders as a str | def render(self, *args, **kwargs):
'''Renders as a str'''
render_to = StringIO()
self.output(render_to, *args, **kwargs)
return render_to.getvalue() |
Outputs to a stream ( like a file or request ) | def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted and self.blox:
self.blox[0].output(to=to, formatted=True, indent=indent, indentation=indentation, *args, **kwargs)
for blok in ... |
Returns the elements HTML start tag | 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)
... |
Outputs to a stream ( like a file or request ) | def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
to.write(self.start_tag)
if not self.tag_self_closes:
to.write(self.end_tag) |
Outputs to a stream ( like a file or request ) | def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted:
to.write(self.start_tag)
to.write('\n')
if not self.tag_self_closes:
for blok in self.blox:
... |
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. | 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... |
Outputs the set text | def output(self, to=None, formatted=False, *args, **kwargs):
'''Outputs the set text'''
to.write('<!DOCTYPE {0}>'.format(self.type)) |
Match a genome VCF to variants in the ClinVar VCF file | 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: ... |
Return Allele data as dict object. | 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 |
Create list of Alleles from VCF line data | 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] |
Parse the VCF info field | 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 ... |
Dict representation of parsed VCF data | 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(... |
Very lightweight parsing of a vcf line to get position. | 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... |
_toStorage - Convert the value to a string representation for storage. | 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 |
_fromStorage - Convert the value from storage ( string ) to the value type. | def _fromStorage(self, value):
'''
_fromStorage - Convert the value from storage (string) to the value type.
@return - The converted value, or "irNull" if no value was defined (and field type is not default/string)
'''
for chainedField in reversed(self.chainedFields):
value = chainedField._fromStorage(... |
_checkCanIndex - Check if we CAN index ( if all fields are indexable ). Also checks the right - most field for hashIndex - if it needs to hash we will hash. | def _checkCanIndex(self):
'''
_checkCanIndex - Check if we CAN index (if all fields are indexable).
Also checks the right-most field for "hashIndex" - if it needs to hash we will hash.
'''
# NOTE: We can't just check the right-most field. For types like pickle that don't support indexing, they don't
# ... |
: returns: sum of lengthes of all ranges or None if one of the ranges is open: rtype: int float or None | def byte_length(self):
"""
:returns: sum of lengthes of all ranges or None if one of the ranges is open
:rtype: int, float or None
"""
sum = 0
for r in self:
if r.is_open():
return None
sum += r.byte_length()
return sum |
: returns: True if one or more range in the list overlaps with another: rtype: bool | def has_overlaps(self):
"""
:returns: True if one or more range in the list overlaps with another
:rtype: bool
"""
sorted_list = sorted(self)
for i in range(0, len(sorted_list) - 1):
if sorted_list[i].overlaps(sorted_list[i + 1]):
return True
... |
: returns: maximum stop in list or None if there s at least one open range: type: int float or None | def max_stop(self):
"""
:returns: maximum stop in list or None if there's at least one open range
:type: int, float or None
"""
m = 0
for r in self:
if r.is_open():
return None
m = max(m, r.stop)
return m |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.