code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def chain_getattr(obj, attr, value=None):
"""Get chain attribute for an object.
"""
try:
return _resolve_value(safe_chain_getattr(obj, attr))
except AttributeError:
return value | def function[chain_getattr, parameter[obj, attr, value]]:
constant[Get chain attribute for an object.
]
<ast.Try object at 0x7da1b0793a00> | keyword[def] identifier[chain_getattr] ( identifier[obj] , identifier[attr] , identifier[value] = keyword[None] ):
literal[string]
keyword[try] :
keyword[return] identifier[_resolve_value] ( identifier[safe_chain_getattr] ( identifier[obj] , identifier[attr] ))
keyword[except] identifier[At... | def chain_getattr(obj, attr, value=None):
"""Get chain attribute for an object.
"""
try:
return _resolve_value(safe_chain_getattr(obj, attr)) # depends on [control=['try'], data=[]]
except AttributeError:
return value # depends on [control=['except'], data=[]] |
async def helo(self, from_host=None):
"""
Sends a SMTP 'HELO' command. - Identifies the client and starts the
session.
If given ``from_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host ... | <ast.AsyncFunctionDef object at 0x7da20c76dea0> | keyword[async] keyword[def] identifier[helo] ( identifier[self] , identifier[from_host] = keyword[None] ):
literal[string]
keyword[if] identifier[from_host] keyword[is] keyword[None] :
identifier[from_host] = identifier[self] . identifier[fqdn]
identifier[code] , identif... | async def helo(self, from_host=None):
"""
Sends a SMTP 'HELO' command. - Identifies the client and starts the
session.
If given ``from_host`` is None, defaults to the client FQDN.
For further details, please check out `RFC 5321 § 4.1.1.1`_.
Args:
from_host (str... |
def _setup_standard_deviations(self, fle):
"""
Reads the standard deviation tables from hdf5 and stores them in
memory
:param fle:
HDF5 Tables as instance of :class:`h5py.File`
"""
# Load in total standard deviation
self.stddevs = {}
self.stdde... | def function[_setup_standard_deviations, parameter[self, fle]]:
constant[
Reads the standard deviation tables from hdf5 and stores them in
memory
:param fle:
HDF5 Tables as instance of :class:`h5py.File`
]
name[self].stddevs assign[=] dictionary[[], []]
... | keyword[def] identifier[_setup_standard_deviations] ( identifier[self] , identifier[fle] ):
literal[string]
identifier[self] . identifier[stddevs] ={}
identifier[self] . identifier[stddevs] [ identifier[const] . identifier[StdDev] . identifier[TOTAL] ]= identifier[hdf_arrays_to_di... | def _setup_standard_deviations(self, fle):
"""
Reads the standard deviation tables from hdf5 and stores them in
memory
:param fle:
HDF5 Tables as instance of :class:`h5py.File`
"""
# Load in total standard deviation
self.stddevs = {}
self.stddevs[const.StdDev.... |
def parse_legacy_argstring(argstring):
'''
Preparses CLI input:
``arg1,arg2`` => ``['arg1', 'arg2']``
``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
'''
argstring = argstring.replace(',', ' , ')
argstring = argstring.replace('[', ' [ ')
argstring = argstring.replace(']', ' ]... | def function[parse_legacy_argstring, parameter[argstring]]:
constant[
Preparses CLI input:
``arg1,arg2`` => ``['arg1', 'arg2']``
``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
]
variable[argstring] assign[=] call[name[argstring].replace, parameter[constant[,], constant[ , ]]]... | keyword[def] identifier[parse_legacy_argstring] ( identifier[argstring] ):
literal[string]
identifier[argstring] = identifier[argstring] . identifier[replace] ( literal[string] , literal[string] )
identifier[argstring] = identifier[argstring] . identifier[replace] ( literal[string] , literal[string] ... | def parse_legacy_argstring(argstring):
"""
Preparses CLI input:
``arg1,arg2`` => ``['arg1', 'arg2']``
``[item1, item2],arg2`` => ``[['item1', 'item2'], arg2]``
"""
argstring = argstring.replace(',', ' , ')
argstring = argstring.replace('[', ' [ ')
argstring = argstring.replace(']', ' ] ... |
def parse_args(self, args, scope):
"""Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError
"""
argu... | def function[parse_args, parameter[self, args, scope]]:
constant[Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxErr... | keyword[def] identifier[parse_args] ( identifier[self] , identifier[args] , identifier[scope] ):
literal[string]
identifier[arguments] = identifier[list] ( identifier[zip] ( identifier[args] ,
[ literal[string] ]* identifier[len] ( identifier[args] ))) keyword[if] identifier[args] keyword... | def parse_args(self, args, scope):
"""Parse arguments to mixin. Add them to scope
as variables. Sets upp special variable @arguments
as well.
args:
args (list): arguments
scope (Scope): current scope
raises:
SyntaxError
"""
arguments = ... |
def start(self, min_nodes=None):
"""
Starts up all the instances in the cloud.
To speed things up, all
instances are started in a seperate thread. To make sure
ElastiCluster is not stopped during creation of an instance, it will
overwrite the sigint handler. As soon as t... | def function[start, parameter[self, min_nodes]]:
constant[
Starts up all the instances in the cloud.
To speed things up, all
instances are started in a seperate thread. To make sure
ElastiCluster is not stopped during creation of an instance, it will
overwrite the sigint... | keyword[def] identifier[start] ( identifier[self] , identifier[min_nodes] = keyword[None] ):
literal[string]
identifier[nodes] = identifier[self] . identifier[get_all_nodes] ()
identifier[log] . identifier[info] ( literal[string] )
keyword[if] identifier[log] . identifier[DO_NO... | def start(self, min_nodes=None):
"""
Starts up all the instances in the cloud.
To speed things up, all
instances are started in a seperate thread. To make sure
ElastiCluster is not stopped during creation of an instance, it will
overwrite the sigint handler. As soon as the l... |
def _csv_temp(self, cursor, fieldnames):
"""Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type f... | def function[_csv_temp, parameter[self, cursor, fieldnames]]:
constant[Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: r... | keyword[def] identifier[_csv_temp] ( identifier[self] , identifier[cursor] , identifier[fieldnames] ):
literal[string]
identifier[temp_fd] , identifier[temp_path] = identifier[tempfile] . identifier[mkstemp] ( identifier[text] = keyword[True] )
keyword[with] identifier[open] ( identifier[... | def _csv_temp(self, cursor, fieldnames):
"""Writes the rows of `cursor` in CSV format to a temporary file and
returns the path to that file.
:param cursor: database cursor containing data to be output
:type cursor: `sqlite3.Cursor`
:param fieldnames: row headings
:type field... |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the ObtainLease response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting ... | def function[read, parameter[self, input_stream, kmip_version]]:
constant[
Read the data encoding the ObtainLease response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting ... | keyword[def] identifier[read] ( identifier[self] , identifier[input_stream] , identifier[kmip_version] = identifier[enums] . identifier[KMIPVersion] . identifier[KMIP_1_0] ):
literal[string]
identifier[super] ( identifier[ObtainLeaseResponsePayload] , identifier[self] ). identifier[read] (
... | def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the ObtainLease response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a re... |
def list_metering_label_rules(self, retrieve_all=True, **_params):
"""Fetches a list of all metering label rules for a label."""
return self.list('metering_label_rules',
self.metering_label_rules_path, retrieve_all,
**_params) | def function[list_metering_label_rules, parameter[self, retrieve_all]]:
constant[Fetches a list of all metering label rules for a label.]
return[call[name[self].list, parameter[constant[metering_label_rules], name[self].metering_label_rules_path, name[retrieve_all]]]] | keyword[def] identifier[list_metering_label_rules] ( identifier[self] , identifier[retrieve_all] = keyword[True] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[list] ( literal[string] ,
identifier[self] . identifier[metering_label_rules_path] , id... | def list_metering_label_rules(self, retrieve_all=True, **_params):
"""Fetches a list of all metering label rules for a label."""
return self.list('metering_label_rules', self.metering_label_rules_path, retrieve_all, **_params) |
def create_action(self):
"""Create actions related to channel selection."""
actions = {}
act = QAction('Load Montage...', self)
act.triggered.connect(self.load_channels)
act.setEnabled(False)
actions['load_channels'] = act
act = QAction('Save Montage...', self)
... | def function[create_action, parameter[self]]:
constant[Create actions related to channel selection.]
variable[actions] assign[=] dictionary[[], []]
variable[act] assign[=] call[name[QAction], parameter[constant[Load Montage...], name[self]]]
call[name[act].triggered.connect, parameter[na... | keyword[def] identifier[create_action] ( identifier[self] ):
literal[string]
identifier[actions] ={}
identifier[act] = identifier[QAction] ( literal[string] , identifier[self] )
identifier[act] . identifier[triggered] . identifier[connect] ( identifier[self] . identifier[load_cha... | def create_action(self):
"""Create actions related to channel selection."""
actions = {}
act = QAction('Load Montage...', self)
act.triggered.connect(self.load_channels)
act.setEnabled(False)
actions['load_channels'] = act
act = QAction('Save Montage...', self)
act.triggered.connect(self... |
def run(cls, row, reader):
""" Invoke the CSV parser on an individual row
The row should already be a dict from the CSV reader.
The reader is passed in so we can easily reference the
CSV document headers & line number when generating
errors.
"""
cls._parse_keys(... | def function[run, parameter[cls, row, reader]]:
constant[ Invoke the CSV parser on an individual row
The row should already be a dict from the CSV reader.
The reader is passed in so we can easily reference the
CSV document headers & line number when generating
errors.
]
... | keyword[def] identifier[run] ( identifier[cls] , identifier[row] , identifier[reader] ):
literal[string]
identifier[cls] . identifier[_parse_keys] ( identifier[row] , identifier[reader] . identifier[line_num] )
identifier[cls] . identifier[_parse_relationships] ( identifier[row] , identif... | def run(cls, row, reader):
""" Invoke the CSV parser on an individual row
The row should already be a dict from the CSV reader.
The reader is passed in so we can easily reference the
CSV document headers & line number when generating
errors.
"""
cls._parse_keys(row, read... |
def delete(self, **kwargs):
"""Deletes a member from a license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
access the REST inte... | def function[delete, parameter[self]]:
constant[Deletes a member from a license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
acc... | keyword[def] identifier[delete] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[kwargs] :
identifier[delete_uri] = identifier[self] . identifier[_meta_data] [ literal[string] ]
... | def delete(self, **kwargs):
"""Deletes a member from a license pool
You need to be careful with this method. When you use it, and it
succeeds on the remote BIG-IP, the configuration of the BIG-IP
will be reloaded. During this process, you will not be able to
access the REST interfac... |
def handle(client_message, handle_event_member=None, handle_event_member_list=None, handle_event_member_attribute_change=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_MEMBER and handle_event_member is not None:
member = MemberC... | def function[handle, parameter[client_message, handle_event_member, handle_event_member_list, handle_event_member_attribute_change, to_object]]:
constant[ Event handler ]
variable[message_type] assign[=] call[name[client_message].get_message_type, parameter[]]
if <ast.BoolOp object at 0x7da1b16a... | keyword[def] identifier[handle] ( identifier[client_message] , identifier[handle_event_member] = keyword[None] , identifier[handle_event_member_list] = keyword[None] , identifier[handle_event_member_attribute_change] = keyword[None] , identifier[to_object] = keyword[None] ):
literal[string]
identifier[mess... | def handle(client_message, handle_event_member=None, handle_event_member_list=None, handle_event_member_attribute_change=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_MEMBER and handle_event_member is not None:
member = MemberC... |
def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
'''
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bas... | def function[file_dict, parameter[]]:
constant[
List the files that belong to a package, grouped by package. Not
specifying any packages will return a list of _every_ file on the system's
package database (not generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' pkg... | keyword[def] identifier[file_dict] (* identifier[packages] ,** identifier[kwargs] ):
literal[string]
identifier[errors] =[]
identifier[ret] ={}
identifier[cmd_files] =[ literal[string] , literal[string] ]
keyword[if] keyword[not] identifier[packages] :
identifier[packages] = iden... | def file_dict(*packages, **kwargs): # pylint: disable=unused-argument
"\n List the files that belong to a package, grouped by package. Not\n specifying any packages will return a list of _every_ file on the system's\n package database (not generally recommended).\n\n CLI Examples:\n\n .. code-block:... |
def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(
klass_node.locals_type.values()
):
for node in association_n... | def function[get_associated, parameter[self, klass_node, level]]:
constant[return associated nodes of a class node]
if compare[name[level] equal[==] constant[0]] begin[:]
return[None]
for taget[name[association_nodes]] in starred[binary_operation[call[name[list], parameter[call[name[klas... | keyword[def] identifier[get_associated] ( identifier[self] , identifier[klass_node] , identifier[level] ):
literal[string]
keyword[if] identifier[level] == literal[int] :
keyword[return]
keyword[for] identifier[association_nodes] keyword[in] identifier[list] ( identifier[... | def get_associated(self, klass_node, level):
"""return associated nodes of a class node"""
if level == 0:
return # depends on [control=['if'], data=[]]
for association_nodes in list(klass_node.instance_attrs_type.values()) + list(klass_node.locals_type.values()):
for node in association_nod... |
def _get_names(names, types):
"""
Get names, bearing in mind that there might be no name,
no type, and that the `:` separator might be wrongly used.
"""
if types == "":
try:
names, types = names.split(":")
except:
pass
return names.split(","), types | def function[_get_names, parameter[names, types]]:
constant[
Get names, bearing in mind that there might be no name,
no type, and that the `:` separator might be wrongly used.
]
if compare[name[types] equal[==] constant[]] begin[:]
<ast.Try object at 0x7da2041d88b0>
return[tuple[... | keyword[def] identifier[_get_names] ( identifier[names] , identifier[types] ):
literal[string]
keyword[if] identifier[types] == literal[string] :
keyword[try] :
identifier[names] , identifier[types] = identifier[names] . identifier[split] ( literal[string] )
keyword[except] ... | def _get_names(names, types):
"""
Get names, bearing in mind that there might be no name,
no type, and that the `:` separator might be wrongly used.
"""
if types == '':
try:
(names, types) = names.split(':') # depends on [control=['try'], data=[]]
except:
pas... |
def format_unitary(mat, decimals=None):
"""Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
... | def function[format_unitary, parameter[mat, decimals]]:
constant[Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no roundi... | keyword[def] identifier[format_unitary] ( identifier[mat] , identifier[decimals] = keyword[None] ):
literal[string]
identifier[num_basis] = identifier[len] ( identifier[mat] )
identifier[mat_complex] = identifier[np] . identifier[zeros] (( identifier[num_basis] , identifier[num_basis] ), identifier[dt... | def format_unitary(mat, decimals=None):
"""Format unitary coming from the backend to present to the Qiskit user.
Args:
mat (list[list]): a list of list of [re, im] complex numbers
decimals (int): the number of decimals in the statevector.
If None, no rounding is done.
Returns:
... |
def messages(fp, key='@message'):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message").
"""
for line in lines(fp):
... | def function[messages, parameter[fp, key]]:
constant[
Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message").
]
f... | keyword[def] identifier[messages] ( identifier[fp] , identifier[key] = literal[string] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[lines] ( identifier[fp] ):
identifier[txt] = identifier[line] . identifier[rstrip] ( literal[string] )
keyword[yield] { identif... | def messages(fp, key='@message'):
"""
Read lines of UTF-8 from the file-like object given in ``fp``, with the
same fault-tolerance as :function:`tagalog.io.lines`, but instead yield
dicts with the line data stored in the key given by ``key`` (default:
"@message").
"""
for line in lines(fp):
... |
def com_google_fonts_check_metadata_nameid_copyright(ttFont, font_metadata):
"""Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ?"""
failed = False
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncoding())
i... | def function[com_google_fonts_check_metadata_nameid_copyright, parameter[ttFont, font_metadata]]:
constant[Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ?]
variable[failed] assign[=] constant[False]
for taget[name[nameRecord]] in starred... | keyword[def] identifier[com_google_fonts_check_metadata_nameid_copyright] ( identifier[ttFont] , identifier[font_metadata] ):
literal[string]
identifier[failed] = keyword[False]
keyword[for] identifier[nameRecord] keyword[in] identifier[ttFont] [ literal[string] ]. identifier[names] :
identifier[st... | def com_google_fonts_check_metadata_nameid_copyright(ttFont, font_metadata):
"""Copyright field for this font on METADATA.pb matches
all copyright notice entries on the name table ?"""
failed = False
for nameRecord in ttFont['name'].names:
string = nameRecord.string.decode(nameRecord.getEncodin... |
def cpp_flag(compiler):
"""Return the -std=c++[0x/11/14] compiler flag.
The c++14 is preferred over c++0x/11 (when it is available).
"""
standards = ['-std=c++14', '-std=c++11', '-std=c++0x']
for standard in standards:
if has_flag(compiler, [standard]):
return standard
raise ... | def function[cpp_flag, parameter[compiler]]:
constant[Return the -std=c++[0x/11/14] compiler flag.
The c++14 is preferred over c++0x/11 (when it is available).
]
variable[standards] assign[=] list[[<ast.Constant object at 0x7da20c7c98a0>, <ast.Constant object at 0x7da20c7cb130>, <ast.Constant ob... | keyword[def] identifier[cpp_flag] ( identifier[compiler] ):
literal[string]
identifier[standards] =[ literal[string] , literal[string] , literal[string] ]
keyword[for] identifier[standard] keyword[in] identifier[standards] :
keyword[if] identifier[has_flag] ( identifier[compiler] ,[ ident... | def cpp_flag(compiler):
"""Return the -std=c++[0x/11/14] compiler flag.
The c++14 is preferred over c++0x/11 (when it is available).
"""
standards = ['-std=c++14', '-std=c++11', '-std=c++0x']
for standard in standards:
if has_flag(compiler, [standard]):
return standard # depends... |
def _node_add_without_peer_leaflist(self, node_sum, child_other):
'''_node_add_without_peer_leaflist
Low-level api: Apply delta child_other to node_sum when there is no peer
of child_other can be found under node_sum. child_other is a leaf-list
node. Element node_sum will be modified du... | def function[_node_add_without_peer_leaflist, parameter[self, node_sum, child_other]]:
constant[_node_add_without_peer_leaflist
Low-level api: Apply delta child_other to node_sum when there is no peer
of child_other can be found under node_sum. child_other is a leaf-list
node. Element n... | keyword[def] identifier[_node_add_without_peer_leaflist] ( identifier[self] , identifier[node_sum] , identifier[child_other] ):
literal[string]
identifier[s_node] = identifier[self] . identifier[device] . identifier[get_schema_node] ( identifier[child_other] )
identifier[e] = identifier[d... | def _node_add_without_peer_leaflist(self, node_sum, child_other):
"""_node_add_without_peer_leaflist
Low-level api: Apply delta child_other to node_sum when there is no peer
of child_other can be found under node_sum. child_other is a leaf-list
node. Element node_sum will be modified during... |
def compute_best_path(local_asn, path1, path2):
"""Compares given paths and returns best path.
Parameters:
-`local_asn`: asn of local bgpspeaker
-`path1`: first path to compare
-`path2`: second path to compare
Best path processing will involve following steps:
1. Select a path... | def function[compute_best_path, parameter[local_asn, path1, path2]]:
constant[Compares given paths and returns best path.
Parameters:
-`local_asn`: asn of local bgpspeaker
-`path1`: first path to compare
-`path2`: second path to compare
Best path processing will involve followi... | keyword[def] identifier[compute_best_path] ( identifier[local_asn] , identifier[path1] , identifier[path2] ):
literal[string]
identifier[best_path] = keyword[None]
identifier[best_path_reason] = identifier[BPR_UNKNOWN]
keyword[if] identifier[best_path] keyword[is] keyword[None] :
... | def compute_best_path(local_asn, path1, path2):
"""Compares given paths and returns best path.
Parameters:
-`local_asn`: asn of local bgpspeaker
-`path1`: first path to compare
-`path2`: second path to compare
Best path processing will involve following steps:
1. Select a path... |
def sh_report(self, full=True, latest=False):
"""
Show shell command necessary to clone this repository
If there is no primary remote url, prefix-comment the command
Keyword Arguments:
full (bool): also include commands to recreate branches and remotes
latest (b... | def function[sh_report, parameter[self, full, latest]]:
constant[
Show shell command necessary to clone this repository
If there is no primary remote url, prefix-comment the command
Keyword Arguments:
full (bool): also include commands to recreate branches and remotes
... | keyword[def] identifier[sh_report] ( identifier[self] , identifier[full] = keyword[True] , identifier[latest] = keyword[False] ):
literal[string]
keyword[def] identifier[pathvar_repr] ( identifier[var] ):
identifier[_var] = identifier[var] . identifier[replace] ( literal[string] , li... | def sh_report(self, full=True, latest=False):
"""
Show shell command necessary to clone this repository
If there is no primary remote url, prefix-comment the command
Keyword Arguments:
full (bool): also include commands to recreate branches and remotes
latest (bool)... |
def register_list(self):
"""Returns a list of the indices for the CPU registers.
The returned indices can be used to read the register content or grab
the register name.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of registers.
"""
... | def function[register_list, parameter[self]]:
constant[Returns a list of the indices for the CPU registers.
The returned indices can be used to read the register content or grab
the register name.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of ... | keyword[def] identifier[register_list] ( identifier[self] ):
literal[string]
identifier[num_items] = identifier[self] . identifier[MAX_NUM_CPU_REGISTERS]
identifier[buf] =( identifier[ctypes] . identifier[c_uint32] * identifier[num_items] )()
identifier[num_regs] = identifier[sel... | def register_list(self):
"""Returns a list of the indices for the CPU registers.
The returned indices can be used to read the register content or grab
the register name.
Args:
self (JLink): the ``JLink`` instance
Returns:
List of registers.
"""
num_... |
def selenium(self):
"""Get the instance of webdriver, it starts the browser if the
webdriver is not yet instantied
:return: a `selenium instance <http://selenium-python.readthedocs.org/
api.html#module-selenium.webdriver.remote.webdriver>`
"""
if not self._web_driver:
... | def function[selenium, parameter[self]]:
constant[Get the instance of webdriver, it starts the browser if the
webdriver is not yet instantied
:return: a `selenium instance <http://selenium-python.readthedocs.org/
api.html#module-selenium.webdriver.remote.webdriver>`
]
if... | keyword[def] identifier[selenium] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_web_driver] :
identifier[self] . identifier[_web_driver] = identifier[self] . identifier[_start_driver] ()
keyword[return] identifier[self] . iden... | def selenium(self):
"""Get the instance of webdriver, it starts the browser if the
webdriver is not yet instantied
:return: a `selenium instance <http://selenium-python.readthedocs.org/
api.html#module-selenium.webdriver.remote.webdriver>`
"""
if not self._web_driver:
se... |
def statistical_inefficiency(X, truncate_acf=True):
""" Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I... | def function[statistical_inefficiency, parameter[X, truncate_acf]]:
constant[ Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statist... | keyword[def] identifier[statistical_inefficiency] ( identifier[X] , identifier[truncate_acf] = keyword[True] ):
literal[string]
keyword[assert] identifier[np] . identifier[ndim] ( identifier[X] [ literal[int] ])== literal[int] , literal[string]
identifier[N] = identifier[_maxlength] ( identifie... | def statistical_inefficiency(X, truncate_acf=True):
""" Estimates the statistical inefficiency from univariate time series X
The statistical inefficiency [1]_ is a measure of the correlatedness of samples in a signal.
Given a signal :math:`{x_t}` with :math:`N` samples and statistical inefficiency :math:`I... |
def yticks(self):
"""Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular"""
return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4) | def function[yticks, parameter[self]]:
constant[Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular]
return[call[name[np].linspace, parameter[call[name[np].min, parameter[call[name[self]][tuple[[<ast.Slice object at 0x7da20cabc400>, <ast.Constant object at 0... | keyword[def] identifier[yticks] ( identifier[self] ):
literal[string]
keyword[return] identifier[np] . identifier[linspace] ( identifier[np] . identifier[min] ( identifier[self] [:, literal[int] ]), identifier[np] . identifier[max] ( identifier[self] [:, literal[int] ]), literal[int] ) | def yticks(self):
"""Compute the yticks labels of this grid, used for plotting the y-axis ticks when visualizing a regular"""
return np.linspace(np.min(self[:, 0]), np.max(self[:, 0]), 4) |
def instruction_list(self):
"""Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
"""
instruction_list = []
for instruction in self.data:
if isinstance(instruction, CompositeGat... | def function[instruction_list, parameter[self]]:
constant[Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
]
variable[instruction_list] assign[=] list[[]]
for taget[name[instruction]] in ... | keyword[def] identifier[instruction_list] ( identifier[self] ):
literal[string]
identifier[instruction_list] =[]
keyword[for] identifier[instruction] keyword[in] identifier[self] . identifier[data] :
keyword[if] identifier[isinstance] ( identifier[instruction] , identifier... | def instruction_list(self):
"""Return a list of instructions for this CompositeGate.
If the CompositeGate itself contains composites, call
this method recursively.
"""
instruction_list = []
for instruction in self.data:
if isinstance(instruction, CompositeGate):
... |
def _update_crypto(self):
"""
根据当前配置内容更新 Crypto 类
"""
if self.__encrypt_mode in ['compatible', 'safe'] and self.__encoding_aes_key is not None:
if self.__token is None or self.__appid is None:
raise NeedParamError('Please provide token and appid parameters in ... | def function[_update_crypto, parameter[self]]:
constant[
根据当前配置内容更新 Crypto 类
]
if <ast.BoolOp object at 0x7da2054a6c80> begin[:]
if <ast.BoolOp object at 0x7da2054a5c90> begin[:]
<ast.Raise object at 0x7da2054a6470>
name[self].__crypto assign[=... | keyword[def] identifier[_update_crypto] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__encrypt_mode] keyword[in] [ literal[string] , literal[string] ] keyword[and] identifier[self] . identifier[__encoding_aes_key] keyword[is] keyword[not] keyword[None] :
... | def _update_crypto(self):
"""
根据当前配置内容更新 Crypto 类
"""
if self.__encrypt_mode in ['compatible', 'safe'] and self.__encoding_aes_key is not None:
if self.__token is None or self.__appid is None:
raise NeedParamError('Please provide token and appid parameters in the construction... |
def feature_detector(self, tokens, index, history):
"""Implementing a slightly modified feature detector.
@param tokens: The tokens from the sentence to tag.
@param index: The current token index to tag.
@param history: The previous tagged tokens.
"""
word = tokens[index... | def function[feature_detector, parameter[self, tokens, index, history]]:
constant[Implementing a slightly modified feature detector.
@param tokens: The tokens from the sentence to tag.
@param index: The current token index to tag.
@param history: The previous tagged tokens.
]
... | keyword[def] identifier[feature_detector] ( identifier[self] , identifier[tokens] , identifier[index] , identifier[history] ):
literal[string]
identifier[word] = identifier[tokens] [ identifier[index] ]
keyword[if] identifier[index] == literal[int] :
identifier[prevword] = i... | def feature_detector(self, tokens, index, history):
"""Implementing a slightly modified feature detector.
@param tokens: The tokens from the sentence to tag.
@param index: The current token index to tag.
@param history: The previous tagged tokens.
"""
word = tokens[index]
if ... |
def __expire_files(self):
"""Because files are always unclean"""
self.__files = OrderedDict(
item for item in self.__files.items() if not item[1].expired
) | def function[__expire_files, parameter[self]]:
constant[Because files are always unclean]
name[self].__files assign[=] call[name[OrderedDict], parameter[<ast.GeneratorExp object at 0x7da2046219c0>]] | keyword[def] identifier[__expire_files] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__files] = identifier[OrderedDict] (
identifier[item] keyword[for] identifier[item] keyword[in] identifier[self] . identifier[__files] . identifier[items] () keyword[if] keywor... | def __expire_files(self):
"""Because files are always unclean"""
self.__files = OrderedDict((item for item in self.__files.items() if not item[1].expired)) |
def _remove_deactivated(contexts):
"""Remove deactivated handlers from the chain"""
# Clean ctx handlers
stack_contexts = tuple([h for h in contexts[0] if h.active])
# Find new head
head = contexts[1]
while head is not None and not head.active:
head = head.old_contexts[1]
# Process... | def function[_remove_deactivated, parameter[contexts]]:
constant[Remove deactivated handlers from the chain]
variable[stack_contexts] assign[=] call[name[tuple], parameter[<ast.ListComp object at 0x7da18c4ce6e0>]]
variable[head] assign[=] call[name[contexts]][constant[1]]
while <ast.Bool... | keyword[def] identifier[_remove_deactivated] ( identifier[contexts] ):
literal[string]
identifier[stack_contexts] = identifier[tuple] ([ identifier[h] keyword[for] identifier[h] keyword[in] identifier[contexts] [ literal[int] ] keyword[if] identifier[h] . identifier[active] ])
identifi... | def _remove_deactivated(contexts):
"""Remove deactivated handlers from the chain"""
# Clean ctx handlers
stack_contexts = tuple([h for h in contexts[0] if h.active])
# Find new head
head = contexts[1]
while head is not None and (not head.active):
head = head.old_contexts[1] # depends on... |
def from_columns(columns, columns_to_ignore=None):
"""
Creates a mapping from kind names to fc_parameters objects
(which are itself mappings from feature calculators to settings)
to extract only the features contained in the columns.
To do so, for every feature name in columns this method
1. sp... | def function[from_columns, parameter[columns, columns_to_ignore]]:
constant[
Creates a mapping from kind names to fc_parameters objects
(which are itself mappings from feature calculators to settings)
to extract only the features contained in the columns.
To do so, for every feature name in colu... | keyword[def] identifier[from_columns] ( identifier[columns] , identifier[columns_to_ignore] = keyword[None] ):
literal[string]
identifier[kind_to_fc_parameters] ={}
keyword[if] identifier[columns_to_ignore] keyword[is] keyword[None] :
identifier[columns_to_ignore] =[]
keyword[for] ... | def from_columns(columns, columns_to_ignore=None):
"""
Creates a mapping from kind names to fc_parameters objects
(which are itself mappings from feature calculators to settings)
to extract only the features contained in the columns.
To do so, for every feature name in columns this method
1. sp... |
def _pstore32(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:]
I = int(offset)
if I >= 0:
... | def function[_pstore32, parameter[ins]]:
constant[ Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
]
variable[value] assign[=] call[name[ins].quad][constant[2]]
variable[offset] assign[=] call[name[ins].quad][constant[1]]
... | keyword[def] identifier[_pstore32] ( identifier[ins] ):
literal[string]
identifier[value] = identifier[ins] . identifier[quad] [ literal[int] ]
identifier[offset] = identifier[ins] . identifier[quad] [ literal[int] ]
identifier[indirect] = identifier[offset] [ literal[int] ]== literal[string]
... | def _pstore32(ins):
""" Stores 2nd parameter at stack pointer (SP) + X, being
X 1st parameter.
1st operand must be a SIGNED integer.
"""
value = ins.quad[2]
offset = ins.quad[1]
indirect = offset[0] == '*'
if indirect:
offset = offset[1:] # depends on [control=['if'], data=[]]
... |
def element_screen_center(self, element):
"""
:returns: The center point of the element.
:rtype: class:`dict` with the field "left" set to the X
coordinate and the field "top" set to the Y
coordinate.
"""
pos = self.element_screen_position(element... | def function[element_screen_center, parameter[self, element]]:
constant[
:returns: The center point of the element.
:rtype: class:`dict` with the field "left" set to the X
coordinate and the field "top" set to the Y
coordinate.
]
variable[pos] ass... | keyword[def] identifier[element_screen_center] ( identifier[self] , identifier[element] ):
literal[string]
identifier[pos] = identifier[self] . identifier[element_screen_position] ( identifier[element] )
identifier[size] = identifier[element] . identifier[size]
identifier[pos] [ ... | def element_screen_center(self, element):
"""
:returns: The center point of the element.
:rtype: class:`dict` with the field "left" set to the X
coordinate and the field "top" set to the Y
coordinate.
"""
pos = self.element_screen_position(element)
si... |
def add_sparse_covariance_matrix(self,x,y,names,iidx,jidx,data):
"""build a pyemu.SparseMatrix instance implied by Vario2d
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
names... | def function[add_sparse_covariance_matrix, parameter[self, x, y, names, iidx, jidx, data]]:
constant[build a pyemu.SparseMatrix instance implied by Vario2d
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-co... | keyword[def] identifier[add_sparse_covariance_matrix] ( identifier[self] , identifier[x] , identifier[y] , identifier[names] , identifier[iidx] , identifier[jidx] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[x] , identifier[np] . identifier[n... | def add_sparse_covariance_matrix(self, x, y, names, iidx, jidx, data):
"""build a pyemu.SparseMatrix instance implied by Vario2d
Parameters
----------
x : (iterable of floats)
x-coordinate locations
y : (iterable of floats)
y-coordinate locations
name... |
def get_input(prompt, default=None, exit_msg='bye!'):
"""
Reads stdin, exits with a message if interrupted, EOF, or a quit message.
:return: The entered input. Converts to an integer if possible.
:rtype: ``str`` or ``int``
"""
try:
response = six.moves.input(prompt)
except (Keyboard... | def function[get_input, parameter[prompt, default, exit_msg]]:
constant[
Reads stdin, exits with a message if interrupted, EOF, or a quit message.
:return: The entered input. Converts to an integer if possible.
:rtype: ``str`` or ``int``
]
<ast.Try object at 0x7da18fe90550>
<ast.Try obj... | keyword[def] identifier[get_input] ( identifier[prompt] , identifier[default] = keyword[None] , identifier[exit_msg] = literal[string] ):
literal[string]
keyword[try] :
identifier[response] = identifier[six] . identifier[moves] . identifier[input] ( identifier[prompt] )
keyword[except] ( iden... | def get_input(prompt, default=None, exit_msg='bye!'):
"""
Reads stdin, exits with a message if interrupted, EOF, or a quit message.
:return: The entered input. Converts to an integer if possible.
:rtype: ``str`` or ``int``
"""
try:
response = six.moves.input(prompt) # depends on [contr... |
def _unpack_case(self, case):
""" Returns the contents of the case to be used in the OPF.
"""
base_mva = case.base_mva
b = case.connected_buses
l = case.online_branches
g = case.online_generators
nb = len(b)
nl = len(l)
ng = len(g)
return ... | def function[_unpack_case, parameter[self, case]]:
constant[ Returns the contents of the case to be used in the OPF.
]
variable[base_mva] assign[=] name[case].base_mva
variable[b] assign[=] name[case].connected_buses
variable[l] assign[=] name[case].online_branches
variab... | keyword[def] identifier[_unpack_case] ( identifier[self] , identifier[case] ):
literal[string]
identifier[base_mva] = identifier[case] . identifier[base_mva]
identifier[b] = identifier[case] . identifier[connected_buses]
identifier[l] = identifier[case] . identifier[online_branc... | def _unpack_case(self, case):
""" Returns the contents of the case to be used in the OPF.
"""
base_mva = case.base_mva
b = case.connected_buses
l = case.online_branches
g = case.online_generators
nb = len(b)
nl = len(l)
ng = len(g)
return (b, l, g, nb, nl, ng, base_mva) |
def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats,
stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Ten... | def function[_batch_norm_op, parameter[self, input_batch, mean, variance, use_batch_stats, stat_dtype]]:
constant[Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A... | keyword[def] identifier[_batch_norm_op] ( identifier[self] , identifier[input_batch] , identifier[mean] , identifier[variance] , identifier[use_batch_stats] ,
identifier[stat_dtype] ):
literal[string]
keyword[if] identifier[self] . identifier[_fused] :
identifier[batch_norm_op] , id... | def _batch_norm_op(self, input_batch, mean, variance, use_batch_stats, stat_dtype):
"""Creates a batch normalization op.
It uses the tf.nn.batch_normalization op by default and the
tf.nn.fused_batch_norm op to support fused batch normalization.
Args:
input_batch: A input Tensor of arbitrary dime... |
def load_character_images(self, verbose=True):
"""
Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.
:return: (Pillow.Image.Image, string) tuples
"""
for dataset in self.character_sets:
assert self.get_data... | def function[load_character_images, parameter[self, verbose]]:
constant[
Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.
:return: (Pillow.Image.Image, string) tuples
]
for taget[name[dataset]] in starred[name[self].c... | keyword[def] identifier[load_character_images] ( identifier[self] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[for] identifier[dataset] keyword[in] identifier[self] . identifier[character_sets] :
keyword[assert] identifier[self] . identifier[get_dataset] ( ident... | def load_character_images(self, verbose=True):
"""
Generator to load all images in the dataset. Yields (image, character) pairs until all images have been loaded.
:return: (Pillow.Image.Image, string) tuples
"""
for dataset in self.character_sets:
assert self.get_dataset(dataset)... |
def _to_epoch(self, ts):
"""
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
"""
year = self.year
tmpts = "%s %s" % (ts, str(self.year))
new_tim... | def function[_to_epoch, parameter[self, ts]]:
constant[
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
]
variable[year] assign[=] name[self].year
variab... | keyword[def] identifier[_to_epoch] ( identifier[self] , identifier[ts] ):
literal[string]
identifier[year] = identifier[self] . identifier[year]
identifier[tmpts] = literal[string] %( identifier[ts] , identifier[str] ( identifier[self] . identifier[year] ))
identifier[new_time] ... | def _to_epoch(self, ts):
"""
Adds a year to the syslog timestamp because syslog doesn't use years
:param ts: The timestamp to add a year to
:return: Date/time string that includes a year
"""
year = self.year
tmpts = '%s %s' % (ts, str(self.year))
new_time = int(calendar.... |
def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value
else:
return None | def function[PythonPercentFormat, parameter[format_str]]:
constant[Use Python % format strings as template format specifiers.]
if call[name[format_str].startswith, parameter[constant[printf ]]] begin[:]
variable[fmt] assign[=] call[name[format_str]][<ast.Slice object at 0x7da18f00ed40>]
... | keyword[def] identifier[PythonPercentFormat] ( identifier[format_str] ):
literal[string]
keyword[if] identifier[format_str] . identifier[startswith] ( literal[string] ):
identifier[fmt] = identifier[format_str] [ identifier[len] ( literal[string] ):]
keyword[return] keyword[lambda] identifier[val... | def PythonPercentFormat(format_str):
"""Use Python % format strings as template format specifiers."""
if format_str.startswith('printf '):
fmt = format_str[len('printf '):]
return lambda value: fmt % value # depends on [control=['if'], data=[]]
else:
return None |
def _append_value(self, v_values, next_value, v_idx=None, n_vals=1):
"""Update a list of parsed values with a new value."""
for _ in range(n_vals):
if v_idx:
try:
v_i = next(v_idx)
except StopIteration:
# Repeating comma... | def function[_append_value, parameter[self, v_values, next_value, v_idx, n_vals]]:
constant[Update a list of parsed values with a new value.]
for taget[name[_]] in starred[call[name[range], parameter[name[n_vals]]]] begin[:]
if name[v_idx] begin[:]
<ast.Try object at 0x7da1b0... | keyword[def] identifier[_append_value] ( identifier[self] , identifier[v_values] , identifier[next_value] , identifier[v_idx] = keyword[None] , identifier[n_vals] = literal[int] ):
literal[string]
keyword[for] identifier[_] keyword[in] identifier[range] ( identifier[n_vals] ):
keywo... | def _append_value(self, v_values, next_value, v_idx=None, n_vals=1):
"""Update a list of parsed values with a new value."""
for _ in range(n_vals):
if v_idx:
try:
v_i = next(v_idx) # depends on [control=['try'], data=[]]
except StopIteration:
# Re... |
def get_latex_maybe_optional_arg(s, pos, **parse_flags):
"""
Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if
success, otherwise returns None.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead.
"""
return Latex... | def function[get_latex_maybe_optional_arg, parameter[s, pos]]:
constant[
Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if
success, otherwise returns None.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead.
]
... | keyword[def] identifier[get_latex_maybe_optional_arg] ( identifier[s] , identifier[pos] ,** identifier[parse_flags] ):
literal[string]
keyword[return] identifier[LatexWalker] ( identifier[s] ,** identifier[parse_flags] ). identifier[get_latex_maybe_optional_arg] ( identifier[pos] = identifier[pos] ) | def get_latex_maybe_optional_arg(s, pos, **parse_flags):
"""
Attempts to parse an optional argument. Returns a tuple `(groupnode, pos, len)` if
success, otherwise returns None.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_maybe_optional_arg()` instead.
"""
return LatexW... |
def command_ack_send(self, command, result, force_mavlink1=False):
'''
Report status of a command. Includes feedback wether the command was
executed.
command : Command ID, as defined by MAV_CMD enum. (uint16_t)
result ... | def function[command_ack_send, parameter[self, command, result, force_mavlink1]]:
constant[
Report status of a command. Includes feedback wether the command was
executed.
command : Command ID, as defined by MAV_CMD enum. (uint16_t)
... | keyword[def] identifier[command_ack_send] ( identifier[self] , identifier[command] , identifier[result] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[send] ( identifier[self] . identifier[command_ack_encode] ( identif... | def command_ack_send(self, command, result, force_mavlink1=False):
"""
Report status of a command. Includes feedback wether the command was
executed.
command : Command ID, as defined by MAV_CMD enum. (uint16_t)
result ... |
def get_instances(self):
"""
Returns the members of the LazyDict
"""
if self._update_members: self.update()
return iter(sorted(self.members.iteritems())) | def function[get_instances, parameter[self]]:
constant[
Returns the members of the LazyDict
]
if name[self]._update_members begin[:]
call[name[self].update, parameter[]]
return[call[name[iter], parameter[call[name[sorted], parameter[call[name[self].members.iteritems, ... | keyword[def] identifier[get_instances] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_update_members] : identifier[self] . identifier[update] ()
keyword[return] identifier[iter] ( identifier[sorted] ( identifier[self] . identifier[members] . identifier[i... | def get_instances(self):
"""
Returns the members of the LazyDict
"""
if self._update_members:
self.update() # depends on [control=['if'], data=[]]
return iter(sorted(self.members.iteritems())) |
def get_families(data_dir=None):
'''Return a list of all basis set families'''
data_dir = fix_data_dir(data_dir)
metadata = get_metadata(data_dir)
families = set()
for v in metadata.values():
families.add(v['family'])
return sorted(list(families)) | def function[get_families, parameter[data_dir]]:
constant[Return a list of all basis set families]
variable[data_dir] assign[=] call[name[fix_data_dir], parameter[name[data_dir]]]
variable[metadata] assign[=] call[name[get_metadata], parameter[name[data_dir]]]
variable[families] assign[=... | keyword[def] identifier[get_families] ( identifier[data_dir] = keyword[None] ):
literal[string]
identifier[data_dir] = identifier[fix_data_dir] ( identifier[data_dir] )
identifier[metadata] = identifier[get_metadata] ( identifier[data_dir] )
identifier[families] = identifier[set] ()
keyword... | def get_families(data_dir=None):
"""Return a list of all basis set families"""
data_dir = fix_data_dir(data_dir)
metadata = get_metadata(data_dir)
families = set()
for v in metadata.values():
families.add(v['family']) # depends on [control=['for'], data=['v']]
return sorted(list(familie... |
def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options,
json=True, **options)
return _run_in_fresh_loop(req) | def function[json_request, parameter[endpoint, verb, session_options]]:
constant[Like :func:`molotov.request` but extracts json from the response.
]
variable[req] assign[=] call[name[functools].partial, parameter[name[_request], name[endpoint], name[verb], name[session_options]]]
return[call[nam... | keyword[def] identifier[json_request] ( identifier[endpoint] , identifier[verb] = literal[string] , identifier[session_options] = keyword[None] ,** identifier[options] ):
literal[string]
identifier[req] = identifier[functools] . identifier[partial] ( identifier[_request] , identifier[endpoint] , identifier... | def json_request(endpoint, verb='GET', session_options=None, **options):
"""Like :func:`molotov.request` but extracts json from the response.
"""
req = functools.partial(_request, endpoint, verb, session_options, json=True, **options)
return _run_in_fresh_loop(req) |
def algorithm(G, method_name, **kwargs):
"""
Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the
:class:`.GraphCollection` ``G``.
For options, see the `list of algorithms
<http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_... | def function[algorithm, parameter[G, method_name]]:
constant[
Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the
:class:`.GraphCollection` ``G``.
For options, see the `list of algorithms
<http://networkx.github.io/documentation/networkx-1.9/referen... | keyword[def] identifier[algorithm] ( identifier[G] , identifier[method_name] ,** identifier[kwargs] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[string] ,
identifier[DeprecationWarning] )
keyword[return] identifier[G] . identifier[analyze] ( identifier[method_name] ,** i... | def algorithm(G, method_name, **kwargs):
"""
Apply a ``method`` from NetworkX to all :ref:`networkx.Graph <networkx:graph>` objects in the
:class:`.GraphCollection` ``G``.
For options, see the `list of algorithms
<http://networkx.github.io/documentation/networkx-1.9/reference/algorithms.html>`_... |
def get_annotations(self):
'''
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering().
'''
... | def function[get_annotations, parameter[self]]:
constant[
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering()... | keyword[def] identifier[get_annotations] ( identifier[self] ):
literal[string]
identifier[rule] = identifier[getConstant] ( literal[string] )
identifier[annotations] ={
literal[string] : identifier[Case] ( identifier[default_value] = keyword[None] , identifier[outp... | def get_annotations(self):
"""
This method gets the annotations for the queryset. Unlike get_ordering() below, it
passes the actual Case() and F() objects that will be evaluated with the queryset, returned
in a dictionary that is compatible with get_ordering().
"""
rule = getCon... |
def detect_with_url(
self, url, return_face_id=True, return_face_landmarks=False, return_face_attributes=None, recognition_model="recognition_01", return_recognition_model=False, custom_headers=None, raw=False, **operation_config):
"""Detect human faces in an image, return face rectangles, and optio... | def function[detect_with_url, parameter[self, url, return_face_id, return_face_landmarks, return_face_attributes, recognition_model, return_recognition_model, custom_headers, raw]]:
constant[Detect human faces in an image, return face rectangles, and optionally
with faceIds, landmarks, and attributes.<b... | keyword[def] identifier[detect_with_url] (
identifier[self] , identifier[url] , identifier[return_face_id] = keyword[True] , identifier[return_face_landmarks] = keyword[False] , identifier[return_face_attributes] = keyword[None] , identifier[recognition_model] = literal[string] , identifier[return_recognition_model]... | def detect_with_url(self, url, return_face_id=True, return_face_landmarks=False, return_face_attributes=None, recognition_model='recognition_01', return_recognition_model=False, custom_headers=None, raw=False, **operation_config):
"""Detect human faces in an image, return face rectangles, and optionally
wit... |
def execute(self, portfolio_name=None):
"""
Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
Raises
-... | def function[execute, parameter[self, portfolio_name]]:
constant[
Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
... | keyword[def] identifier[execute] ( identifier[self] , identifier[portfolio_name] = keyword[None] ):
literal[string]
keyword[assert] identifier[self] . identifier[order_id] == literal[int] , literal[string]
keyword[assert] identifier[len] ( identifier[self] . identifier[loans] )> literal... | def execute(self, portfolio_name=None):
"""
Place the order with LendingClub
Parameters
----------
portfolio_name : string
The name of the portfolio to add the invested loan notes to.
This can be a new or existing portfolio name.
Raises
-----... |
def read_loom(filename: PathLike, sparse: bool = True, cleanup: bool = False, X_name: str = 'spliced',
obs_names: str = 'CellID', var_names: str = 'Gene', dtype: str='float32', **kwargs) -> AnnData:
"""Read ``.loom``-formatted hdf5 file.
This reads the whole file into memory.
Beware that you... | def function[read_loom, parameter[filename, sparse, cleanup, X_name, obs_names, var_names, dtype]]:
constant[Read ``.loom``-formatted hdf5 file.
This reads the whole file into memory.
Beware that you have to explicitly state when you want to read the file as
sparse data.
Parameters
------... | keyword[def] identifier[read_loom] ( identifier[filename] : identifier[PathLike] , identifier[sparse] : identifier[bool] = keyword[True] , identifier[cleanup] : identifier[bool] = keyword[False] , identifier[X_name] : identifier[str] = literal[string] ,
identifier[obs_names] : identifier[str] = literal[string] , ide... | def read_loom(filename: PathLike, sparse: bool=True, cleanup: bool=False, X_name: str='spliced', obs_names: str='CellID', var_names: str='Gene', dtype: str='float32', **kwargs) -> AnnData:
"""Read ``.loom``-formatted hdf5 file.
This reads the whole file into memory.
Beware that you have to explicitly stat... |
def get_engine_from_session(dbsession: Session) -> Engine:
"""
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
"""
engine = dbsession.bind
assert isinstance(engine, Engine)
return engine | def function[get_engine_from_session, parameter[dbsession]]:
constant[
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
]
variable[engine] assign[=] name[dbsession].bind
assert[call[name[isinstance], parameter[name[engine], name[Engine]]]]
return[name[engine]] | keyword[def] identifier[get_engine_from_session] ( identifier[dbsession] : identifier[Session] )-> identifier[Engine] :
literal[string]
identifier[engine] = identifier[dbsession] . identifier[bind]
keyword[assert] identifier[isinstance] ( identifier[engine] , identifier[Engine] )
keyword[return... | def get_engine_from_session(dbsession: Session) -> Engine:
"""
Gets the SQLAlchemy :class:`Engine` from a SQLAlchemy :class:`Session`.
"""
engine = dbsession.bind
assert isinstance(engine, Engine)
return engine |
def run(self, arguments=None):
"""
Parse the logfile.
Ask each filter if it accepts the line. It will only be printed if all
filters accept the line.
"""
# add arguments from filter classes before calling superclass run
for f in self.filters:
for fa i... | def function[run, parameter[self, arguments]]:
constant[
Parse the logfile.
Ask each filter if it accepts the line. It will only be printed if all
filters accept the line.
]
for taget[name[f]] in starred[name[self].filters] begin[:]
for taget[name[fa]] in... | keyword[def] identifier[run] ( identifier[self] , identifier[arguments] = keyword[None] ):
literal[string]
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[filters] :
keyword[for] identifier[fa] keyword[in] identifier[f] . identifier[filterArgs] :
... | def run(self, arguments=None):
"""
Parse the logfile.
Ask each filter if it accepts the line. It will only be printed if all
filters accept the line.
"""
# add arguments from filter classes before calling superclass run
for f in self.filters:
for fa in f.filterArgs:
... |
def check_causatives(self, case_obj=None, institute_obj=None):
"""Check if there are any variants that are previously marked causative
Loop through all variants that are marked 'causative' for an
institute and check if any of the variants are present in the
current case.
... | def function[check_causatives, parameter[self, case_obj, institute_obj]]:
constant[Check if there are any variants that are previously marked causative
Loop through all variants that are marked 'causative' for an
institute and check if any of the variants are present in the
... | keyword[def] identifier[check_causatives] ( identifier[self] , identifier[case_obj] = keyword[None] , identifier[institute_obj] = keyword[None] ):
literal[string]
identifier[institute_id] = identifier[case_obj] [ literal[string] ] keyword[if] identifier[case_obj] keyword[else] identifier[institu... | def check_causatives(self, case_obj=None, institute_obj=None):
"""Check if there are any variants that are previously marked causative
Loop through all variants that are marked 'causative' for an
institute and check if any of the variants are present in the
current case.
... |
def current_version(self, object, relations_as_of=None, check_db=False):
"""
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so ... | def function[current_version, parameter[self, object, relations_as_of, check_db]]:
constant[
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'... | keyword[def] identifier[current_version] ( identifier[self] , identifier[object] , identifier[relations_as_of] = keyword[None] , identifier[check_db] = keyword[False] ):
literal[string]
keyword[if] identifier[object] . identifier[version_end_date] keyword[is] keyword[None] keyword[and] keyword... | def current_version(self, object, relations_as_of=None, check_db=False):
"""
Return the current version of the given object.
The current version is the one having its version_end_date set to NULL.
If there is not such a version then it means the object has been
'deleted' and so ther... |
def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Volume Header Descriptor.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Header... | def function[new, parameter[self]]:
constant[
A method to create a new UDF Logical Volume Header Descriptor.
Parameters:
None.
Returns:
Nothing.
]
if name[self]._initialized begin[:]
<ast.Raise object at 0x7da1b0f0d8a0>
name[self].unique... | keyword[def] identifier[new] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] )
identifier[self] . identifier[unique_id] = litera... | def new(self):
# type: () -> None
'\n A method to create a new UDF Logical Volume Header Descriptor.\n\n Parameters:\n None.\n Returns:\n Nothing.\n '
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Header Descriptor a... |
def bed(args):
"""
%prog fasta map.out
Convert MSTMAP output into bed format.
"""
p = OptionParser(bed.__doc__)
p.add_option("--switch", default=False, action="store_true",
help="Switch reference and aligned map elements [default: %default]")
opts, args = p.parse_args(args)... | def function[bed, parameter[args]]:
constant[
%prog fasta map.out
Convert MSTMAP output into bed format.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[bed].__doc__]]
call[name[p].add_option, parameter[constant[--switch]]]
<ast.Tuple object at 0x7da1b0900640... | keyword[def] identifier[bed] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[bed] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = keyword[False] , identifier[action] = literal[string] ,
identifier... | def bed(args):
"""
%prog fasta map.out
Convert MSTMAP output into bed format.
"""
p = OptionParser(bed.__doc__)
p.add_option('--switch', default=False, action='store_true', help='Switch reference and aligned map elements [default: %default]')
(opts, args) = p.parse_args(args)
if len(arg... |
def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'''
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.... | def function[add_lock, parameter[packages, root]]:
constant[
Add a package lock. Specify packages to lock by exact name.
root
operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.add_lock <package name>
salt '*' pkg.add_lock <package1>... | keyword[def] identifier[add_lock] ( identifier[packages] , identifier[root] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[salt] . identifier[utils] . identifier[versions] . identifier[warn_until] ( literal[string] , literal[string] )
identifier[locks] = identifier[list_locks] ( ... | def add_lock(packages, root=None, **kwargs): # pylint: disable=unused-argument
'\n Add a package lock. Specify packages to lock by exact name.\n\n root\n operate on a different root directory.\n\n CLI Example:\n\n .. code-block:: bash\n\n salt \'*\' pkg.add_lock <package name>\n sa... |
def atlas_find_missing_zonefile_availability( peer_table=None, con=None, path=None, missing_zonefile_info=None ):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... | def function[atlas_find_missing_zonefile_availability, parameter[peer_table, con, path, missing_zonefile_info]]:
constant[
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missin... | keyword[def] identifier[atlas_find_missing_zonefile_availability] ( identifier[peer_table] = keyword[None] , identifier[con] = keyword[None] , identifier[path] = keyword[None] , identifier[missing_zonefile_info] = keyword[None] ):
literal[string]
identifier[bit_offset] = literal[int]
identifier... | def atlas_find_missing_zonefile_availability(peer_table=None, con=None, path=None, missing_zonefile_info=None):
"""
Find the set of missing zonefiles, as well as their popularity amongst
our neighbors.
Only consider zonefiles that are known by at least
one peer; otherwise they're missing from
... |
def atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=None, con=None, path=None):
"""
Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_st... | def function[atlasdb_get_zonefiles_by_hash, parameter[zonefile_hash, block_height, con, path]]:
constant[
Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present'... | keyword[def] identifier[atlasdb_get_zonefiles_by_hash] ( identifier[zonefile_hash] , identifier[block_height] = keyword[None] , identifier[con] = keyword[None] , identifier[path] = keyword[None] ):
literal[string]
keyword[with] identifier[AtlasDBOpen] ( identifier[con] = identifier[con] , identifier[path]... | def atlasdb_get_zonefiles_by_hash(zonefile_hash, block_height=None, con=None, path=None):
"""
Find all instances of this zone file in the atlasdb.
Optionally filter on block height
Returns [{'name': ..., 'zonefile_hash': ..., 'txid': ..., 'inv_index': ..., 'block_height': ..., 'present': ..., 'tried_st... |
def SetWriteBack(self, filename):
"""Sets the config file which will receive any modifications.
The main config file can be made writable, but directing all Set()
operations into a secondary location. This secondary location will
receive any updates and will override the options for this file.
Arg... | def function[SetWriteBack, parameter[self, filename]]:
constant[Sets the config file which will receive any modifications.
The main config file can be made writable, but directing all Set()
operations into a secondary location. This secondary location will
receive any updates and will override the ... | keyword[def] identifier[SetWriteBack] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[try] :
identifier[self] . identifier[writeback] = identifier[self] . identifier[LoadSecondaryConfig] ( identifier[filename] )
identifier[self] . identifier[MergeData] ( identifier[self] ... | def SetWriteBack(self, filename):
"""Sets the config file which will receive any modifications.
The main config file can be made writable, but directing all Set()
operations into a secondary location. This secondary location will
receive any updates and will override the options for this file.
Arg... |
def alignPronunciations(pronI, pronA):
'''
Align the phones in two pronunciations
'''
# First prep the two pronunctions
pronI = [char for char in pronI]
pronA = [char for char in pronA]
# Remove any elements not in the other list (but maintain order)
pronITmp = pronI
pronAT... | def function[alignPronunciations, parameter[pronI, pronA]]:
constant[
Align the phones in two pronunciations
]
variable[pronI] assign[=] <ast.ListComp object at 0x7da18f00f3d0>
variable[pronA] assign[=] <ast.ListComp object at 0x7da18f00cca0>
variable[pronITmp] assign[=] name[pro... | keyword[def] identifier[alignPronunciations] ( identifier[pronI] , identifier[pronA] ):
literal[string]
identifier[pronI] =[ identifier[char] keyword[for] identifier[char] keyword[in] identifier[pronI] ]
identifier[pronA] =[ identifier[char] keyword[for] identifier[char] keyword[in] iden... | def alignPronunciations(pronI, pronA):
"""
Align the phones in two pronunciations
"""
# First prep the two pronunctions
pronI = [char for char in pronI]
pronA = [char for char in pronA]
# Remove any elements not in the other list (but maintain order)
pronITmp = pronI
pronATmp = pronA... |
def setproctitle(text):
"""
This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The module is described here: https://... | def function[setproctitle, parameter[text]]:
constant[
This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The mod... | keyword[def] identifier[setproctitle] ( identifier[text] ):
literal[string]
keyword[try] :
keyword[import] identifier[setproctitle]
keyword[except] identifier[Exception] keyword[as] identifier[e] :
keyword[return] keyword[None]
keyword[else] :
identifier[prev] = ... | def setproctitle(text):
"""
This is a wrapper for setproctitle.setproctitle(). The call sets
'text' as the new process title and returns the previous value.
The module is commonly not installed. If missing, nothing is changed,
and the call returns None.
The module is described here: https://... |
def extract_chm (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CHM archive."""
return [cmd, os.path.abspath(archive), outdir] | def function[extract_chm, parameter[archive, compression, cmd, verbosity, interactive, outdir]]:
constant[Extract a CHM archive.]
return[list[[<ast.Name object at 0x7da1b07ad7e0>, <ast.Call object at 0x7da1b07af730>, <ast.Name object at 0x7da1b07aca30>]]] | keyword[def] identifier[extract_chm] ( identifier[archive] , identifier[compression] , identifier[cmd] , identifier[verbosity] , identifier[interactive] , identifier[outdir] ):
literal[string]
keyword[return] [ identifier[cmd] , identifier[os] . identifier[path] . identifier[abspath] ( identifier[archive] ... | def extract_chm(archive, compression, cmd, verbosity, interactive, outdir):
"""Extract a CHM archive."""
return [cmd, os.path.abspath(archive), outdir] |
def rgb_to_hsl(r, g=None, b=None):
"""Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360],... | def function[rgb_to_hsl, parameter[r, g, b]]:
constant[Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the... | keyword[def] identifier[rgb_to_hsl] ( identifier[r] , identifier[g] = keyword[None] , identifier[b] = keyword[None] ):
literal[string]
keyword[if] identifier[type] ( identifier[r] ) keyword[in] [ identifier[list] , identifier[tuple] ]:
identifier[r] , identifier[g] , identifier[b] = identifier[r]
id... | def rgb_to_hsl(r, g=None, b=None):
"""Convert the color from RGB coordinates to HSL.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
The color as an (h, s, l) tuple in the range:
h[0...360... |
def ucs_manager_connect(self, ucsm_ip):
"""Connects to a UCS Manager."""
if not self.ucsmsdk:
self.ucsmsdk = self._import_ucsmsdk()
ucsm = CONF.ml2_cisco_ucsm.ucsms.get(ucsm_ip)
if not ucsm or not ucsm.ucsm_username or not ucsm.ucsm_password:
LOG.error('UCS Mana... | def function[ucs_manager_connect, parameter[self, ucsm_ip]]:
constant[Connects to a UCS Manager.]
if <ast.UnaryOp object at 0x7da1b1a5e0b0> begin[:]
name[self].ucsmsdk assign[=] call[name[self]._import_ucsmsdk, parameter[]]
variable[ucsm] assign[=] call[name[CONF].ml2_cisco_ucsm.... | keyword[def] identifier[ucs_manager_connect] ( identifier[self] , identifier[ucsm_ip] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[ucsmsdk] :
identifier[self] . identifier[ucsmsdk] = identifier[self] . identifier[_import_ucsmsdk] ()
identifier[u... | def ucs_manager_connect(self, ucsm_ip):
"""Connects to a UCS Manager."""
if not self.ucsmsdk:
self.ucsmsdk = self._import_ucsmsdk() # depends on [control=['if'], data=[]]
ucsm = CONF.ml2_cisco_ucsm.ucsms.get(ucsm_ip)
if not ucsm or not ucsm.ucsm_username or (not ucsm.ucsm_password):
LOG... |
def F(self, value):
"""State Transition matrix"""
self._F = value
self._F_inv = self.inv(self._F) | def function[F, parameter[self, value]]:
constant[State Transition matrix]
name[self]._F assign[=] name[value]
name[self]._F_inv assign[=] call[name[self].inv, parameter[name[self]._F]] | keyword[def] identifier[F] ( identifier[self] , identifier[value] ):
literal[string]
identifier[self] . identifier[_F] = identifier[value]
identifier[self] . identifier[_F_inv] = identifier[self] . identifier[inv] ( identifier[self] . identifier[_F] ) | def F(self, value):
"""State Transition matrix"""
self._F = value
self._F_inv = self.inv(self._F) |
def get_labels(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number/labels <http://developer.github.com/v3/issues/labels>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Label.Label`
"""
return github.PaginatedList.PaginatedList(
github.L... | def function[get_labels, parameter[self]]:
constant[
:calls: `GET /repos/:owner/:repo/issues/:number/labels <http://developer.github.com/v3/issues/labels>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Label.Label`
]
return[call[name[github].PaginatedList.Pag... | keyword[def] identifier[get_labels] ( identifier[self] ):
literal[string]
keyword[return] identifier[github] . identifier[PaginatedList] . identifier[PaginatedList] (
identifier[github] . identifier[Label] . identifier[Label] ,
identifier[self] . identifier[_requester] ,
... | def get_labels(self):
"""
:calls: `GET /repos/:owner/:repo/issues/:number/labels <http://developer.github.com/v3/issues/labels>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Label.Label`
"""
return github.PaginatedList.PaginatedList(github.Label.Label, self._req... |
def init(plugindirs=[]):
"""Initialize the plugin framework"""
# initialize the builtin plugins
from .translators import yang,yin,dsdl
yang.pyang_plugin_init()
yin.pyang_plugin_init()
dsdl.pyang_plugin_init()
# initialize installed plugins
for ep in pkg_resources.iter_entry_points(grou... | def function[init, parameter[plugindirs]]:
constant[Initialize the plugin framework]
from relative_module[translators] import module[yang], module[yin], module[dsdl]
call[name[yang].pyang_plugin_init, parameter[]]
call[name[yin].pyang_plugin_init, parameter[]]
call[name[dsdl].pyang_p... | keyword[def] identifier[init] ( identifier[plugindirs] =[]):
literal[string]
keyword[from] . identifier[translators] keyword[import] identifier[yang] , identifier[yin] , identifier[dsdl]
identifier[yang] . identifier[pyang_plugin_init] ()
identifier[yin] . identifier[pyang_plugin_init] (... | def init(plugindirs=[]):
"""Initialize the plugin framework"""
# initialize the builtin plugins
from .translators import yang, yin, dsdl
yang.pyang_plugin_init()
yin.pyang_plugin_init()
dsdl.pyang_plugin_init()
# initialize installed plugins
for ep in pkg_resources.iter_entry_points(grou... |
def set_palette_name(self, palette_name):
"""If the given palette matches an existing one, shows it in the
combobox
"""
combo = self.get_widget('palette_name')
found = False
log.debug("wanting palette: %r", palette_name)
for i in combo.get_model():
if ... | def function[set_palette_name, parameter[self, palette_name]]:
constant[If the given palette matches an existing one, shows it in the
combobox
]
variable[combo] assign[=] call[name[self].get_widget, parameter[constant[palette_name]]]
variable[found] assign[=] constant[False]
... | keyword[def] identifier[set_palette_name] ( identifier[self] , identifier[palette_name] ):
literal[string]
identifier[combo] = identifier[self] . identifier[get_widget] ( literal[string] )
identifier[found] = keyword[False]
identifier[log] . identifier[debug] ( literal[string] , ... | def set_palette_name(self, palette_name):
"""If the given palette matches an existing one, shows it in the
combobox
"""
combo = self.get_widget('palette_name')
found = False
log.debug('wanting palette: %r', palette_name)
for i in combo.get_model():
if i[0] == palette_name:
... |
def set_permission(self, permission, value, parent=False, admin=False):
""" Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful.
"""
try:
if not getattr(self, 'parent_{}'.format(permission)) ... | def function[set_permission, parameter[self, permission, value, parent, admin]]:
constant[ Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful.
]
<ast.Try object at 0x7da1b04bdf60> | keyword[def] identifier[set_permission] ( identifier[self] , identifier[permission] , identifier[value] , identifier[parent] = keyword[False] , identifier[admin] = keyword[False] ):
literal[string]
keyword[try] :
keyword[if] keyword[not] identifier[getattr] ( identifier[self] , liter... | def set_permission(self, permission, value, parent=False, admin=False):
""" Sets permission for personal information.
Returns False silently if unable to set permission.
Returns True if successful.
"""
try:
if not getattr(self, 'parent_{}'.format(permission)) and (not par... |
def parseFromDelimitedString(obj, buf, offset=0):
"""
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which
writes the size (and offset) of the buffer before writing the object.
This function handles parsing this message starting from offset 0.
@returns how many bytes of @buf were consu... | def function[parseFromDelimitedString, parameter[obj, buf, offset]]:
constant[
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which
writes the size (and offset) of the buffer before writing the object.
This function handles parsing this message starting from offset 0.
@returns how ... | keyword[def] identifier[parseFromDelimitedString] ( identifier[obj] , identifier[buf] , identifier[offset] = literal[int] ):
literal[string]
identifier[size] , identifier[pos] = identifier[_DecodeVarint] ( identifier[buf] , identifier[offset] )
identifier[obj] . identifier[ParseFromString] ( identifie... | def parseFromDelimitedString(obj, buf, offset=0):
"""
Stanford CoreNLP uses the Java "writeDelimitedTo" function, which
writes the size (and offset) of the buffer before writing the object.
This function handles parsing this message starting from offset 0.
@returns how many bytes of @buf were consu... |
def _import_submodules(package_name):
""" Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
"""
package = sys.modules[package_name]
out = {}
for lo... | def function[_import_submodules, parameter[package_name]]:
constant[ Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
]
variable[package] assign[=... | keyword[def] identifier[_import_submodules] ( identifier[package_name] ):
literal[string]
identifier[package] = identifier[sys] . identifier[modules] [ identifier[package_name] ]
identifier[out] ={}
keyword[for] identifier[loader] , identifier[name] , identifier[is_pkg] keyword[in] identifier[... | def _import_submodules(package_name):
""" Import all submodules of a module, recursively
Adapted from: http://stackoverflow.com/a/25083161
:param package_name: Package name
:type package_name: str
:rtype: dict[types.ModuleType]
"""
package = sys.modules[package_name]
out = {}
for (l... |
def export(self, last_checkpoint, output_dir):
"""Builds a prediction graph and xports the model.
Args:
last_checkpoint: Path to the latest checkpoint file from training.
output_dir: Path to the folder to be used to output the model.
"""
logging.info('Exporting prediction graph to %s', outp... | def function[export, parameter[self, last_checkpoint, output_dir]]:
constant[Builds a prediction graph and xports the model.
Args:
last_checkpoint: Path to the latest checkpoint file from training.
output_dir: Path to the folder to be used to output the model.
]
call[name[logging].i... | keyword[def] identifier[export] ( identifier[self] , identifier[last_checkpoint] , identifier[output_dir] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] , identifier[output_dir] )
keyword[with] identifier[tf] . identifier[Session] ( identifier[graph] = identifier[tf] . id... | def export(self, last_checkpoint, output_dir):
"""Builds a prediction graph and xports the model.
Args:
last_checkpoint: Path to the latest checkpoint file from training.
output_dir: Path to the folder to be used to output the model.
"""
logging.info('Exporting prediction graph to %s', outp... |
def review_args(self, obj, show_repr=False, heading='Arguments'):
"""
Reviews the given argument specification. Can review the
meta-arguments (launch_args) or the arguments themselves.
"""
args = obj.args if isinstance(obj, Launcher) else obj
print('\n%s\n' % self.summary... | def function[review_args, parameter[self, obj, show_repr, heading]]:
constant[
Reviews the given argument specification. Can review the
meta-arguments (launch_args) or the arguments themselves.
]
variable[args] assign[=] <ast.IfExp object at 0x7da1afe0c1f0>
call[name[prin... | keyword[def] identifier[review_args] ( identifier[self] , identifier[obj] , identifier[show_repr] = keyword[False] , identifier[heading] = literal[string] ):
literal[string]
identifier[args] = identifier[obj] . identifier[args] keyword[if] identifier[isinstance] ( identifier[obj] , identifier[Lau... | def review_args(self, obj, show_repr=False, heading='Arguments'):
"""
Reviews the given argument specification. Can review the
meta-arguments (launch_args) or the arguments themselves.
"""
args = obj.args if isinstance(obj, Launcher) else obj
print('\n%s\n' % self.summary_heading(hea... |
def voronoi_from_pixel_centers(pixel_centers):
"""Compute the Voronoi grid of the pixelization, using the pixel centers.
Parameters
----------
pixel_centers : ndarray
The (y,x) centre of every Voronoi pixel.
"""
return scipy.spatial.Voronoi(np.asarray([pixel_... | def function[voronoi_from_pixel_centers, parameter[pixel_centers]]:
constant[Compute the Voronoi grid of the pixelization, using the pixel centers.
Parameters
----------
pixel_centers : ndarray
The (y,x) centre of every Voronoi pixel.
]
return[call[name[scipy].sp... | keyword[def] identifier[voronoi_from_pixel_centers] ( identifier[pixel_centers] ):
literal[string]
keyword[return] identifier[scipy] . identifier[spatial] . identifier[Voronoi] ( identifier[np] . identifier[asarray] ([ identifier[pixel_centers] [:, literal[int] ], identifier[pixel_centers] [:, lit... | def voronoi_from_pixel_centers(pixel_centers):
"""Compute the Voronoi grid of the pixelization, using the pixel centers.
Parameters
----------
pixel_centers : ndarray
The (y,x) centre of every Voronoi pixel.
"""
return scipy.spatial.Voronoi(np.asarray([pixel_centers[... |
def metadata(self):
"""Return extracted metadata."""
output = dict(self.defaults)
output.update(self.extra_metadata)
return output | def function[metadata, parameter[self]]:
constant[Return extracted metadata.]
variable[output] assign[=] call[name[dict], parameter[name[self].defaults]]
call[name[output].update, parameter[name[self].extra_metadata]]
return[name[output]] | keyword[def] identifier[metadata] ( identifier[self] ):
literal[string]
identifier[output] = identifier[dict] ( identifier[self] . identifier[defaults] )
identifier[output] . identifier[update] ( identifier[self] . identifier[extra_metadata] )
keyword[return] identifier[output] | def metadata(self):
"""Return extracted metadata."""
output = dict(self.defaults)
output.update(self.extra_metadata)
return output |
def start_background_task(self, target, *args, **kwargs):
"""Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param targe... | def function[start_background_task, parameter[self, target]]:
constant[Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:p... | keyword[def] identifier[start_background_task] ( identifier[self] , identifier[target] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[eio] . identifier[start_background_task] ( identifier[target] ,* identifier[args] ,** identifier[kwargs... | def start_background_task(self, target, *args, **kwargs):
"""Start a background task using the appropriate async model.
This is a utility function that applications can use to start a
background task using the method that is compatible with the
selected async mode.
:param target: t... |
def _transfers(reaction, delta, elements, result, epsilon):
"""Yield transfers obtained from result."""
left = set(c for c, _ in reaction.left)
right = set(c for c, _ in reaction.right)
for c1, c2 in product(left, right):
items = {}
for e in elements:
v = result.get_value(del... | def function[_transfers, parameter[reaction, delta, elements, result, epsilon]]:
constant[Yield transfers obtained from result.]
variable[left] assign[=] call[name[set], parameter[<ast.GeneratorExp object at 0x7da20c6c44f0>]]
variable[right] assign[=] call[name[set], parameter[<ast.GeneratorExp ... | keyword[def] identifier[_transfers] ( identifier[reaction] , identifier[delta] , identifier[elements] , identifier[result] , identifier[epsilon] ):
literal[string]
identifier[left] = identifier[set] ( identifier[c] keyword[for] identifier[c] , identifier[_] keyword[in] identifier[reaction] . identifier... | def _transfers(reaction, delta, elements, result, epsilon):
"""Yield transfers obtained from result."""
left = set((c for (c, _) in reaction.left))
right = set((c for (c, _) in reaction.right))
for (c1, c2) in product(left, right):
items = {}
for e in elements:
v = result.get... |
def backward(A, pobs, T=None, beta_out=None):
"""Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observat... | def function[backward, parameter[A, pobs, T, beta_out]]:
constant[Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation pro... | keyword[def] identifier[backward] ( identifier[A] , identifier[pobs] , identifier[T] = keyword[None] , identifier[beta_out] = keyword[None] ):
literal[string]
keyword[if] identifier[__impl__] == identifier[__IMPL_PYTHON__] :
keyword[return] identifier[ip] . identifier[backward] ( identifier[A] ,... | def backward(A, pobs, T=None, beta_out=None):
"""Compute all backward coefficients. With scaling!
Parameters
----------
A : ndarray((N,N), dtype = float)
transition matrix of the hidden states
pobs : ndarray((T,N), dtype = float)
pobs[t,i] is the observation probability for observat... |
def defend_file_methods(coro):
"""
Decorator. Raises exception when file methods called with wrapped by
:py:class:`aioftp.AsyncPathIOContext` file object.
"""
@functools.wraps(coro)
async def wrapper(self, file, *args, **kwargs):
if isinstance(file, AsyncPathIOContext):
raise... | def function[defend_file_methods, parameter[coro]]:
constant[
Decorator. Raises exception when file methods called with wrapped by
:py:class:`aioftp.AsyncPathIOContext` file object.
]
<ast.AsyncFunctionDef object at 0x7da1b00b0220>
return[name[wrapper]] | keyword[def] identifier[defend_file_methods] ( identifier[coro] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[coro] )
keyword[async] keyword[def] identifier[wrapper] ( identifier[self] , identifier[file] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] ... | def defend_file_methods(coro):
"""
Decorator. Raises exception when file methods called with wrapped by
:py:class:`aioftp.AsyncPathIOContext` file object.
"""
@functools.wraps(coro)
async def wrapper(self, file, *args, **kwargs):
if isinstance(file, AsyncPathIOContext):
rais... |
def integrate_storage(self, timeseries, position, **kwargs):
"""
Integrates storage into grid.
See :class:`~.grid.network.StorageControl` for more information.
"""
StorageControl(edisgo=self, timeseries=timeseries,
position=position, **kwargs) | def function[integrate_storage, parameter[self, timeseries, position]]:
constant[
Integrates storage into grid.
See :class:`~.grid.network.StorageControl` for more information.
]
call[name[StorageControl], parameter[]] | keyword[def] identifier[integrate_storage] ( identifier[self] , identifier[timeseries] , identifier[position] ,** identifier[kwargs] ):
literal[string]
identifier[StorageControl] ( identifier[edisgo] = identifier[self] , identifier[timeseries] = identifier[timeseries] ,
identifier[position... | def integrate_storage(self, timeseries, position, **kwargs):
"""
Integrates storage into grid.
See :class:`~.grid.network.StorageControl` for more information.
"""
StorageControl(edisgo=self, timeseries=timeseries, position=position, **kwargs) |
def getDepartments(self):
"""Returns a list of the departments assigned to the Analyses
from this Analysis Request
"""
departments = list()
for analysis in self.getAnalyses(full_objects=True):
department = analysis.getDepartment()
if department and departm... | def function[getDepartments, parameter[self]]:
constant[Returns a list of the departments assigned to the Analyses
from this Analysis Request
]
variable[departments] assign[=] call[name[list], parameter[]]
for taget[name[analysis]] in starred[call[name[self].getAnalyses, paramete... | keyword[def] identifier[getDepartments] ( identifier[self] ):
literal[string]
identifier[departments] = identifier[list] ()
keyword[for] identifier[analysis] keyword[in] identifier[self] . identifier[getAnalyses] ( identifier[full_objects] = keyword[True] ):
identifier[depa... | def getDepartments(self):
"""Returns a list of the departments assigned to the Analyses
from this Analysis Request
"""
departments = list()
for analysis in self.getAnalyses(full_objects=True):
department = analysis.getDepartment()
if department and department not in departmen... |
def lifted_pauli(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transfor... | def function[lifted_pauli, parameter[pauli_sum, qubits]]:
constant[
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transformation. ... | keyword[def] identifier[lifted_pauli] ( identifier[pauli_sum] : identifier[Union] [ identifier[PauliSum] , identifier[PauliTerm] ], identifier[qubits] : identifier[List] [ identifier[int] ]):
literal[string]
keyword[if] identifier[isinstance] ( identifier[pauli_sum] , identifier[PauliTerm] ):
ide... | def lifted_pauli(pauli_sum: Union[PauliSum, PauliTerm], qubits: List[int]):
"""
Takes a PauliSum object along with a list of
qubits and returns a matrix corresponding the tensor representation of the
object.
Useful for generating the full Hamiltonian after a particular fermion to
pauli transfor... |
def main():
"""Test code called from commandline"""
model = load_model('../data/hmmdefs')
hmm = model.hmms['r-We']
for state_name in hmm.state_names:
print(state_name)
state = model.states[state_name]
print(state.means_)
print(model)
model2 = load_model('../data/prior.hmm... | def function[main, parameter[]]:
constant[Test code called from commandline]
variable[model] assign[=] call[name[load_model], parameter[constant[../data/hmmdefs]]]
variable[hmm] assign[=] call[name[model].hmms][constant[r-We]]
for taget[name[state_name]] in starred[name[hmm].state_names]... | keyword[def] identifier[main] ():
literal[string]
identifier[model] = identifier[load_model] ( literal[string] )
identifier[hmm] = identifier[model] . identifier[hmms] [ literal[string] ]
keyword[for] identifier[state_name] keyword[in] identifier[hmm] . identifier[state_names] :
ident... | def main():
"""Test code called from commandline"""
model = load_model('../data/hmmdefs')
hmm = model.hmms['r-We']
for state_name in hmm.state_names:
print(state_name)
state = model.states[state_name]
print(state.means_) # depends on [control=['for'], data=['state_name']]
pr... |
def build_mv_grid_district(self, poly_id, subst_id, grid_district_geo_data,
station_geo_data):
"""Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also use... | def function[build_mv_grid_district, parameter[self, poly_id, subst_id, grid_district_geo_data, station_geo_data]]:
constant[Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also ... | keyword[def] identifier[build_mv_grid_district] ( identifier[self] , identifier[poly_id] , identifier[subst_id] , identifier[grid_district_geo_data] ,
identifier[station_geo_data] ):
literal[string]
identifier[mv_station] = identifier[MVStationDing0] ( identifier[id_db] = identifier[subst_id] , i... | def build_mv_grid_district(self, poly_id, subst_id, grid_district_geo_data, station_geo_data):
"""Initiates single MV grid_district including station and grid
Parameters
----------
poly_id: int
ID of grid_district according to database table. Also used as ID for created grid #TO... |
def bio_write(self, buf):
"""
If the Connection was created with a memory BIO, this method can be
used to add bytes to the read end of that memory BIO. The Connection
can then read the bytes (for example, in response to a call to
:meth:`recv`).
:param buf: The string to... | def function[bio_write, parameter[self, buf]]:
constant[
If the Connection was created with a memory BIO, this method can be
used to add bytes to the read end of that memory BIO. The Connection
can then read the bytes (for example, in response to a call to
:meth:`recv`).
... | keyword[def] identifier[bio_write] ( identifier[self] , identifier[buf] ):
literal[string]
identifier[buf] = identifier[_text_to_bytes_and_warn] ( literal[string] , identifier[buf] )
keyword[if] identifier[self] . identifier[_into_ssl] keyword[is] keyword[None] :
keyword[r... | def bio_write(self, buf):
"""
If the Connection was created with a memory BIO, this method can be
used to add bytes to the read end of that memory BIO. The Connection
can then read the bytes (for example, in response to a call to
:meth:`recv`).
:param buf: The string to put... |
def ancestral(args):
"""
%prog ancestral ancestral.txt assembly.fasta
Karyotype evolution of pineapple. The figure is inspired by Amphioxus paper
Figure 3 and Tetradon paper Figure 9.
"""
p = OptionParser(ancestral.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="8x7")
i... | def function[ancestral, parameter[args]]:
constant[
%prog ancestral ancestral.txt assembly.fasta
Karyotype evolution of pineapple. The figure is inspired by Amphioxus paper
Figure 3 and Tetradon paper Figure 9.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[ancestral]._... | keyword[def] identifier[ancestral] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[ancestral] . identifier[__doc__] )
identifier[opts] , identifier[args] , identifier[iopts] = identifier[p] . identifier[set_image_options] ( identifier[args] , identifier[figs... | def ancestral(args):
"""
%prog ancestral ancestral.txt assembly.fasta
Karyotype evolution of pineapple. The figure is inspired by Amphioxus paper
Figure 3 and Tetradon paper Figure 9.
"""
p = OptionParser(ancestral.__doc__)
(opts, args, iopts) = p.set_image_options(args, figsize='8x7')
... |
def to_dict(self, val=UNSET):
"""Creates dict object from dict2 object
Args:
val (:obj:`dict2`): Value to create from
Returns:
Equivalent dict object.
"""
if val is UNSET:
val = self
if isinstance(val, dict2) or isinstance(val, dict)... | def function[to_dict, parameter[self, val]]:
constant[Creates dict object from dict2 object
Args:
val (:obj:`dict2`): Value to create from
Returns:
Equivalent dict object.
]
if compare[name[val] is name[UNSET]] begin[:]
variable[val] assi... | keyword[def] identifier[to_dict] ( identifier[self] , identifier[val] = identifier[UNSET] ):
literal[string]
keyword[if] identifier[val] keyword[is] identifier[UNSET] :
identifier[val] = identifier[self]
keyword[if] identifier[isinstance] ( identifier[val] , identifier[d... | def to_dict(self, val=UNSET):
"""Creates dict object from dict2 object
Args:
val (:obj:`dict2`): Value to create from
Returns:
Equivalent dict object.
"""
if val is UNSET:
val = self # depends on [control=['if'], data=['val']]
if isinstance(val, dic... |
def _inject_constructor(self, cls, func, name, resolution_level, keep,
trace):
"""
Modifying Methods in Place - after the recipe 15.7 in the Python
Cookbook by Ken Seehof. The original constructors may be restored
later.
"""
try:
co... | def function[_inject_constructor, parameter[self, cls, func, name, resolution_level, keep, trace]]:
constant[
Modifying Methods in Place - after the recipe 15.7 in the Python
Cookbook by Ken Seehof. The original constructors may be restored
later.
]
<ast.Try object at 0x7da18... | keyword[def] identifier[_inject_constructor] ( identifier[self] , identifier[cls] , identifier[func] , identifier[name] , identifier[resolution_level] , identifier[keep] ,
identifier[trace] ):
literal[string]
keyword[try] :
identifier[constructor] = identifier[cls] . identifier[__init... | def _inject_constructor(self, cls, func, name, resolution_level, keep, trace):
"""
Modifying Methods in Place - after the recipe 15.7 in the Python
Cookbook by Ken Seehof. The original constructors may be restored
later.
"""
try:
constructor = cls.__init__ # depends on [... |
def to_segwizard(segs, target, header=True, coltype=LIGOTimeGPS):
"""Write the given `SegmentList` to a file in SegWizard format.
Parameters
----------
segs : :class:`~gwpy.segments.SegmentList`
The list of segments to write.
target : `file`, `str`
An open file, or file path, to wh... | def function[to_segwizard, parameter[segs, target, header, coltype]]:
constant[Write the given `SegmentList` to a file in SegWizard format.
Parameters
----------
segs : :class:`~gwpy.segments.SegmentList`
The list of segments to write.
target : `file`, `str`
An open file, or fi... | keyword[def] identifier[to_segwizard] ( identifier[segs] , identifier[target] , identifier[header] = keyword[True] , identifier[coltype] = identifier[LIGOTimeGPS] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[target] , identifier[string_types] ):
keyword[with] identifie... | def to_segwizard(segs, target, header=True, coltype=LIGOTimeGPS):
"""Write the given `SegmentList` to a file in SegWizard format.
Parameters
----------
segs : :class:`~gwpy.segments.SegmentList`
The list of segments to write.
target : `file`, `str`
An open file, or file path, to wh... |
def issues(self, from_date=DEFAULT_DATETIME,
offset=None, max_issues=MAX_ISSUES):
"""Get the information of a list of issues.
:param from_date: retrieve issues that where updated from that date;
dates are converted to UTC
:param offset: starting position for the searc... | def function[issues, parameter[self, from_date, offset, max_issues]]:
constant[Get the information of a list of issues.
:param from_date: retrieve issues that where updated from that date;
dates are converted to UTC
:param offset: starting position for the search
:param max_... | keyword[def] identifier[issues] ( identifier[self] , identifier[from_date] = identifier[DEFAULT_DATETIME] ,
identifier[offset] = keyword[None] , identifier[max_issues] = identifier[MAX_ISSUES] ):
literal[string]
identifier[resource] = identifier[self] . identifier[RISSUES] + identifier[self] . ide... | def issues(self, from_date=DEFAULT_DATETIME, offset=None, max_issues=MAX_ISSUES):
"""Get the information of a list of issues.
:param from_date: retrieve issues that where updated from that date;
dates are converted to UTC
:param offset: starting position for the search
:param ma... |
def func_call(self, t):
"""
For function calls e.g. TEXT (tostring([area],"%.2f"))
"""
func, params = t
func_name = func.value
func.value = "({}({}))".format(func_name, params)
return func | def function[func_call, parameter[self, t]]:
constant[
For function calls e.g. TEXT (tostring([area],"%.2f"))
]
<ast.Tuple object at 0x7da2041da830> assign[=] name[t]
variable[func_name] assign[=] name[func].value
name[func].value assign[=] call[constant[({}({}))].format,... | keyword[def] identifier[func_call] ( identifier[self] , identifier[t] ):
literal[string]
identifier[func] , identifier[params] = identifier[t]
identifier[func_name] = identifier[func] . identifier[value]
identifier[func] . identifier[value] = literal[string] . identifier[format]... | def func_call(self, t):
"""
For function calls e.g. TEXT (tostring([area],"%.2f"))
"""
(func, params) = t
func_name = func.value
func.value = '({}({}))'.format(func_name, params)
return func |
def ReadHuntOutputPluginLogEntries(self,
hunt_id,
output_plugin_id,
offset,
count,
with_type=None):
"""Reads hunt output plugin log... | def function[ReadHuntOutputPluginLogEntries, parameter[self, hunt_id, output_plugin_id, offset, count, with_type]]:
constant[Reads hunt output plugin log entries.]
variable[all_entries] assign[=] list[[]]
for taget[name[flow_obj]] in starred[call[name[self]._GetHuntFlows, parameter[name[hunt_id]... | keyword[def] identifier[ReadHuntOutputPluginLogEntries] ( identifier[self] ,
identifier[hunt_id] ,
identifier[output_plugin_id] ,
identifier[offset] ,
identifier[count] ,
identifier[with_type] = keyword[None] ):
literal[string]
identifier[all_entries] =[]
keyword[for] identifier[flow_obj] keyw... | def ReadHuntOutputPluginLogEntries(self, hunt_id, output_plugin_id, offset, count, with_type=None):
"""Reads hunt output plugin log entries."""
all_entries = []
for flow_obj in self._GetHuntFlows(hunt_id):
for entry in self.ReadFlowOutputPluginLogEntries(flow_obj.client_id, flow_obj.flow_id, output_... |
def set_node_attr(self, name, attr, value):
'''
API: set_node_attr(self, name, attr)
Description:
Sets attr attribute of node named name to value.
Input:
name: Name of node.
attr: Attribute of node to set.
Pre:
Graph should have this no... | def function[set_node_attr, parameter[self, name, attr, value]]:
constant[
API: set_node_attr(self, name, attr)
Description:
Sets attr attribute of node named name to value.
Input:
name: Name of node.
attr: Attribute of node to set.
Pre:
... | keyword[def] identifier[set_node_attr] ( identifier[self] , identifier[name] , identifier[attr] , identifier[value] ):
literal[string]
identifier[self] . identifier[get_node] ( identifier[name] ). identifier[set_attr] ( identifier[attr] , identifier[value] ) | def set_node_attr(self, name, attr, value):
"""
API: set_node_attr(self, name, attr)
Description:
Sets attr attribute of node named name to value.
Input:
name: Name of node.
attr: Attribute of node to set.
Pre:
Graph should have this node.
... |
def _add(self, codeobj):
"""Add a child (variable) to this object."""
assert isinstance(codeobj, CodeVariable)
self.variables.append(codeobj) | def function[_add, parameter[self, codeobj]]:
constant[Add a child (variable) to this object.]
assert[call[name[isinstance], parameter[name[codeobj], name[CodeVariable]]]]
call[name[self].variables.append, parameter[name[codeobj]]] | keyword[def] identifier[_add] ( identifier[self] , identifier[codeobj] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[codeobj] , identifier[CodeVariable] )
identifier[self] . identifier[variables] . identifier[append] ( identifier[codeobj] ) | def _add(self, codeobj):
"""Add a child (variable) to this object."""
assert isinstance(codeobj, CodeVariable)
self.variables.append(codeobj) |
def export_obj(vertices, triangles, filename):
"""
Exports a mesh in the (.obj) format.
"""
with open(filename, 'w') as fh:
for v in vertices:
fh.write("v {} {} {}\n".format(*v))
for f in triangles:
fh.write("f {} {} {}\n".format(*(f + 1... | def function[export_obj, parameter[vertices, triangles, filename]]:
constant[
Exports a mesh in the (.obj) format.
]
with call[name[open], parameter[name[filename], constant[w]]] begin[:]
for taget[name[v]] in starred[name[vertices]] begin[:]
call[name[fh]... | keyword[def] identifier[export_obj] ( identifier[vertices] , identifier[triangles] , identifier[filename] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[fh] :
keyword[for] identifier[v] keyword[in] identifier[vertices] :
... | def export_obj(vertices, triangles, filename):
"""
Exports a mesh in the (.obj) format.
"""
with open(filename, 'w') as fh:
for v in vertices:
fh.write('v {} {} {}\n'.format(*v)) # depends on [control=['for'], data=['v']]
for f in triangles:
fh.write('f {} {} {}\... |
def restore(self, remotepath):
''' Usage: restore <remotepath> - \
restore a file from the recycle bin
remotepath - the remote path to restore
'''
rpath = get_pcs_path(remotepath)
# by default, only 1000 items, more than that sounds a bit crazy
pars = {
'method' : 'listrecycle' }
self.pd("Searching fo... | def function[restore, parameter[self, remotepath]]:
constant[ Usage: restore <remotepath> - restore a file from the recycle bin
remotepath - the remote path to restore
]
variable[rpath] assign[=] call[name[get_pcs_path], parameter[name[remotepath]]]
variable[pars] assign[=] dictionary[[<ast.... | keyword[def] identifier[restore] ( identifier[self] , identifier[remotepath] ):
literal[string]
identifier[rpath] = identifier[get_pcs_path] ( identifier[remotepath] )
identifier[pars] ={
literal[string] : literal[string] }
identifier[self] . identifier[pd] ( literal[string] )
keyword[return] ... | def restore(self, remotepath):
""" Usage: restore <remotepath> - restore a file from the recycle bin
remotepath - the remote path to restore
"""
rpath = get_pcs_path(remotepath) # by default, only 1000 items, more than that sounds a bit crazy
pars = {'method': 'listrecycle'}
self.pd('Searching for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.