code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _gate_pre_offset(self, gate):
"""
Return the offset to use before placing this gate.
:param string gate: The name of the gate whose pre-offset is desired.
:return: Offset to use before the gate.
:rtype: float
"""
try:
gates = self.settings['gates'... | def function[_gate_pre_offset, parameter[self, gate]]:
constant[
Return the offset to use before placing this gate.
:param string gate: The name of the gate whose pre-offset is desired.
:return: Offset to use before the gate.
:rtype: float
]
<ast.Try object at 0x7da1... | keyword[def] identifier[_gate_pre_offset] ( identifier[self] , identifier[gate] ):
literal[string]
keyword[try] :
identifier[gates] = identifier[self] . identifier[settings] [ literal[string] ]
identifier[delta_pos] = identifier[gates] [ identifier[gate] . identifier[__cla... | def _gate_pre_offset(self, gate):
"""
Return the offset to use before placing this gate.
:param string gate: The name of the gate whose pre-offset is desired.
:return: Offset to use before the gate.
:rtype: float
"""
try:
gates = self.settings['gates']
de... |
def decode_obj_table(table_entries, plugin):
"""Return root of obj table. Converts user-class objects"""
entries = []
for entry in table_entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.classID]... | def function[decode_obj_table, parameter[table_entries, plugin]]:
constant[Return root of obj table. Converts user-class objects]
variable[entries] assign[=] list[[]]
for taget[name[entry]] in starred[name[table_entries]] begin[:]
if call[name[isinstance], parameter[name[entry], ... | keyword[def] identifier[decode_obj_table] ( identifier[table_entries] , identifier[plugin] ):
literal[string]
identifier[entries] =[]
keyword[for] identifier[entry] keyword[in] identifier[table_entries] :
keyword[if] identifier[isinstance] ( identifier[entry] , identifier[Container] ):
... | def decode_obj_table(table_entries, plugin):
"""Return root of obj table. Converts user-class objects"""
entries = []
for entry in table_entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.classID]... |
def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(
include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.c... | def function[get_transactions, parameter[self, include_investment]]:
constant[Returns the transaction data as a Pandas DataFrame.]
call[name[assert_pd], parameter[]]
variable[s] assign[=] call[name[StringIO], parameter[call[name[self].get_transactions_csv, parameter[]]]]
call[name[s].see... | keyword[def] identifier[get_transactions] ( identifier[self] , identifier[include_investment] = keyword[False] ):
literal[string]
identifier[assert_pd] ()
identifier[s] = identifier[StringIO] ( identifier[self] . identifier[get_transactions_csv] (
identifier[include_investment] = ... | def get_transactions(self, include_investment=False):
"""Returns the transaction data as a Pandas DataFrame."""
assert_pd()
s = StringIO(self.get_transactions_csv(include_investment=include_investment))
s.seek(0)
df = pd.read_csv(s, parse_dates=['Date'])
df.columns = [c.lower().replace(' ', '_')... |
def serialize(script_string):
'''
str -> bytearray
'''
string_tokens = script_string.split()
serialized_script = bytearray()
for token in string_tokens:
if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4':
raise NotImplementedError('{} is a bad idea.'.format(token))
... | def function[serialize, parameter[script_string]]:
constant[
str -> bytearray
]
variable[string_tokens] assign[=] call[name[script_string].split, parameter[]]
variable[serialized_script] assign[=] call[name[bytearray], parameter[]]
for taget[name[token]] in starred[name[string_to... | keyword[def] identifier[serialize] ( identifier[script_string] ):
literal[string]
identifier[string_tokens] = identifier[script_string] . identifier[split] ()
identifier[serialized_script] = identifier[bytearray] ()
keyword[for] identifier[token] keyword[in] identifier[string_tokens] :
... | def serialize(script_string):
"""
str -> bytearray
"""
string_tokens = script_string.split()
serialized_script = bytearray()
for token in string_tokens:
if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4':
raise NotImplementedError('{} is a bad idea.'.format(token)) # ... |
def _set_esp_auth(self, v, load=False):
"""
Setter method for esp_auth, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_auth (algorithm-type-ah)
If this variable is read-only (config: false) in the
source YANG file, then _set_esp... | def function[_set_esp_auth, parameter[self, v, load]]:
constant[
Setter method for esp_auth, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_auth (algorithm-type-ah)
If this variable is read-only (config: false) in the
source... | keyword[def] identifier[_set_esp_auth] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
ident... | def _set_esp_auth(self, v, load=False):
"""
Setter method for esp_auth, mapped from YANG variable /routing_system/interface/ve/ipv6/interface_ospfv3_conf/authentication/ipsec_auth_key_config/esp_auth (algorithm-type-ah)
If this variable is read-only (config: false) in the
source YANG file, then _set_esp... |
def retrieveVals(self):
"""Retrieve values for graphs."""
for iface in self._ifaceList:
stats = self._ifaceStats.get(iface)
graph_name = 'netiface_traffic_%s' % iface
if self.hasGraph(graph_name):
self.setGraphVal(graph_name, 'rx', stats.get('rxbytes')... | def function[retrieveVals, parameter[self]]:
constant[Retrieve values for graphs.]
for taget[name[iface]] in starred[name[self]._ifaceList] begin[:]
variable[stats] assign[=] call[name[self]._ifaceStats.get, parameter[name[iface]]]
variable[graph_name] assign[=] binary_op... | keyword[def] identifier[retrieveVals] ( identifier[self] ):
literal[string]
keyword[for] identifier[iface] keyword[in] identifier[self] . identifier[_ifaceList] :
identifier[stats] = identifier[self] . identifier[_ifaceStats] . identifier[get] ( identifier[iface] )
iden... | def retrieveVals(self):
"""Retrieve values for graphs."""
for iface in self._ifaceList:
stats = self._ifaceStats.get(iface)
graph_name = 'netiface_traffic_%s' % iface
if self.hasGraph(graph_name):
self.setGraphVal(graph_name, 'rx', stats.get('rxbytes') * 8)
self.s... |
def sens_batmon_encode(self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6):
'''
Battery pack monitoring data for Li-Ion batteries
temperature ... | def function[sens_batmon_encode, parameter[self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6]]:
constant[
Battery pack monitoring data for Li-Ion batteries
tem... | keyword[def] identifier[sens_batmon_encode] ( identifier[self] , identifier[temperature] , identifier[voltage] , identifier[current] , identifier[SoC] , identifier[batterystatus] , identifier[serialnumber] , identifier[hostfetcontrol] , identifier[cellvoltage1] , identifier[cellvoltage2] , identifier[cellvoltage3] , ... | def sens_batmon_encode(self, temperature, voltage, current, SoC, batterystatus, serialnumber, hostfetcontrol, cellvoltage1, cellvoltage2, cellvoltage3, cellvoltage4, cellvoltage5, cellvoltage6):
"""
Battery pack monitoring data for Li-Ion batteries
temperature : Batter... |
def edge_val_set(self, graph, orig, dest, idx, key, branch, turn, tick, value):
"""Set this key of this edge to this value."""
if (branch, turn, tick) in self._btts:
raise TimeError
self._btts.add((branch, turn, tick))
graph, orig, dest, key, value = map(self.pack, (graph, or... | def function[edge_val_set, parameter[self, graph, orig, dest, idx, key, branch, turn, tick, value]]:
constant[Set this key of this edge to this value.]
if compare[tuple[[<ast.Name object at 0x7da2047ea530>, <ast.Name object at 0x7da2047eb190>, <ast.Name object at 0x7da2047e8a60>]] in name[self]._btts] b... | keyword[def] identifier[edge_val_set] ( identifier[self] , identifier[graph] , identifier[orig] , identifier[dest] , identifier[idx] , identifier[key] , identifier[branch] , identifier[turn] , identifier[tick] , identifier[value] ):
literal[string]
keyword[if] ( identifier[branch] , identifier[turn... | def edge_val_set(self, graph, orig, dest, idx, key, branch, turn, tick, value):
"""Set this key of this edge to this value."""
if (branch, turn, tick) in self._btts:
raise TimeError # depends on [control=['if'], data=[]]
self._btts.add((branch, turn, tick))
(graph, orig, dest, key, value) = map... |
def set_store_to(self, store_to):
"""Update store_to in Cache and backend."""
assert store_to is None or isinstance(store_to, Cache), \
"store_to needs to be None or a Cache object."
assert store_to is None or store_to.cl_size <= self.cl_size, \
"cl_size may only increase... | def function[set_store_to, parameter[self, store_to]]:
constant[Update store_to in Cache and backend.]
assert[<ast.BoolOp object at 0x7da207f985b0>]
assert[<ast.BoolOp object at 0x7da207f99990>]
name[self].store_to assign[=] name[store_to]
name[self].backend.store_to assign[=] name[store... | keyword[def] identifier[set_store_to] ( identifier[self] , identifier[store_to] ):
literal[string]
keyword[assert] identifier[store_to] keyword[is] keyword[None] keyword[or] identifier[isinstance] ( identifier[store_to] , identifier[Cache] ), literal[string]
keyword[assert] identifi... | def set_store_to(self, store_to):
"""Update store_to in Cache and backend."""
assert store_to is None or isinstance(store_to, Cache), 'store_to needs to be None or a Cache object.'
assert store_to is None or store_to.cl_size <= self.cl_size, 'cl_size may only increase towards main memory.'
self.store_to... |
def get_nearest_entry(self, entry, type_measurement):
"""!
@brief Find nearest entry of node for the specified entry.
@param[in] entry (cfentry): Entry that is used for calculation distance.
@param[in] type_measurement (measurement_type): Measurement type that is used for o... | def function[get_nearest_entry, parameter[self, entry, type_measurement]]:
constant[!
@brief Find nearest entry of node for the specified entry.
@param[in] entry (cfentry): Entry that is used for calculation distance.
@param[in] type_measurement (measurement_type): Measurement t... | keyword[def] identifier[get_nearest_entry] ( identifier[self] , identifier[entry] , identifier[type_measurement] ):
literal[string]
identifier[min_key] = keyword[lambda] identifier[cur_entity] : identifier[cur_entity] . identifier[get_distance] ( identifier[entry] , identifier[type_measurement... | def get_nearest_entry(self, entry, type_measurement):
"""!
@brief Find nearest entry of node for the specified entry.
@param[in] entry (cfentry): Entry that is used for calculation distance.
@param[in] type_measurement (measurement_type): Measurement type that is used for obtaining ... |
def checkFITSFormat(filelist, ivmlist=None):
"""
This code will check whether or not files are GEIS or WAIVER FITS and
convert them to MEF if found. It also keeps the IVMLIST consistent with
the input filelist, in the case that some inputs get dropped during
the check/conversion.
"""
if ivml... | def function[checkFITSFormat, parameter[filelist, ivmlist]]:
constant[
This code will check whether or not files are GEIS or WAIVER FITS and
convert them to MEF if found. It also keeps the IVMLIST consistent with
the input filelist, in the case that some inputs get dropped during
the check/conve... | keyword[def] identifier[checkFITSFormat] ( identifier[filelist] , identifier[ivmlist] = keyword[None] ):
literal[string]
keyword[if] identifier[ivmlist] keyword[is] keyword[None] :
identifier[ivmlist] =[ keyword[None] keyword[for] identifier[l] keyword[in] identifier[filelist] ]
ident... | def checkFITSFormat(filelist, ivmlist=None):
"""
This code will check whether or not files are GEIS or WAIVER FITS and
convert them to MEF if found. It also keeps the IVMLIST consistent with
the input filelist, in the case that some inputs get dropped during
the check/conversion.
"""
if ivml... |
def _valid(m, comment=VALID_RESPONSE, out=None):
'''
Return valid status.
'''
return _set_status(m, status=True, comment=comment, out=out) | def function[_valid, parameter[m, comment, out]]:
constant[
Return valid status.
]
return[call[name[_set_status], parameter[name[m]]]] | keyword[def] identifier[_valid] ( identifier[m] , identifier[comment] = identifier[VALID_RESPONSE] , identifier[out] = keyword[None] ):
literal[string]
keyword[return] identifier[_set_status] ( identifier[m] , identifier[status] = keyword[True] , identifier[comment] = identifier[comment] , identifier[out]... | def _valid(m, comment=VALID_RESPONSE, out=None):
"""
Return valid status.
"""
return _set_status(m, status=True, comment=comment, out=out) |
def get_connection_string(connection=None):
"""return SQLAlchemy connection string if it is set
:param connection: get the SQLAlchemy connection string #TODO
:rtype: str
"""
if not connection:
config = configparser.ConfigParser()
cfp = defaults.config_file_path
if os.path.ex... | def function[get_connection_string, parameter[connection]]:
constant[return SQLAlchemy connection string if it is set
:param connection: get the SQLAlchemy connection string #TODO
:rtype: str
]
if <ast.UnaryOp object at 0x7da18f7221a0> begin[:]
variable[config] assign[=] cal... | keyword[def] identifier[get_connection_string] ( identifier[connection] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[connection] :
identifier[config] = identifier[configparser] . identifier[ConfigParser] ()
identifier[cfp] = identifier[defaults] . identifier[co... | def get_connection_string(connection=None):
"""return SQLAlchemy connection string if it is set
:param connection: get the SQLAlchemy connection string #TODO
:rtype: str
"""
if not connection:
config = configparser.ConfigParser()
cfp = defaults.config_file_path
if os.path.ex... |
def _markup(p_todo, p_focus):
"""
Returns an attribute spec for the colors that correspond to the given todo
item.
"""
pri = p_todo.priority()
pri = 'pri_' + pri if pri else PaletteItem.DEFAULT
if not p_focus:
attr_dict = {None: pri}
else:
# use '_focus' palette entries ... | def function[_markup, parameter[p_todo, p_focus]]:
constant[
Returns an attribute spec for the colors that correspond to the given todo
item.
]
variable[pri] assign[=] call[name[p_todo].priority, parameter[]]
variable[pri] assign[=] <ast.IfExp object at 0x7da207f03820>
if <as... | keyword[def] identifier[_markup] ( identifier[p_todo] , identifier[p_focus] ):
literal[string]
identifier[pri] = identifier[p_todo] . identifier[priority] ()
identifier[pri] = literal[string] + identifier[pri] keyword[if] identifier[pri] keyword[else] identifier[PaletteItem] . identifier[DEFAULT] ... | def _markup(p_todo, p_focus):
"""
Returns an attribute spec for the colors that correspond to the given todo
item.
"""
pri = p_todo.priority()
pri = 'pri_' + pri if pri else PaletteItem.DEFAULT
if not p_focus:
attr_dict = {None: pri} # depends on [control=['if'], data=[]]
else:
... |
def to_csv(self,*args,**kwargs):
"""overload of pandas.DataFrame.to_csv() to account
for parameter transformation so that the saved
ParameterEnsemble csv is not in Log10 space
Parameters
----------
*args : list
positional arguments to pass to pandas.DataFrame... | def function[to_csv, parameter[self]]:
constant[overload of pandas.DataFrame.to_csv() to account
for parameter transformation so that the saved
ParameterEnsemble csv is not in Log10 space
Parameters
----------
*args : list
positional arguments to pass to pand... | keyword[def] identifier[to_csv] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[retrans] = keyword[False]
keyword[if] identifier[self] . identifier[istransformed] :
identifier[self] . identifier[_back_transform] ( identifier[inplac... | def to_csv(self, *args, **kwargs):
"""overload of pandas.DataFrame.to_csv() to account
for parameter transformation so that the saved
ParameterEnsemble csv is not in Log10 space
Parameters
----------
*args : list
positional arguments to pass to pandas.DataFrame.t... |
def _prepare_discharge_hook(req, client):
''' Return the hook function (called when the response is received.)
This allows us to intercept the response and do any necessary
macaroon discharge before returning.
'''
class Retry:
# Define a local class so that we can use its class variable as
... | def function[_prepare_discharge_hook, parameter[req, client]]:
constant[ Return the hook function (called when the response is received.)
This allows us to intercept the response and do any necessary
macaroon discharge before returning.
]
class class[Retry, parameter[]] begin[:]
... | keyword[def] identifier[_prepare_discharge_hook] ( identifier[req] , identifier[client] ):
literal[string]
keyword[class] identifier[Retry] :
identifier[count] = literal[int]
keyword[def] identifier[hook] ( identifier[response] ,* identifier[args] ,** identifier[kwargs] ):
... | def _prepare_discharge_hook(req, client):
""" Return the hook function (called when the response is received.)
This allows us to intercept the response and do any necessary
macaroon discharge before returning.
"""
class Retry:
# Define a local class so that we can use its class variable as... |
def is_valid(self):
""" Only retain SNPs or single indels, and are bi-allelic
"""
return len(self.ref) == 1 and \
len(self.alt) == 1 and \
len(self.alt[0]) == 1 | def function[is_valid, parameter[self]]:
constant[ Only retain SNPs or single indels, and are bi-allelic
]
return[<ast.BoolOp object at 0x7da2044c1b40>] | keyword[def] identifier[is_valid] ( identifier[self] ):
literal[string]
keyword[return] identifier[len] ( identifier[self] . identifier[ref] )== literal[int] keyword[and] identifier[len] ( identifier[self] . identifier[alt] )== literal[int] keyword[and] identifier[len] ( identifier[self] . ide... | def is_valid(self):
""" Only retain SNPs or single indels, and are bi-allelic
"""
return len(self.ref) == 1 and len(self.alt) == 1 and (len(self.alt[0]) == 1) |
def fill_dataset_tree(self, tree, data_sets):
"""
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
for index, (time... | def function[fill_dataset_tree, parameter[self, tree, data_sets]]:
constant[
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
]
call[call[name[tree].model, parameter[]].removeRows,... | keyword[def] identifier[fill_dataset_tree] ( identifier[self] , identifier[tree] , identifier[data_sets] ):
literal[string]
identifier[tree] . identifier[model] (). identifier[removeRows] ( literal[int] , identifier[tree] . identifier[model] (). identifier[rowCount] ())
keyword[for] iden... | def fill_dataset_tree(self, tree, data_sets):
"""
fills the tree with data sets where datasets is a dictionary of the form
Args:
tree:
data_sets: a dataset
Returns:
"""
tree.model().removeRows(0, tree.model().rowCount())
for (index, (time, script)) i... |
def complete_offer(self, offer_id, complete_dict):
"""
Completes an offer
:param complete_dict: the complete dict with the template id
:param offer_id: the offer id
:return: Response
"""
return self._create_put_request(
resource=OFFERS,
bi... | def function[complete_offer, parameter[self, offer_id, complete_dict]]:
constant[
Completes an offer
:param complete_dict: the complete dict with the template id
:param offer_id: the offer id
:return: Response
]
return[call[name[self]._create_put_request, parameter[]... | keyword[def] identifier[complete_offer] ( identifier[self] , identifier[offer_id] , identifier[complete_dict] ):
literal[string]
keyword[return] identifier[self] . identifier[_create_put_request] (
identifier[resource] = identifier[OFFERS] ,
identifier[billomat_id] = identifier[o... | def complete_offer(self, offer_id, complete_dict):
"""
Completes an offer
:param complete_dict: the complete dict with the template id
:param offer_id: the offer id
:return: Response
"""
return self._create_put_request(resource=OFFERS, billomat_id=offer_id, command=COMPL... |
def v1_stream_id_associations(tags, stream_id):
'''Retrieve associations for a given stream_id.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the association.
'''
stream_id =... | def function[v1_stream_id_associations, parameter[tags, stream_id]]:
constant[Retrieve associations for a given stream_id.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the assoc... | keyword[def] identifier[v1_stream_id_associations] ( identifier[tags] , identifier[stream_id] ):
literal[string]
identifier[stream_id] = identifier[stream_id] . identifier[decode] ( literal[string] ). identifier[strip] ()
keyword[return] { literal[string] : identifier[tags] . identifier[assocs_by_stre... | def v1_stream_id_associations(tags, stream_id):
"""Retrieve associations for a given stream_id.
The associations returned have the exact same structure as defined
in the ``v1_tag_associate`` route with one addition: a ``tag``
field contains the full tag name for the association.
"""
stream_id =... |
def LoadPlugins(cls):
"""Load all registered iotile.update_record plugins."""
if cls.PLUGINS_LOADED:
return
reg = ComponentRegistry()
for _, record in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record)
cls.PLUGINS_LOADED = True | def function[LoadPlugins, parameter[cls]]:
constant[Load all registered iotile.update_record plugins.]
if name[cls].PLUGINS_LOADED begin[:]
return[None]
variable[reg] assign[=] call[name[ComponentRegistry], parameter[]]
for taget[tuple[[<ast.Name object at 0x7da20c6c7a30>, <ast.N... | keyword[def] identifier[LoadPlugins] ( identifier[cls] ):
literal[string]
keyword[if] identifier[cls] . identifier[PLUGINS_LOADED] :
keyword[return]
identifier[reg] = identifier[ComponentRegistry] ()
keyword[for] identifier[_] , identifier[record] keyword[in] i... | def LoadPlugins(cls):
"""Load all registered iotile.update_record plugins."""
if cls.PLUGINS_LOADED:
return # depends on [control=['if'], data=[]]
reg = ComponentRegistry()
for (_, record) in reg.load_extensions('iotile.update_record'):
cls.RegisterRecordType(record) # depends on [cont... |
def hexdump( src, length=16, sep='.', start = 0):
'''
@brief Return {src} in hex dump.
@param[in] length {Int} Nb Bytes by row.
@param[in] sep {Char} For the text part, {sep} will be used for non ASCII char.
@return {Str} The hexdump
@note Full support for python2 and python3 !
'''
result = [];
# Python3 su... | def function[hexdump, parameter[src, length, sep, start]]:
constant[
@brief Return {src} in hex dump.
@param[in] length {Int} Nb Bytes by row.
@param[in] sep {Char} For the text part, {sep} will be used for non ASCII char.
@return {Str} The hexdump
@note Full support for python2 and python3 !
]
... | keyword[def] identifier[hexdump] ( identifier[src] , identifier[length] = literal[int] , identifier[sep] = literal[string] , identifier[start] = literal[int] ):
literal[string]
identifier[result] =[];
keyword[try] :
identifier[xrange] ( literal[int] , literal[int] );
keyword[except] identifier[NameErr... | def hexdump(src, length=16, sep='.', start=0):
"""
@brief Return {src} in hex dump.
@param[in] length {Int} Nb Bytes by row.
@param[in] sep {Char} For the text part, {sep} will be used for non ASCII char.
@return {Str} The hexdump
@note Full support for python2 and python3 !
"""
result = [] # Python3 s... |
def json_qs_parser(body):
"""
Parses response body from JSON, XML or query string.
:param body:
string
:returns:
:class:`dict`, :class:`list` if input is JSON or query string,
:class:`xml.etree.ElementTree.Element` if XML.
"""
try:
# Try JSON first.
ret... | def function[json_qs_parser, parameter[body]]:
constant[
Parses response body from JSON, XML or query string.
:param body:
string
:returns:
:class:`dict`, :class:`list` if input is JSON or query string,
:class:`xml.etree.ElementTree.Element` if XML.
]
<ast.Try obje... | keyword[def] identifier[json_qs_parser] ( identifier[body] ):
literal[string]
keyword[try] :
keyword[return] identifier[json] . identifier[loads] ( identifier[body] )
keyword[except] ( identifier[OverflowError] , identifier[TypeError] , identifier[ValueError] ):
keyword[pass]
... | def json_qs_parser(body):
"""
Parses response body from JSON, XML or query string.
:param body:
string
:returns:
:class:`dict`, :class:`list` if input is JSON or query string,
:class:`xml.etree.ElementTree.Element` if XML.
"""
try:
# Try JSON first.
ret... |
def available_dataset_ids(self, reader_name=None, composites=False):
"""Get names of available datasets, globally or just for *reader_name*
if specified, that can be loaded.
Available dataset names are determined by what each individual reader
can load. This is normally determined by wh... | def function[available_dataset_ids, parameter[self, reader_name, composites]]:
constant[Get names of available datasets, globally or just for *reader_name*
if specified, that can be loaded.
Available dataset names are determined by what each individual reader
can load. This is normally ... | keyword[def] identifier[available_dataset_ids] ( identifier[self] , identifier[reader_name] = keyword[None] , identifier[composites] = keyword[False] ):
literal[string]
keyword[try] :
keyword[if] identifier[reader_name] :
identifier[readers] =[ identifier[self] . iden... | def available_dataset_ids(self, reader_name=None, composites=False):
"""Get names of available datasets, globally or just for *reader_name*
if specified, that can be loaded.
Available dataset names are determined by what each individual reader
can load. This is normally determined by what f... |
def permissions_for(self, member):
"""Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters
----------
... | def function[permissions_for, parameter[self, member]]:
constant[Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parame... | keyword[def] identifier[permissions_for] ( identifier[self] , identifier[member] ):
literal[string]
identifier[o] = identifier[self] . identifier[guild] . identifier[owner]
keyword[if] ... | def permissions_for(self, member):
"""Handles permission resolution for the current :class:`Member`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
Parameters
----------
... |
def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = "inputs" if problem.has_inputs else "targets"
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [
_encode(inputs, ... | def function[predict, parameter[inputs_list, problem, request_fn]]:
constant[Encodes inputs, makes request to deployed TF model, and decodes outputs.]
assert[call[name[isinstance], parameter[name[inputs_list], name[list]]]]
variable[fname] assign[=] <ast.IfExp object at 0x7da1b20e4fd0>
varia... | keyword[def] identifier[predict] ( identifier[inputs_list] , identifier[problem] , identifier[request_fn] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[inputs_list] , identifier[list] )
identifier[fname] = literal[string] keyword[if] identifier[problem] . identifier[has_inputs] ... | def predict(inputs_list, problem, request_fn):
"""Encodes inputs, makes request to deployed TF model, and decodes outputs."""
assert isinstance(inputs_list, list)
fname = 'inputs' if problem.has_inputs else 'targets'
input_encoder = problem.feature_info[fname].encoder
input_ids_list = [_encode(input... |
def _find_local_handlers(cls, handlers, namespace, configs):
"""Add name info to every "local" (present in the body of this class)
handler and add it to the mapping.
"""
for aname, avalue in namespace.items():
sig_name, config = cls._is_handler(aname, avalue)
if ... | def function[_find_local_handlers, parameter[cls, handlers, namespace, configs]]:
constant[Add name info to every "local" (present in the body of this class)
handler and add it to the mapping.
]
for taget[tuple[[<ast.Name object at 0x7da1b1047310>, <ast.Name object at 0x7da1b10473a0>]]] ... | keyword[def] identifier[_find_local_handlers] ( identifier[cls] , identifier[handlers] , identifier[namespace] , identifier[configs] ):
literal[string]
keyword[for] identifier[aname] , identifier[avalue] keyword[in] identifier[namespace] . identifier[items] ():
identifier[sig_name] ... | def _find_local_handlers(cls, handlers, namespace, configs):
"""Add name info to every "local" (present in the body of this class)
handler and add it to the mapping.
"""
for (aname, avalue) in namespace.items():
(sig_name, config) = cls._is_handler(aname, avalue)
if sig_name:
... |
def container(dec):
"""Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator
"""
# Credits: http://stackoverflow.com/a/1167248/1798683
@wraps(d... | def function[container, parameter[dec]]:
constant[Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator
]
def function[meta_decorator, para... | keyword[def] identifier[container] ( identifier[dec] ):
literal[string]
@ identifier[wraps] ( identifier[dec] )
keyword[def] identifier[meta_decorator] ( identifier[f] ):
identifier[decorator] = identifier[dec] ( identifier[f] )
identifier[decorator] . identifier[orig_func] = id... | def container(dec):
"""Meta-decorator (for decorating decorators)
Keeps around original decorated function as a property ``orig_func``
:param dec: Decorator to decorate
:type dec: function
:returns: Decorated decorator
"""
# Credits: http://stackoverflow.com/a/1167248/1798683
@wraps(... |
def resolve_heron_suffix_issue(abs_pex_path, class_path):
"""Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this Heron ... | def function[resolve_heron_suffix_issue, parameter[abs_pex_path, class_path]]:
constant[Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the ... | keyword[def] identifier[resolve_heron_suffix_issue] ( identifier[abs_pex_path] , identifier[class_path] ):
literal[string]
identifier[importer] = identifier[zipimport] . identifier[zipimporter] ( identifier[abs_pex_path] )
identifier[importer] . identifier[load_module] ( literal[string] )
identifi... | def resolve_heron_suffix_issue(abs_pex_path, class_path):
"""Resolves duplicate package suffix problems
When dynamically loading a pex file and a corresponding python class (bolt/spout/topology),
if the top level package in which to-be-loaded classes reside is named 'heron', the path conflicts
with this Hero... |
def read_files(files, readers, **kwargs):
"""Read the files in `files` with the reader objects in `readers`.
Parameters
----------
files : list [str]
A list of file paths to be read by the readers. Supported files are
limited to text and nxml files.
readers : list [Reader instances]... | def function[read_files, parameter[files, readers]]:
constant[Read the files in `files` with the reader objects in `readers`.
Parameters
----------
files : list [str]
A list of file paths to be read by the readers. Supported files are
limited to text and nxml files.
readers : li... | keyword[def] identifier[read_files] ( identifier[files] , identifier[readers] ,** identifier[kwargs] ):
literal[string]
identifier[reading_content] =[ identifier[Content] . identifier[from_file] ( identifier[filepath] ) keyword[for] identifier[filepath] keyword[in] identifier[files] ]
identifier[ou... | def read_files(files, readers, **kwargs):
"""Read the files in `files` with the reader objects in `readers`.
Parameters
----------
files : list [str]
A list of file paths to be read by the readers. Supported files are
limited to text and nxml files.
readers : list [Reader instances]... |
async def issue_events(self):
""" This function will be automatically run from main.py and triggers the following functions:
- on_unit_created
- on_unit_destroyed
- on_building_construction_complete
"""
await self._issue_unit_dead_events()
await self._issue_unit_a... | <ast.AsyncFunctionDef object at 0x7da18dc993f0> | keyword[async] keyword[def] identifier[issue_events] ( identifier[self] ):
literal[string]
keyword[await] identifier[self] . identifier[_issue_unit_dead_events] ()
keyword[await] identifier[self] . identifier[_issue_unit_added_events] ()
keyword[for] identifier[unit] keyword[... | async def issue_events(self):
""" This function will be automatically run from main.py and triggers the following functions:
- on_unit_created
- on_unit_destroyed
- on_building_construction_complete
"""
await self._issue_unit_dead_events()
await self._issue_unit_added_events(... |
def save_context(self) -> bool:
"""Save current position."""
self._contexts.append(self._cursor.position)
return True | def function[save_context, parameter[self]]:
constant[Save current position.]
call[name[self]._contexts.append, parameter[name[self]._cursor.position]]
return[constant[True]] | keyword[def] identifier[save_context] ( identifier[self] )-> identifier[bool] :
literal[string]
identifier[self] . identifier[_contexts] . identifier[append] ( identifier[self] . identifier[_cursor] . identifier[position] )
keyword[return] keyword[True] | def save_context(self) -> bool:
"""Save current position."""
self._contexts.append(self._cursor.position)
return True |
def create_pw(length=8, digits=2, upper=2, lower=2):
"""Create a random password
From Stackoverflow:
http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator
Create a random password with the specified length and no. of
digit, upper and lower case letters.
:para... | def function[create_pw, parameter[length, digits, upper, lower]]:
constant[Create a random password
From Stackoverflow:
http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator
Create a random password with the specified length and no. of
digit, upper and lower c... | keyword[def] identifier[create_pw] ( identifier[length] = literal[int] , identifier[digits] = literal[int] , identifier[upper] = literal[int] , identifier[lower] = literal[int] ):
literal[string]
identifier[seed] ( identifier[time] ())
identifier[lowercase] = identifier[string] . identifier[ascii_lo... | def create_pw(length=8, digits=2, upper=2, lower=2):
"""Create a random password
From Stackoverflow:
http://stackoverflow.com/questions/7479442/high-quality-simple-random-password-generator
Create a random password with the specified length and no. of
digit, upper and lower case letters.
:para... |
def reads(s, format, **kwargs):
"""Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
returned will always be in the current version's format.
Parameters
----------
s : unicode
The raw unicode string t... | def function[reads, parameter[s, format]]:
constant[Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
returned will always be in the current version's format.
Parameters
----------
s : unicode
The... | keyword[def] identifier[reads] ( identifier[s] , identifier[format] ,** identifier[kwargs] ):
literal[string]
identifier[format] = identifier[unicode] ( identifier[format] )
keyword[if] identifier[format] == literal[string] keyword[or] identifier[format] == literal[string] :
keyword[return... | def reads(s, format, **kwargs):
"""Read a notebook from a string and return the NotebookNode object.
This function properly handles notebooks of any version. The notebook
returned will always be in the current version's format.
Parameters
----------
s : unicode
The raw unicode string t... |
def _N_lines():
''' Determine how many lines to print, such that the number of items
displayed will fit on the terminal (i.e one 'screen-ful' of items)
This looks at the environmental prompt variable, and tries to determine
how many lines it takes up.
On Windows... | def function[_N_lines, parameter[]]:
constant[ Determine how many lines to print, such that the number of items
displayed will fit on the terminal (i.e one 'screen-ful' of items)
This looks at the environmental prompt variable, and tries to determine
how many lines it takes ... | keyword[def] identifier[_N_lines] ():
literal[string]
identifier[lines_in_prompt] = literal[int]
keyword[if] literal[string] keyword[in] identifier[sys] . identifier[platform] :
identifier[lines_in_prompt] += literal[int]
identifier[a] =... | def _N_lines():
""" Determine how many lines to print, such that the number of items
displayed will fit on the terminal (i.e one 'screen-ful' of items)
This looks at the environmental prompt variable, and tries to determine
how many lines it takes up.
On Windows, it... |
def graph_to_gdfs(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True):
"""
Convert a graph into node and/or edge GeoDataFrames
Parameters
----------
G : networkx multidigraph
nodes : bool
if True, convert graph nodes to a GeoDataFrame and return it
edges : bool
... | def function[graph_to_gdfs, parameter[G, nodes, edges, node_geometry, fill_edge_geometry]]:
constant[
Convert a graph into node and/or edge GeoDataFrames
Parameters
----------
G : networkx multidigraph
nodes : bool
if True, convert graph nodes to a GeoDataFrame and return it
edg... | keyword[def] identifier[graph_to_gdfs] ( identifier[G] , identifier[nodes] = keyword[True] , identifier[edges] = keyword[True] , identifier[node_geometry] = keyword[True] , identifier[fill_edge_geometry] = keyword[True] ):
literal[string]
keyword[if] keyword[not] ( identifier[nodes] keyword[or] identif... | def graph_to_gdfs(G, nodes=True, edges=True, node_geometry=True, fill_edge_geometry=True):
"""
Convert a graph into node and/or edge GeoDataFrames
Parameters
----------
G : networkx multidigraph
nodes : bool
if True, convert graph nodes to a GeoDataFrame and return it
edges : bool
... |
def write(self, proto):
"""
:param proto: capnp HTMPredictionModelProto message builder
"""
super(HTMPredictionModel, self).writeBaseToProto(proto.modelBase)
proto.numRunCalls = self.__numRunCalls
proto.minLikelihoodThreshold = self._minLikelihoodThreshold
proto.maxPredictionsPerStep = self... | def function[write, parameter[self, proto]]:
constant[
:param proto: capnp HTMPredictionModelProto message builder
]
call[call[name[super], parameter[name[HTMPredictionModel], name[self]]].writeBaseToProto, parameter[name[proto].modelBase]]
name[proto].numRunCalls assign[=] name[self].__... | keyword[def] identifier[write] ( identifier[self] , identifier[proto] ):
literal[string]
identifier[super] ( identifier[HTMPredictionModel] , identifier[self] ). identifier[writeBaseToProto] ( identifier[proto] . identifier[modelBase] )
identifier[proto] . identifier[numRunCalls] = identifier[self] .... | def write(self, proto):
"""
:param proto: capnp HTMPredictionModelProto message builder
"""
super(HTMPredictionModel, self).writeBaseToProto(proto.modelBase)
proto.numRunCalls = self.__numRunCalls
proto.minLikelihoodThreshold = self._minLikelihoodThreshold
proto.maxPredictionsPerStep = self.... |
def toNumber (str, default=None):
"""toNumber(str[, default]) -> integer | float | default
Converts the given string to a numeric value. The string may be a
hexadecimal, integer, or floating number. If string could not be
converted, default (None) is returned.
Examples:
>>> n = toNumber("0x... | def function[toNumber, parameter[str, default]]:
constant[toNumber(str[, default]) -> integer | float | default
Converts the given string to a numeric value. The string may be a
hexadecimal, integer, or floating number. If string could not be
converted, default (None) is returned.
Examples:
... | keyword[def] identifier[toNumber] ( identifier[str] , identifier[default] = keyword[None] ):
literal[string]
identifier[value] = identifier[default]
keyword[try] :
keyword[if] identifier[str] . identifier[startswith] ( literal[string] ):
identifier[value] = identifier[int] ( i... | def toNumber(str, default=None):
"""toNumber(str[, default]) -> integer | float | default
Converts the given string to a numeric value. The string may be a
hexadecimal, integer, or floating number. If string could not be
converted, default (None) is returned.
Examples:
>>> n = toNumber("0x2... |
def adjoint(self):
"""Return the adjoint operator."""
if not self.is_linear:
raise ValueError('operator with nonzero pad_const ({}) is not'
' linear and has no adjoint'
''.format(self.pad_const))
return -PartialDerivative(sel... | def function[adjoint, parameter[self]]:
constant[Return the adjoint operator.]
if <ast.UnaryOp object at 0x7da1b1e46410> begin[:]
<ast.Raise object at 0x7da1b1e464a0>
return[<ast.UnaryOp object at 0x7da1b1e46950>] | keyword[def] identifier[adjoint] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_linear] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string]
literal[string] . identifier[format] ( ident... | def adjoint(self):
"""Return the adjoint operator."""
if not self.is_linear:
raise ValueError('operator with nonzero pad_const ({}) is not linear and has no adjoint'.format(self.pad_const)) # depends on [control=['if'], data=[]]
return -PartialDerivative(self.range, self.axis, self.domain, _ADJ_MET... |
def short(self):
'''Short-form of the unit title, excluding any unit date, as an instance
of :class:`~eulxml.xmlmap.eadmap.UnitTitle` . Can be used with formatting
anywhere the full form of the unittitle can be used.'''
# if there is no unitdate to remove, just return the current object
... | def function[short, parameter[self]]:
constant[Short-form of the unit title, excluding any unit date, as an instance
of :class:`~eulxml.xmlmap.eadmap.UnitTitle` . Can be used with formatting
anywhere the full form of the unittitle can be used.]
if <ast.UnaryOp object at 0x7da1b28799c0> b... | keyword[def] identifier[short] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[unitdate] :
keyword[return] identifier[self]
identifier[ut] = identifier[UnitTitle] ( identifier[node] = identifi... | def short(self):
"""Short-form of the unit title, excluding any unit date, as an instance
of :class:`~eulxml.xmlmap.eadmap.UnitTitle` . Can be used with formatting
anywhere the full form of the unittitle can be used."""
# if there is no unitdate to remove, just return the current object
if n... |
def send_os_command(self, os_command_text, is_priority=False):
"""
Send a command to the operating system running in this partition.
Parameters:
os_command_text (string): The text of the operating system command.
is_priority (bool):
Boolean controlling whether ... | def function[send_os_command, parameter[self, os_command_text, is_priority]]:
constant[
Send a command to the operating system running in this partition.
Parameters:
os_command_text (string): The text of the operating system command.
is_priority (bool):
Boolean... | keyword[def] identifier[send_os_command] ( identifier[self] , identifier[os_command_text] , identifier[is_priority] = keyword[False] ):
literal[string]
identifier[body] ={ literal[string] : identifier[is_priority] ,
literal[string] : identifier[os_command_text] }
identifier[self] ... | def send_os_command(self, os_command_text, is_priority=False):
"""
Send a command to the operating system running in this partition.
Parameters:
os_command_text (string): The text of the operating system command.
is_priority (bool):
Boolean controlling whether this... |
def size(self):
"""
Size of LazyCell: the size of the intension plus accounting for
excluded and included additions.
The exclusions are assumed to be part of the set
The inclusions are assumed to NOT be part of the intension
"""
return self._size_full_intension ... | def function[size, parameter[self]]:
constant[
Size of LazyCell: the size of the intension plus accounting for
excluded and included additions.
The exclusions are assumed to be part of the set
The inclusions are assumed to NOT be part of the intension
]
return[binar... | keyword[def] identifier[size] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_size_full_intension] - identifier[len] ( identifier[self] . identifier[exclude] )+ identifier[len] ( identifier[self] . identifier[include] ) | def size(self):
"""
Size of LazyCell: the size of the intension plus accounting for
excluded and included additions.
The exclusions are assumed to be part of the set
The inclusions are assumed to NOT be part of the intension
"""
return self._size_full_intension - len(se... |
def pypy_json_encode(value, pretty=False):
"""
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
"""
global _dealing_with_problem
if pretty:
return pretty_json(value)
try:
_buffer = UnicodeBuilder(2048)
_value2json(value, _buffer)
output = _buffer.build()
return... | def function[pypy_json_encode, parameter[value, pretty]]:
constant[
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
]
<ast.Global object at 0x7da1b20aa0e0>
if name[pretty] begin[:]
return[call[name[pretty_json], parameter[name[value]]]]
<ast.Try object at 0x7da1b20a83a0> | keyword[def] identifier[pypy_json_encode] ( identifier[value] , identifier[pretty] = keyword[False] ):
literal[string]
keyword[global] identifier[_dealing_with_problem]
keyword[if] identifier[pretty] :
keyword[return] identifier[pretty_json] ( identifier[value] )
keyword[try] :
... | def pypy_json_encode(value, pretty=False):
"""
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
"""
global _dealing_with_problem
if pretty:
return pretty_json(value) # depends on [control=['if'], data=[]]
try:
_buffer = UnicodeBuilder(2048)
_value2json(value, _buffer)
... |
def setup_pilotpoints_grid(ml=None,sr=None,ibound=None,prefix_dict=None,
every_n_cell=4,
use_ibound_zones=False,
pp_dir='.',tpl_dir='.',
shapename="pp.shp"):
""" setup regularly-spaced (gridded) pilot point p... | def function[setup_pilotpoints_grid, parameter[ml, sr, ibound, prefix_dict, every_n_cell, use_ibound_zones, pp_dir, tpl_dir, shapename]]:
constant[ setup regularly-spaced (gridded) pilot point parameterization
Parameters
----------
ml : flopy.mbase
a flopy mbase dervied type. If None, sr m... | keyword[def] identifier[setup_pilotpoints_grid] ( identifier[ml] = keyword[None] , identifier[sr] = keyword[None] , identifier[ibound] = keyword[None] , identifier[prefix_dict] = keyword[None] ,
identifier[every_n_cell] = literal[int] ,
identifier[use_ibound_zones] = keyword[False] ,
identifier[pp_dir] = literal[s... | def setup_pilotpoints_grid(ml=None, sr=None, ibound=None, prefix_dict=None, every_n_cell=4, use_ibound_zones=False, pp_dir='.', tpl_dir='.', shapename='pp.shp'):
""" setup regularly-spaced (gridded) pilot point parameterization
Parameters
----------
ml : flopy.mbase
a flopy mbase dervied type. ... |
def definite_article(word, gender=MALE, role=SUBJECT):
""" Returns the definite article (der/die/das/die) for a given word.
"""
return article_definite.get((gender[:1].lower(), role[:3].lower())) | def function[definite_article, parameter[word, gender, role]]:
constant[ Returns the definite article (der/die/das/die) for a given word.
]
return[call[name[article_definite].get, parameter[tuple[[<ast.Call object at 0x7da1b26aece0>, <ast.Call object at 0x7da1b26afa00>]]]]] | keyword[def] identifier[definite_article] ( identifier[word] , identifier[gender] = identifier[MALE] , identifier[role] = identifier[SUBJECT] ):
literal[string]
keyword[return] identifier[article_definite] . identifier[get] (( identifier[gender] [: literal[int] ]. identifier[lower] (), identifier[role] [:... | def definite_article(word, gender=MALE, role=SUBJECT):
""" Returns the definite article (der/die/das/die) for a given word.
"""
return article_definite.get((gender[:1].lower(), role[:3].lower())) |
def _updateInferenceStats(self, statistics, objectName=None):
"""
Updates the inference statistics.
Parameters:
----------------------------
@param statistics (dict)
Dictionary in which to write the statistics
@param objectName (str)
Name of the inferred object, if kn... | def function[_updateInferenceStats, parameter[self, statistics, objectName]]:
constant[
Updates the inference statistics.
Parameters:
----------------------------
@param statistics (dict)
Dictionary in which to write the statistics
@param objectName (str)
Name of ... | keyword[def] identifier[_updateInferenceStats] ( identifier[self] , identifier[statistics] , identifier[objectName] = keyword[None] ):
literal[string]
identifier[L4Representations] = identifier[self] . identifier[getL4Representations] ()
identifier[L4PredictedCells] = identifier[self] . identifier[get... | def _updateInferenceStats(self, statistics, objectName=None):
"""
Updates the inference statistics.
Parameters:
----------------------------
@param statistics (dict)
Dictionary in which to write the statistics
@param objectName (str)
Name of the inferred object, if kn... |
def ipinfo_ip_check(ip):
"""Checks ipinfo.io for basic WHOIS-type data on an IP address"""
if not is_IPv4Address(ip):
return None
response = requests.get('http://ipinfo.io/%s/json' % ip)
return response.json() | def function[ipinfo_ip_check, parameter[ip]]:
constant[Checks ipinfo.io for basic WHOIS-type data on an IP address]
if <ast.UnaryOp object at 0x7da1b28ae080> begin[:]
return[constant[None]]
variable[response] assign[=] call[name[requests].get, parameter[binary_operation[constant[http://i... | keyword[def] identifier[ipinfo_ip_check] ( identifier[ip] ):
literal[string]
keyword[if] keyword[not] identifier[is_IPv4Address] ( identifier[ip] ):
keyword[return] keyword[None]
identifier[response] = identifier[requests] . identifier[get] ( literal[string] % identifier[ip] )
keywo... | def ipinfo_ip_check(ip):
"""Checks ipinfo.io for basic WHOIS-type data on an IP address"""
if not is_IPv4Address(ip):
return None # depends on [control=['if'], data=[]]
response = requests.get('http://ipinfo.io/%s/json' % ip)
return response.json() |
def intercepts(self, joinpoint):
"""Self target interception if self is enabled
:param joinpoint: advices executor
"""
result = None
if self.enable:
interception = getattr(self, Interceptor.INTERCEPTION)
joinpoint.exec_ctx[Interceptor.INTERCEPTION] = ... | def function[intercepts, parameter[self, joinpoint]]:
constant[Self target interception if self is enabled
:param joinpoint: advices executor
]
variable[result] assign[=] constant[None]
if name[self].enable begin[:]
variable[interception] assign[=] call[name[geta... | keyword[def] identifier[intercepts] ( identifier[self] , identifier[joinpoint] ):
literal[string]
identifier[result] = keyword[None]
keyword[if] identifier[self] . identifier[enable] :
identifier[interception] = identifier[getattr] ( identifier[self] , identifier[Intercep... | def intercepts(self, joinpoint):
"""Self target interception if self is enabled
:param joinpoint: advices executor
"""
result = None
if self.enable:
interception = getattr(self, Interceptor.INTERCEPTION)
joinpoint.exec_ctx[Interceptor.INTERCEPTION] = self
result = in... |
def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, str):
return value
elif isinstance(value, dict):
try:
value = value['url']
except KeyError:
raise ValidationError("dictionary must contain an 'url' ... | def function[to_python, parameter[self, value]]:
constant[Convert value if needed.]
if call[name[isinstance], parameter[name[value], name[str]]] begin[:]
return[name[value]] | keyword[def] identifier[to_python] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[str] ):
keyword[return] identifier[value]
keyword[elif] identifier[isinstance] ( identifier[value] , identifier[... | def to_python(self, value):
"""Convert value if needed."""
if isinstance(value, str):
return value # depends on [control=['if'], data=[]]
elif isinstance(value, dict):
try:
value = value['url'] # depends on [control=['try'], data=[]]
except KeyError:
raise V... |
def ckgpav(inst, sclkdp, tol, ref):
"""
Get pointing (attitude) and angular velocity
for a specified spacecraft clock time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html
:param inst: NAIF ID of instrument, spacecraft, or structure.
:type inst: int
:param sclkdp: Enc... | def function[ckgpav, parameter[inst, sclkdp, tol, ref]]:
constant[
Get pointing (attitude) and angular velocity
for a specified spacecraft clock time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html
:param inst: NAIF ID of instrument, spacecraft, or structure.
:type i... | keyword[def] identifier[ckgpav] ( identifier[inst] , identifier[sclkdp] , identifier[tol] , identifier[ref] ):
literal[string]
identifier[inst] = identifier[ctypes] . identifier[c_int] ( identifier[inst] )
identifier[sclkdp] = identifier[ctypes] . identifier[c_double] ( identifier[sclkdp] )
ident... | def ckgpav(inst, sclkdp, tol, ref):
"""
Get pointing (attitude) and angular velocity
for a specified spacecraft clock time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckgpav_c.html
:param inst: NAIF ID of instrument, spacecraft, or structure.
:type inst: int
:param sclkdp: Enc... |
def next(self):
"""Return 'next' version. Eg, next(1.2) is 1.2_"""
if self.tokens:
other = self.copy()
tok = other.tokens.pop()
other.tokens.append(tok.next())
return other
else:
return Version.inf | def function[next, parameter[self]]:
constant[Return 'next' version. Eg, next(1.2) is 1.2_]
if name[self].tokens begin[:]
variable[other] assign[=] call[name[self].copy, parameter[]]
variable[tok] assign[=] call[name[other].tokens.pop, parameter[]]
call[na... | keyword[def] identifier[next] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[tokens] :
identifier[other] = identifier[self] . identifier[copy] ()
identifier[tok] = identifier[other] . identifier[tokens] . identifier[pop] ()
id... | def next(self):
"""Return 'next' version. Eg, next(1.2) is 1.2_"""
if self.tokens:
other = self.copy()
tok = other.tokens.pop()
other.tokens.append(tok.next())
return other # depends on [control=['if'], data=[]]
else:
return Version.inf |
def log(self, message):
"""
打印或写日志
:params message: 要打印或要写的日志
"""
theLog = '[日志名:%s] [时间:%s] \n[内容:\n%s]\n\n' % (
self.startName, timestamp_to_time(get_current_timestamp()), message)
if not self.fileName:
print(theLog)
else:
... | def function[log, parameter[self, message]]:
constant[
打印或写日志
:params message: 要打印或要写的日志
]
variable[theLog] assign[=] binary_operation[constant[[日志名:%s] [时间:%s]
[内容:
%s]
] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b14d1e40>, <ast.Call object at 0x... | keyword[def] identifier[log] ( identifier[self] , identifier[message] ):
literal[string]
identifier[theLog] = literal[string] %(
identifier[self] . identifier[startName] , identifier[timestamp_to_time] ( identifier[get_current_timestamp] ()), identifier[message] )
keyword[if] key... | def log(self, message):
"""
打印或写日志
:params message: 要打印或要写的日志
"""
theLog = '[日志名:%s] [时间:%s] \n[内容:\n%s]\n\n' % (self.startName, timestamp_to_time(get_current_timestamp()), message)
if not self.fileName:
print(theLog) # depends on [control=['if'], data=[]]
else:
... |
def command_line_arguments(command_line_parameters):
"""Defines the command line parameters that are accepted."""
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
# - t... | def function[command_line_arguments, parameter[command_line_parameters]]:
constant[Defines the command line parameters that are accepted.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[-a], constant[--algorithms]]]
... | keyword[def] identifier[command_line_arguments] ( identifier[command_line_parameters] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = literal[string] , identifier[formatter_class] = identifier[argparse] . identifier[ArgumentDefaultsHelpF... | def command_line_arguments(command_line_parameters):
"""Defines the command line parameters that are accepted."""
# create parser
parser = argparse.ArgumentParser(description='Execute baseline algorithms with default parameters', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# add parameters
... |
def save_freesurfer_morph(filename, obj, face_count=0):
'''
save_freesurfer_morph(filename, obj) saves the given object using nibabel.freesurfer.io's
write_morph_data function, and returns the given filename.
'''
fsio.write_morph_data(filename, obj, fnum=face_count)
return filename | def function[save_freesurfer_morph, parameter[filename, obj, face_count]]:
constant[
save_freesurfer_morph(filename, obj) saves the given object using nibabel.freesurfer.io's
write_morph_data function, and returns the given filename.
]
call[name[fsio].write_morph_data, parameter[name[filen... | keyword[def] identifier[save_freesurfer_morph] ( identifier[filename] , identifier[obj] , identifier[face_count] = literal[int] ):
literal[string]
identifier[fsio] . identifier[write_morph_data] ( identifier[filename] , identifier[obj] , identifier[fnum] = identifier[face_count] )
keyword[return] ide... | def save_freesurfer_morph(filename, obj, face_count=0):
"""
save_freesurfer_morph(filename, obj) saves the given object using nibabel.freesurfer.io's
write_morph_data function, and returns the given filename.
"""
fsio.write_morph_data(filename, obj, fnum=face_count)
return filename |
def mpl_rc_context(f):
"""
Decorator for MPLPlot methods applying the matplotlib rc params
in the plots fig_rcparams while when method is called.
"""
def wrapper(self, *args, **kwargs):
with _rc_context(self.fig_rcparams):
return f(self, *args, **kwargs)
return wrapper | def function[mpl_rc_context, parameter[f]]:
constant[
Decorator for MPLPlot methods applying the matplotlib rc params
in the plots fig_rcparams while when method is called.
]
def function[wrapper, parameter[self]]:
with call[name[_rc_context], parameter[name[self].fig_rcparam... | keyword[def] identifier[mpl_rc_context] ( identifier[f] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[with] identifier[_rc_context] ( identifier[self] . identifier[fig_rcparams] ):
keyword[return] identi... | def mpl_rc_context(f):
"""
Decorator for MPLPlot methods applying the matplotlib rc params
in the plots fig_rcparams while when method is called.
"""
def wrapper(self, *args, **kwargs):
with _rc_context(self.fig_rcparams):
return f(self, *args, **kwargs) # depends on [control=[... |
def _pkcs1imify(self, data):
"""
turn a 20-byte SHA1 hash into a blob of data as large as the key's N,
using PKCS1's \"emsa-pkcs1-v1_5\" encoding. totally bizarre.
"""
size = len(util.deflate_long(self.n, 0))
filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) -... | def function[_pkcs1imify, parameter[self, data]]:
constant[
turn a 20-byte SHA1 hash into a blob of data as large as the key's N,
using PKCS1's "emsa-pkcs1-v1_5" encoding. totally bizarre.
]
variable[size] assign[=] call[name[len], parameter[call[name[util].deflate_long, paramet... | keyword[def] identifier[_pkcs1imify] ( identifier[self] , identifier[data] ):
literal[string]
identifier[size] = identifier[len] ( identifier[util] . identifier[deflate_long] ( identifier[self] . identifier[n] , literal[int] ))
identifier[filler] = identifier[max_byte] *( identifier[size] ... | def _pkcs1imify(self, data):
"""
turn a 20-byte SHA1 hash into a blob of data as large as the key's N,
using PKCS1's "emsa-pkcs1-v1_5" encoding. totally bizarre.
"""
size = len(util.deflate_long(self.n, 0))
filler = max_byte * (size - len(SHA1_DIGESTINFO) - len(data) - 3)
return... |
def get_unavailable_brokers(zk, partition_metadata):
"""Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas.
"""
topic_data = zk.get_topics(partition_metadata.topic)
topic = partition_metadata.topic
partition = partition_m... | def function[get_unavailable_brokers, parameter[zk, partition_metadata]]:
constant[Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas.
]
variable[topic_data] assign[=] call[name[zk].get_topics, parameter[name[partition_me... | keyword[def] identifier[get_unavailable_brokers] ( identifier[zk] , identifier[partition_metadata] ):
literal[string]
identifier[topic_data] = identifier[zk] . identifier[get_topics] ( identifier[partition_metadata] . identifier[topic] )
identifier[topic] = identifier[partition_metadata] . identifier[... | def get_unavailable_brokers(zk, partition_metadata):
"""Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas.
"""
topic_data = zk.get_topics(partition_metadata.topic)
topic = partition_metadata.topic
partition = partition_m... |
def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.... | def function[update_app_icon, parameter[self]]:
constant[
Update the app icon if the user is not trying to resize the window.
]
if <ast.BoolOp object at 0x7da20c6e5a80> begin[:]
return[None]
variable[cur_time] assign[=] call[name[time].time, parameter[]]
if compar... | keyword[def] identifier[update_app_icon] ( identifier[self] ):
literal[string]
keyword[if] identifier[os] . identifier[name] == literal[string] keyword[or] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[return]
identifier[cur_tim... | def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return # depends on [control=['if'], data=[]]
... |
def decode_payload(self, specialize = False):
"""Decode payload from the element passed to the stanza constructor.
Iterates over stanza children and creates StanzaPayload objects for
them. Called automatically by `get_payload()` and other methods that
access the payload.
For th... | def function[decode_payload, parameter[self, specialize]]:
constant[Decode payload from the element passed to the stanza constructor.
Iterates over stanza children and creates StanzaPayload objects for
them. Called automatically by `get_payload()` and other methods that
access the paylo... | keyword[def] identifier[decode_payload] ( identifier[self] , identifier[specialize] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[_payload] keyword[is] keyword[not] keyword[None] :
keyword[return]
keyword[if] identifier[self] . id... | def decode_payload(self, specialize=False):
"""Decode payload from the element passed to the stanza constructor.
Iterates over stanza children and creates StanzaPayload objects for
them. Called automatically by `get_payload()` and other methods that
access the payload.
For the `Sta... |
def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
Y... | def function[variable_map_items, parameter[variable_map]]:
constant[Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variabl... | keyword[def] identifier[variable_map_items] ( identifier[variable_map] ):
literal[string]
keyword[for] identifier[key] , identifier[var_or_vars] keyword[in] identifier[six] . identifier[iteritems] ( identifier[variable_map] ):
keyword[if] identifier[isinstance] ( identifier[var_or_vars] ,( identifier[... | def variable_map_items(variable_map):
"""Yields an iterator over (string, variable) pairs in the variable map.
In general, variable maps map variable names to either a `tf.Variable`, or
list of `tf.Variable`s (in case of sliced variables).
Args:
variable_map: dict, variable map over which to iterate.
... |
def convert_body_to_bytes(resp):
"""
If the request body is a string, encode it to bytes (for python3 support)
By default yaml serializes to utf-8 encoded bytestrings.
When this cassette is loaded by python3, it's automatically decoded
into unicode strings. This makes sure that it stays a bytestrin... | def function[convert_body_to_bytes, parameter[resp]]:
constant[
If the request body is a string, encode it to bytes (for python3 support)
By default yaml serializes to utf-8 encoded bytestrings.
When this cassette is loaded by python3, it's automatically decoded
into unicode strings. This makes... | keyword[def] identifier[convert_body_to_bytes] ( identifier[resp] ):
literal[string]
keyword[try] :
keyword[if] identifier[resp] [ literal[string] ][ literal[string] ] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[isinstance] ( identifier[resp] [ literal[string]... | def convert_body_to_bytes(resp):
"""
If the request body is a string, encode it to bytes (for python3 support)
By default yaml serializes to utf-8 encoded bytestrings.
When this cassette is loaded by python3, it's automatically decoded
into unicode strings. This makes sure that it stays a bytestrin... |
def dependency(self, node1, node2):
"indicate that node1 depends on node2"
self.graph.add_node(node1)
self.graph.add_node(node2)
self.graph.add_edge(node2, node1) | def function[dependency, parameter[self, node1, node2]]:
constant[indicate that node1 depends on node2]
call[name[self].graph.add_node, parameter[name[node1]]]
call[name[self].graph.add_node, parameter[name[node2]]]
call[name[self].graph.add_edge, parameter[name[node2], name[node1]]] | keyword[def] identifier[dependency] ( identifier[self] , identifier[node1] , identifier[node2] ):
literal[string]
identifier[self] . identifier[graph] . identifier[add_node] ( identifier[node1] )
identifier[self] . identifier[graph] . identifier[add_node] ( identifier[node2] )
ide... | def dependency(self, node1, node2):
"""indicate that node1 depends on node2"""
self.graph.add_node(node1)
self.graph.add_node(node2)
self.graph.add_edge(node2, node1) |
def update_clipboard(self, text):
'''将文本复制到系统剪贴板里面'''
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(text, -1)
self.toast(_('{0} copied to clipboard'.format(text))) | def function[update_clipboard, parameter[self, text]]:
constant[将文本复制到系统剪贴板里面]
variable[clipboard] assign[=] call[name[Gtk].Clipboard.get, parameter[name[Gdk].SELECTION_CLIPBOARD]]
call[name[clipboard].set_text, parameter[name[text], <ast.UnaryOp object at 0x7da1b1d52650>]]
call[name[sel... | keyword[def] identifier[update_clipboard] ( identifier[self] , identifier[text] ):
literal[string]
identifier[clipboard] = identifier[Gtk] . identifier[Clipboard] . identifier[get] ( identifier[Gdk] . identifier[SELECTION_CLIPBOARD] )
identifier[clipboard] . identifier[set_text] ( identifi... | def update_clipboard(self, text):
"""将文本复制到系统剪贴板里面"""
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
clipboard.set_text(text, -1)
self.toast(_('{0} copied to clipboard'.format(text))) |
def queue_declare(self, queue, durable, exclusive, auto_delete,
warn_if_exists=False, arguments=None):
"""Declare a named queue."""
if warn_if_exists and self.queue_exists(queue):
warnings.warn(QueueAlreadyExistsWarning(
QueueAlreadyExistsWarning.__doc__))
... | def function[queue_declare, parameter[self, queue, durable, exclusive, auto_delete, warn_if_exists, arguments]]:
constant[Declare a named queue.]
if <ast.BoolOp object at 0x7da1b0fc44c0> begin[:]
call[name[warnings].warn, parameter[call[name[QueueAlreadyExistsWarning], parameter[name[Que... | keyword[def] identifier[queue_declare] ( identifier[self] , identifier[queue] , identifier[durable] , identifier[exclusive] , identifier[auto_delete] ,
identifier[warn_if_exists] = keyword[False] , identifier[arguments] = keyword[None] ):
literal[string]
keyword[if] identifier[warn_if_exists] ke... | def queue_declare(self, queue, durable, exclusive, auto_delete, warn_if_exists=False, arguments=None):
"""Declare a named queue."""
if warn_if_exists and self.queue_exists(queue):
warnings.warn(QueueAlreadyExistsWarning(QueueAlreadyExistsWarning.__doc__)) # depends on [control=['if'], data=[]]
retu... |
def get_signing_key(self, key_type="", owner="", kid=None, **kwargs):
"""
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Ext... | def function[get_signing_key, parameter[self, key_type, owner, kid]]:
constant[
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwarg... | keyword[def] identifier[get_signing_key] ( identifier[self] , identifier[key_type] = literal[string] , identifier[owner] = literal[string] , identifier[kid] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( literal[string] , identifier[k... | def get_signing_key(self, key_type='', owner='', kid=None, **kwargs):
"""
Shortcut to use for signing keys only.
:param key_type: Type of key (rsa, ec, oct, ..)
:param owner: Who is the owner of the keys, "" == me (default)
:param kid: A Key Identifier
:param kwargs: Extra k... |
def _write_fact(self, fact_tuple):
"""
Create new fact element and populate attributes.
Once the child is prepared append it to ``fact_list``.
"""
fact = self.document.createElement("fact")
fact.setAttribute('start', fact_tuple.start)
fact.setAttribute('end', fac... | def function[_write_fact, parameter[self, fact_tuple]]:
constant[
Create new fact element and populate attributes.
Once the child is prepared append it to ``fact_list``.
]
variable[fact] assign[=] call[name[self].document.createElement, parameter[constant[fact]]]
call[na... | keyword[def] identifier[_write_fact] ( identifier[self] , identifier[fact_tuple] ):
literal[string]
identifier[fact] = identifier[self] . identifier[document] . identifier[createElement] ( literal[string] )
identifier[fact] . identifier[setAttribute] ( literal[string] , identifier[fact_tup... | def _write_fact(self, fact_tuple):
"""
Create new fact element and populate attributes.
Once the child is prepared append it to ``fact_list``.
"""
fact = self.document.createElement('fact')
fact.setAttribute('start', fact_tuple.start)
fact.setAttribute('end', fact_tuple.end)
... |
def stemmed(text):
"""
Returns a list of simplified and stemmed down terms for the inputted text.
This will remove common terms and words from the search and return only
the important root terms. This is useful in searching algorithms.
:param text | <str>
:return [<str>,... | def function[stemmed, parameter[text]]:
constant[
Returns a list of simplified and stemmed down terms for the inputted text.
This will remove common terms and words from the search and return only
the important root terms. This is useful in searching algorithms.
:param text | <st... | keyword[def] identifier[stemmed] ( identifier[text] ):
literal[string]
identifier[terms] = identifier[re] . identifier[split] ( literal[string] , identifier[toAscii] ( identifier[text] ))
identifier[output] =[]
keyword[for] identifier[term] keyword[in] identifier[terms] :
keywor... | def stemmed(text):
"""
Returns a list of simplified and stemmed down terms for the inputted text.
This will remove common terms and words from the search and return only
the important root terms. This is useful in searching algorithms.
:param text | <str>
:return [<str>,... |
def export_as_string(self):
"""
Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables.
"""
cql = "\n\n".join([self.as_cql_query() + ';'] +
self.user_type_strings() +
... | def function[export_as_string, parameter[self]]:
constant[
Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables.
]
variable[cql] assign[=] call[constant[
].join, parameter[binary_operation[binary_operation[binary_op... | keyword[def] identifier[export_as_string] ( identifier[self] ):
literal[string]
identifier[cql] = literal[string] . identifier[join] ([ identifier[self] . identifier[as_cql_query] ()+ literal[string] ]+
identifier[self] . identifier[user_type_strings] ()+
[ identifier[f] . identifi... | def export_as_string(self):
"""
Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables.
"""
cql = '\n\n'.join([self.as_cql_query() + ';'] + self.user_type_strings() + [f.export_as_string() for f in self.functions.values()] + [... |
def append(self, clause, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, th... | def function[append, parameter[self, clause, is_atmost]]:
constant[
Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an A... | keyword[def] identifier[append] ( identifier[self] , identifier[clause] , identifier[is_atmost] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[is_atmost] :
identifier[self] . identifier[nv] = identifier[max] ([ identifier[abs] ( identifier[l] ) keyword[for] ... | def append(self, clause, is_atmost=False):
"""
Add a single clause or a single AtMostK constraint to CNF+ formula.
This method additionally updates the number of variables, i.e.
variable ``self.nv``, used in the formula.
If the clause is an AtMostK constraint, this s... |
def is_stopword(self, text):
"""
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which word... | def function[is_stopword, parameter[self, text]]:
constant[
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the p... | keyword[def] identifier[is_stopword] ( identifier[self] , identifier[text] ):
literal[string]
identifier[found_content_word] = keyword[False]
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[analyze] ( identifier[text] ):
keyword[if] keyword[not] ... | def is_stopword(self, text):
"""
Determine whether a single word is a stopword, or whether a short
phrase is made entirely of stopwords, disregarding context.
Use of this function should be avoided; it's better to give the text
in context and let the process determine which words ar... |
def start_tty(self, conf, interactive):
"""Startup a tty"""
try:
api = conf.harpoon.docker_context_maker().api
container_id = conf.container_id
stdin = conf.harpoon.tty_stdin
stdout = conf.harpoon.tty_stdout
stderr = conf.harpoon.tty_stderr
... | def function[start_tty, parameter[self, conf, interactive]]:
constant[Startup a tty]
<ast.Try object at 0x7da20c6c6890> | keyword[def] identifier[start_tty] ( identifier[self] , identifier[conf] , identifier[interactive] ):
literal[string]
keyword[try] :
identifier[api] = identifier[conf] . identifier[harpoon] . identifier[docker_context_maker] (). identifier[api]
identifier[container_id] = ... | def start_tty(self, conf, interactive):
"""Startup a tty"""
try:
api = conf.harpoon.docker_context_maker().api
container_id = conf.container_id
stdin = conf.harpoon.tty_stdin
stdout = conf.harpoon.tty_stdout
stderr = conf.harpoon.tty_stderr
if callable(stdin):
... |
def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict((f.name, getattr(self, f.name))
for f in self._struct) | def function[_asdict, parameter[self]]:
constant[Return an OrderedDict of the fields.]
return[call[name[OrderedDict], parameter[<ast.GeneratorExp object at 0x7da1b1f20190>]]] | keyword[def] identifier[_asdict] ( identifier[self] ):
literal[string]
keyword[return] identifier[OrderedDict] (( identifier[f] . identifier[name] , identifier[getattr] ( identifier[self] , identifier[f] . identifier[name] ))
keyword[for] identifier[f] keyword[in] identifier[self] . id... | def _asdict(self):
"""Return an OrderedDict of the fields."""
return OrderedDict(((f.name, getattr(self, f.name)) for f in self._struct)) |
def make_inst():
"""make_inst: prepare data for the diet model"""
F,c,d = multidict({ # cost # composition
"QPounder" : [ 1.84, {"Cal":510, "Carbo":34, "Protein":28,
"VitA":15, "VitC": 6, "Calc":30, "Iron":20}],
"McLean" : [ 2.19, {"Cal":370, "Carbo":35,... | def function[make_inst, parameter[]]:
constant[make_inst: prepare data for the diet model]
<ast.Tuple object at 0x7da18f00feb0> assign[=] call[name[multidict], parameter[dictionary[[<ast.Constant object at 0x7da18f00d000>, <ast.Constant object at 0x7da18f00f340>, <ast.Constant object at 0x7da18f00e1d0>,... | keyword[def] identifier[make_inst] ():
literal[string]
identifier[F] , identifier[c] , identifier[d] = identifier[multidict] ({
literal[string] :[ literal[int] ,{ literal[string] : literal[int] , literal[string] : literal[int] , literal[string] : literal[int] ,
literal[string] : literal[int] , li... | def make_inst():
"""make_inst: prepare data for the diet model""" # cost # composition
(F, c, d) = multidict({'QPounder': [1.84, {'Cal': 510, 'Carbo': 34, 'Protein': 28, 'VitA': 15, 'VitC': 6, 'Calc': 30, 'Iron': 20}], 'McLean': [2.19, {'Cal': 370, 'Carbo': 35, 'Protein': 24, 'VitA': 15, 'VitC': 10, 'Calc': 20... |
def show_profit_attribution(round_trips):
"""
Prints the share of total PnL contributed by each
traded name.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
ax : matplotli... | def function[show_profit_attribution, parameter[round_trips]]:
constant[
Prints the share of total PnL contributed by each
traded name.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract... | keyword[def] identifier[show_profit_attribution] ( identifier[round_trips] ):
literal[string]
identifier[total_pnl] = identifier[round_trips] [ literal[string] ]. identifier[sum] ()
identifier[pnl_attribution] = identifier[round_trips] . identifier[groupby] ( literal[string] )[ literal[string] ]. ide... | def show_profit_attribution(round_trips):
"""
Prints the share of total PnL contributed by each
traded name.
Parameters
----------
round_trips : pd.DataFrame
DataFrame with one row per round trip trade.
- See full explanation in round_trips.extract_round_trips
ax : matplotli... |
def insertReadGroup(self, readGroup):
"""
Inserts the specified readGroup into the DB.
"""
statsJson = json.dumps(protocol.toJsonDict(readGroup.getStats()))
experimentJson = json.dumps(
protocol.toJsonDict(readGroup.getExperiment()))
try:
models.Re... | def function[insertReadGroup, parameter[self, readGroup]]:
constant[
Inserts the specified readGroup into the DB.
]
variable[statsJson] assign[=] call[name[json].dumps, parameter[call[name[protocol].toJsonDict, parameter[call[name[readGroup].getStats, parameter[]]]]]]
variable[ex... | keyword[def] identifier[insertReadGroup] ( identifier[self] , identifier[readGroup] ):
literal[string]
identifier[statsJson] = identifier[json] . identifier[dumps] ( identifier[protocol] . identifier[toJsonDict] ( identifier[readGroup] . identifier[getStats] ()))
identifier[experimentJson]... | def insertReadGroup(self, readGroup):
"""
Inserts the specified readGroup into the DB.
"""
statsJson = json.dumps(protocol.toJsonDict(readGroup.getStats()))
experimentJson = json.dumps(protocol.toJsonDict(readGroup.getExperiment()))
try:
models.Readgroup.create(id=readGroup.getId... |
def include_file(self, path, include_dirs = []):
"""
Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str)
"""
if s... | def function[include_file, parameter[self, path, include_dirs]]:
constant[
Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str)
... | keyword[def] identifier[include_file] ( identifier[self] , identifier[path] , identifier[include_dirs] =[]):
literal[string]
keyword[if] identifier[self] . identifier[include_includes] :
keyword[if] identifier[self] . identifier[debug] : identifier[print] ( literal[string] % identifi... | def include_file(self, path, include_dirs=[]):
"""
Includes a file into the current model.
@param path: Path to the file to be included.
@type path: str
@param include_dirs: Optional alternate include search path.
@type include_dirs: list(str)
"""
if self.includ... |
def draw(self, data):
"""Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Specifically, zero-width
... | def function[draw, parameter[self, data]]:
constant[Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Spe... | keyword[def] identifier[draw] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[data] . identifier[translate] (
identifier[self] . identifier[g1_charset] keyword[if] identifier[self] . identifier[charset] keyword[else] identifier[self] . identifier[... | def draw(self, data):
"""Display decoded characters at the current cursor position and
advances the cursor if :data:`~pyte.modes.DECAWM` is set.
:param str data: text to display.
.. versionchanged:: 0.5.0
Character width is taken into account. Specifically, zero-width
... |
def _get_p_p_id_and_contract(self):
"""Get id of consumption profile."""
contracts = {}
try:
raw_res = yield from self._session.get(PROFILE_URL,
timeout=self._timeout)
except OSError:
raise PyHydroQuebecError("Can... | def function[_get_p_p_id_and_contract, parameter[self]]:
constant[Get id of consumption profile.]
variable[contracts] assign[=] dictionary[[], []]
<ast.Try object at 0x7da1b0f05c90>
variable[content] assign[=] <ast.YieldFrom object at 0x7da1b0f05f30>
variable[soup] assign[=] call[nam... | keyword[def] identifier[_get_p_p_id_and_contract] ( identifier[self] ):
literal[string]
identifier[contracts] ={}
keyword[try] :
identifier[raw_res] = keyword[yield] keyword[from] identifier[self] . identifier[_session] . identifier[get] ( identifier[PROFILE_URL] ,
... | def _get_p_p_id_and_contract(self):
"""Get id of consumption profile."""
contracts = {}
try:
raw_res = (yield from self._session.get(PROFILE_URL, timeout=self._timeout)) # depends on [control=['try'], data=[]]
except OSError:
raise PyHydroQuebecError('Can not get profile page') # depen... |
def size_footing_for_capacity(sl, vertical_load, fos=1.0, length_to_width=1.0, verbose=0, **kwargs):
"""
Determine the size of a footing given an aspect ratio and a load
:param sl: Soil object
:param vertical_load: The applied load to the foundation
:param fos: The target factor of safety
:param... | def function[size_footing_for_capacity, parameter[sl, vertical_load, fos, length_to_width, verbose]]:
constant[
Determine the size of a footing given an aspect ratio and a load
:param sl: Soil object
:param vertical_load: The applied load to the foundation
:param fos: The target factor of safety... | keyword[def] identifier[size_footing_for_capacity] ( identifier[sl] , identifier[vertical_load] , identifier[fos] = literal[int] , identifier[length_to_width] = literal[int] , identifier[verbose] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[method] = identifier[kwargs] . identifier[g... | def size_footing_for_capacity(sl, vertical_load, fos=1.0, length_to_width=1.0, verbose=0, **kwargs):
"""
Determine the size of a footing given an aspect ratio and a load
:param sl: Soil object
:param vertical_load: The applied load to the foundation
:param fos: The target factor of safety
:param... |
def seqs_from_fastacmd(acc_list, blast_db,is_protein=True):
"""Get dict of description:seq from fastacmd."""
fasta_cmd_res = fasta_cmd_get_seqs(acc_list, blast_db=blast_db, \
is_protein=is_protein)
recs = FastaCmdFinder(fasta_cmd_res['StdOut'])
result = {}
for rec in recs:
try:
... | def function[seqs_from_fastacmd, parameter[acc_list, blast_db, is_protein]]:
constant[Get dict of description:seq from fastacmd.]
variable[fasta_cmd_res] assign[=] call[name[fasta_cmd_get_seqs], parameter[name[acc_list]]]
variable[recs] assign[=] call[name[FastaCmdFinder], parameter[call[name[fa... | keyword[def] identifier[seqs_from_fastacmd] ( identifier[acc_list] , identifier[blast_db] , identifier[is_protein] = keyword[True] ):
literal[string]
identifier[fasta_cmd_res] = identifier[fasta_cmd_get_seqs] ( identifier[acc_list] , identifier[blast_db] = identifier[blast_db] , identifier[is_protein] = id... | def seqs_from_fastacmd(acc_list, blast_db, is_protein=True):
"""Get dict of description:seq from fastacmd."""
fasta_cmd_res = fasta_cmd_get_seqs(acc_list, blast_db=blast_db, is_protein=is_protein)
recs = FastaCmdFinder(fasta_cmd_res['StdOut'])
result = {}
for rec in recs:
try:
re... |
def _build_ds_from_instruction(instruction, ds_from_file_fn):
"""Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the d... | def function[_build_ds_from_instruction, parameter[instruction, ds_from_file_fn]]:
constant[Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `f... | keyword[def] identifier[_build_ds_from_instruction] ( identifier[instruction] , identifier[ds_from_file_fn] ):
literal[string]
identifier[examples_ds] = identifier[ds_from_file_fn] ( identifier[instruction] [ literal[string] ])
identifier[mask_ds] = identifier[_build_mask_ds] (
identifier[mask_offset]... | def _build_ds_from_instruction(instruction, ds_from_file_fn):
"""Map an instruction to a real datasets for one particular shard.
Args:
instruction: A `dict` of `tf.Tensor` containing the instruction to load
the particular shard (filename, mask,...)
ds_from_file_fn: `fct`, function which returns the... |
def _countmatrix(lxs):
""" fill a matrix with pairwise data sharing """
## an empty matrix
share = np.zeros((lxs.shape[0], lxs.shape[0]))
## fill above
names = range(lxs.shape[0])
for row in lxs:
for samp1, samp2 in itertools.combinations(names, 2):
shared = lxs[samp1, ... | def function[_countmatrix, parameter[lxs]]:
constant[ fill a matrix with pairwise data sharing ]
variable[share] assign[=] call[name[np].zeros, parameter[tuple[[<ast.Subscript object at 0x7da1b0035810>, <ast.Subscript object at 0x7da1b0037b80>]]]]
variable[names] assign[=] call[name[range], para... | keyword[def] identifier[_countmatrix] ( identifier[lxs] ):
literal[string]
identifier[share] = identifier[np] . identifier[zeros] (( identifier[lxs] . identifier[shape] [ literal[int] ], identifier[lxs] . identifier[shape] [ literal[int] ]))
identifier[names] = identifier[range] ( identifi... | def _countmatrix(lxs):
""" fill a matrix with pairwise data sharing """
## an empty matrix
share = np.zeros((lxs.shape[0], lxs.shape[0]))
## fill above
names = range(lxs.shape[0])
for row in lxs:
for (samp1, samp2) in itertools.combinations(names, 2):
shared = lxs[samp1, lxs[... |
def is_method(func):
"""Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators.
"""
func0 = _actualfunc(func)
argNames = getargnames(getargspecs(... | def function[is_method, parameter[func]]:
constant[Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators.
]
variable[func0] assign[=] call[n... | keyword[def] identifier[is_method] ( identifier[func] ):
literal[string]
identifier[func0] = identifier[_actualfunc] ( identifier[func] )
identifier[argNames] = identifier[getargnames] ( identifier[getargspecs] ( identifier[func0] ))
keyword[if] identifier[len] ( identifier[argNames] )> literal[... | def is_method(func):
"""Detects if the given callable is a method. In context of pytypes this
function is more reliable than plain inspect.ismethod, e.g. it automatically
bypasses wrappers from typechecked and override decorators.
"""
func0 = _actualfunc(func)
argNames = getargnames(getargspecs(... |
def start(self, channel):
"""Start running this virtual device including any necessary worker threads.
Args:
channel (IOTilePushChannel): the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface
"""
if self._start... | def function[start, parameter[self, channel]]:
constant[Start running this virtual device including any necessary worker threads.
Args:
channel (IOTilePushChannel): the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface
... | keyword[def] identifier[start] ( identifier[self] , identifier[channel] ):
literal[string]
keyword[if] identifier[self] . identifier[_started] :
keyword[raise] identifier[InternalError] ( literal[string] )
identifier[self] . identifier[_push_channel] = identifier[channel] ... | def start(self, channel):
"""Start running this virtual device including any necessary worker threads.
Args:
channel (IOTilePushChannel): the channel with a stream and trace
routine for streaming and tracing data through a VirtualInterface
"""
if self._started:
... |
def fave_slices(self, user_id=None):
"""Favorite slices for a user"""
if not user_id:
user_id = g.user.id
qry = (
db.session.query(
models.Slice,
models.FavStar.dttm,
)
.join(
models.FavStar,
... | def function[fave_slices, parameter[self, user_id]]:
constant[Favorite slices for a user]
if <ast.UnaryOp object at 0x7da1b2060e50> begin[:]
variable[user_id] assign[=] name[g].user.id
variable[qry] assign[=] call[call[call[name[db].session.query, parameter[name[models].Slice, na... | keyword[def] identifier[fave_slices] ( identifier[self] , identifier[user_id] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[user_id] :
identifier[user_id] = identifier[g] . identifier[user] . identifier[id]
identifier[qry] =(
identifier[db]... | def fave_slices(self, user_id=None):
"""Favorite slices for a user"""
if not user_id:
user_id = g.user.id # depends on [control=['if'], data=[]]
qry = db.session.query(models.Slice, models.FavStar.dttm).join(models.FavStar, sqla.and_(models.FavStar.user_id == int(user_id), models.FavStar.class_name... |
def _get_route_args(self, namespace, route, tag=False): # pylint: disable=unused-argument
"""Returns a list of name / value string pairs representing the arguments for
a particular route."""
data_type, _ = unwrap_nullable(route.arg_data_type)
if is_struct_type(data_type):
ar... | def function[_get_route_args, parameter[self, namespace, route, tag]]:
constant[Returns a list of name / value string pairs representing the arguments for
a particular route.]
<ast.Tuple object at 0x7da18f58fb50> assign[=] call[name[unwrap_nullable], parameter[name[route].arg_data_type]]
... | keyword[def] identifier[_get_route_args] ( identifier[self] , identifier[namespace] , identifier[route] , identifier[tag] = keyword[False] ):
literal[string]
identifier[data_type] , identifier[_] = identifier[unwrap_nullable] ( identifier[route] . identifier[arg_data_type] )
keyword[if] i... | def _get_route_args(self, namespace, route, tag=False): # pylint: disable=unused-argument
'Returns a list of name / value string pairs representing the arguments for\n a particular route.'
(data_type, _) = unwrap_nullable(route.arg_data_type)
if is_struct_type(data_type):
arg_list = []
... |
def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = uti... | def function[convert, parameter[self, key, value]]:
constant[Get the serialized value for a given key.]
if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[self]._dtypes] begin[:]
call[name[self].read_types, parameter[]]
if compare[name[key] <ast.NotIn object a... | keyword[def] identifier[convert] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[key] keyword[not] keyword[in] identifier[self] . identifier[_dtypes] :
identifier[self] . identifier[read_types] ()
keyword[if] identifi... | def convert(self, key, value):
"""Get the serialized value for a given key."""
if key not in self._dtypes:
self.read_types()
if key not in self._dtypes:
name = utils.name(value)
serializer = utils.serializer(name)
deserializer = utils.deserializer(name)
... |
def _FormatServiceText(self, service):
"""Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service.
"""
string_segments = [
service.name,
'\... | def function[_FormatServiceText, parameter[self, service]]:
constant[Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service.
]
variable[string_seg... | keyword[def] identifier[_FormatServiceText] ( identifier[self] , identifier[service] ):
literal[string]
identifier[string_segments] =[
identifier[service] . identifier[name] ,
literal[string] . identifier[format] ( identifier[service] . identifier[image_path] ),
literal[string] . identifier[... | def _FormatServiceText(self, service):
"""Produces a human readable multi-line string representing the service.
Args:
service (WindowsService): service to format.
Returns:
str: human readable representation of a Windows Service.
"""
string_segments = [service.name, '\tImage Path = ... |
def relative_to_all(features, groups, bin_edges, weight_func,
use_orig_distr,
group_ids, num_groups,
return_networkx_graph, out_weights_path):
"""
Computes the given function (aka weight or distance) between histogram from each of the groups to a "gran... | def function[relative_to_all, parameter[features, groups, bin_edges, weight_func, use_orig_distr, group_ids, num_groups, return_networkx_graph, out_weights_path]]:
constant[
Computes the given function (aka weight or distance) between histogram from each of the groups to a "grand histogram" derived from all... | keyword[def] identifier[relative_to_all] ( identifier[features] , identifier[groups] , identifier[bin_edges] , identifier[weight_func] ,
identifier[use_orig_distr] ,
identifier[group_ids] , identifier[num_groups] ,
identifier[return_networkx_graph] , identifier[out_weights_path] ):
literal[string]
... | def relative_to_all(features, groups, bin_edges, weight_func, use_orig_distr, group_ids, num_groups, return_networkx_graph, out_weights_path):
"""
Computes the given function (aka weight or distance) between histogram from each of the groups to a "grand histogram" derived from all groups.
Parameters
--... |
def complete(self, text: str) -> Iterable[str]:
"""Return an iterable of possible completions for the given text in
this namespace."""
assert not text.startswith(":")
if "/" in text:
prefix, suffix = text.split("/", maxsplit=1)
results = itertools.chain(
... | def function[complete, parameter[self, text]]:
constant[Return an iterable of possible completions for the given text in
this namespace.]
assert[<ast.UnaryOp object at 0x7da1b033d7e0>]
if compare[constant[/] in name[text]] begin[:]
<ast.Tuple object at 0x7da1b033d570> assign[... | keyword[def] identifier[complete] ( identifier[self] , identifier[text] : identifier[str] )-> identifier[Iterable] [ identifier[str] ]:
literal[string]
keyword[assert] keyword[not] identifier[text] . identifier[startswith] ( literal[string] )
keyword[if] literal[string] keyword[in] i... | def complete(self, text: str) -> Iterable[str]:
"""Return an iterable of possible completions for the given text in
this namespace."""
assert not text.startswith(':')
if '/' in text:
(prefix, suffix) = text.split('/', maxsplit=1)
results = itertools.chain(self.__complete_alias(prefix... |
def rule_from_pattern(pattern, base_path=None, source=None):
"""
Take a .gitignore match pattern, such as "*.py[cod]" or "**/*.bak",
and return an IgnoreRule suitable for matching against files and
directories. Patterns which do not match files, such as comments
and blank lines, will return None.
Because git allo... | def function[rule_from_pattern, parameter[pattern, base_path, source]]:
constant[
Take a .gitignore match pattern, such as "*.py[cod]" or "**/*.bak",
and return an IgnoreRule suitable for matching against files and
directories. Patterns which do not match files, such as comments
and blank lines, will return... | keyword[def] identifier[rule_from_pattern] ( identifier[pattern] , identifier[base_path] = keyword[None] , identifier[source] = keyword[None] ):
literal[string]
keyword[if] identifier[base_path] keyword[and] identifier[base_path] != identifier[abspath] ( identifier[base_path] ):
keyword[raise] identifier[... | def rule_from_pattern(pattern, base_path=None, source=None):
"""
Take a .gitignore match pattern, such as "*.py[cod]" or "**/*.bak",
and return an IgnoreRule suitable for matching against files and
directories. Patterns which do not match files, such as comments
and blank lines, will return None.
Because git a... |
def MI_references(self,
env,
objectName,
resultClassName,
role,
propertyList):
# pylint: disable=invalid-name
"""Return instances of an association class.
Implements the WBEM operation ... | def function[MI_references, parameter[self, env, objectName, resultClassName, role, propertyList]]:
constant[Return instances of an association class.
Implements the WBEM operation References in terms
of the references method. A derived class will not normally
override this method.
... | keyword[def] identifier[MI_references] ( identifier[self] ,
identifier[env] ,
identifier[objectName] ,
identifier[resultClassName] ,
identifier[role] ,
identifier[propertyList] ):
literal[string]
identifier[logger] = identifier[env] . identifier[get_logger] ()
identifier[logger] . i... | def MI_references(self, env, objectName, resultClassName, role, propertyList):
# pylint: disable=invalid-name
'Return instances of an association class.\n\n Implements the WBEM operation References in terms\n of the references method. A derived class will not normally\n override this metho... |
def calc_std(c0, c1=[]):
""" Calculates the variance of the data."""
if c1 == []:
return numpy.std(c0, 0)
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1
else:
p0 = 1
p1 = int(math.ceil(prop))
return numpy.std(numpy... | def function[calc_std, parameter[c0, c1]]:
constant[ Calculates the variance of the data.]
if compare[name[c1] equal[==] list[[]]] begin[:]
return[call[name[numpy].std, parameter[name[c0], constant[0]]]]
variable[prop] assign[=] binary_operation[call[name[float], parameter[call[name[len]... | keyword[def] identifier[calc_std] ( identifier[c0] , identifier[c1] =[]):
literal[string]
keyword[if] identifier[c1] ==[]:
keyword[return] identifier[numpy] . identifier[std] ( identifier[c0] , literal[int] )
identifier[prop] = identifier[float] ( identifier[len] ( identifier[c0] ))/ identi... | def calc_std(c0, c1=[]):
""" Calculates the variance of the data."""
if c1 == []:
return numpy.std(c0, 0) # depends on [control=['if'], data=[]]
prop = float(len(c0)) / float(len(c1))
if prop < 1:
p0 = int(math.ceil(1 / prop))
p1 = 1 # depends on [control=['if'], data=['prop']]... |
def pst(self):
""" get the pyemu.Pst attribute
Returns
-------
pst : pyemu.Pst
Note
----
returns a references
If LinearAnalysis.__pst is None, then the pst attribute is
dynamically loaded before returning
"""
if self.__ps... | def function[pst, parameter[self]]:
constant[ get the pyemu.Pst attribute
Returns
-------
pst : pyemu.Pst
Note
----
returns a references
If LinearAnalysis.__pst is None, then the pst attribute is
dynamically loaded before returning
... | keyword[def] identifier[pst] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__pst] keyword[is] keyword[None] keyword[and] identifier[self] . identifier[pst_arg] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] +... | def pst(self):
""" get the pyemu.Pst attribute
Returns
-------
pst : pyemu.Pst
Note
----
returns a references
If LinearAnalysis.__pst is None, then the pst attribute is
dynamically loaded before returning
"""
if self.__pst is Non... |
def _construct_instance(self, constructor, full_name, *args, **kwargs):
""" Creates a new node. Checks if the new node needs to know the trajectory.
:param constructor: The constructor to use
:param full_name: Full name of node
:param args: Arguments passed to constructor
:para... | def function[_construct_instance, parameter[self, constructor, full_name]]:
constant[ Creates a new node. Checks if the new node needs to know the trajectory.
:param constructor: The constructor to use
:param full_name: Full name of node
:param args: Arguments passed to constructor
... | keyword[def] identifier[_construct_instance] ( identifier[self] , identifier[constructor] , identifier[full_name] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[getattr] ( identifier[constructor] , literal[string] , keyword[False] ):
keyword[retur... | def _construct_instance(self, constructor, full_name, *args, **kwargs):
""" Creates a new node. Checks if the new node needs to know the trajectory.
:param constructor: The constructor to use
:param full_name: Full name of node
:param args: Arguments passed to constructor
:param kw... |
def readlines(self, sizehint=-1):
"""
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines retur... | def function[readlines, parameter[self, sizehint]]:
constant[
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of ... | keyword[def] identifier[readlines] ( identifier[self] , identifier[sizehint] =- literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[closed] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[lines] =[]
keyword[while] keywor... | def readlines(self, sizehint=-1):
"""
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.... |
def download(self, spec, tmpdir):
"""Locate and/or download `spec` to `tmpdir`, returning a local path
`spec` may be a ``Requirement`` object, or a string containing a URL,
an existing local filename, or a project/version requirement spec
(i.e. the string form of a ``Requirement`` objec... | def function[download, parameter[self, spec, tmpdir]]:
constant[Locate and/or download `spec` to `tmpdir`, returning a local path
`spec` may be a ``Requirement`` object, or a string containing a URL,
an existing local filename, or a project/version requirement spec
(i.e. the string form... | keyword[def] identifier[download] ( identifier[self] , identifier[spec] , identifier[tmpdir] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[spec] , identifier[Requirement] ):
identifier[scheme] = identifier[URL_SCHEME] ( identifier[spec] )
... | def download(self, spec, tmpdir):
"""Locate and/or download `spec` to `tmpdir`, returning a local path
`spec` may be a ``Requirement`` object, or a string containing a URL,
an existing local filename, or a project/version requirement spec
(i.e. the string form of a ``Requirement`` object). ... |
def parse_exclusions(exclusions):
""" Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances
"""
fname = fileutil.osfn(exclusions)
if os.path.exists(fname):
with open(fname) as f:
flines = f.readlines()
else:
pri... | def function[parse_exclusions, parameter[exclusions]]:
constant[ Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances
]
variable[fname] assign[=] call[name[fileutil].osfn, parameter[name[exclusions]]]
if call[name[os].path.exists,... | keyword[def] identifier[parse_exclusions] ( identifier[exclusions] ):
literal[string]
identifier[fname] = identifier[fileutil] . identifier[osfn] ( identifier[exclusions] )
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[fname] ):
keyword[with] identifier[ope... | def parse_exclusions(exclusions):
""" Read in exclusion definitions from file named by 'exclusions'
and return a list of positions and distances
"""
fname = fileutil.osfn(exclusions)
if os.path.exists(fname):
with open(fname) as f:
flines = f.readlines() # depends on [contro... |
def deactivate(self, address):
""" Deactivate an address from the connection pool,
if present, remove from the routing table and also closing
all idle connections to that address.
"""
log_debug("[#0000] C: <ROUTING> Deactivating address %r", address)
# We use `discard` i... | def function[deactivate, parameter[self, address]]:
constant[ Deactivate an address from the connection pool,
if present, remove from the routing table and also closing
all idle connections to that address.
]
call[name[log_debug], parameter[constant[[#0000] C: <ROUTING> Deactiva... | keyword[def] identifier[deactivate] ( identifier[self] , identifier[address] ):
literal[string]
identifier[log_debug] ( literal[string] , identifier[address] )
identifier[self] . identifier[routing_table] . identifier[routers] . identifier[discard] ( identifier[address] )... | def deactivate(self, address):
""" Deactivate an address from the connection pool,
if present, remove from the routing table and also closing
all idle connections to that address.
"""
log_debug('[#0000] C: <ROUTING> Deactivating address %r', address)
# We use `discard` instead of `r... |
def sync_scheduler(self):
"""Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. If a scheduler entry is not ... | def function[sync_scheduler, parameter[self]]:
constant[Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. I... | keyword[def] identifier[sync_scheduler] ( identifier[self] ):
literal[string]
identifier[url] = literal[string] %( identifier[self] . identifier[config] [ literal[string] ][ literal[string] ],
literal[string] , literal[string] )
keyword[try] :
identifier[req]... | def sync_scheduler(self):
"""Download the scheduler.info file and perform a smart comparison
with what we currently have so that we don't overwrite the
last_run timestamp
To do a smart comparison, we go over each entry in the
server's scheduler file. If a scheduler entry is not pres... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.