code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_predictions_under_minimal_repair(instance, repair_options, optimum):
'''
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
'''
inst = instance.to_file()
repops = repair... | def function[get_predictions_under_minimal_repair, parameter[instance, repair_options, optimum]]:
constant[
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
]
variable[inst] a... | keyword[def] identifier[get_predictions_under_minimal_repair] ( identifier[instance] , identifier[repair_options] , identifier[optimum] ):
literal[string]
identifier[inst] = identifier[instance] . identifier[to_file] ()
identifier[repops] = identifier[repair_options] . identifier[to_file] ()
iden... | def get_predictions_under_minimal_repair(instance, repair_options, optimum):
"""
Computes the set of signs on edges/vertices that can be cautiously
derived from [instance], minus those that are a direct consequence
of obs_[ev]label predicates
"""
inst = instance.to_file()
repops = repair_opt... |
def load_remote_molecule(url, format=None):
'''Load a molecule from the remote location specified by *url*.
**Example**
::
load_remote_molecule('https://raw.github.com/chemlab/chemlab-testdata/master/benzene.mol')
'''
filename, headers = urlretrieve(url)
return load_molecule(filename... | def function[load_remote_molecule, parameter[url, format]]:
constant[Load a molecule from the remote location specified by *url*.
**Example**
::
load_remote_molecule('https://raw.github.com/chemlab/chemlab-testdata/master/benzene.mol')
]
<ast.Tuple object at 0x7da2054a7df0> assig... | keyword[def] identifier[load_remote_molecule] ( identifier[url] , identifier[format] = keyword[None] ):
literal[string]
identifier[filename] , identifier[headers] = identifier[urlretrieve] ( identifier[url] )
keyword[return] identifier[load_molecule] ( identifier[filename] , identifier[format] = iden... | def load_remote_molecule(url, format=None):
"""Load a molecule from the remote location specified by *url*.
**Example**
::
load_remote_molecule('https://raw.github.com/chemlab/chemlab-testdata/master/benzene.mol')
"""
(filename, headers) = urlretrieve(url)
return load_molecule(filena... |
def update(self, old_line, new_line, once=False):
"""Replace all lines matching `old_line` with `new_line`.
If ``once`` is set to True, remove only the first instance.
"""
nb = 0
for i, line in enumerate(self.lines):
if line.match(old_line):
self.line... | def function[update, parameter[self, old_line, new_line, once]]:
constant[Replace all lines matching `old_line` with `new_line`.
If ``once`` is set to True, remove only the first instance.
]
variable[nb] assign[=] constant[0]
for taget[tuple[[<ast.Name object at 0x7da1b2344a30>,... | keyword[def] identifier[update] ( identifier[self] , identifier[old_line] , identifier[new_line] , identifier[once] = keyword[False] ):
literal[string]
identifier[nb] = literal[int]
keyword[for] identifier[i] , identifier[line] keyword[in] identifier[enumerate] ( identifier[self] . ide... | def update(self, old_line, new_line, once=False):
"""Replace all lines matching `old_line` with `new_line`.
If ``once`` is set to True, remove only the first instance.
"""
nb = 0
for (i, line) in enumerate(self.lines):
if line.match(old_line):
self.lines[i] = new_line
... |
def list_order_by(l,firstItems):
"""given a list and a list of items to be first, return the list in the
same order except that it begins with each of the first items."""
l=list(l)
for item in firstItems[::-1]: #backwards
if item in l:
l.remove(item)
l.insert(0,item)
... | def function[list_order_by, parameter[l, firstItems]]:
constant[given a list and a list of items to be first, return the list in the
same order except that it begins with each of the first items.]
variable[l] assign[=] call[name[list], parameter[name[l]]]
for taget[name[item]] in starred[cal... | keyword[def] identifier[list_order_by] ( identifier[l] , identifier[firstItems] ):
literal[string]
identifier[l] = identifier[list] ( identifier[l] )
keyword[for] identifier[item] keyword[in] identifier[firstItems] [::- literal[int] ]:
keyword[if] identifier[item] keyword[in] identifier... | def list_order_by(l, firstItems):
"""given a list and a list of items to be first, return the list in the
same order except that it begins with each of the first items."""
l = list(l)
for item in firstItems[::-1]: #backwards
if item in l:
l.remove(item)
l.insert(0, item)... |
def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditB... | def function[_fill_temporary_buffer, parameter[self, cursor, text, html]]:
constant[fill the area below the active editting zone with text]
variable[current_pos] assign[=] call[call[name[self]._control.textCursor, parameter[]].position, parameter[]]
call[name[cursor].beginEditBlock, parameter[]]... | keyword[def] identifier[_fill_temporary_buffer] ( identifier[self] , identifier[cursor] , identifier[text] , identifier[html] = keyword[False] ):
literal[string]
identifier[current_pos] = identifier[self] . identifier[_control] . identifier[textCursor] (). identifier[position] ()
identif... | def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosit... |
def data(self, index, role = Qt.DisplayRole):
""" Returns the data at an index for a certain role
"""
try:
if role == Qt.DisplayRole:
return to_string(self._cellValue(index), masked=self._cellMask(index),
decode_bytes=self.encoding, ma... | def function[data, parameter[self, index, role]]:
constant[ Returns the data at an index for a certain role
]
<ast.Try object at 0x7da1b0414fa0> | keyword[def] identifier[data] ( identifier[self] , identifier[index] , identifier[role] = identifier[Qt] . identifier[DisplayRole] ):
literal[string]
keyword[try] :
keyword[if] identifier[role] == identifier[Qt] . identifier[DisplayRole] :
keyword[return] identifier[... | def data(self, index, role=Qt.DisplayRole):
""" Returns the data at an index for a certain role
"""
try:
if role == Qt.DisplayRole:
return to_string(self._cellValue(index), masked=self._cellMask(index), decode_bytes=self.encoding, maskFormat=self.maskFormat, strFormat=self.strFormat,... |
def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
... | def function[add, parameter[lhs, rhs]]:
constant[Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size... | keyword[def] identifier[add] ( identifier[lhs] , identifier[rhs] ):
literal[string]
keyword[return] identifier[_ufunc_helper] (
identifier[lhs] ,
identifier[rhs] ,
identifier[op] . identifier[broadcast_add] ,
identifier[operator] . identifier[add] ,
identifier[_internal] . id... | def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting.
Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and
``mx.nd.broadcast_plus(lhs, rhs)``.
.. note::
If the corresponding dimensions of two arrays have the same size or one of them has size 1,
... |
def usesTime(self, fmt=None):
'''
Check if the format uses the creation time of the record.
'''
if fmt is None:
fmt = self._fmt
if not isinstance(fmt, basestring):
fmt = fmt[0]
return fmt.find('%(asctime)') >= 0 | def function[usesTime, parameter[self, fmt]]:
constant[
Check if the format uses the creation time of the record.
]
if compare[name[fmt] is constant[None]] begin[:]
variable[fmt] assign[=] name[self]._fmt
if <ast.UnaryOp object at 0x7da2054a78e0> begin[:]
... | keyword[def] identifier[usesTime] ( identifier[self] , identifier[fmt] = keyword[None] ):
literal[string]
keyword[if] identifier[fmt] keyword[is] keyword[None] :
identifier[fmt] = identifier[self] . identifier[_fmt]
keyword[if] keyword[not] identifier[isinstance] ( i... | def usesTime(self, fmt=None):
"""
Check if the format uses the creation time of the record.
"""
if fmt is None:
fmt = self._fmt # depends on [control=['if'], data=['fmt']]
if not isinstance(fmt, basestring):
fmt = fmt[0] # depends on [control=['if'], data=[]]
return fmt... |
def _read_bytes(self, b):
"""Reads the requested number of bytes from a streaming message body.
:param int b: Number of bytes to read
:raises NotSupportedError: if content type is not supported
"""
_LOGGER.debug("%d bytes requested from stream with content type: %s", b, self.con... | def function[_read_bytes, parameter[self, b]]:
constant[Reads the requested number of bytes from a streaming message body.
:param int b: Number of bytes to read
:raises NotSupportedError: if content type is not supported
]
call[name[_LOGGER].debug, parameter[constant[%d bytes re... | keyword[def] identifier[_read_bytes] ( identifier[self] , identifier[b] ):
literal[string]
identifier[_LOGGER] . identifier[debug] ( literal[string] , identifier[b] , identifier[self] . identifier[content_type] )
keyword[if] literal[int] <= identifier[b] <= identifier[len] ( identifier[se... | def _read_bytes(self, b):
"""Reads the requested number of bytes from a streaming message body.
:param int b: Number of bytes to read
:raises NotSupportedError: if content type is not supported
"""
_LOGGER.debug('%d bytes requested from stream with content type: %s', b, self.content_typ... |
def get_device_activity(self, type_p):
"""Gets the current activity type of given devices or device groups.
in type_p of type :class:`DeviceType`
return activity of type :class:`DeviceActivity`
raises :class:`OleErrorInvalidarg`
Invalid device type.
"""
... | def function[get_device_activity, parameter[self, type_p]]:
constant[Gets the current activity type of given devices or device groups.
in type_p of type :class:`DeviceType`
return activity of type :class:`DeviceActivity`
raises :class:`OleErrorInvalidarg`
Invalid device ty... | keyword[def] identifier[get_device_activity] ( identifier[self] , identifier[type_p] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[type_p] , identifier[list] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[for] identifi... | def get_device_activity(self, type_p):
"""Gets the current activity type of given devices or device groups.
in type_p of type :class:`DeviceType`
return activity of type :class:`DeviceActivity`
raises :class:`OleErrorInvalidarg`
Invalid device type.
"""
if... |
def marathon_on_marathon(name='marathon-user'):
""" Context manager for altering the marathon client for MoM
:param name: service name of MoM to use
:type name: str
"""
toml_config_o = config.get_config()
dcos_url = config.get_config_val('core.dcos_url', toml_config_o)
service_name = 'servi... | def function[marathon_on_marathon, parameter[name]]:
constant[ Context manager for altering the marathon client for MoM
:param name: service name of MoM to use
:type name: str
]
variable[toml_config_o] assign[=] call[name[config].get_config, parameter[]]
variable[dcos_url] assign[=] ... | keyword[def] identifier[marathon_on_marathon] ( identifier[name] = literal[string] ):
literal[string]
identifier[toml_config_o] = identifier[config] . identifier[get_config] ()
identifier[dcos_url] = identifier[config] . identifier[get_config_val] ( literal[string] , identifier[toml_config_o] )
... | def marathon_on_marathon(name='marathon-user'):
""" Context manager for altering the marathon client for MoM
:param name: service name of MoM to use
:type name: str
"""
toml_config_o = config.get_config()
dcos_url = config.get_config_val('core.dcos_url', toml_config_o)
service_name = 'servic... |
def delete_location(self):
"""Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
"""
# normally this should only remove one triple each
for s, p, o in self._graph.triples((None, GEO_NS.lat, None)):
self._graph.remove((s, p, o))
for s, p, o in s... | def function[delete_location, parameter[self]]:
constant[Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
]
for taget[tuple[[<ast.Name object at 0x7da2041d85e0>, <ast.Name object at 0x7da2041db6d0>, <ast.Name object at 0x7da2041d9db0>]]] in starred[call[name[self]._grap... | keyword[def] identifier[delete_location] ( identifier[self] ):
literal[string]
keyword[for] identifier[s] , identifier[p] , identifier[o] keyword[in] identifier[self] . identifier[_graph] . identifier[triples] (( keyword[None] , identifier[GEO_NS] . identifier[lat] , keyword[None] )):
... | def delete_location(self):
"""Deletes all the `geo:lat` and `geo:long` metadata properties on your Thing
"""
# normally this should only remove one triple each
for (s, p, o) in self._graph.triples((None, GEO_NS.lat, None)):
self._graph.remove((s, p, o)) # depends on [control=['for'], data=[... |
def write_two_phases(filename, data, io):
"""
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no actio... | def function[write_two_phases, parameter[filename, data, io]]:
constant[
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data th... | keyword[def] identifier[write_two_phases] ( identifier[filename] , identifier[data] , identifier[io] ):
literal[string]
identifier[write_flag] = keyword[True]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[filename] ):
keyword[with] identifi... | def write_two_phases(filename, data, io):
"""
Writes a file in two phase to the filesystem.
First write the data to a temporary file (in the same directory) and than renames the temporary file. If the
file already exists and its content is equal to the data that must be written no action is... |
def _remove_from_index_operations(self, which, transforms):
"""
Helper preventing copy code.
Remove given what (transform prior etc) from which param index ops.
"""
if len(transforms) == 0:
transforms = which.properties()
removed = np.empty((0,), dtype=int)
... | def function[_remove_from_index_operations, parameter[self, which, transforms]]:
constant[
Helper preventing copy code.
Remove given what (transform prior etc) from which param index ops.
]
if compare[call[name[len], parameter[name[transforms]]] equal[==] constant[0]] begin[:]
... | keyword[def] identifier[_remove_from_index_operations] ( identifier[self] , identifier[which] , identifier[transforms] ):
literal[string]
keyword[if] identifier[len] ( identifier[transforms] )== literal[int] :
identifier[transforms] = identifier[which] . identifier[properties] ()
... | def _remove_from_index_operations(self, which, transforms):
"""
Helper preventing copy code.
Remove given what (transform prior etc) from which param index ops.
"""
if len(transforms) == 0:
transforms = which.properties() # depends on [control=['if'], data=[]]
removed = np.e... |
def accept(self, origin, protocol):
"""
Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
associated with thi... | def function[accept, parameter[self, origin, protocol]]:
constant[
Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
... | keyword[def] identifier[accept] ( identifier[self] , identifier[origin] , identifier[protocol] ):
literal[string]
keyword[for] identifier[factory] keyword[in] identifier[self] . identifier[store] . identifier[powerupsFor] ( identifier[IBoxReceiverFactory] ):
keyword[if] id... | def accept(self, origin, protocol):
"""
Create a new route attached to a L{IBoxReceiver} created by the
L{IBoxReceiverFactory} with the indicated protocol.
@type origin: C{unicode}
@param origin: The identifier of a route on the peer which will be
associated with this co... |
def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError
return self._unpickle(result) | def function[pop, parameter[self]]:
constant[
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
]
variable[result] assign[=] call[name[self].redis.spop, parameter[name[self].key]]
if compare[name[result] is constant[None]] be... | keyword[def] identifier[pop] ( identifier[self] ):
literal[string]
identifier[result] = identifier[self] . identifier[redis] . identifier[spop] ( identifier[self] . identifier[key] )
keyword[if] identifier[result] keyword[is] keyword[None] :
keyword[raise] identifier[KeyEr... | def pop(self):
"""
Remove and return an arbitrary element from the set.
Raises :exc:`KeyError` if the set is empty.
"""
result = self.redis.spop(self.key)
if result is None:
raise KeyError # depends on [control=['if'], data=[]]
return self._unpickle(result) |
def active_brokers(self):
"""Return set of brokers that are not inactive or decommissioned."""
return {
broker
for broker in self._brokers
if not broker.inactive and not broker.decommissioned
} | def function[active_brokers, parameter[self]]:
constant[Return set of brokers that are not inactive or decommissioned.]
return[<ast.SetComp object at 0x7da1b077a800>] | keyword[def] identifier[active_brokers] ( identifier[self] ):
literal[string]
keyword[return] {
identifier[broker]
keyword[for] identifier[broker] keyword[in] identifier[self] . identifier[_brokers]
keyword[if] keyword[not] identifier[broker] . identifier[inactive]... | def active_brokers(self):
"""Return set of brokers that are not inactive or decommissioned."""
return {broker for broker in self._brokers if not broker.inactive and (not broker.decommissioned)} |
def add_task_hook(self, task_hook):
"""Registers a specified task hook to this context
:type task_hook: heron.instance.src.python.utils.topology.ITaskHook
:param task_hook: Implementation of ITaskHook
"""
if not isinstance(task_hook, ITaskHook):
raise TypeError("In add_task_hook(): attempt to... | def function[add_task_hook, parameter[self, task_hook]]:
constant[Registers a specified task hook to this context
:type task_hook: heron.instance.src.python.utils.topology.ITaskHook
:param task_hook: Implementation of ITaskHook
]
if <ast.UnaryOp object at 0x7da204347c70> begin[:]
<a... | keyword[def] identifier[add_task_hook] ( identifier[self] , identifier[task_hook] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[task_hook] , identifier[ITaskHook] ):
keyword[raise] identifier[TypeError] ( literal[string]
% identifier[str] ( identifier[type... | def add_task_hook(self, task_hook):
"""Registers a specified task hook to this context
:type task_hook: heron.instance.src.python.utils.topology.ITaskHook
:param task_hook: Implementation of ITaskHook
"""
if not isinstance(task_hook, ITaskHook):
raise TypeError('In add_task_hook(): attempt ... |
def _ParseCmdItem(self, cmd_input, template_file=None):
"""Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template wa... | def function[_ParseCmdItem, parameter[self, cmd_input, template_file]]:
constant[Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
Cl... | keyword[def] identifier[_ParseCmdItem] ( identifier[self] , identifier[cmd_input] , identifier[template_file] = keyword[None] ):
literal[string]
identifier[fsm] = identifier[textfsm] . identifier[TextFSM] ( identifier[template_file] )
keyword[if] keyword[not] identifier[self] . identifier[_keys... | def _ParseCmdItem(self, cmd_input, template_file=None):
"""Creates Texttable with output of command.
Args:
cmd_input: String, Device response.
template_file: File object, template to parse with.
Returns:
TextTable containing command output.
Raises:
CliTableError: A template wa... |
def mapper_from_grid_stack_and_border(self, grid_stack, border):
"""Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rectangular pixelization's geo... | def function[mapper_from_grid_stack_and_border, parameter[self, grid_stack, border]]:
constant[Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rec... | keyword[def] identifier[mapper_from_grid_stack_and_border] ( identifier[self] , identifier[grid_stack] , identifier[border] ):
literal[string]
keyword[if] identifier[border] keyword[is] keyword[not] keyword[None] :
identifier[relocated_grid_stack] = identifier[border] . identifier... | def mapper_from_grid_stack_and_border(self, grid_stack, border):
"""Setup a rectangular mapper from a rectangular pixelization, as follows:
1) If a border is supplied, relocate all of the grid-stack's regular and sub grid pixels beyond the border.
2) Determine the rectangular pixelization's geometr... |
def member_update(self, repl_id, member_id, params):
"""apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise False
"""
repl... | def function[member_update, parameter[self, repl_id, member_id, params]]:
constant[apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise Fal... | keyword[def] identifier[member_update] ( identifier[self] , identifier[repl_id] , identifier[member_id] , identifier[params] ):
literal[string]
identifier[repl] = identifier[self] [ identifier[repl_id] ]
identifier[result] = identifier[repl] . identifier[member_update] ( identifier[member_... | def member_update(self, repl_id, member_id, params):
"""apply new params to replica set member
Args:
repl_id - replica set identity
member_id - member index
params - new member's params
return True if operation success otherwise False
"""
repl = self[... |
def _update_cache(self, course, taskid):
"""
Updates the cache
:param course: a Course object
:param taskid: a (valid) task id
:raise InvalidNameException, TaskNotFoundException, TaskUnreadableException
"""
if not id_checker(taskid):
raise InvalidNameE... | def function[_update_cache, parameter[self, course, taskid]]:
constant[
Updates the cache
:param course: a Course object
:param taskid: a (valid) task id
:raise InvalidNameException, TaskNotFoundException, TaskUnreadableException
]
if <ast.UnaryOp object at 0x7da1... | keyword[def] identifier[_update_cache] ( identifier[self] , identifier[course] , identifier[taskid] ):
literal[string]
keyword[if] keyword[not] identifier[id_checker] ( identifier[taskid] ):
keyword[raise] identifier[InvalidNameException] ( literal[string] + identifier[taskid] )
... | def _update_cache(self, course, taskid):
"""
Updates the cache
:param course: a Course object
:param taskid: a (valid) task id
:raise InvalidNameException, TaskNotFoundException, TaskUnreadableException
"""
if not id_checker(taskid):
raise InvalidNameException('Ta... |
def crypto_hash(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = ffi.new("unsigned char[]", crypto_hash_BYTES)
rc = lib.crypto_hash(digest, message, len(message))
ensure(rc == 0,
'Unexpected library error',
... | def function[crypto_hash, parameter[message]]:
constant[
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
]
variable[digest] assign[=] call[name[ffi].new, parameter[constant[unsigned char[]], name[crypto_hash_BYTES]]]
variable[rc] assign[=] call[na... | keyword[def] identifier[crypto_hash] ( identifier[message] ):
literal[string]
identifier[digest] = identifier[ffi] . identifier[new] ( literal[string] , identifier[crypto_hash_BYTES] )
identifier[rc] = identifier[lib] . identifier[crypto_hash] ( identifier[digest] , identifier[message] , identifier[le... | def crypto_hash(message):
"""
Hashes and returns the message ``message``.
:param message: bytes
:rtype: bytes
"""
digest = ffi.new('unsigned char[]', crypto_hash_BYTES)
rc = lib.crypto_hash(digest, message, len(message))
ensure(rc == 0, 'Unexpected library error', raising=exc.RuntimeErr... |
def show_external_release_file(root, request):
"""
Download a release from a download url from its package information.
Must be used with :func:`pyshop.helpers.download.renderer_factory`
to download the release file.
:return: download informations
:rtype: dict
"""
session = DBSession()
... | def function[show_external_release_file, parameter[root, request]]:
constant[
Download a release from a download url from its package information.
Must be used with :func:`pyshop.helpers.download.renderer_factory`
to download the release file.
:return: download informations
:rtype: dict
... | keyword[def] identifier[show_external_release_file] ( identifier[root] , identifier[request] ):
literal[string]
identifier[session] = identifier[DBSession] ()
identifier[settings] = identifier[request] . identifier[registry] . identifier[settings]
identifier[whlify] = identifier[asbool] ( ident... | def show_external_release_file(root, request):
"""
Download a release from a download url from its package information.
Must be used with :func:`pyshop.helpers.download.renderer_factory`
to download the release file.
:return: download informations
:rtype: dict
"""
session = DBSession()
... |
def special_format_field(self, obj, format_spec):
"""Know about any special formats"""
if format_spec == "env":
return "${{{0}}}".format(obj)
elif format_spec == "from_env":
if obj not in os.environ:
raise NoSuchEnvironmentVariable(wanted=obj)
... | def function[special_format_field, parameter[self, obj, format_spec]]:
constant[Know about any special formats]
if compare[name[format_spec] equal[==] constant[env]] begin[:]
return[call[constant[${{{0}}}].format, parameter[name[obj]]]] | keyword[def] identifier[special_format_field] ( identifier[self] , identifier[obj] , identifier[format_spec] ):
literal[string]
keyword[if] identifier[format_spec] == literal[string] :
keyword[return] literal[string] . identifier[format] ( identifier[obj] )
keyword[elif] id... | def special_format_field(self, obj, format_spec):
"""Know about any special formats"""
if format_spec == 'env':
return '${{{0}}}'.format(obj) # depends on [control=['if'], data=[]]
elif format_spec == 'from_env':
if obj not in os.environ:
raise NoSuchEnvironmentVariable(wanted=o... |
def _try_assign_utc_time(self, raw_time, time_base):
"""Try to assign a UTC time to this reading."""
# Check if the raw time is encoded UTC since y2k or just uptime
if raw_time != IOTileEvent.InvalidRawTime and (raw_time & (1 << 31)):
y2k_offset = self.raw_time ^ (1 << 31)
... | def function[_try_assign_utc_time, parameter[self, raw_time, time_base]]:
constant[Try to assign a UTC time to this reading.]
if <ast.BoolOp object at 0x7da2041dacb0> begin[:]
variable[y2k_offset] assign[=] binary_operation[name[self].raw_time <ast.BitXor object at 0x7da2590d6b00> binary... | keyword[def] identifier[_try_assign_utc_time] ( identifier[self] , identifier[raw_time] , identifier[time_base] ):
literal[string]
keyword[if] identifier[raw_time] != identifier[IOTileEvent] . identifier[InvalidRawTime] keyword[and] ( identifier[raw_time] &( literal[int] << literal[int]... | def _try_assign_utc_time(self, raw_time, time_base):
"""Try to assign a UTC time to this reading."""
# Check if the raw time is encoded UTC since y2k or just uptime
if raw_time != IOTileEvent.InvalidRawTime and raw_time & 1 << 31:
y2k_offset = self.raw_time ^ 1 << 31
return self._Y2KReferenc... |
def _evaluate(self, indices, norm_distances, out=None):
"""Evaluate linear interpolation.
Modified for in-place evaluation and treatment of out-of-bounds
points by implicitly assuming 0 at the next node."""
# slice for broadcasting over trailing dimensions in self.values
vslice ... | def function[_evaluate, parameter[self, indices, norm_distances, out]]:
constant[Evaluate linear interpolation.
Modified for in-place evaluation and treatment of out-of-bounds
points by implicitly assuming 0 at the next node.]
variable[vslice] assign[=] binary_operation[tuple[[<ast.Call... | keyword[def] identifier[_evaluate] ( identifier[self] , identifier[indices] , identifier[norm_distances] , identifier[out] = keyword[None] ):
literal[string]
identifier[vslice] =( identifier[slice] ( keyword[None] ),)+( keyword[None] ,)*( identifier[self] . identifier[values] . identifier[... | def _evaluate(self, indices, norm_distances, out=None):
"""Evaluate linear interpolation.
Modified for in-place evaluation and treatment of out-of-bounds
points by implicitly assuming 0 at the next node."""
# slice for broadcasting over trailing dimensions in self.values
vslice = (slice(Non... |
def from_connections(cls, caption, connections):
"""Create a new Data Source give a list of Connections."""
root = ET.Element('datasource', caption=caption, version='10.0', inline='true')
outer_connection = ET.SubElement(root, 'connection')
outer_connection.set('class', 'federated')
... | def function[from_connections, parameter[cls, caption, connections]]:
constant[Create a new Data Source give a list of Connections.]
variable[root] assign[=] call[name[ET].Element, parameter[constant[datasource]]]
variable[outer_connection] assign[=] call[name[ET].SubElement, parameter[name[root... | keyword[def] identifier[from_connections] ( identifier[cls] , identifier[caption] , identifier[connections] ):
literal[string]
identifier[root] = identifier[ET] . identifier[Element] ( literal[string] , identifier[caption] = identifier[caption] , identifier[version] = literal[string] , identifier[... | def from_connections(cls, caption, connections):
"""Create a new Data Source give a list of Connections."""
root = ET.Element('datasource', caption=caption, version='10.0', inline='true')
outer_connection = ET.SubElement(root, 'connection')
outer_connection.set('class', 'federated')
named_conns = ET... |
def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql... | def function[db_exec_with_cursor, parameter[self, cursor, sql]]:
constant[Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected.]
variable[sql] assign[=] call[name[self].localize_sql, parameter[name[sql]]]
<ast.Try object at ... | keyword[def] identifier[db_exec_with_cursor] ( identifier[self] , identifier[cursor] , identifier[sql] : identifier[str] ,* identifier[args] )-> identifier[int] :
literal[string]
identifier[sql] = identifier[self] . identifier[localize_sql] ( identifier[sql] )
keyword[try] :
i... | def db_exec_with_cursor(self, cursor, sql: str, *args) -> int:
"""Executes SQL on a supplied cursor, with "?" placeholders,
substituting in the arguments. Returns number of rows affected."""
sql = self.localize_sql(sql)
try:
debug_sql(sql, args)
cursor.execute(sql, args)
retu... |
def shortenIDs(doc, prefix, unprotectedElements=None):
"""
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shor... | def function[shortenIDs, parameter[doc, prefix, unprotectedElements]]:
constant[
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the num... | keyword[def] identifier[shortenIDs] ( identifier[doc] , identifier[prefix] , identifier[unprotectedElements] = keyword[None] ):
literal[string]
identifier[num] = literal[int]
identifier[identifiedElements] = identifier[findElementsWithId] ( identifier[doc] . identifier[documentElement] )
keywor... | def shortenIDs(doc, prefix, unprotectedElements=None):
"""
Shortens ID names used in the document. ID names referenced the most often are assigned the
shortest ID names.
If the list unprotectedElements is provided, only IDs from this list will be shortened.
Returns the number of bytes saved by shor... |
def light_travel_time_to_detector(self, det):
""" Return the light travel time from this detector
Parameters
----------
det: Detector
The other detector to determine the light travel time to.
Returns
-------
time: float
The light travel t... | def function[light_travel_time_to_detector, parameter[self, det]]:
constant[ Return the light travel time from this detector
Parameters
----------
det: Detector
The other detector to determine the light travel time to.
Returns
-------
time: float
... | keyword[def] identifier[light_travel_time_to_detector] ( identifier[self] , identifier[det] ):
literal[string]
identifier[d] = identifier[self] . identifier[location] - identifier[det] . identifier[location]
keyword[return] identifier[float] ( identifier[d] . identifier[dot] ( identifier... | def light_travel_time_to_detector(self, det):
""" Return the light travel time from this detector
Parameters
----------
det: Detector
The other detector to determine the light travel time to.
Returns
-------
time: float
The light travel time ... |
def get_trees(self, data, showerrors = False): # -> list:
""" returns a list of trees with valid guesses """
if not all(check(self._productionset.alphabet, [x]) for x in data):
raise ValueError("Unknown element in {}, alphabet:{}".format(str(data), self.productionset.alphabet))
resul... | def function[get_trees, parameter[self, data, showerrors]]:
constant[ returns a list of trees with valid guesses ]
if <ast.UnaryOp object at 0x7da20c795990> begin[:]
<ast.Raise object at 0x7da20c7950f0>
variable[result] assign[=] call[name[self].__recursive_parser, parameter[name[self]._... | keyword[def] identifier[get_trees] ( identifier[self] , identifier[data] , identifier[showerrors] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[all] ( identifier[check] ( identifier[self] . identifier[_productionset] . identifier[alphabet] ,[ identifier[x] ]) keyword[for... | def get_trees(self, data, showerrors=False): # -> list:
' returns a list of trees with valid guesses '
if not all((check(self._productionset.alphabet, [x]) for x in data)):
raise ValueError('Unknown element in {}, alphabet:{}'.format(str(data), self.productionset.alphabet)) # depends on [control=['if'... |
def scrub(zpool, stop=False, pause=False):
'''
Scrub a storage pool
zpool : string
Name of storage pool
stop : boolean
If ``True``, cancel ongoing scrub
pause : boolean
If ``True``, pause ongoing scrub
.. versionadded:: 2018.3.0
.. note::
Pau... | def function[scrub, parameter[zpool, stop, pause]]:
constant[
Scrub a storage pool
zpool : string
Name of storage pool
stop : boolean
If ``True``, cancel ongoing scrub
pause : boolean
If ``True``, pause ongoing scrub
.. versionadded:: 2018.3.0
.. note... | keyword[def] identifier[scrub] ( identifier[zpool] , identifier[stop] = keyword[False] , identifier[pause] = keyword[False] ):
literal[string]
keyword[if] identifier[stop] :
identifier[action] =[ literal[string] ]
keyword[elif] identifier[pause] :
identifier[action] =[ literal... | def scrub(zpool, stop=False, pause=False):
"""
Scrub a storage pool
zpool : string
Name of storage pool
stop : boolean
If ``True``, cancel ongoing scrub
pause : boolean
If ``True``, pause ongoing scrub
.. versionadded:: 2018.3.0
.. note::
Pau... |
def _merge_fields(a, b):
"""Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first.
"""
a_names = set(x[0] for x in a)
b_names = set(x[0] for x in b)
a_keep = a_names - b_names
fields = []
for name, field in a:
if name in a_keep:
... | def function[_merge_fields, parameter[a, b]]:
constant[Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first.
]
variable[a_names] assign[=] call[name[set], parameter[<ast.GeneratorExp object at 0x7da20c9903d0>]]
variable[b_names] assign[=] call[... | keyword[def] identifier[_merge_fields] ( identifier[a] , identifier[b] ):
literal[string]
identifier[a_names] = identifier[set] ( identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in] identifier[a] )
identifier[b_names] = identifier[set] ( identifier[x] [ literal[int] ] keyword[for... | def _merge_fields(a, b):
"""Merge two lists of fields.
Fields in `b` override fields in `a`. Fields in `a` are output first.
"""
a_names = set((x[0] for x in a))
b_names = set((x[0] for x in b))
a_keep = a_names - b_names
fields = []
for (name, field) in a:
if name in a_keep:
... |
def stationary_distribution(self):
r""" Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary
"""
assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), \
'No unique stationary distri... | def function[stationary_distribution, parameter[self]]:
constant[ Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary
]
assert[call[name[_tmatrix_disconnected].is_connected, parameter[name[self]._Tij]]]
imp... | keyword[def] identifier[stationary_distribution] ( identifier[self] ):
literal[string]
keyword[assert] identifier[_tmatrix_disconnected] . identifier[is_connected] ( identifier[self] . identifier[_Tij] , identifier[strong] = keyword[False] ), literal[string]
keyword[import] identifier[m... | def stationary_distribution(self):
""" Compute stationary distribution of hidden states if possible.
Raises
------
ValueError if the HMM is not stationary
"""
assert _tmatrix_disconnected.is_connected(self._Tij, strong=False), 'No unique stationary distribution because transiti... |
def open_gsr(self):
"""
Open the GSR file located in the in self.outdir.
Returns :class:`GsrFile` object, None if file could not be found or file is not readable.
"""
gsr_path = self.gsr_path
if not gsr_path:
if self.status == self.S_OK:
logger... | def function[open_gsr, parameter[self]]:
constant[
Open the GSR file located in the in self.outdir.
Returns :class:`GsrFile` object, None if file could not be found or file is not readable.
]
variable[gsr_path] assign[=] name[self].gsr_path
if <ast.UnaryOp object at 0x7da... | keyword[def] identifier[open_gsr] ( identifier[self] ):
literal[string]
identifier[gsr_path] = identifier[self] . identifier[gsr_path]
keyword[if] keyword[not] identifier[gsr_path] :
keyword[if] identifier[self] . identifier[status] == identifier[self] . identifier[S_OK] :... | def open_gsr(self):
"""
Open the GSR file located in the in self.outdir.
Returns :class:`GsrFile` object, None if file could not be found or file is not readable.
"""
gsr_path = self.gsr_path
if not gsr_path:
if self.status == self.S_OK:
logger.critical("%s reache... |
def clustal_align_protein(recs, work_dir, outfmt="fasta"):
"""
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, "prot-start.fasta")
align_file = op.join(work_dir, "prot.aln")
SeqIO.write(recs, file(fasta_file, "w"), "fasta")
... | def function[clustal_align_protein, parameter[recs, work_dir, outfmt]]:
constant[
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
]
variable[fasta_file] assign[=] call[name[op].join, parameter[name[work_dir], constant[prot-start.fasta]]]
variable[alig... | keyword[def] identifier[clustal_align_protein] ( identifier[recs] , identifier[work_dir] , identifier[outfmt] = literal[string] ):
literal[string]
identifier[fasta_file] = identifier[op] . identifier[join] ( identifier[work_dir] , literal[string] )
identifier[align_file] = identifier[op] . identifier[... | def clustal_align_protein(recs, work_dir, outfmt='fasta'):
"""
Align given proteins with clustalw.
recs are iterable of Biopython SeqIO objects
"""
fasta_file = op.join(work_dir, 'prot-start.fasta')
align_file = op.join(work_dir, 'prot.aln')
SeqIO.write(recs, file(fasta_file, 'w'), 'fasta')
... |
def set_status(self, status):
"""
Save the new status and call all defined callbacks
"""
self.status = status
for callback in self._update_status_callbacks:
callback(self) | def function[set_status, parameter[self, status]]:
constant[
Save the new status and call all defined callbacks
]
name[self].status assign[=] name[status]
for taget[name[callback]] in starred[name[self]._update_status_callbacks] begin[:]
call[name[callback], param... | keyword[def] identifier[set_status] ( identifier[self] , identifier[status] ):
literal[string]
identifier[self] . identifier[status] = identifier[status]
keyword[for] identifier[callback] keyword[in] identifier[self] . identifier[_update_status_callbacks] :
identifier[call... | def set_status(self, status):
"""
Save the new status and call all defined callbacks
"""
self.status = status
for callback in self._update_status_callbacks:
callback(self) # depends on [control=['for'], data=['callback']] |
def transform(self, context, handler, result):
"""Transform the value returned by the controller endpoint.
This extension transforms returned values if the endpoint has a return type annotation.
"""
handler = handler.__func__ if hasattr(handler, '__func__') else handler
annotation = getattr(handler, '__ann... | def function[transform, parameter[self, context, handler, result]]:
constant[Transform the value returned by the controller endpoint.
This extension transforms returned values if the endpoint has a return type annotation.
]
variable[handler] assign[=] <ast.IfExp object at 0x7da2043460e0>
... | keyword[def] identifier[transform] ( identifier[self] , identifier[context] , identifier[handler] , identifier[result] ):
literal[string]
identifier[handler] = identifier[handler] . identifier[__func__] keyword[if] identifier[hasattr] ( identifier[handler] , literal[string] ) keyword[else] identifier[handle... | def transform(self, context, handler, result):
"""Transform the value returned by the controller endpoint.
This extension transforms returned values if the endpoint has a return type annotation.
"""
handler = handler.__func__ if hasattr(handler, '__func__') else handler
annotation = getattr(handler, ... |
def key_callback(self, window, key, scancode, action, mods):
"""press ESCAPE to quite the application"""
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.SetWindowShouldClose(self.window, True) | def function[key_callback, parameter[self, window, key, scancode, action, mods]]:
constant[press ESCAPE to quite the application]
if <ast.BoolOp object at 0x7da20c76cca0> begin[:]
call[name[glfw].SetWindowShouldClose, parameter[name[self].window, constant[True]]] | keyword[def] identifier[key_callback] ( identifier[self] , identifier[window] , identifier[key] , identifier[scancode] , identifier[action] , identifier[mods] ):
literal[string]
keyword[if] identifier[key] == identifier[glfw] . identifier[KEY_ESCAPE] keyword[and] identifier[action] == identifier... | def key_callback(self, window, key, scancode, action, mods):
"""press ESCAPE to quite the application"""
if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
glfw.SetWindowShouldClose(self.window, True) # depends on [control=['if'], data=[]] |
def set_creation_date(self, p_date=date.today()):
"""
Sets the creation date of a todo. Should be passed a date object.
"""
self.fields['creationDate'] = p_date
# not particularly pretty, but inspired by
# http://bugs.python.org/issue1519638 non-existent matches trigger
... | def function[set_creation_date, parameter[self, p_date]]:
constant[
Sets the creation date of a todo. Should be passed a date object.
]
call[name[self].fields][constant[creationDate]] assign[=] name[p_date]
name[self].src assign[=] call[name[re].sub, parameter[constant[^(x \d{4}-... | keyword[def] identifier[set_creation_date] ( identifier[self] , identifier[p_date] = identifier[date] . identifier[today] ()):
literal[string]
identifier[self] . identifier[fields] [ literal[string] ]= identifier[p_date]
identifier[self] . identifier[src] = ide... | def set_creation_date(self, p_date=date.today()):
"""
Sets the creation date of a todo. Should be passed a date object.
"""
self.fields['creationDate'] = p_date
# not particularly pretty, but inspired by
# http://bugs.python.org/issue1519638 non-existent matches trigger
# exceptions,... |
def count(self, other, r, attrs=None, info={}):
""" Gray & Moore based fast dual tree counting.
r is the edge of bins:
-inf or r[i-1] < count[i] <= r[i]
attrs: None or tuple
if tuple, attrs = (attr_self, attr_other)
Returns: count,
... | def function[count, parameter[self, other, r, attrs, info]]:
constant[ Gray & Moore based fast dual tree counting.
r is the edge of bins:
-inf or r[i-1] < count[i] <= r[i]
attrs: None or tuple
if tuple, attrs = (attr_self, attr_other)
Returns: ... | keyword[def] identifier[count] ( identifier[self] , identifier[other] , identifier[r] , identifier[attrs] = keyword[None] , identifier[info] ={}):
literal[string]
identifier[r] = identifier[numpy] . identifier[array] ( identifier[r] , identifier[dtype] = literal[string] )
keyword[return]... | def count(self, other, r, attrs=None, info={}):
""" Gray & Moore based fast dual tree counting.
r is the edge of bins:
-inf or r[i-1] < count[i] <= r[i]
attrs: None or tuple
if tuple, attrs = (attr_self, attr_other)
Returns: count,
... |
def get_result(self, client, check):
"""
Returns an event for a given client & result name.
"""
data = self._request('GET', '/results/{}/{}'.format(client, check))
return data.json() | def function[get_result, parameter[self, client, check]]:
constant[
Returns an event for a given client & result name.
]
variable[data] assign[=] call[name[self]._request, parameter[constant[GET], call[constant[/results/{}/{}].format, parameter[name[client], name[check]]]]]
return[ca... | keyword[def] identifier[get_result] ( identifier[self] , identifier[client] , identifier[check] ):
literal[string]
identifier[data] = identifier[self] . identifier[_request] ( literal[string] , literal[string] . identifier[format] ( identifier[client] , identifier[check] ))
keyword[return]... | def get_result(self, client, check):
"""
Returns an event for a given client & result name.
"""
data = self._request('GET', '/results/{}/{}'.format(client, check))
return data.json() |
def has_data(self):
"""Return whether or not the stash has any data available or not."""
if not hasattr(self, '_has_data'):
try:
next(iter(self.delegate.keys()))
self._has_data = True
except StopIteration:
self._has_data = False
... | def function[has_data, parameter[self]]:
constant[Return whether or not the stash has any data available or not.]
if <ast.UnaryOp object at 0x7da1b11c4700> begin[:]
<ast.Try object at 0x7da1b11c4580>
return[name[self]._has_data] | keyword[def] identifier[has_data] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[try] :
identifier[next] ( identifier[iter] ( identifier[self] . identifier[delegate] . identifier[keys... | def has_data(self):
"""Return whether or not the stash has any data available or not."""
if not hasattr(self, '_has_data'):
try:
next(iter(self.delegate.keys()))
self._has_data = True # depends on [control=['try'], data=[]]
except StopIteration:
self._has_dat... |
def listwrap(value):
"""
PERFORMS THE FOLLOWING TRANSLATION
None -> []
value -> [value]
[...] -> [...] (unchanged list)
##MOTIVATION##
OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE,
OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS
TEDIOUS.... | def function[listwrap, parameter[value]]:
constant[
PERFORMS THE FOLLOWING TRANSLATION
None -> []
value -> [value]
[...] -> [...] (unchanged list)
##MOTIVATION##
OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE,
OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH ... | keyword[def] identifier[listwrap] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] == keyword[None] :
keyword[return] identifier[FlatList] ()
keyword[elif] identifier[is_list] ( identifier[value] ):
keyword[return] identifier[wrap] ( identifier[value] )
k... | def listwrap(value):
"""
PERFORMS THE FOLLOWING TRANSLATION
None -> []
value -> [value]
[...] -> [...] (unchanged list)
##MOTIVATION##
OFTEN IT IS NICE TO ALLOW FUNCTION PARAMETERS TO BE ASSIGNED A VALUE,
OR A list-OF-VALUES, OR NULL. CHECKING FOR WHICH THE CALLER USED IS
TEDIOUS.... |
def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... | def function[generate_astrometric_catalog, parameter[imglist]]:
constant[Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images t... | keyword[def] identifier[generate_astrometric_catalog] ( identifier[imglist] ,** identifier[pars] ):
literal[string]
identifier[temp_pars] = identifier[pars] . identifier[copy] ()
keyword[if] identifier[pars] [ literal[string] ]== keyword[True] :
identifier[pars] [ literal[string] ]= lit... | def generate_astrometric_catalog(imglist, **pars):
"""Generates a catalog of all sources from an existing astrometric catalog are in or near the FOVs of the images in
the input list.
Parameters
----------
imglist : list
List of one or more calibrated fits images that will be used for ca... |
def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return QDuelingModel(input_block, backbone, extra_args['action_space']) | def function[instantiate, parameter[self]]:
constant[ Instantiate the model ]
variable[input_block] assign[=] call[name[self].input_block.instantiate, parameter[]]
variable[backbone] assign[=] call[name[self].backbone.instantiate, parameter[]]
return[call[name[QDuelingModel], parameter[name[... | keyword[def] identifier[instantiate] ( identifier[self] ,** identifier[extra_args] ):
literal[string]
identifier[input_block] = identifier[self] . identifier[input_block] . identifier[instantiate] ()
identifier[backbone] = identifier[self] . identifier[backbone] . identifier[instantiate] (... | def instantiate(self, **extra_args):
""" Instantiate the model """
input_block = self.input_block.instantiate()
backbone = self.backbone.instantiate(**extra_args)
return QDuelingModel(input_block, backbone, extra_args['action_space']) |
def cyclic_dt_feat_names(time:bool=True, add_linear:bool=False)->List[str]:
"Return feature names of date/time cycles as produced by `cyclic_dt_features`."
fs = ['cos','sin']
attr = [f'{r}_{f}' for r in 'weekday day_month month_year day_year'.split() for f in fs]
if time: attr += [f'{r}_{f}' for r in 'h... | def function[cyclic_dt_feat_names, parameter[time, add_linear]]:
constant[Return feature names of date/time cycles as produced by `cyclic_dt_features`.]
variable[fs] assign[=] list[[<ast.Constant object at 0x7da1b1dd9ba0>, <ast.Constant object at 0x7da1b1ddafb0>]]
variable[attr] assign[=] <ast.L... | keyword[def] identifier[cyclic_dt_feat_names] ( identifier[time] : identifier[bool] = keyword[True] , identifier[add_linear] : identifier[bool] = keyword[False] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[fs] =[ literal[string] , literal[string] ]
identifier[attr] =[ literal[s... | def cyclic_dt_feat_names(time: bool=True, add_linear: bool=False) -> List[str]:
"""Return feature names of date/time cycles as produced by `cyclic_dt_features`."""
fs = ['cos', 'sin']
attr = [f'{r}_{f}' for r in 'weekday day_month month_year day_year'.split() for f in fs]
if time:
attr += [f'{r}... |
def allowPatternsForNameChecking(self, patternsFunc, patternsClass):
"""
Allow name exceptions by given patterns.
@param patternsFunc: patterns of special function names
@param patternsClass: patterns of special class names
"""
cfgParser = self.linter.cfgfile_parser
... | def function[allowPatternsForNameChecking, parameter[self, patternsFunc, patternsClass]]:
constant[
Allow name exceptions by given patterns.
@param patternsFunc: patterns of special function names
@param patternsClass: patterns of special class names
]
variable[cfgParser... | keyword[def] identifier[allowPatternsForNameChecking] ( identifier[self] , identifier[patternsFunc] , identifier[patternsClass] ):
literal[string]
identifier[cfgParser] = identifier[self] . identifier[linter] . identifier[cfgfile_parser]
identifier[nameChecker] = identifier[self] . identi... | def allowPatternsForNameChecking(self, patternsFunc, patternsClass):
"""
Allow name exceptions by given patterns.
@param patternsFunc: patterns of special function names
@param patternsClass: patterns of special class names
"""
cfgParser = self.linter.cfgfile_parser
nameChec... |
def in_interactive_session():
""" check if we're running in an interactive shell
returns True if running under python/ipython interactive shell
"""
from pandas import get_option
def check_main():
try:
import __main__ as main
except ModuleNotFoundError:
retur... | def function[in_interactive_session, parameter[]]:
constant[ check if we're running in an interactive shell
returns True if running under python/ipython interactive shell
]
from relative_module[pandas] import module[get_option]
def function[check_main, parameter[]]:
<ast.Try object ... | keyword[def] identifier[in_interactive_session] ():
literal[string]
keyword[from] identifier[pandas] keyword[import] identifier[get_option]
keyword[def] identifier[check_main] ():
keyword[try] :
keyword[import] identifier[__main__] keyword[as] identifier[main]
... | def in_interactive_session():
""" check if we're running in an interactive shell
returns True if running under python/ipython interactive shell
"""
from pandas import get_option
def check_main():
try:
import __main__ as main # depends on [control=['try'], data=[]]
exce... |
def Network_setCacheDisabled(self, cacheDisabled):
"""
Function path: Network.setCacheDisabled
Domain: Network
Method name: setCacheDisabled
Parameters:
Required arguments:
'cacheDisabled' (type: boolean) -> Cache disabled state.
No return value.
Description: Toggles ignoring cache for... | def function[Network_setCacheDisabled, parameter[self, cacheDisabled]]:
constant[
Function path: Network.setCacheDisabled
Domain: Network
Method name: setCacheDisabled
Parameters:
Required arguments:
'cacheDisabled' (type: boolean) -> Cache disabled state.
No return value.
Descri... | keyword[def] identifier[Network_setCacheDisabled] ( identifier[self] , identifier[cacheDisabled] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[cacheDisabled] ,( identifier[bool] ,)
), literal[string] % identifier[type] (
identifier[cacheDisabled] )
identifier[subdom_funcs] = i... | def Network_setCacheDisabled(self, cacheDisabled):
"""
Function path: Network.setCacheDisabled
Domain: Network
Method name: setCacheDisabled
Parameters:
Required arguments:
'cacheDisabled' (type: boolean) -> Cache disabled state.
No return value.
Description: Toggles ignoring cache f... |
def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy = "never"):
"""
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interfac... | def function[updateMappingsOnDeviceType, parameter[self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy]]:
constant[
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the app... | keyword[def] identifier[updateMappingsOnDeviceType] ( identifier[self] , identifier[thingTypeId] , identifier[logicalInterfaceId] , identifier[mappingsObject] , identifier[notificationStrategy] = literal[string] ):
literal[string]
identifier[req] = identifier[ApiClient] . identifier[oneThingTypeMap... | def updateMappingsOnDeviceType(self, thingTypeId, logicalInterfaceId, mappingsObject, notificationStrategy='never'):
"""
Add mappings for a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the id of the application interface thes... |
def _parse_resolution(res):
""" Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float
"""
if isinstance(res, str):
return float(res.strip('m'))
if isinstance(res, (int, flo... | def function[_parse_resolution, parameter[res]]:
constant[ Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float
]
if call[name[isinstance], parameter[name[res], name[str]]] begin[:]
r... | keyword[def] identifier[_parse_resolution] ( identifier[res] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[res] , identifier[str] ):
keyword[return] identifier[float] ( identifier[res] . identifier[strip] ( literal[string] ))
keyword[if] identifier[isin... | def _parse_resolution(res):
""" Helper method for parsing given resolution. It will also try to parse a string into float
:return: A float value of resolution
:rtype: float
"""
if isinstance(res, str):
return float(res.strip('m')) # depends on [control=['if'], data=[]]
if i... |
def add_step(self, step, step_id):
""" Add a step to the list. The first step added becomes the initial
step. """
assert step_id not in self._steps
assert step_id not in self._order
assert isinstance(step, Step)
self._steps[step_id] = step
self._order.append(step... | def function[add_step, parameter[self, step, step_id]]:
constant[ Add a step to the list. The first step added becomes the initial
step. ]
assert[compare[name[step_id] <ast.NotIn object at 0x7da2590d7190> name[self]._steps]]
assert[compare[name[step_id] <ast.NotIn object at 0x7da2590d7190> name[... | keyword[def] identifier[add_step] ( identifier[self] , identifier[step] , identifier[step_id] ):
literal[string]
keyword[assert] identifier[step_id] keyword[not] keyword[in] identifier[self] . identifier[_steps]
keyword[assert] identifier[step_id] keyword[not] keyword[in] identifi... | def add_step(self, step, step_id):
""" Add a step to the list. The first step added becomes the initial
step. """
assert step_id not in self._steps
assert step_id not in self._order
assert isinstance(step, Step)
self._steps[step_id] = step
self._order.append(step_id) |
def _readse(self, pos):
"""Return interpretation of next bits as a signed exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
codenum, pos = self._readue(pos)
... | def function[_readse, parameter[self, pos]]:
constant[Return interpretation of next bits as a signed exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
]
<ast.Tuple obje... | keyword[def] identifier[_readse] ( identifier[self] , identifier[pos] ):
literal[string]
identifier[codenum] , identifier[pos] = identifier[self] . identifier[_readue] ( identifier[pos] )
identifier[m] =( identifier[codenum] + literal[int] )// literal[int]
keyword[if] keyword[no... | def _readse(self, pos):
"""Return interpretation of next bits as a signed exponential-Golomb code.
Advances position to after the read code.
Raises ReadError if the end of the bitstring is encountered while
reading the code.
"""
(codenum, pos) = self._readue(pos)
m = (code... |
def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
... | def function[exists, parameter[cls, excludes_]]:
constant[ Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a dat... | keyword[def] identifier[exists] ( identifier[cls] , identifier[excludes_] ,** identifier[filters] ):
literal[string]
identifier[results] = identifier[cls] . identifier[query] . identifier[filter] (** identifier[filters] ). identifier[exclude] (** identifier[excludes_] )
keyword[return] id... | def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
:par... |
def to_dict(self):
"""Returns a dict with the representation of this task configuration object."""
properties = find_class_properties(self.__class__)
config = {
name: self.__getattribute__(name) for name, _ in properties
}
return config | def function[to_dict, parameter[self]]:
constant[Returns a dict with the representation of this task configuration object.]
variable[properties] assign[=] call[name[find_class_properties], parameter[name[self].__class__]]
variable[config] assign[=] <ast.DictComp object at 0x7da20c6a9000>
ret... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
identifier[properties] = identifier[find_class_properties] ( identifier[self] . identifier[__class__] )
identifier[config] ={
identifier[name] : identifier[self] . identifier[__getattribute__] ( identifier[nam... | def to_dict(self):
"""Returns a dict with the representation of this task configuration object."""
properties = find_class_properties(self.__class__)
config = {name: self.__getattribute__(name) for (name, _) in properties}
return config |
def get_selinux_status():
"""
get SELinux status of host
:return: string, one of Enforced, Permissive, Disabled
"""
getenforce_command_exists()
# alternatively, we could read directly from /sys/fs/selinux/{enforce,status}, but status is
# empty (why?) and enforce doesn't tell whether SELinu... | def function[get_selinux_status, parameter[]]:
constant[
get SELinux status of host
:return: string, one of Enforced, Permissive, Disabled
]
call[name[getenforce_command_exists], parameter[]]
variable[o] assign[=] call[call[name[run_cmd], parameter[list[[<ast.Constant object at 0x7d... | keyword[def] identifier[get_selinux_status] ():
literal[string]
identifier[getenforce_command_exists] ()
identifier[o] = identifier[run_cmd] ([ literal[string] ], identifier[return_output] = keyword[True] ). identifier[strip] ()
identifier[logger] . identifier[debug] ( literal[string] ,... | def get_selinux_status():
"""
get SELinux status of host
:return: string, one of Enforced, Permissive, Disabled
"""
getenforce_command_exists()
# alternatively, we could read directly from /sys/fs/selinux/{enforce,status}, but status is
# empty (why?) and enforce doesn't tell whether SELinu... |
def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = (
self.output_parent_dir
+ PyFunceble.OUTPUTS["analytic"]["dir... | def function[_analytic_host_file_directory, parameter[self]]:
constant[
Return the analytic directory to write depending of the matched
status.
]
variable[output_dir] assign[=] binary_operation[name[self].output_parent_dir + call[call[call[name[PyFunceble].OUTPUTS][constant[analy... | keyword[def] identifier[_analytic_host_file_directory] ( identifier[self] ):
literal[string]
identifier[output_dir] =(
identifier[self] . identifier[output_parent_dir]
+ identifier[PyFunceble] . identifier[OUTPUTS] [ literal[string] ][ literal[string] ][ literal[string] ... | def _analytic_host_file_directory(self):
"""
Return the analytic directory to write depending of the matched
status.
"""
# We construct the path to the analytic directory.
output_dir = self.output_parent_dir + PyFunceble.OUTPUTS['analytic']['directories']['parent']
if self.domain... |
def equalizer(self, frequency, width_q, gain_db):
'''Apply a two-pole peaking equalisation (EQ) filter to boost or
reduce around a given frequency.
This effect can be applied multiple times to produce complex EQ curves.
Parameters
----------
frequency : float
... | def function[equalizer, parameter[self, frequency, width_q, gain_db]]:
constant[Apply a two-pole peaking equalisation (EQ) filter to boost or
reduce around a given frequency.
This effect can be applied multiple times to produce complex EQ curves.
Parameters
----------
fr... | keyword[def] identifier[equalizer] ( identifier[self] , identifier[frequency] , identifier[width_q] , identifier[gain_db] ):
literal[string]
keyword[if] keyword[not] identifier[is_number] ( identifier[frequency] ) keyword[or] identifier[frequency] <= literal[int] :
keyword[raise] i... | def equalizer(self, frequency, width_q, gain_db):
"""Apply a two-pole peaking equalisation (EQ) filter to boost or
reduce around a given frequency.
This effect can be applied multiple times to produce complex EQ curves.
Parameters
----------
frequency : float
The... |
def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view["library_tree_view"].get_cursor()[0]
... | def function[_on_remove_library, parameter[self]]:
constant[Callback method handling the removal of an existing library
]
call[call[name[self].view][constant[library_tree_view]].grab_focus, parameter[]]
if call[name[react_to_event], parameter[name[self].view, call[name[self].view][consta... | keyword[def] identifier[_on_remove_library] ( identifier[self] ,* identifier[event] ):
literal[string]
identifier[self] . identifier[view] [ literal[string] ]. identifier[grab_focus] ()
keyword[if] identifier[react_to_event] ( identifier[self] . identifier[view] , identifier[self] . ident... | def _on_remove_library(self, *event):
"""Callback method handling the removal of an existing library
"""
self.view['library_tree_view'].grab_focus()
if react_to_event(self.view, self.view['library_tree_view'], event):
path = self.view['library_tree_view'].get_cursor()[0]
if path is n... |
def exportCertificate(self, certName, outFolder=None):
"""
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
certName - na... | def function[exportCertificate, parameter[self, certName, outFolder]]:
constant[
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
... | keyword[def] identifier[exportCertificate] ( identifier[self] , identifier[certName] , identifier[outFolder] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : literal[string] }
identifier[url] = identifier[self] . identifier[_url] + literal[string] . identifier[for... | def exportCertificate(self, certName, outFolder=None):
"""
This operation downloads an SSL certificate. The file returned by
the server is an X.509 certificate. The downloaded certificate can
be imported into a client that is making HTTP requests.
Inputs:
certName - name o... |
def Vector(self, off):
"""Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
x = off + self.Get(N.UOffsetTFlags, off)
# data starts after metadata containing the ve... | def function[Vector, parameter[self, off]]:
constant[Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object.]
call[name[N].enforce_number, parameter[name[off], name[N].UOffsetTFlags]]
<ast.AugAssign object at 0x7da18fe90b20>
variable[x] ass... | keyword[def] identifier[Vector] ( identifier[self] , identifier[off] ):
literal[string]
identifier[N] . identifier[enforce_number] ( identifier[off] , identifier[N] . identifier[UOffsetTFlags] )
identifier[off] += identifier[self] . identifier[Pos]
identifier[x] = identifier[off... | def Vector(self, off):
"""Vector retrieves the start of data of the vector whose offset is
stored at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
x = off + self.Get(N.UOffsetTFlags, off)
# data starts after metadata containing the vector length
x += ... |
def _load(self):
"""Load the session from the store, by the id from cookie"""
self.session_id = self._session_object.get_session_id()
# protection against session_id tampering
if self.session_id and not self._valid_session_id(self.session_id):
self.session_id = None
... | def function[_load, parameter[self]]:
constant[Load the session from the store, by the id from cookie]
name[self].session_id assign[=] call[name[self]._session_object.get_session_id, parameter[]]
if <ast.BoolOp object at 0x7da1b05d9600> begin[:]
name[self].session_id assign[=] co... | keyword[def] identifier[_load] ( identifier[self] ):
literal[string]
identifier[self] . identifier[session_id] = identifier[self] . identifier[_session_object] . identifier[get_session_id] ()
keyword[if] identifier[self] . identifier[session_id] keyword[and] keyword[not] ide... | def _load(self):
"""Load the session from the store, by the id from cookie"""
self.session_id = self._session_object.get_session_id()
# protection against session_id tampering
if self.session_id and (not self._valid_session_id(self.session_id)):
self.session_id = None # depends on [control=['if... |
def _scaled_int(s):
r"""Convert a 3 byte string to a signed integer value."""
s = bytearray(s) # For Python 2
# Get leftmost bit (sign) as 1 (if 0) or -1 (if 1)
sign = 1 - ((s[0] & 0x80) >> 6)
# Combine remaining bits
int_val = (((s[0] & 0x7f) << 16) | (s[1] << 8) | s[2])
log.debug('Sourc... | def function[_scaled_int, parameter[s]]:
constant[Convert a 3 byte string to a signed integer value.]
variable[s] assign[=] call[name[bytearray], parameter[name[s]]]
variable[sign] assign[=] binary_operation[constant[1] - binary_operation[binary_operation[call[name[s]][constant[0]] <ast.BitAnd o... | keyword[def] identifier[_scaled_int] ( identifier[s] ):
literal[string]
identifier[s] = identifier[bytearray] ( identifier[s] )
identifier[sign] = literal[int] -(( identifier[s] [ literal[int] ]& literal[int] )>> literal[int] )
identifier[int_val] =((( identifier[s] [ literal[int] ]& ... | def _scaled_int(s):
"""Convert a 3 byte string to a signed integer value."""
s = bytearray(s) # For Python 2
# Get leftmost bit (sign) as 1 (if 0) or -1 (if 1)
sign = 1 - ((s[0] & 128) >> 6)
# Combine remaining bits
int_val = (s[0] & 127) << 16 | s[1] << 8 | s[2]
log.debug('Source: %s Int: ... |
def get_top(self):
'''
Returns the high data derived from the top file
'''
tops, errors = self.get_tops()
try:
merged_tops = self.merge_tops(tops)
except TypeError as err:
merged_tops = OrderedDict()
errors.append('Error encountered whi... | def function[get_top, parameter[self]]:
constant[
Returns the high data derived from the top file
]
<ast.Tuple object at 0x7da1b21f1630> assign[=] call[name[self].get_tops, parameter[]]
<ast.Try object at 0x7da18dc9aa10>
return[tuple[[<ast.Name object at 0x7da204623eb0>, <ast.Nam... | keyword[def] identifier[get_top] ( identifier[self] ):
literal[string]
identifier[tops] , identifier[errors] = identifier[self] . identifier[get_tops] ()
keyword[try] :
identifier[merged_tops] = identifier[self] . identifier[merge_tops] ( identifier[tops] )
keyword[ex... | def get_top(self):
"""
Returns the high data derived from the top file
"""
(tops, errors) = self.get_tops()
try:
merged_tops = self.merge_tops(tops) # depends on [control=['try'], data=[]]
except TypeError as err:
merged_tops = OrderedDict()
errors.append('Error ... |
def capitalize_keys(suspect):
"""
:param suspect:
:return new dict with capitalized keys:
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.')
converted = {}
for key in list(suspect):
if not isinstance(key, six.string_types):
continue
... | def function[capitalize_keys, parameter[suspect]]:
constant[
:param suspect:
:return new dict with capitalized keys:
]
if <ast.UnaryOp object at 0x7da18f810190> begin[:]
<ast.Raise object at 0x7da18f8100d0>
variable[converted] assign[=] dictionary[[], []]
for taget[na... | keyword[def] identifier[capitalize_keys] ( identifier[suspect] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[suspect] , identifier[dict] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[converted] ={}
keyword[for] identifier[k... | def capitalize_keys(suspect):
"""
:param suspect:
:return new dict with capitalized keys:
"""
if not isinstance(suspect, dict):
raise TypeError('you must pass a dict.') # depends on [control=['if'], data=[]]
converted = {}
for key in list(suspect):
if not isinstance(key, six... |
def parse(date, dayfirst=True):
'''Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: convert '-' to '?' when used... | def function[parse, parameter[date, dayfirst]]:
constant[Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: co... | keyword[def] identifier[parse] ( identifier[date] , identifier[dayfirst] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[date] :
keyword[return] keyword[None]
keyword[if] identifier[isinstance] ( identifier[date] , identifier[FlexiDate] ):
keyword[return] ... | def parse(date, dayfirst=True):
"""Parse a `date` into a `FlexiDate`.
@param date: the date to parse - may be a string, datetime.date,
datetime.datetime or FlexiDate.
TODO: support for quarters e.g. Q4 1980 or 1954 Q3
TODO: support latin stuff like M.DCC.LIII
TODO: convert '-' to '?' when used... |
def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
... | def function[get_session_info, parameter[self, session]]:
constant[get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.... | keyword[def] identifier[get_session_info] ( identifier[self] , identifier[session] = literal[int] ):
literal[string]
keyword[if] identifier[session] <= literal[int] :
identifier[session] += identifier[self] . identifier[session_number]
identifier[query] = literal[string]
... | def get_session_info(self, session=0):
"""get info about a session
Parameters
----------
session : int
Session number to retrieve. The current session is 0, and negative
numbers count back from current session, so -1 is previous session.
Returns
---... |
def a_send_line(text, ctx):
"""Send text line to the controller followed by `os.linesep`."""
if hasattr(text, '__iter__'):
try:
ctx.ctrl.sendline(text.next())
except StopIteration:
ctx.finished = True
else:
ctx.ctrl.sendline(text)
return True | def function[a_send_line, parameter[text, ctx]]:
constant[Send text line to the controller followed by `os.linesep`.]
if call[name[hasattr], parameter[name[text], constant[__iter__]]] begin[:]
<ast.Try object at 0x7da18eb54160>
return[constant[True]] | keyword[def] identifier[a_send_line] ( identifier[text] , identifier[ctx] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[text] , literal[string] ):
keyword[try] :
identifier[ctx] . identifier[ctrl] . identifier[sendline] ( identifier[text] . identifier[next] ())
... | def a_send_line(text, ctx):
"""Send text line to the controller followed by `os.linesep`."""
if hasattr(text, '__iter__'):
try:
ctx.ctrl.sendline(text.next()) # depends on [control=['try'], data=[]]
except StopIteration:
ctx.finished = True # depends on [control=['excep... |
def serve(request, tail, server):
"""
Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are the context of an application, f... | def function[serve, parameter[request, tail, server]]:
constant[
Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are t... | keyword[def] identifier[serve] ( identifier[request] , identifier[tail] , identifier[server] ):
literal[string]
keyword[if] identifier[request] . identifier[GET] :
identifier[body] = literal[string]
keyword[else] :
keyword[try] :
identifier[body] = identifier[request]... | def serve(request, tail, server):
"""
Django adapter. It has three arguments:
#. ``request`` is a Django request object,
#. ``tail`` is everything that's left from an URL, which adapter is
attached to,
#. ``server`` is a pyws server object.
First two are the context of an application, f... |
def wherenotin(self, fieldname, value):
"""
Logical opposite of `wherein`.
"""
return self.wherein(fieldname, value, negate=True) | def function[wherenotin, parameter[self, fieldname, value]]:
constant[
Logical opposite of `wherein`.
]
return[call[name[self].wherein, parameter[name[fieldname], name[value]]]] | keyword[def] identifier[wherenotin] ( identifier[self] , identifier[fieldname] , identifier[value] ):
literal[string]
keyword[return] identifier[self] . identifier[wherein] ( identifier[fieldname] , identifier[value] , identifier[negate] = keyword[True] ) | def wherenotin(self, fieldname, value):
"""
Logical opposite of `wherein`.
"""
return self.wherein(fieldname, value, negate=True) |
def prepare(session_data={}, #pylint: disable=dangerous-default-value
passphrase=None):
"""
Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _fu... | def function[prepare, parameter[session_data, passphrase]]:
constant[
Returns *session_dict* as a base64 encrypted json string.
The full encrypted text is special crafted to be compatible
with openssl. It can be decrypted with:
$ echo _full_encypted_ | openssl aes-256-cbc -d ... | keyword[def] identifier[prepare] ( identifier[session_data] ={},
identifier[passphrase] = keyword[None] ):
literal[string]
keyword[if] identifier[passphrase] keyword[is] keyword[None] :
identifier[passphrase] = identifier[settings] . identifier[DJAODJIN_SECRET_KEY]
identi... | def prepare(session_data={}, passphrase=None): #pylint: disable=dangerous-default-value
'\n Returns *session_dict* as a base64 encrypted json string.\n\n The full encrypted text is special crafted to be compatible\n with openssl. It can be decrypted with:\n\n $ echo _full_encypted_ | ... |
def hfoslog(*what, **kwargs):
"""Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optional log source, ... | def function[hfoslog, parameter[]]:
constant[Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optio... | keyword[def] identifier[hfoslog] (* identifier[what] ,** identifier[kwargs] ):
literal[string]
keyword[global] identifier[count]
keyword[global] identifier[verbosity]
identifier[count] += literal[int]
identifier[lvl] = identifier[kwargs] . identifier[get] ( literal[string] , ide... | def hfoslog(*what, **kwargs):
"""Logs all *what arguments.
:param *what: Loggable objects (i.e. they have a string representation)
:param lvl: Debug message level
:param exc: Switch to better handle exceptions, use if logging in an
except clause
:param emitter: Optional log source, ... |
def nvmlDeviceGetPowerState(handle):
r"""
/**
* Deprecated: Use \ref nvmlDeviceGetPerformanceState. This function exposes an incorrect generalization.
*
* Retrieve the current performance state for the device.
*
* For Fermi &tm; or newer fully supported devices.
*
* See \ref n... | def function[nvmlDeviceGetPowerState, parameter[handle]]:
constant[
/**
* Deprecated: Use \ref nvmlDeviceGetPerformanceState. This function exposes an incorrect generalization.
*
* Retrieve the current performance state for the device.
*
* For Fermi &tm; or newer fully supported dev... | keyword[def] identifier[nvmlDeviceGetPowerState] ( identifier[handle] ):
literal[string]
identifier[c_pstate] = identifier[_nvmlPstates_t] ()
identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] )
identifier[ret] = identifier[fn] ( identifier[handle] , identifier[byref] ( identi... | def nvmlDeviceGetPowerState(handle):
"""
/**
* Deprecated: Use \\ref nvmlDeviceGetPerformanceState. This function exposes an incorrect generalization.
*
* Retrieve the current performance state for the device.
*
* For Fermi &tm; or newer fully supported devices.
*
* See \\ref ... |
def _validate_error_response_model(self, paths, mods):
'''
Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration
'''
for path, ops in paths:
for opname, opobj in six.iteritems(ops):
... | def function[_validate_error_response_model, parameter[self, paths, mods]]:
constant[
Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration
]
for taget[tuple[[<ast.Name object at 0x7da1b1c16fe0>, <ast.Na... | keyword[def] identifier[_validate_error_response_model] ( identifier[self] , identifier[paths] , identifier[mods] ):
literal[string]
keyword[for] identifier[path] , identifier[ops] keyword[in] identifier[paths] :
keyword[for] identifier[opname] , identifier[opobj] keyword[in] ide... | def _validate_error_response_model(self, paths, mods):
"""
Helper function to help validate the convention established in the swagger file on how
to handle response code mapping/integration
"""
for (path, ops) in paths:
for (opname, opobj) in six.iteritems(ops):
if op... |
def split_camel_case(text) -> list:
"""Splits words from CamelCase text."""
return list(reduce(
lambda a, b: (a + [b] if b.isupper() else a[:-1] + [a[-1] + b]),
text,
[]
)) | def function[split_camel_case, parameter[text]]:
constant[Splits words from CamelCase text.]
return[call[name[list], parameter[call[name[reduce], parameter[<ast.Lambda object at 0x7da2041da200>, name[text], list[[]]]]]]] | keyword[def] identifier[split_camel_case] ( identifier[text] )-> identifier[list] :
literal[string]
keyword[return] identifier[list] ( identifier[reduce] (
keyword[lambda] identifier[a] , identifier[b] :( identifier[a] +[ identifier[b] ] keyword[if] identifier[b] . identifier[isupper] () keyword[el... | def split_camel_case(text) -> list:
"""Splits words from CamelCase text."""
return list(reduce(lambda a, b: a + [b] if b.isupper() else a[:-1] + [a[-1] + b], text, [])) |
def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- serve... | def function[info, parameter[self, section]]:
constant[The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information... | keyword[def] identifier[info] ( identifier[self] , identifier[section] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] ]
keyword[if] identifier[section] :
identifier[cmd] . identifier[append] ( identifier[section] )
keyword[return] identifier[s... | def info(self, section=None):
"""The INFO command returns information and statistics about the server
in a format that is simple to parse by computers and easy to read by
humans.
The optional parameter can be used to select a specific section of
information:
- server: G... |
def from_path(kls, vertices):
"""
Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges.
"""
if vertices.shape[0] == 0:
return PrecomputedSkeleton()
skel = PrecomputedSkeleton(vertices)
edges = np.zeros(shape=(skel.vertices.shape[0] ... | def function[from_path, parameter[kls, vertices]]:
constant[
Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges.
]
if compare[call[name[vertices].shape][constant[0]] equal[==] constant[0]] begin[:]
return[call[name[PrecomputedSke... | keyword[def] identifier[from_path] ( identifier[kls] , identifier[vertices] ):
literal[string]
keyword[if] identifier[vertices] . identifier[shape] [ literal[int] ]== literal[int] :
keyword[return] identifier[PrecomputedSkeleton] ()
identifier[skel] = identifier[PrecomputedSkeleton] ( identi... | def from_path(kls, vertices):
"""
Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges.
"""
if vertices.shape[0] == 0:
return PrecomputedSkeleton() # depends on [control=['if'], data=[]]
skel = PrecomputedSkeleton(vertices)
edges ... |
def map_tqdm(self):
"""
Perform a function on every item while displaying a progress bar.
:return: A list of yielded values
"""
with Pool(self.cpu_count) as pool:
vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))]
... | def function[map_tqdm, parameter[self]]:
constant[
Perform a function on every item while displaying a progress bar.
:return: A list of yielded values
]
with call[name[Pool], parameter[name[self].cpu_count]] begin[:]
variable[vals] assign[=] <ast.ListComp object ... | keyword[def] identifier[map_tqdm] ( identifier[self] ):
literal[string]
keyword[with] identifier[Pool] ( identifier[self] . identifier[cpu_count] ) keyword[as] identifier[pool] :
identifier[vals] =[ identifier[v] keyword[for] identifier[v] keyword[in] identifier[tqdm] ( identifie... | def map_tqdm(self):
"""
Perform a function on every item while displaying a progress bar.
:return: A list of yielded values
"""
with Pool(self.cpu_count) as pool:
vals = [v for v in tqdm(pool.imap_unordered(self._func, self._iterable), total=len(self._iterable))]
pool.cl... |
def report_usage_to_host(host_ip, vmid):
#base value
cpu_usage = 0.0
os_mem_usage = 0.0
task_mem_usage = 0.0
io_usage = 0.0
cpu_usage = get_cpu_usage()
os_mem_usage = get_os_mem_usage()
task_mem_usage = get_task_mem_usage()
io_usage = get_io_usage()
usage = str(vmid.strip())+' | '+str(cpu_usage)+' | '+str... | def function[report_usage_to_host, parameter[host_ip, vmid]]:
variable[cpu_usage] assign[=] constant[0.0]
variable[os_mem_usage] assign[=] constant[0.0]
variable[task_mem_usage] assign[=] constant[0.0]
variable[io_usage] assign[=] constant[0.0]
variable[cpu_usage] assign[=] call[... | keyword[def] identifier[report_usage_to_host] ( identifier[host_ip] , identifier[vmid] ):
identifier[cpu_usage] = literal[int]
identifier[os_mem_usage] = literal[int]
identifier[task_mem_usage] = literal[int]
identifier[io_usage] = literal[int]
identifier[cpu_usage] = identifier[get_cpu_usage] ()
i... | def report_usage_to_host(host_ip, vmid): #base value
cpu_usage = 0.0
os_mem_usage = 0.0
task_mem_usage = 0.0
io_usage = 0.0
cpu_usage = get_cpu_usage()
os_mem_usage = get_os_mem_usage()
task_mem_usage = get_task_mem_usage()
io_usage = get_io_usage()
usage = str(vmid.strip()) + ' | '... |
def _get_expiration(self, headers: dict) -> int:
"""Gets the expiration time of the data from the response headers.
Args:
headers: dictionary of headers from ESI
Returns:
value of seconds from now the data expires
"""
expiration_str = headers.get('expire... | def function[_get_expiration, parameter[self, headers]]:
constant[Gets the expiration time of the data from the response headers.
Args:
headers: dictionary of headers from ESI
Returns:
value of seconds from now the data expires
]
variable[expiration_str]... | keyword[def] identifier[_get_expiration] ( identifier[self] , identifier[headers] : identifier[dict] )-> identifier[int] :
literal[string]
identifier[expiration_str] = identifier[headers] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[expiration_str] :
... | def _get_expiration(self, headers: dict) -> int:
"""Gets the expiration time of the data from the response headers.
Args:
headers: dictionary of headers from ESI
Returns:
value of seconds from now the data expires
"""
expiration_str = headers.get('expires')
... |
def _get_hosts_from_names(self, names):
""" validate hostnames from a list of names
"""
result = set()
hosts = map(lambda x: x.strip(), names.split(','))
for h in hosts:
if valid_hostname(h.split(':')[0]):
result.add(h if ':' in h else '%s:%d' % (h, se... | def function[_get_hosts_from_names, parameter[self, names]]:
constant[ validate hostnames from a list of names
]
variable[result] assign[=] call[name[set], parameter[]]
variable[hosts] assign[=] call[name[map], parameter[<ast.Lambda object at 0x7da18f09d4b0>, call[name[names].split, para... | keyword[def] identifier[_get_hosts_from_names] ( identifier[self] , identifier[names] ):
literal[string]
identifier[result] = identifier[set] ()
identifier[hosts] = identifier[map] ( keyword[lambda] identifier[x] : identifier[x] . identifier[strip] (), identifier[names] . identifier[split... | def _get_hosts_from_names(self, names):
""" validate hostnames from a list of names
"""
result = set()
hosts = map(lambda x: x.strip(), names.split(','))
for h in hosts:
if valid_hostname(h.split(':')[0]):
result.add(h if ':' in h else '%s:%d' % (h, self.PORT)) # depends on ... |
def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
""" Saves just the currently set fields in the database. """
# Backwards compat, deprecated argument
if "dotnotation" in kwargs:
del kwargs["dotnotation"]
if data is None:
data = dotdict... | def function[save_partial, parameter[self, data, allow_protected_fields]]:
constant[ Saves just the currently set fields in the database. ]
if compare[constant[dotnotation] in name[kwargs]] begin[:]
<ast.Delete object at 0x7da1b26a34f0>
if compare[name[data] is constant[None]] begin[:]
... | keyword[def] identifier[save_partial] ( identifier[self] , identifier[data] = keyword[None] , identifier[allow_protected_fields] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
keyword[del] identifier... | def save_partial(self, data=None, allow_protected_fields=False, **kwargs):
""" Saves just the currently set fields in the database. """
# Backwards compat, deprecated argument
if 'dotnotation' in kwargs:
del kwargs['dotnotation'] # depends on [control=['if'], data=['kwargs']]
if data is None:
... |
def run(self, test: unittest.TestSuite):
"""
Given a TestSuite, will create one process per test case whenever possible and run them concurrently.
Will then wait for the result and return them
:param test: the TestSuite to run
:return: a summary of the test run
"""
... | def function[run, parameter[self, test]]:
constant[
Given a TestSuite, will create one process per test case whenever possible and run them concurrently.
Will then wait for the result and return them
:param test: the TestSuite to run
:return: a summary of the test run
]
... | keyword[def] identifier[run] ( identifier[self] , identifier[test] : identifier[unittest] . identifier[TestSuite] ):
literal[string]
identifier[start_time] = identifier[time] . identifier[time] ()
identifier[process] =[]
identifier[resource_manager] = identifier[multiprocessing] .... | def run(self, test: unittest.TestSuite):
"""
Given a TestSuite, will create one process per test case whenever possible and run them concurrently.
Will then wait for the result and return them
:param test: the TestSuite to run
:return: a summary of the test run
"""
start... |
def footer(self):
'''
Returns the axis instance where the footer will be printed
'''
return self.footer_left(on=False), self.footer_center(on=False), \
self.footer_right(on=False) | def function[footer, parameter[self]]:
constant[
Returns the axis instance where the footer will be printed
]
return[tuple[[<ast.Call object at 0x7da1b0eae4d0>, <ast.Call object at 0x7da1b0eae260>, <ast.Call object at 0x7da1b0eae080>]]] | keyword[def] identifier[footer] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[footer_left] ( identifier[on] = keyword[False] ), identifier[self] . identifier[footer_center] ( identifier[on] = keyword[False] ), identifier[self] . identifier[footer_right] ( ide... | def footer(self):
"""
Returns the axis instance where the footer will be printed
"""
return (self.footer_left(on=False), self.footer_center(on=False), self.footer_right(on=False)) |
async def _send_chunk(self, chunk):
"""
Transmit a chunk (no bundling for now).
"""
self.__log_debug('> %s', chunk)
await self.__transport._send_data(serialize_packet(
self._local_port,
self._remote_port,
self._remote_verification_tag,
... | <ast.AsyncFunctionDef object at 0x7da18dc07fd0> | keyword[async] keyword[def] identifier[_send_chunk] ( identifier[self] , identifier[chunk] ):
literal[string]
identifier[self] . identifier[__log_debug] ( literal[string] , identifier[chunk] )
keyword[await] identifier[self] . identifier[__transport] . identifier[_send_data] ( identifier... | async def _send_chunk(self, chunk):
"""
Transmit a chunk (no bundling for now).
"""
self.__log_debug('> %s', chunk)
await self.__transport._send_data(serialize_packet(self._local_port, self._remote_port, self._remote_verification_tag, chunk)) |
def main(*argv,
filesystem=None,
do_exit=True,
stdout=None,
stderr=None):
"""Main method for the cli.
We allow the filesystem to be overridden for test purposes."""
try:
mdcli = MdCLI()
mdcli.filesystem = filesystem
mdcli.stdout = stdout or ... | def function[main, parameter[]]:
constant[Main method for the cli.
We allow the filesystem to be overridden for test purposes.]
<ast.Try object at 0x7da1b2898100> | keyword[def] identifier[main] (* identifier[argv] ,
identifier[filesystem] = keyword[None] ,
identifier[do_exit] = keyword[True] ,
identifier[stdout] = keyword[None] ,
identifier[stderr] = keyword[None] ):
literal[string]
keyword[try] :
identifier[mdcli] = identifier[MdCLI] ()
identif... | def main(*argv, filesystem=None, do_exit=True, stdout=None, stderr=None):
"""Main method for the cli.
We allow the filesystem to be overridden for test purposes."""
try:
mdcli = MdCLI()
mdcli.filesystem = filesystem
mdcli.stdout = stdout or sys.stdout
mdcli.stderr = stderr o... |
def check(text):
"""Check the text."""
err = "misc.illogic"
msg = u"'{}' is illogical."
illogics = [
"preplan",
"more than .{1,10} all",
"appraisal valuations?",
"(?:i|you|he|she|it|y'all|all y'all|you all|they) could care less",
"least worst",
"much-need... | def function[check, parameter[text]]:
constant[Check the text.]
variable[err] assign[=] constant[misc.illogic]
variable[msg] assign[=] constant['{}' is illogical.]
variable[illogics] assign[=] list[[<ast.Constant object at 0x7da1b063abc0>, <ast.Constant object at 0x7da1b063b250>, <ast.Co... | keyword[def] identifier[check] ( identifier[text] ):
literal[string]
identifier[err] = literal[string]
identifier[msg] = literal[string]
identifier[illogics] =[
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[string] ,
literal[strin... | def check(text):
"""Check the text."""
err = 'misc.illogic'
msg = u"'{}' is illogical."
illogics = ['preplan', 'more than .{1,10} all', 'appraisal valuations?', "(?:i|you|he|she|it|y'all|all y'all|you all|they) could care less", 'least worst', 'much-needed gaps?', 'much-needed voids?', 'no longer requir... |
def dcm(self):
"""
Get the DCM
:returns: 3x3 array
"""
if self._dcm is None:
if self._q is not None:
# try to get dcm from q
self._dcm = self._q_to_dcm(self.q)
elif self._euler is not None:
# try to get get ... | def function[dcm, parameter[self]]:
constant[
Get the DCM
:returns: 3x3 array
]
if compare[name[self]._dcm is constant[None]] begin[:]
if compare[name[self]._q is_not constant[None]] begin[:]
name[self]._dcm assign[=] call[name[self]._q_to... | keyword[def] identifier[dcm] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_dcm] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[_q] keyword[is] keyword[not] keyword[None] :
identifier[self] . ... | def dcm(self):
"""
Get the DCM
:returns: 3x3 array
"""
if self._dcm is None:
if self._q is not None:
# try to get dcm from q
self._dcm = self._q_to_dcm(self.q) # depends on [control=['if'], data=[]]
elif self._euler is not None:
# try... |
def setup_Jupyter():
"""
Set up a Jupyter notebook with a few defaults.
"""
sns.set(context = "paper", font = "monospace")
warnings.filterwarnings("ignore")
pd.set_option("display.max_rows", 500)
pd.set_option("display.max_columns", 500)
plt.rcParams["figure.figsize"] = (17, 10) | def function[setup_Jupyter, parameter[]]:
constant[
Set up a Jupyter notebook with a few defaults.
]
call[name[sns].set, parameter[]]
call[name[warnings].filterwarnings, parameter[constant[ignore]]]
call[name[pd].set_option, parameter[constant[display.max_rows], constant[500]]]
... | keyword[def] identifier[setup_Jupyter] ():
literal[string]
identifier[sns] . identifier[set] ( identifier[context] = literal[string] , identifier[font] = literal[string] )
identifier[warnings] . identifier[filterwarnings] ( literal[string] )
identifier[pd] . identifier[set_option] ( literal[strin... | def setup_Jupyter():
"""
Set up a Jupyter notebook with a few defaults.
"""
sns.set(context='paper', font='monospace')
warnings.filterwarnings('ignore')
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
plt.rcParams['figure.figsize'] = (17, 10) |
def report(self, output_file=sys.stdout):
"""Report analysis outcome in human readable form."""
max_perf = self.results['max_perf']
if self._args and self._args.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file)
if self._args and self._args.verbose >=... | def function[report, parameter[self, output_file]]:
constant[Report analysis outcome in human readable form.]
variable[max_perf] assign[=] call[name[self].results][constant[max_perf]]
if <ast.BoolOp object at 0x7da2041db4f0> begin[:]
call[name[print], parameter[call[constant[{}].... | keyword[def] identifier[report] ( identifier[self] , identifier[output_file] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[max_perf] = identifier[self] . identifier[results] [ literal[string] ]
keyword[if] identifier[self] . identifier[_args] keyword[and] identif... | def report(self, output_file=sys.stdout):
"""Report analysis outcome in human readable form."""
max_perf = self.results['max_perf']
if self._args and self._args.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file) # depends on [control=['if'], data=[]]
if self._args and sel... |
def run_step(context):
"""pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
of possible expressions, ... | def function[run_step, parameter[context]]:
constant[pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
... | keyword[def] identifier[run_step] ( identifier[context] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[format_expression] = identifier[context] . identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[format_expression] :
i... | def run_step(context):
"""pypyr step saves current utc datetime to context.
Args:
context: pypyr.context.Context. Mandatory.
The following context key is optional:
- nowUtcIn. str. Datetime formatting expression. For full list
of possible expressions, ... |
def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg':'File deleted at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) | def function[delete, parameter[self, filepath]]:
constant[
Delete the specified file.
]
<ast.Try object at 0x7da2047eb880> | keyword[def] identifier[delete] ( identifier[self] , identifier[filepath] ):
literal[string]
keyword[try] :
identifier[self] . identifier[fs] . identifier[delete] ( identifier[filepath] )
identifier[self] . identifier[write] ({ literal[string] : literal[string] . identifie... | def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg': 'File deleted at {}'.format(filepath)}) # depends on [control=['try'], data=[]]
except OSError:
raise tornado.web.HTTPError(404) # depends on [control=['e... |
def build(self):
"""Build straight helix along z-axis, starting with CA1 on x-axis"""
ang_per_res = (2 * numpy.pi) / self.residues_per_turn
atom_offsets = _atom_offsets[self.helix_type]
if self.handedness == 'l':
handedness = -1
else:
handedness = 1
... | def function[build, parameter[self]]:
constant[Build straight helix along z-axis, starting with CA1 on x-axis]
variable[ang_per_res] assign[=] binary_operation[binary_operation[constant[2] * name[numpy].pi] / name[self].residues_per_turn]
variable[atom_offsets] assign[=] call[name[_atom_offsets]... | keyword[def] identifier[build] ( identifier[self] ):
literal[string]
identifier[ang_per_res] =( literal[int] * identifier[numpy] . identifier[pi] )/ identifier[self] . identifier[residues_per_turn]
identifier[atom_offsets] = identifier[_atom_offsets] [ identifier[self] . identifier[helix_... | def build(self):
"""Build straight helix along z-axis, starting with CA1 on x-axis"""
ang_per_res = 2 * numpy.pi / self.residues_per_turn
atom_offsets = _atom_offsets[self.helix_type]
if self.handedness == 'l':
handedness = -1 # depends on [control=['if'], data=[]]
else:
handedness ... |
def default_indexes(
coords: Mapping[Any, Variable],
dims: Iterable,
) -> 'OrderedDict[Any, pd.Index]':
"""Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
... | def function[default_indexes, parameter[coords, dims]]:
constant[Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
Iterable of dimension names.
Return... | keyword[def] identifier[default_indexes] (
identifier[coords] : identifier[Mapping] [ identifier[Any] , identifier[Variable] ],
identifier[dims] : identifier[Iterable] ,
)-> literal[string] :
literal[string]
keyword[return] identifier[OrderedDict] (( identifier[key] , identifier[coords] [ identifier[key... | def default_indexes(coords: Mapping[Any, Variable], dims: Iterable) -> 'OrderedDict[Any, pd.Index]':
"""Default indexes for a Dataset/DataArray.
Parameters
----------
coords : Mapping[Any, xarray.Variable]
Coordinate variables from which to draw default indexes.
dims : iterable
Itera... |
def scan_line(self, line, regex):
"""Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE)) | def function[scan_line, parameter[self, line, regex]]:
constant[Checks if regex is in line, returns bool]
return[call[name[bool], parameter[call[name[re].search, parameter[name[regex], name[line]]]]]] | keyword[def] identifier[scan_line] ( identifier[self] , identifier[line] , identifier[regex] ):
literal[string]
keyword[return] identifier[bool] ( identifier[re] . identifier[search] ( identifier[regex] , identifier[line] , identifier[flags] = identifier[re] . identifier[IGNORECASE] )) | def scan_line(self, line, regex):
"""Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE)) |
def is_element_in_database(element='', database='ENDF_VII'):
"""will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
... | def function[is_element_in_database, parameter[element, database]]:
constant[will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list... | keyword[def] identifier[is_element_in_database] ( identifier[element] = literal[string] , identifier[database] = literal[string] ):
literal[string]
keyword[if] identifier[element] == literal[string] :
keyword[return] keyword[False]
identifier[list_entry_from_database] = identifier[get_lis... | def is_element_in_database(element='', database='ENDF_VII'):
"""will try to find the element in the folder (database) specified
Parameters:
==========
element: string. Name of the element. Not case sensitive
database: string (default is 'ENDF_VII'). Name of folder that has the list of elements
... |
def _sumterm_prime(lexer):
"""Return a sum term' expression, eliminates left recursion."""
tok = next(lexer)
# '|' XORTERM SUMTERM'
if isinstance(tok, OP_or):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm
... | def function[_sumterm_prime, parameter[lexer]]:
constant[Return a sum term' expression, eliminates left recursion.]
variable[tok] assign[=] call[name[next], parameter[name[lexer]]]
if call[name[isinstance], parameter[name[tok], name[OP_or]]] begin[:]
variable[xorterm] assign[=] c... | keyword[def] identifier[_sumterm_prime] ( identifier[lexer] ):
literal[string]
identifier[tok] = identifier[next] ( identifier[lexer] )
keyword[if] identifier[isinstance] ( identifier[tok] , identifier[OP_or] ):
identifier[xorterm] = identifier[_xorterm] ( identifier[lexer] )
i... | def _sumterm_prime(lexer):
"""Return a sum term' expression, eliminates left recursion."""
tok = next(lexer)
# '|' XORTERM SUMTERM'
if isinstance(tok, OP_or):
xorterm = _xorterm(lexer)
sumterm_prime = _sumterm_prime(lexer)
if sumterm_prime is None:
return xorterm # d... |
def load(self, filename, ctx=None, allow_missing=False,
ignore_extra=False, restore_prefix=''):
"""Load parameters from file.
Parameters
----------
filename : str
Path to parameter file.
ctx : Context or list of Context
Context(s) initialize ... | def function[load, parameter[self, filename, ctx, allow_missing, ignore_extra, restore_prefix]]:
constant[Load parameters from file.
Parameters
----------
filename : str
Path to parameter file.
ctx : Context or list of Context
Context(s) initialize loaded... | keyword[def] identifier[load] ( identifier[self] , identifier[filename] , identifier[ctx] = keyword[None] , identifier[allow_missing] = keyword[False] ,
identifier[ignore_extra] = keyword[False] , identifier[restore_prefix] = literal[string] ):
literal[string]
keyword[if] identifier[restore_prefi... | def load(self, filename, ctx=None, allow_missing=False, ignore_extra=False, restore_prefix=''):
"""Load parameters from file.
Parameters
----------
filename : str
Path to parameter file.
ctx : Context or list of Context
Context(s) initialize loaded parameters... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.