code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def sample(self, batch_size, batch_idxs=None):
"""Return a randomized batch of experiences
# Argument
batch_size (int): Size of the all batch
batch_idxs (int): Indexes to extract
# Returns
A list of experiences randomly selected
"""
# It is no... | def function[sample, parameter[self, batch_size, batch_idxs]]:
constant[Return a randomized batch of experiences
# Argument
batch_size (int): Size of the all batch
batch_idxs (int): Indexes to extract
# Returns
A list of experiences randomly selected
... | keyword[def] identifier[sample] ( identifier[self] , identifier[batch_size] , identifier[batch_idxs] = keyword[None] ):
literal[string]
keyword[assert] identifier[self] . identifier[nb_entries] >= identifier[self] . identifier[window_length] + literal[i... | def sample(self, batch_size, batch_idxs=None):
"""Return a randomized batch of experiences
# Argument
batch_size (int): Size of the all batch
batch_idxs (int): Indexes to extract
# Returns
A list of experiences randomly selected
"""
# It is not possib... |
def substitute_xml(cls, value, make_quoted_attribute=False):
"""Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will become &. If you wan... | def function[substitute_xml, parameter[cls, value, make_quoted_attribute]]:
constant[Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will bec... | keyword[def] identifier[substitute_xml] ( identifier[cls] , identifier[value] , identifier[make_quoted_attribute] = keyword[False] ):
literal[string]
identifier[value] = identifier[cls] . identifier[AMPERSAND_OR_BRACKET] . identifier[sub] (
identifier[cls] . identifier[_substitute... | def substitute_xml(cls, value, make_quoted_attribute=False):
"""Substitute XML entities for special XML characters.
:param value: A string to be substituted. The less-than sign
will become <, the greater-than sign will become >,
and any ampersands will become &. If you want am... |
def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
ox, oy = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl ... | def function[draw, parameter[self, surface]]:
constant[ Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
]
<ast.Tuple object at 0x7da207f02650> assign[=] call[name[self]._map_layer.get_center_offset, parame... | keyword[def] identifier[draw] ( identifier[self] , identifier[surface] ):
literal[string]
identifier[ox] , identifier[oy] = identifier[self] . identifier[_map_layer] . identifier[get_center_offset] ()
identifier[new_surfaces] = identifier[list] ()
identifier[spritedict] = identif... | def draw(self, surface):
""" Draw all sprites and map onto the surface
:param surface: pygame surface to draw to
:type surface: pygame.surface.Surface
"""
(ox, oy) = self._map_layer.get_center_offset()
new_surfaces = list()
spritedict = self.spritedict
gl = self.get_layer_of... |
def handle(self, key, value):
'''
Processes a vaild stats request
@param key: The key that matched the request
@param value: The value associated with the key
'''
# break down key
elements = key.split(":")
stats = elements[1]
appid = elements[2]
... | def function[handle, parameter[self, key, value]]:
constant[
Processes a vaild stats request
@param key: The key that matched the request
@param value: The value associated with the key
]
variable[elements] assign[=] call[name[key].split, parameter[constant[:]]]
... | keyword[def] identifier[handle] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
identifier[elements] = identifier[key] . identifier[split] ( literal[string] )
identifier[stats] = identifier[elements] [ literal[int] ]
identifier[appid] = identi... | def handle(self, key, value):
"""
Processes a vaild stats request
@param key: The key that matched the request
@param value: The value associated with the key
"""
# break down key
elements = key.split(':')
stats = elements[1]
appid = elements[2]
uuid = value
... |
def reload_module(module):
"""
Reload the Python module
"""
try:
# For Python 2.x
reload(module)
except (ImportError, NameError):
# For <= Python3.3:
import imp
imp.reload(module)
except (ImportError, NameError):
# For >= Python3.4
import i... | def function[reload_module, parameter[module]]:
constant[
Reload the Python module
]
<ast.Try object at 0x7da1b1fbb070> | keyword[def] identifier[reload_module] ( identifier[module] ):
literal[string]
keyword[try] :
identifier[reload] ( identifier[module] )
keyword[except] ( identifier[ImportError] , identifier[NameError] ):
keyword[import] identifier[imp]
identifier[imp] . identifi... | def reload_module(module):
"""
Reload the Python module
"""
try:
# For Python 2.x
reload(module) # depends on [control=['try'], data=[]]
except (ImportError, NameError):
# For <= Python3.3:
import imp
imp.reload(module) # depends on [control=['except'], data... |
def _generate_injection_cmd(self, meta_data):
""" example injector response:
[
{
"config_path":"/configs/cli_config.py",
"path":"/opt/cia-cli/cia_sdk/config",
"user":"injector",
"status_code":201,
"chmod":755,
... | def function[_generate_injection_cmd, parameter[self, meta_data]]:
constant[ example injector response:
[
{
"config_path":"/configs/cli_config.py",
"path":"/opt/cia-cli/cia_sdk/config",
"user":"injector",
"status_code":201,
... | keyword[def] identifier[_generate_injection_cmd] ( identifier[self] , identifier[meta_data] ):
literal[string]
identifier[cmd] =[]
identifier[self] . identifier[_validate_templates] ( identifier[meta_data] )
keyword[for] identifier[i] , identifier[config_data] keyword[in] ident... | def _generate_injection_cmd(self, meta_data):
""" example injector response:
[
{
"config_path":"/configs/cli_config.py",
"path":"/opt/cia-cli/cia_sdk/config",
"user":"injector",
"status_code":201,
"chmod":755,
"ch... |
def link(self, definition, doc1, doc2, edgeAttributes, waitForSync = False) :
"A shorthand for createEdge that takes two documents as input"
if type(doc1) is DOC.Document :
if not doc1._id :
doc1.save()
doc1_id = doc1._id
else :
doc1_id = doc1
... | def function[link, parameter[self, definition, doc1, doc2, edgeAttributes, waitForSync]]:
constant[A shorthand for createEdge that takes two documents as input]
if compare[call[name[type], parameter[name[doc1]]] is name[DOC].Document] begin[:]
if <ast.UnaryOp object at 0x7da1b0f5bfa0> be... | keyword[def] identifier[link] ( identifier[self] , identifier[definition] , identifier[doc1] , identifier[doc2] , identifier[edgeAttributes] , identifier[waitForSync] = keyword[False] ):
literal[string]
keyword[if] identifier[type] ( identifier[doc1] ) keyword[is] identifier[DOC] . identifier[Doc... | def link(self, definition, doc1, doc2, edgeAttributes, waitForSync=False):
"""A shorthand for createEdge that takes two documents as input"""
if type(doc1) is DOC.Document:
if not doc1._id:
doc1.save() # depends on [control=['if'], data=[]]
doc1_id = doc1._id # depends on [control=... |
def _from_dict(cls, _dict):
"""Initialize a LeadingSentence object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location'))
if 'element_l... | def function[_from_dict, parameter[cls, _dict]]:
constant[Initialize a LeadingSentence object from a json dictionary.]
variable[args] assign[=] dictionary[[], []]
if compare[constant[text] in name[_dict]] begin[:]
call[name[args]][constant[text]] assign[=] call[name[_dict].get, p... | keyword[def] identifier[_from_dict] ( identifier[cls] , identifier[_dict] ):
literal[string]
identifier[args] ={}
keyword[if] literal[string] keyword[in] identifier[_dict] :
identifier[args] [ literal[string] ]= identifier[_dict] . identifier[get] ( literal[string] )
... | def _from_dict(cls, _dict):
"""Initialize a LeadingSentence object from a json dictionary."""
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text') # depends on [control=['if'], data=['_dict']]
if 'location' in _dict:
args['location'] = Location._from_dict(_dict.get('location')... |
def get_class_that_defined_method(meth):
""" Gets the class object which defined a given method
@meth: a class method
-> owner class object
"""
if inspect.ismethod(meth):
for cls in inspect.getmro(meth.__self__.__class__):
if cls.__dict__.get(meth.__name__) is meth:
... | def function[get_class_that_defined_method, parameter[meth]]:
constant[ Gets the class object which defined a given method
@meth: a class method
-> owner class object
]
if call[name[inspect].ismethod, parameter[name[meth]]] begin[:]
for taget[name[cls]] in starred[c... | keyword[def] identifier[get_class_that_defined_method] ( identifier[meth] ):
literal[string]
keyword[if] identifier[inspect] . identifier[ismethod] ( identifier[meth] ):
keyword[for] identifier[cls] keyword[in] identifier[inspect] . identifier[getmro] ( identifier[meth] . identifier[__self__] ... | def get_class_that_defined_method(meth):
""" Gets the class object which defined a given method
@meth: a class method
-> owner class object
"""
if inspect.ismethod(meth):
for cls in inspect.getmro(meth.__self__.__class__):
if cls.__dict__.get(meth.__name__) is meth:
... |
def get_configs(args, command_args, ansible_args=()):
"""
Glob the current directory for Molecule config files, instantiate config
objects, and returns a list.
:param args: A dict of options, arguments and commands from the CLI.
:param command_args: A dict of options passed to the subcommand from
... | def function[get_configs, parameter[args, command_args, ansible_args]]:
constant[
Glob the current directory for Molecule config files, instantiate config
objects, and returns a list.
:param args: A dict of options, arguments and commands from the CLI.
:param command_args: A dict of options pas... | keyword[def] identifier[get_configs] ( identifier[args] , identifier[command_args] , identifier[ansible_args] =()):
literal[string]
identifier[configs] =[
identifier[config] . identifier[Config] (
identifier[molecule_file] = identifier[util] . identifier[abs_path] ( identifier[c] ),
identifi... | def get_configs(args, command_args, ansible_args=()):
"""
Glob the current directory for Molecule config files, instantiate config
objects, and returns a list.
:param args: A dict of options, arguments and commands from the CLI.
:param command_args: A dict of options passed to the subcommand from
... |
def get_jobs(self, prefix=None):
""" Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is specified as a querys... | def function[get_jobs, parameter[self, prefix]]:
constant[ Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is... | keyword[def] identifier[get_jobs] ( identifier[self] , identifier[prefix] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : identifier[prefix] }
keyword[return] identifier[self] . identifier[request] ( identifier[method] = literal[string] , identifier[params] = id... | def get_jobs(self, prefix=None):
""" Lists all the jobs registered with Nomad.
https://www.nomadproject.io/docs/http/jobs.html
arguments:
- prefix :(str) optional, specifies a string to filter jobs on based on an prefix.
This is specified as a querystrin... |
def isoformat(self, sep='T'):
"""
Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
The formatted datetime... | def function[isoformat, parameter[self, sep]]:
constant[
Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
... | keyword[def] identifier[isoformat] ( identifier[self] , identifier[sep] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[microsecond] == literal[int] :
keyword[return] identifier[self] . identifier[strftime] ( literal[string] % identifier[sep] )
... | def isoformat(self, sep='T'):
"""
Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
The formatted datetime as ... |
def key_set(self, predicate=None):
"""
Returns a List clone of the keys contained in this map or the keys of the entries filtered with the predicate if
provided.
**Warning:
The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.**
... | def function[key_set, parameter[self, predicate]]:
constant[
Returns a List clone of the keys contained in this map or the keys of the entries filtered with the predicate if
provided.
**Warning:
The list is NOT backed by the map, so changes to the map are NOT reflected in the li... | keyword[def] identifier[key_set] ( identifier[self] , identifier[predicate] = keyword[None] ):
literal[string]
keyword[if] identifier[predicate] :
identifier[predicate_data] = identifier[self] . identifier[_to_data] ( identifier[predicate] )
keyword[return] identifier[se... | def key_set(self, predicate=None):
"""
Returns a List clone of the keys contained in this map or the keys of the entries filtered with the predicate if
provided.
**Warning:
The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.**
... |
def notConnectedNodes(self) -> Set[str]:
"""
Returns the names of nodes in the registry this node is NOT connected
to.
"""
return set(self.registry.keys()) - self.conns | def function[notConnectedNodes, parameter[self]]:
constant[
Returns the names of nodes in the registry this node is NOT connected
to.
]
return[binary_operation[call[name[set], parameter[call[name[self].registry.keys, parameter[]]]] - name[self].conns]] | keyword[def] identifier[notConnectedNodes] ( identifier[self] )-> identifier[Set] [ identifier[str] ]:
literal[string]
keyword[return] identifier[set] ( identifier[self] . identifier[registry] . identifier[keys] ())- identifier[self] . identifier[conns] | def notConnectedNodes(self) -> Set[str]:
"""
Returns the names of nodes in the registry this node is NOT connected
to.
"""
return set(self.registry.keys()) - self.conns |
def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3,
maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True):
"""
Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to... | def function[phot, parameter[fits_filename, x_in, y_in, aperture, sky, swidth, apcor, maxcount, exptime, zmag, extno, centroid]]:
constant[
Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to measure source... | keyword[def] identifier[phot] ( identifier[fits_filename] , identifier[x_in] , identifier[y_in] , identifier[aperture] = literal[int] , identifier[sky] = literal[int] , identifier[swidth] = literal[int] , identifier[apcor] = literal[int] ,
identifier[maxcount] = literal[int] , identifier[exptime] = literal[int] , id... | def phot(fits_filename, x_in, y_in, aperture=15, sky=20, swidth=10, apcor=0.3, maxcount=30000.0, exptime=1.0, zmag=None, extno=0, centroid=True):
"""
Compute the centroids and magnitudes of a bunch sources on fits image.
:rtype : astropy.table.Table
:param fits_filename: Name of fits image to measure ... |
def ground_height(self):
'''return height above ground in feet'''
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
global ElevationMap
ret = ElevationMap.GetElevation(lat, lon)
ret -= gen_settings.wgs84_to_AMSL
return ret * 3.2807 | def function[ground_height, parameter[self]]:
constant[return height above ground in feet]
variable[lat] assign[=] call[call[call[name[self].pkt][constant[I105]]][constant[Lat]]][constant[val]]
variable[lon] assign[=] call[call[call[name[self].pkt][constant[I105]]][constant[Lon]]][constant[val]]... | keyword[def] identifier[ground_height] ( identifier[self] ):
literal[string]
identifier[lat] = identifier[self] . identifier[pkt] [ literal[string] ][ literal[string] ][ literal[string] ]
identifier[lon] = identifier[self] . identifier[pkt] [ literal[string] ][ literal[string] ][ literal[s... | def ground_height(self):
"""return height above ground in feet"""
lat = self.pkt['I105']['Lat']['val']
lon = self.pkt['I105']['Lon']['val']
global ElevationMap
ret = ElevationMap.GetElevation(lat, lon)
ret -= gen_settings.wgs84_to_AMSL
return ret * 3.2807 |
def calc_qib2_v1(self):
"""Calculate the first inflow component released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|NFk|
|DMin|
|DMax|
Required derived parameter:
|WZ|
Required state sequence:
|BoWa|
Calculated flux sequence:
|QIB2|
... | def function[calc_qib2_v1, parameter[self]]:
constant[Calculate the first inflow component released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|NFk|
|DMin|
|DMax|
Required derived parameter:
|WZ|
Required state sequence:
|BoWa|
Calculat... | keyword[def] identifier[calc_qib2_v1] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess]
identifier[der] = identifier[self] . identifier[parameters] . identifier[derived] . identifier[fastaccess]
ident... | def calc_qib2_v1(self):
"""Calculate the first inflow component released from the soil.
Required control parameters:
|NHRU|
|Lnk|
|NFk|
|DMin|
|DMax|
Required derived parameter:
|WZ|
Required state sequence:
|BoWa|
Calculated flux sequence:
|QIB2|
... |
def namedtuple_storable(namedtuple, *args, **kwargs):
"""
Storable factory for named tuples.
"""
return default_storable(namedtuple, namedtuple._fields, *args, **kwargs) | def function[namedtuple_storable, parameter[namedtuple]]:
constant[
Storable factory for named tuples.
]
return[call[name[default_storable], parameter[name[namedtuple], name[namedtuple]._fields, <ast.Starred object at 0x7da1b16165c0>]]] | keyword[def] identifier[namedtuple_storable] ( identifier[namedtuple] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[default_storable] ( identifier[namedtuple] , identifier[namedtuple] . identifier[_fields] ,* identifier[args] ,** identifier[kwargs] ) | def namedtuple_storable(namedtuple, *args, **kwargs):
"""
Storable factory for named tuples.
"""
return default_storable(namedtuple, namedtuple._fields, *args, **kwargs) |
def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) | def function[hstrlen, parameter[self, name, key]]:
constant[
Return the number of bytes stored in the value of ``key``
within hash ``name``
]
with name[self].pipe begin[:]
return[call[name[pipe].hstrlen, parameter[call[name[self].redis_key, parameter[name[name]]], name[ke... | keyword[def] identifier[hstrlen] ( identifier[self] , identifier[name] , identifier[key] ):
literal[string]
keyword[with] identifier[self] . identifier[pipe] keyword[as] identifier[pipe] :
keyword[return] identifier[pipe] . identifier[hstrlen] ( identifier[self] . identifier[redis_... | def hstrlen(self, name, key):
"""
Return the number of bytes stored in the value of ``key``
within hash ``name``
"""
with self.pipe as pipe:
return pipe.hstrlen(self.redis_key(name), key) # depends on [control=['with'], data=['pipe']] |
def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size',
'time_healpy', 'time_self', 'ratio'],
dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in ... | def function[bench_report, parameter[results]]:
constant[Print a report for given benchmark results to the console.]
variable[table] assign[=] call[name[Table], parameter[]]
for taget[name[row]] in starred[name[results]] begin[:]
call[name[table].add_row, parameter[name[row]]]
... | keyword[def] identifier[bench_report] ( identifier[results] ):
literal[string]
identifier[table] = identifier[Table] ( identifier[names] =[ literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] ],
identifier[dtype] =[ literal[... | def bench_report(results):
"""Print a report for given benchmark results to the console."""
table = Table(names=['function', 'nest', 'nside', 'size', 'time_healpy', 'time_self', 'ratio'], dtype=['S20', bool, int, int, float, float, float], masked=True)
for row in results:
table.add_row(row) # depen... |
def use_winlegacy():
"""
Forces use of the legacy Windows CryptoAPI. This should only be used on
Windows XP or for testing. It is less full-featured than the Cryptography
Next Generation (CNG) API, and as a result the elliptic curve and PSS
padding features are implemented in pure Python. This isn't... | def function[use_winlegacy, parameter[]]:
constant[
Forces use of the legacy Windows CryptoAPI. This should only be used on
Windows XP or for testing. It is less full-featured than the Cryptography
Next Generation (CNG) API, and as a result the elliptic curve and PSS
padding features are impleme... | keyword[def] identifier[use_winlegacy] ():
literal[string]
keyword[if] identifier[sys] . identifier[platform] != literal[string] :
identifier[plat] = identifier[platform] . identifier[system] () keyword[or] identifier[sys] . identifier[platform]
keyword[if] identifier[plat] == litera... | def use_winlegacy():
"""
Forces use of the legacy Windows CryptoAPI. This should only be used on
Windows XP or for testing. It is less full-featured than the Cryptography
Next Generation (CNG) API, and as a result the elliptic curve and PSS
padding features are implemented in pure Python. This isn't... |
def refresh_from_pdb(self, pdb_state):
"""
Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels
"""
if 'step' in pdb_state and 'fname' in pdb_state['step']:
fname = p... | def function[refresh_from_pdb, parameter[self, pdb_state]]:
constant[
Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels
]
if <ast.BoolOp object at 0x7da20eb286d0> begin[:]
... | keyword[def] identifier[refresh_from_pdb] ( identifier[self] , identifier[pdb_state] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[pdb_state] keyword[and] literal[string] keyword[in] identifier[pdb_state] [ literal[string] ]:
identifier[fname] = identifie... | def refresh_from_pdb(self, pdb_state):
"""
Refresh Variable Explorer and Editor from a Pdb session,
after running any pdb command.
See publish_pdb_state and notify_spyder in spyder_kernels
"""
if 'step' in pdb_state and 'fname' in pdb_state['step']:
fname = pdb_state['st... |
def setuptools_setup(setup_fpath=None, module=None, **kwargs):
# TODO: Learn this better
# https://docs.python.org/3.1/distutils/apiref.html
# https://pythonhosted.org/an_example_pypi_project/setuptools.html
# https://docs.python.org/2/distutils/setupscript.html https://docs.python.org/2/distutils/setup... | def function[setuptools_setup, parameter[setup_fpath, module]]:
constant[
Arguments which can be passed to setuptools::
============ ===== ===========
Install-Data Value Description
------------ ----- -----------
*packages ... | keyword[def] identifier[setuptools_setup] ( identifier[setup_fpath] = keyword[None] , identifier[module] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[utool] . identifier[util_inject] keyword[import] identifier[inject_colored_exceptions]
identifier[inject_... | def setuptools_setup(setup_fpath=None, module=None, **kwargs):
# TODO: Learn this better
# https://docs.python.org/3.1/distutils/apiref.html
# https://pythonhosted.org/an_example_pypi_project/setuptools.html
# https://docs.python.org/2/distutils/setupscript.html https://docs.python.org/2/distutils/setup... |
def filter_instance(inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname in inst.properties.keys():
if... | def function[filter_instance, parameter[inst, plist]]:
constant[Remove properties from an instance that aren't in the PropertyList
inst -- The CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
]
if compare[name[plist] is_not constant[None]] beg... | keyword[def] identifier[filter_instance] ( identifier[inst] , identifier[plist] ):
literal[string]
keyword[if] identifier[plist] keyword[is] keyword[not] keyword[None] :
keyword[for] identifier[pname] keyword[in] identifier[inst] . identifier[properties] . identifier[keys] ():
... | def filter_instance(inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname in inst.properties.keys():
if ... |
def readAccelRange( self ):
"""!
Reads the range of accelerometer setup.
@return an int value.
It should be one of the following values:
@see ACCEL_RANGE_2G
@see ACCEL_RANGE_4G
@see ACCEL_RANGE_8G
@see ACCEL_RANGE_16G
... | def function[readAccelRange, parameter[self]]:
constant[!
Reads the range of accelerometer setup.
@return an int value.
It should be one of the following values:
@see ACCEL_RANGE_2G
@see ACCEL_RANGE_4G
@see ACCEL_RANGE_8G
... | keyword[def] identifier[readAccelRange] ( identifier[self] ):
literal[string]
identifier[raw_data] = identifier[self] . identifier[_readByte] ( identifier[self] . identifier[REG_ACCEL_CONFIG] )
identifier[raw_data] =( identifier[raw_data] | literal[int] )^ literal[int]
keyword[re... | def readAccelRange(self):
"""!
Reads the range of accelerometer setup.
@return an int value.
It should be one of the following values:
@see ACCEL_RANGE_2G
@see ACCEL_RANGE_4G
@see ACCEL_RANGE_8G
@see ACCEL_RANGE_16G
"... |
def source_pipe(self, source, ps=None):
"""Create a source pipe for a source, giving it access to download files to the local cache"""
if isinstance(source, string_types):
source = self.source(source)
source.dataset = self.dataset
source._bundle = self
iter_source,... | def function[source_pipe, parameter[self, source, ps]]:
constant[Create a source pipe for a source, giving it access to download files to the local cache]
if call[name[isinstance], parameter[name[source], name[string_types]]] begin[:]
variable[source] assign[=] call[name[self].source, pa... | keyword[def] identifier[source_pipe] ( identifier[self] , identifier[source] , identifier[ps] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[source] , identifier[string_types] ):
identifier[source] = identifier[self] . identifier[source] ( identifi... | def source_pipe(self, source, ps=None):
"""Create a source pipe for a source, giving it access to download files to the local cache"""
if isinstance(source, string_types):
source = self.source(source) # depends on [control=['if'], data=[]]
source.dataset = self.dataset
source._bundle = self
... |
def max_flow_preflowpush(self, source, sink, algo = 'FIFO', display = None):
'''
API: max_flow_preflowpush(self, source, sink, algo = 'FIFO',
display = None)
Description:
Finds maximum flow from source to sink by a depth-first search based
augmen... | def function[max_flow_preflowpush, parameter[self, source, sink, algo, display]]:
constant[
API: max_flow_preflowpush(self, source, sink, algo = 'FIFO',
display = None)
Description:
Finds maximum flow from source to sink by a depth-first search based
... | keyword[def] identifier[max_flow_preflowpush] ( identifier[self] , identifier[source] , identifier[sink] , identifier[algo] = literal[string] , identifier[display] = keyword[None] ):
literal[string]
keyword[if] identifier[display] == keyword[None] :
identifier[display] = identifier[se... | def max_flow_preflowpush(self, source, sink, algo='FIFO', display=None):
"""
API: max_flow_preflowpush(self, source, sink, algo = 'FIFO',
display = None)
Description:
Finds maximum flow from source to sink by a depth-first search based
augmenting pat... |
def nreturned(self):
"""
Extract counters if available (lazy).
Looks for nreturned, nReturned, or nMatched counter.
"""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters()
return self._nreturned | def function[nreturned, parameter[self]]:
constant[
Extract counters if available (lazy).
Looks for nreturned, nReturned, or nMatched counter.
]
if <ast.UnaryOp object at 0x7da1b1780be0> begin[:]
name[self]._counters_calculated assign[=] constant[True]
... | keyword[def] identifier[nreturned] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_counters_calculated] :
identifier[self] . identifier[_counters_calculated] = keyword[True]
identifier[self] . identifier[_extract_counters] (... | def nreturned(self):
"""
Extract counters if available (lazy).
Looks for nreturned, nReturned, or nMatched counter.
"""
if not self._counters_calculated:
self._counters_calculated = True
self._extract_counters() # depends on [control=['if'], data=[]]
return self._nr... |
def get_datasets(dataset_ids,**kwargs):
"""
Get a single dataset, by ID
"""
user_id = int(kwargs.get('user_id'))
datasets = []
if len(dataset_ids) == 0:
return []
try:
dataset_rs = db.DBSession.query(Dataset.id,
Dataset.type,
Dataset.unit_... | def function[get_datasets, parameter[dataset_ids]]:
constant[
Get a single dataset, by ID
]
variable[user_id] assign[=] call[name[int], parameter[call[name[kwargs].get, parameter[constant[user_id]]]]]
variable[datasets] assign[=] list[[]]
if compare[call[name[len], parameter[... | keyword[def] identifier[get_datasets] ( identifier[dataset_ids] ,** identifier[kwargs] ):
literal[string]
identifier[user_id] = identifier[int] ( identifier[kwargs] . identifier[get] ( literal[string] ))
identifier[datasets] =[]
keyword[if] identifier[len] ( identifier[dataset_ids] )== literal[... | def get_datasets(dataset_ids, **kwargs):
"""
Get a single dataset, by ID
"""
user_id = int(kwargs.get('user_id'))
datasets = []
if len(dataset_ids) == 0:
return [] # depends on [control=['if'], data=[]]
try:
dataset_rs = db.DBSession.query(Dataset.id, Dataset.type, Datas... |
def from_words(cls, words, prefix=0, flatten=False):
"""
Given an iterable of words, return the corresponding table.
The table is built by accumulating, for each word, for each sub-word,
the number of occurrences of the corresponding next character.
:param words: an iter... | def function[from_words, parameter[cls, words, prefix, flatten]]:
constant[
Given an iterable of words, return the corresponding table.
The table is built by accumulating, for each word, for each sub-word,
the number of occurrences of the corresponding next character.
:p... | keyword[def] identifier[from_words] ( identifier[cls] , identifier[words] , identifier[prefix] = literal[int] , identifier[flatten] = keyword[False] ):
literal[string]
identifier[table] = identifier[defaultdict] ( keyword[lambda] : identifier[defaultdict] ( identifier[int] ))
keyword[for] ... | def from_words(cls, words, prefix=0, flatten=False):
"""
Given an iterable of words, return the corresponding table.
The table is built by accumulating, for each word, for each sub-word,
the number of occurrences of the corresponding next character.
:param words: an iterable... |
def read_vest_pickle(gname, score_dir):
"""Read in VEST scores for given gene.
Parameters
----------
gname : str
name of gene
score_dir : str
directory containing vest scores
Returns
-------
gene_vest : dict or None
dict containing vest scores for gene. Returns ... | def function[read_vest_pickle, parameter[gname, score_dir]]:
constant[Read in VEST scores for given gene.
Parameters
----------
gname : str
name of gene
score_dir : str
directory containing vest scores
Returns
-------
gene_vest : dict or None
dict containing... | keyword[def] identifier[read_vest_pickle] ( identifier[gname] , identifier[score_dir] ):
literal[string]
identifier[vest_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[score_dir] , identifier[gname] + literal[string] )
keyword[if] identifier[os] . identifier[path] . identif... | def read_vest_pickle(gname, score_dir):
"""Read in VEST scores for given gene.
Parameters
----------
gname : str
name of gene
score_dir : str
directory containing vest scores
Returns
-------
gene_vest : dict or None
dict containing vest scores for gene. Returns ... |
def register_repeating_metric(self, metric_name, frequency, getter):
'''Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record the value with Carbon.
... | def function[register_repeating_metric, parameter[self, metric_name, frequency, getter]]:
constant[Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record ... | keyword[def] identifier[register_repeating_metric] ( identifier[self] , identifier[metric_name] , identifier[frequency] , identifier[getter] ):
literal[string]
identifier[l] = identifier[task] . identifier[LoopingCall] ( identifier[self] . identifier[_publish_repeating_metric] , identifier[metric_n... | def register_repeating_metric(self, metric_name, frequency, getter):
"""Record hits to a metric at a specified interval.
Args:
metric_name: The name of the metric to record with Carbon.
frequency: The frequency with which to poll the getter and record the value with Carbon.
... |
def getLocationRepresentation(self):
"""
Get the full population representation of the location layer.
"""
activeCells = np.array([], dtype="uint32")
totalPrevCells = 0
for module in self.L6aModules:
activeCells = np.append(activeCells,
module.getActiveCells(... | def function[getLocationRepresentation, parameter[self]]:
constant[
Get the full population representation of the location layer.
]
variable[activeCells] assign[=] call[name[np].array, parameter[list[[]]]]
variable[totalPrevCells] assign[=] constant[0]
for taget[name[module]] in ... | keyword[def] identifier[getLocationRepresentation] ( identifier[self] ):
literal[string]
identifier[activeCells] = identifier[np] . identifier[array] ([], identifier[dtype] = literal[string] )
identifier[totalPrevCells] = literal[int]
keyword[for] identifier[module] keyword[in] identifier[se... | def getLocationRepresentation(self):
"""
Get the full population representation of the location layer.
"""
activeCells = np.array([], dtype='uint32')
totalPrevCells = 0
for module in self.L6aModules:
activeCells = np.append(activeCells, module.getActiveCells() + totalPrevCells)
t... |
def step(sampler, x, delta, fraction=None, tries=0):
"""Sample a new feasible point from the point `x` in direction `delta`."""
prob = sampler.problem
valid = ((np.abs(delta) > sampler.feasibility_tol) &
np.logical_not(prob.variable_fixed))
# permissible alphas for staying in variable bou... | def function[step, parameter[sampler, x, delta, fraction, tries]]:
constant[Sample a new feasible point from the point `x` in direction `delta`.]
variable[prob] assign[=] name[sampler].problem
variable[valid] assign[=] binary_operation[compare[call[name[np].abs, parameter[name[delta]]] greater[>... | keyword[def] identifier[step] ( identifier[sampler] , identifier[x] , identifier[delta] , identifier[fraction] = keyword[None] , identifier[tries] = literal[int] ):
literal[string]
identifier[prob] = identifier[sampler] . identifier[problem]
identifier[valid] =(( identifier[np] . identifier[abs] ( i... | def step(sampler, x, delta, fraction=None, tries=0):
"""Sample a new feasible point from the point `x` in direction `delta`."""
prob = sampler.problem
valid = (np.abs(delta) > sampler.feasibility_tol) & np.logical_not(prob.variable_fixed)
# permissible alphas for staying in variable bounds
valphas =... |
def json_encoder_default(obj):
"""JSON encoder function that handles some numpy types."""
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj)
if isinstance(obj, np.integer):
return str(obj)
elif isinstance(obj, np.floating):
... | def function[json_encoder_default, parameter[obj]]:
constant[JSON encoder function that handles some numpy types.]
if <ast.BoolOp object at 0x7da18ede41c0> begin[:]
return[call[name[str], parameter[name[obj]]]]
if call[name[isinstance], parameter[name[obj], name[np].integer]] begin[:]
... | keyword[def] identifier[json_encoder_default] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[numbers] . identifier[Integral] ) keyword[and] ( identifier[obj] < identifier[min_safe_integer] keyword[or] identifier[obj] > identifier[max_safe_integer] ... | def json_encoder_default(obj):
"""JSON encoder function that handles some numpy types."""
if isinstance(obj, numbers.Integral) and (obj < min_safe_integer or obj > max_safe_integer):
return str(obj) # depends on [control=['if'], data=[]]
if isinstance(obj, np.integer):
return str(obj) # de... |
def update_module_types():
"""
Download the repositories for all of the firmware_module_type records and
update them using the `module.json` files from the repositories themselves.
Currently only works for git repositories.
"""
local_url = config["local_server"]["url"]
server = Server(local_... | def function[update_module_types, parameter[]]:
constant[
Download the repositories for all of the firmware_module_type records and
update them using the `module.json` files from the repositories themselves.
Currently only works for git repositories.
]
variable[local_url] assign[=] call[... | keyword[def] identifier[update_module_types] ():
literal[string]
identifier[local_url] = identifier[config] [ literal[string] ][ literal[string] ]
identifier[server] = identifier[Server] ( identifier[local_url] )
identifier[db] = identifier[server] [ identifier[FIRMWARE_MODULE_TYPE] ]
identi... | def update_module_types():
"""
Download the repositories for all of the firmware_module_type records and
update them using the `module.json` files from the repositories themselves.
Currently only works for git repositories.
"""
local_url = config['local_server']['url']
server = Server(local_... |
def add(self, *nonterminals):
# type: (Iterable[Type[Nonterminal]]) -> None
"""
Add nonterminals into the set.
:param nonterminals: Nonterminals to insert.
:raise NotNonterminalException: If the object doesn't inherit from Nonterminal class.
"""
for nonterm in non... | def function[add, parameter[self]]:
constant[
Add nonterminals into the set.
:param nonterminals: Nonterminals to insert.
:raise NotNonterminalException: If the object doesn't inherit from Nonterminal class.
]
for taget[name[nonterm]] in starred[name[nonterminals]] begin[... | keyword[def] identifier[add] ( identifier[self] ,* identifier[nonterminals] ):
literal[string]
keyword[for] identifier[nonterm] keyword[in] identifier[nonterminals] :
keyword[if] identifier[nonterm] keyword[in] identifier[self] :
keyword[continue]
... | def add(self, *nonterminals):
# type: (Iterable[Type[Nonterminal]]) -> None
"\n Add nonterminals into the set.\n :param nonterminals: Nonterminals to insert.\n :raise NotNonterminalException: If the object doesn't inherit from Nonterminal class.\n "
for nonterm in nonterminals:
... |
def _make_it_so(self, command, calls, *args, **kwargs):
""" Perform some error-checked XMLRPC calls.
"""
observer = kwargs.pop('observer', False)
args = (self._fields["hash"],) + args
try:
for call in calls:
self._engine.LOG.debug("%s%s torrent #%s (%s... | def function[_make_it_so, parameter[self, command, calls]]:
constant[ Perform some error-checked XMLRPC calls.
]
variable[observer] assign[=] call[name[kwargs].pop, parameter[constant[observer], constant[False]]]
variable[args] assign[=] binary_operation[tuple[[<ast.Subscript object at 0... | keyword[def] identifier[_make_it_so] ( identifier[self] , identifier[command] , identifier[calls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[observer] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
identifier[args] =( identifier[se... | def _make_it_so(self, command, calls, *args, **kwargs):
""" Perform some error-checked XMLRPC calls.
"""
observer = kwargs.pop('observer', False)
args = (self._fields['hash'],) + args
try:
for call in calls:
self._engine.LOG.debug('%s%s torrent #%s (%s)' % (command[0].upper()... |
def beta(self):
"""
Courant-Snyder parameter :math:`\\beta`.
"""
beta = _np.sqrt(self.sx)/self.emit
return beta | def function[beta, parameter[self]]:
constant[
Courant-Snyder parameter :math:`\beta`.
]
variable[beta] assign[=] binary_operation[call[name[_np].sqrt, parameter[name[self].sx]] / name[self].emit]
return[name[beta]] | keyword[def] identifier[beta] ( identifier[self] ):
literal[string]
identifier[beta] = identifier[_np] . identifier[sqrt] ( identifier[self] . identifier[sx] )/ identifier[self] . identifier[emit]
keyword[return] identifier[beta] | def beta(self):
"""
Courant-Snyder parameter :math:`\\beta`.
"""
beta = _np.sqrt(self.sx) / self.emit
return beta |
def pv_count(self):
"""
Returns the physical volume count.
"""
self.open()
count = lvm_vg_get_pv_count(self.handle)
self.close()
return count | def function[pv_count, parameter[self]]:
constant[
Returns the physical volume count.
]
call[name[self].open, parameter[]]
variable[count] assign[=] call[name[lvm_vg_get_pv_count], parameter[name[self].handle]]
call[name[self].close, parameter[]]
return[name[count]] | keyword[def] identifier[pv_count] ( identifier[self] ):
literal[string]
identifier[self] . identifier[open] ()
identifier[count] = identifier[lvm_vg_get_pv_count] ( identifier[self] . identifier[handle] )
identifier[self] . identifier[close] ()
keyword[return] identifier... | def pv_count(self):
"""
Returns the physical volume count.
"""
self.open()
count = lvm_vg_get_pv_count(self.handle)
self.close()
return count |
def prepare_display(self):
"""Prepare the display.
This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.
When data or display parameters change, the internal state of the line plot gets updated. This method takes
that internal state and u... | def function[prepare_display, parameter[self]]:
constant[Prepare the display.
This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.
When data or display parameters change, the internal state of the line plot gets updated. This method takes
... | keyword[def] identifier[prepare_display] ( identifier[self] ):
literal[string]
identifier[displayed_dimensional_calibration] = identifier[self] . identifier[__displayed_dimensional_calibration]
identifier[intensity_calibration] = identifier[self] . identifier[__intensity_calibration]
... | def prepare_display(self):
"""Prepare the display.
This method gets called by the canvas layout/draw engine after being triggered by a call to `update`.
When data or display parameters change, the internal state of the line plot gets updated. This method takes
that internal state and updat... |
def signalcommand(func):
"""Python decorator for management command handle defs that sends out a pre/post signal."""
def inner(self, *args, **kwargs):
pre_command.send(self.__class__, args=args, kwargs=kwargs)
ret = func(self, *args, **kwargs)
post_command.send(self.__class__, args=args... | def function[signalcommand, parameter[func]]:
constant[Python decorator for management command handle defs that sends out a pre/post signal.]
def function[inner, parameter[self]]:
call[name[pre_command].send, parameter[name[self].__class__]]
variable[ret] assign[=] call[n... | keyword[def] identifier[signalcommand] ( identifier[func] ):
literal[string]
keyword[def] identifier[inner] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
identifier[pre_command] . identifier[send] ( identifier[self] . identifier[__class__] , identifier[args] = identifier[args]... | def signalcommand(func):
"""Python decorator for management command handle defs that sends out a pre/post signal."""
def inner(self, *args, **kwargs):
pre_command.send(self.__class__, args=args, kwargs=kwargs)
ret = func(self, *args, **kwargs)
post_command.send(self.__class__, args=args... |
def prepare(args):
"""
%prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile>
Inferred file names
---------------------------------------------
`lookuptblfile` : rearraylibrary.lookup
`rearraylibfile`: rearraylibrary.fasta
Pick sequences from the original library file a... | def function[prepare, parameter[args]]:
constant[
%prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile>
Inferred file names
---------------------------------------------
`lookuptblfile` : rearraylibrary.lookup
`rearraylibfile`: rearraylibrary.fasta
Pick sequences f... | keyword[def] identifier[prepare] ( identifier[args] ):
literal[string]
keyword[from] identifier[operator] keyword[import] identifier[itemgetter]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[fasta] keyword[import] identifier[Fasta] , identifier[SeqIO]
identifier[p] = ... | def prepare(args):
"""
%prog prepare --rearray_lib=<rearraylibrary> --orig_lib_file=<origlibfile>
Inferred file names
---------------------------------------------
`lookuptblfile` : rearraylibrary.lookup
`rearraylibfile`: rearraylibrary.fasta
Pick sequences from the original library file a... |
def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs | def function[get_queryset, parameter[self]]:
constant[ Returns all the approved topics or posts. ]
variable[qs] assign[=] call[call[name[super], parameter[]].get_queryset, parameter[]]
variable[qs] assign[=] call[name[qs].filter, parameter[]]
return[name[qs]] | keyword[def] identifier[get_queryset] ( identifier[self] ):
literal[string]
identifier[qs] = identifier[super] (). identifier[get_queryset] ()
identifier[qs] = identifier[qs] . identifier[filter] ( identifier[approved] = keyword[True] )
keyword[return] identifier[qs] | def get_queryset(self):
""" Returns all the approved topics or posts. """
qs = super().get_queryset()
qs = qs.filter(approved=True)
return qs |
def parseBtop(btopString):
"""
Parse a BTOP string.
The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If C{btopString} is not valid BTOP.
@return: A generator that yields a series of integers and 2-tuples of
... | def function[parseBtop, parameter[btopString]]:
constant[
Parse a BTOP string.
The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If C{btopString} is not valid BTOP.
@return: A generator that yields a serie... | keyword[def] identifier[parseBtop] ( identifier[btopString] ):
literal[string]
identifier[isdigit] = identifier[str] . identifier[isdigit]
identifier[value] = keyword[None]
identifier[queryLetter] = keyword[None]
keyword[for] identifier[offset] , identifier[char] keyword[in] identifier... | def parseBtop(btopString):
"""
Parse a BTOP string.
The format is described at https://www.ncbi.nlm.nih.gov/books/NBK279682/
@param btopString: A C{str} BTOP sequence.
@raise ValueError: If C{btopString} is not valid BTOP.
@return: A generator that yields a series of integers and 2-tuples of
... |
def _get_chromecast_from_host(host, tries=None, retry_wait=None, timeout=None,
blocking=True):
"""Creates a Chromecast object from a zeroconf host."""
# Build device status from the mDNS info, this information is
# the primary source and the remaining will be fetched
# late... | def function[_get_chromecast_from_host, parameter[host, tries, retry_wait, timeout, blocking]]:
constant[Creates a Chromecast object from a zeroconf host.]
<ast.Tuple object at 0x7da18dc9a7d0> assign[=] name[host]
call[name[_LOGGER].debug, parameter[constant[_get_chromecast_from_host %s], name[h... | keyword[def] identifier[_get_chromecast_from_host] ( identifier[host] , identifier[tries] = keyword[None] , identifier[retry_wait] = keyword[None] , identifier[timeout] = keyword[None] ,
identifier[blocking] = keyword[True] ):
literal[string]
identifier[ip_address] , identifier[port] , iden... | def _get_chromecast_from_host(host, tries=None, retry_wait=None, timeout=None, blocking=True):
"""Creates a Chromecast object from a zeroconf host."""
# Build device status from the mDNS info, this information is
# the primary source and the remaining will be fetched
# later on.
(ip_address, port, u... |
def endpoint_get(auth=None, **kwargs):
'''
Get a single endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_endpoint(**kwargs) | def function[endpoint_get, parameter[auth]]:
constant[
Get a single endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5
]
variable[cloud] assign[=] call[name[get_operator_cloud], parameter[name[auth]]]
variabl... | keyword[def] identifier[endpoint_get] ( identifier[auth] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[cloud] = identifier[get_operator_cloud] ( identifier[auth] )
identifier[kwargs] = identifier[_clean_kwargs] (** identifier[kwargs] )
keyword[return] identifier[cloud] . i... | def endpoint_get(auth=None, **kwargs):
"""
Get a single endpoint
CLI Example:
.. code-block:: bash
salt '*' keystoneng.endpoint_get id=02cffaa173b2460f98e40eda3748dae5
"""
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.get_endpoint(**kwargs) |
def ip_access_control_list_mappings(self):
"""
Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAc... | def function[ip_access_control_list_mappings, parameter[self]]:
constant[
Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_acces... | keyword[def] identifier[ip_access_control_list_mappings] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_ip_access_control_list_mappings] keyword[is] keyword[None] :
identifier[self] . identifier[_ip_access_control_list_mappings] = identifier[IpAcces... | def ip_access_control_list_mappings(self):
"""
Access the ip_access_control_list_mappings
:returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingList
:rtype: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccess... |
def process_rename(self, client, tag_value, resource_set):
"""
Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value
"""
self.log.info("Renaming tag on %s instances" % (len(resource_set... | def function[process_rename, parameter[self, client, tag_value, resource_set]]:
constant[
Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value
]
call[name[self].log.info, parameter[bin... | keyword[def] identifier[process_rename] ( identifier[self] , identifier[client] , identifier[tag_value] , identifier[resource_set] ):
literal[string]
identifier[self] . identifier[log] . identifier[info] ( literal[string] %( identifier[len] ( identifier[resource_set] )))
identifier[old_key... | def process_rename(self, client, tag_value, resource_set):
"""
Move source tag value to destination tag value
- Collect value from old tag
- Delete old tag
- Create new tag & assign stored value
"""
self.log.info('Renaming tag on %s instances' % len(resource_set))
ol... |
def separate(polylines, f_mx_dist=2, mn_group_len=4):
"""
split polylines wherever crinkles are found
"""
s = []
for n in range(len(polylines) - 1, -1, -1):
c = polylines[n]
separated = False
start = 0
for m in range(mn_group_len, len(c) - 1):
if m - sta... | def function[separate, parameter[polylines, f_mx_dist, mn_group_len]]:
constant[
split polylines wherever crinkles are found
]
variable[s] assign[=] list[[]]
for taget[name[n]] in starred[call[name[range], parameter[binary_operation[call[name[len], parameter[name[polylines]]] - constant[... | keyword[def] identifier[separate] ( identifier[polylines] , identifier[f_mx_dist] = literal[int] , identifier[mn_group_len] = literal[int] ):
literal[string]
identifier[s] =[]
keyword[for] identifier[n] keyword[in] identifier[range] ( identifier[len] ( identifier[polylines] )- literal[int] ,- lite... | def separate(polylines, f_mx_dist=2, mn_group_len=4):
"""
split polylines wherever crinkles are found
"""
s = []
for n in range(len(polylines) - 1, -1, -1):
c = polylines[n]
separated = False
start = 0
for m in range(mn_group_len, len(c) - 1):
if m - start... |
def kwargs_from_client(client, assert_hostname=False):
"""
More or less stolen from docker-py's kwargs_from_env
https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py
:type client : docker.Client
"""
from docker import tls
if client.base_url i... | def function[kwargs_from_client, parameter[client, assert_hostname]]:
constant[
More or less stolen from docker-py's kwargs_from_env
https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py
:type client : docker.Client
]
from relative_module[doc... | keyword[def] identifier[kwargs_from_client] ( identifier[client] , identifier[assert_hostname] = keyword[False] ):
literal[string]
keyword[from] identifier[docker] keyword[import] identifier[tls]
keyword[if] identifier[client] . identifier[base_url] keyword[in] ( literal[string] , literal[string... | def kwargs_from_client(client, assert_hostname=False):
"""
More or less stolen from docker-py's kwargs_from_env
https://github.com/docker/docker-py/blob/c0ec5512ae7ab90f7fac690064e37181186b1928/docker/utils/utils.py
:type client : docker.Client
"""
from docker import tls
if client.base_url i... |
def describeSObjects(self, sObjectTypes):
'''
An array-based version of describeSObject; describes metadata (field list
and object properties) for the specified object or array of objects.
'''
self._setHeaders('describeSObjects')
return self._handleResultTyping(self._sforce.service.describeSObje... | def function[describeSObjects, parameter[self, sObjectTypes]]:
constant[
An array-based version of describeSObject; describes metadata (field list
and object properties) for the specified object or array of objects.
]
call[name[self]._setHeaders, parameter[constant[describeSObjects]]]
re... | keyword[def] identifier[describeSObjects] ( identifier[self] , identifier[sObjectTypes] ):
literal[string]
identifier[self] . identifier[_setHeaders] ( literal[string] )
keyword[return] identifier[self] . identifier[_handleResultTyping] ( identifier[self] . identifier[_sforce] . identifier[service] .... | def describeSObjects(self, sObjectTypes):
"""
An array-based version of describeSObject; describes metadata (field list
and object properties) for the specified object or array of objects.
"""
self._setHeaders('describeSObjects')
return self._handleResultTyping(self._sforce.service.describeSObje... |
def mprocess(name, config_path, port=None, timeout=180, silence_stdout=True):
"""start 'name' process with params from config_path.
Args:
name - process name or path
config_path - path to file where should be stored configuration
port - process's port
timeout - specify how long, ... | def function[mprocess, parameter[name, config_path, port, timeout, silence_stdout]]:
constant[start 'name' process with params from config_path.
Args:
name - process name or path
config_path - path to file where should be stored configuration
port - process's port
timeout - s... | keyword[def] identifier[mprocess] ( identifier[name] , identifier[config_path] , identifier[port] = keyword[None] , identifier[timeout] = literal[int] , identifier[silence_stdout] = keyword[True] ):
literal[string]
identifier[logger] . identifier[debug] (
literal[string]
literal[string] . ident... | def mprocess(name, config_path, port=None, timeout=180, silence_stdout=True):
"""start 'name' process with params from config_path.
Args:
name - process name or path
config_path - path to file where should be stored configuration
port - process's port
timeout - specify how long, ... |
def add_environment(self, environment, sync=True):
"""
add an environment to this OS instance.
:param environment: the environment to add on this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the environment object on list to be... | def function[add_environment, parameter[self, environment, sync]]:
constant[
add an environment to this OS instance.
:param environment: the environment to add on this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the environmen... | keyword[def] identifier[add_environment] ( identifier[self] , identifier[environment] , identifier[sync] = keyword[True] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] keyword[not] identifier[sync] :
identifier[self] . identifier[en... | def add_environment(self, environment, sync=True):
"""
add an environment to this OS instance.
:param environment: the environment to add on this OS instance
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the environment object on list to be add... |
def not_empty(message=None) -> Filter_T:
"""
Validate any object to ensure it's not empty (is None or has no elements).
"""
def validate(value):
if value is None:
_raise_failure(message)
if hasattr(value, '__len__') and value.__len__() == 0:
_raise_failure(messag... | def function[not_empty, parameter[message]]:
constant[
Validate any object to ensure it's not empty (is None or has no elements).
]
def function[validate, parameter[value]]:
if compare[name[value] is constant[None]] begin[:]
call[name[_raise_failure], para... | keyword[def] identifier[not_empty] ( identifier[message] = keyword[None] )-> identifier[Filter_T] :
literal[string]
keyword[def] identifier[validate] ( identifier[value] ):
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[_raise_failure] ( identifier[message] ... | def not_empty(message=None) -> Filter_T:
"""
Validate any object to ensure it's not empty (is None or has no elements).
"""
def validate(value):
if value is None:
_raise_failure(message) # depends on [control=['if'], data=[]]
if hasattr(value, '__len__') and value.__len__()... |
def admin_cmd(argv=sys.argv[1:]): # pragma: no cover
"""\
Activate or delete models.
Models are usually made active right after fitting (see command
pld-fit). The 'activate' command allows you to explicitly set the
currently active model. Use 'pld-list' to get an overview of all
available models along with thei... | def function[admin_cmd, parameter[argv]]:
constant[Activate or delete models.
Models are usually made active right after fitting (see command
pld-fit). The 'activate' command allows you to explicitly set the
currently active model. Use 'pld-list' to get an overview of all
available models along with their ve... | keyword[def] identifier[admin_cmd] ( identifier[argv] = identifier[sys] . identifier[argv] [ literal[int] :]):
literal[string]
identifier[arguments] = identifier[docopt] ( identifier[admin_cmd] . identifier[__doc__] , identifier[argv] = identifier[argv] )
identifier[initialize_config] ( identifier[__m... | def admin_cmd(argv=sys.argv[1:]): # pragma: no cover
"Activate or delete models.\n\nModels are usually made active right after fitting (see command\npld-fit). The 'activate' command allows you to explicitly set the\ncurrently active model. Use 'pld-list' to get an overview of all\navailable models along with the... |
def get_paths(path_tokens):
""" Given a list of parser path tokens, return a list of path objects
for them.
"""
if len(path_tokens) == 0:
return []
token = path_tokens.pop()
path = PathToken(token.alias, token.path)
return [path] + get_paths(path_tokens) | def function[get_paths, parameter[path_tokens]]:
constant[ Given a list of parser path tokens, return a list of path objects
for them.
]
if compare[call[name[len], parameter[name[path_tokens]]] equal[==] constant[0]] begin[:]
return[list[[]]]
variable[token] assign[=] call[name[p... | keyword[def] identifier[get_paths] ( identifier[path_tokens] ):
literal[string]
keyword[if] identifier[len] ( identifier[path_tokens] )== literal[int] :
keyword[return] []
identifier[token] = identifier[path_tokens] . identifier[pop] ()
identifier[path] = identifier[PathToken] ( identi... | def get_paths(path_tokens):
""" Given a list of parser path tokens, return a list of path objects
for them.
"""
if len(path_tokens) == 0:
return [] # depends on [control=['if'], data=[]]
token = path_tokens.pop()
path = PathToken(token.alias, token.path)
return [path] + get_paths(pa... |
def create_api_pool_deploy(self):
"""Get an instance of Api Pool Deploy services facade."""
return ApiPoolDeploy(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | def function[create_api_pool_deploy, parameter[self]]:
constant[Get an instance of Api Pool Deploy services facade.]
return[call[name[ApiPoolDeploy], parameter[name[self].networkapi_url, name[self].user, name[self].password, name[self].user_ldap]]] | keyword[def] identifier[create_api_pool_deploy] ( identifier[self] ):
literal[string]
keyword[return] identifier[ApiPoolDeploy] (
identifier[self] . identifier[networkapi_url] ,
identifier[self] . identifier[user] ,
identifier[self] . identifier[password] ,
iden... | def create_api_pool_deploy(self):
"""Get an instance of Api Pool Deploy services facade."""
return ApiPoolDeploy(self.networkapi_url, self.user, self.password, self.user_ldap) |
def comments(self, *bug_ids):
"""Get the comments of the given bugs.
:param bug_ids: list of bug identifiers
"""
# Hack. The first value must be a valid bug id
resource = urijoin(self.RBUG, bug_ids[0], self.RCOMMENT)
params = {
self.PIDS: bug_ids
}
... | def function[comments, parameter[self]]:
constant[Get the comments of the given bugs.
:param bug_ids: list of bug identifiers
]
variable[resource] assign[=] call[name[urijoin], parameter[name[self].RBUG, call[name[bug_ids]][constant[0]], name[self].RCOMMENT]]
variable[params] as... | keyword[def] identifier[comments] ( identifier[self] ,* identifier[bug_ids] ):
literal[string]
identifier[resource] = identifier[urijoin] ( identifier[self] . identifier[RBUG] , identifier[bug_ids] [ literal[int] ], identifier[self] . identifier[RCOMMENT] )
identifier[params] ={
... | def comments(self, *bug_ids):
"""Get the comments of the given bugs.
:param bug_ids: list of bug identifiers
"""
# Hack. The first value must be a valid bug id
resource = urijoin(self.RBUG, bug_ids[0], self.RCOMMENT)
params = {self.PIDS: bug_ids}
response = self.call(resource, param... |
def _backward_slice_indirect(self, cfgnode, sim_successors, current_function_addr):
"""
Try to resolve an indirect jump by slicing backwards
"""
# TODO: make this a real indirect jump resolver under the new paradigm
irsb = sim_successors.artifacts['irsb'] # shorthand
l... | def function[_backward_slice_indirect, parameter[self, cfgnode, sim_successors, current_function_addr]]:
constant[
Try to resolve an indirect jump by slicing backwards
]
variable[irsb] assign[=] call[name[sim_successors].artifacts][constant[irsb]]
call[name[l].debug, parameter[co... | keyword[def] identifier[_backward_slice_indirect] ( identifier[self] , identifier[cfgnode] , identifier[sim_successors] , identifier[current_function_addr] ):
literal[string]
identifier[irsb] = identifier[sim_successors] . identifier[artifacts] [ literal[string] ]
identifier[l] ... | def _backward_slice_indirect(self, cfgnode, sim_successors, current_function_addr):
"""
Try to resolve an indirect jump by slicing backwards
"""
# TODO: make this a real indirect jump resolver under the new paradigm
irsb = sim_successors.artifacts['irsb'] # shorthand
l.debug('Resolving ... |
def break_to_bytes(value):
"""
Breaks a value into values of less than 255 that form value when multiplied.
(Or almost do so with primes)
Returns a tuple
"""
if value < 256:
return (value,)
c = 256
least = (0, 255)
for i in range(254):
c -= 1
rest = value % c
... | def function[break_to_bytes, parameter[value]]:
constant[
Breaks a value into values of less than 255 that form value when multiplied.
(Or almost do so with primes)
Returns a tuple
]
if compare[name[value] less[<] constant[256]] begin[:]
return[tuple[[<ast.Name object at 0x7da1b1... | keyword[def] identifier[break_to_bytes] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] < literal[int] :
keyword[return] ( identifier[value] ,)
identifier[c] = literal[int]
identifier[least] =( literal[int] , literal[int] )
keyword[for] identifier[i] keyword... | def break_to_bytes(value):
"""
Breaks a value into values of less than 255 that form value when multiplied.
(Or almost do so with primes)
Returns a tuple
"""
if value < 256:
return (value,) # depends on [control=['if'], data=['value']]
c = 256
least = (0, 255)
for i in range... |
def _pytypes_excepthook(exctype, value, tb):
""""An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The latter automatically installs this... | def function[_pytypes_excepthook, parameter[exctype, value, tb]]:
constant["An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The lat... | keyword[def] identifier[_pytypes_excepthook] ( identifier[exctype] , identifier[value] , identifier[tb] ):
literal[string]
keyword[if] identifier[pytypes] . identifier[clean_traceback] keyword[and] identifier[issubclass] ( identifier[exctype] , identifier[TypeError] ):
identifier[traceback] . i... | def _pytypes_excepthook(exctype, value, tb):
""""An excepthook suitable for use as sys.excepthook, that strips away
the part of the traceback belonging to pytypes' internals.
Can be switched on and off via pytypes.clean_traceback
or pytypes.set_clean_traceback.
The latter automatically installs this... |
def range(self, start, end=None, step=1, numPartitions=None):
"""
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the sta... | def function[range, parameter[self, start, end, step, numPartitions]]:
constant[
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param... | keyword[def] identifier[range] ( identifier[self] , identifier[start] , identifier[end] = keyword[None] , identifier[step] = literal[int] , identifier[numPartitions] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[sparkSession] . identifier[range] ( identifier[star... | def range(self, start, end=None, step=1, numPartitions=None):
"""
Create a :class:`DataFrame` with single :class:`pyspark.sql.types.LongType` column named
``id``, containing elements in a range from ``start`` to ``end`` (exclusive) with
step value ``step``.
:param start: the start v... |
def basic_dependencies(self):
"""
Accesses basic dependencies from the XML output
:getter: Returns the dependency graph for basic dependencies
:type: corenlp_xml.dependencies.DependencyGraph
"""
if self._basic_dependencies is None:
deps = self._element.xpath... | def function[basic_dependencies, parameter[self]]:
constant[
Accesses basic dependencies from the XML output
:getter: Returns the dependency graph for basic dependencies
:type: corenlp_xml.dependencies.DependencyGraph
]
if compare[name[self]._basic_dependencies is const... | keyword[def] identifier[basic_dependencies] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_basic_dependencies] keyword[is] keyword[None] :
identifier[deps] = identifier[self] . identifier[_element] . identifier[xpath] ( literal[string] )
... | def basic_dependencies(self):
"""
Accesses basic dependencies from the XML output
:getter: Returns the dependency graph for basic dependencies
:type: corenlp_xml.dependencies.DependencyGraph
"""
if self._basic_dependencies is None:
deps = self._element.xpath('dependenci... |
def words_to_word_ids(data=None, word_to_id=None, unk_key='UNK'):
"""Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Represent the unknow... | def function[words_to_word_ids, parameter[data, word_to_id, unk_key]]:
constant[Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Repre... | keyword[def] identifier[words_to_word_ids] ( identifier[data] = keyword[None] , identifier[word_to_id] = keyword[None] , identifier[unk_key] = literal[string] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
... | def words_to_word_ids(data=None, word_to_id=None, unk_key='UNK'):
"""Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Represent the unknow... |
def download(self, directory, structure=True):
"""
Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder stru... | def function[download, parameter[self, directory, structure]]:
constant[
Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.... | keyword[def] identifier[download] ( identifier[self] , identifier[directory] , identifier[structure] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[manager] . identifier[download] ( identifier[self] , identifier[directory] , identifier[structure] = identifier[stru... | def download(self, directory, structure=True):
"""
Fetches the object from storage, and writes it to the specified
directory. The directory must exist before calling this method.
If the object name represents a nested folder structure, such as
"foo/bar/baz.txt", that folder structur... |
def count(self, *_clauses, **kwargs):
"""Return the count of results for the given filter set."""
# NOTE: this does not have support for limit and offset since I can't
# see how this is useful. Still, there might be compatibility issues
# with people using these flags. Let's see how it g... | def function[count, parameter[self]]:
constant[Return the count of results for the given filter set.]
if <ast.UnaryOp object at 0x7da1b1e8de10> begin[:]
return[constant[0]]
variable[args] assign[=] call[name[self]._args_to_clause, parameter[name[kwargs]]]
variable[query] assign[=... | keyword[def] identifier[count] ( identifier[self] ,* identifier[_clauses] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[exists] :
keyword[return] literal[int]
identifier[args] = identifier[self]... | def count(self, *_clauses, **kwargs):
"""Return the count of results for the given filter set."""
# NOTE: this does not have support for limit and offset since I can't
# see how this is useful. Still, there might be compatibility issues
# with people using these flags. Let's see how it goes.
if not ... |
def centroid(coo):
"""Calculates the centroid from a 3D point cloud and returns the coordinates
:param coo: Array of coordinate arrays
:returns : centroid coordinates as list
"""
return list(map(np.mean, (([c[0] for c in coo]), ([c[1] for c in coo]), ([c[2] for c in coo])))) | def function[centroid, parameter[coo]]:
constant[Calculates the centroid from a 3D point cloud and returns the coordinates
:param coo: Array of coordinate arrays
:returns : centroid coordinates as list
]
return[call[name[list], parameter[call[name[map], parameter[name[np].mean, tuple[[<ast.ListC... | keyword[def] identifier[centroid] ( identifier[coo] ):
literal[string]
keyword[return] identifier[list] ( identifier[map] ( identifier[np] . identifier[mean] ,(([ identifier[c] [ literal[int] ] keyword[for] identifier[c] keyword[in] identifier[coo] ]),([ identifier[c] [ literal[int] ] keyword[for] ide... | def centroid(coo):
"""Calculates the centroid from a 3D point cloud and returns the coordinates
:param coo: Array of coordinate arrays
:returns : centroid coordinates as list
"""
return list(map(np.mean, ([c[0] for c in coo], [c[1] for c in coo], [c[2] for c in coo]))) |
def _sortHTML(titlesAlignments, by, limit=None):
"""
Return an C{IPython.display.HTML} object with the alignments sorted by the
given attribute.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount',... | def function[_sortHTML, parameter[titlesAlignments, by, limit]]:
constant[
Return an C{IPython.display.HTML} object with the alignments sorted by the
given attribute.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param by: A C{str}, one of 'length', 'maxScore', 'medianSc... | keyword[def] identifier[_sortHTML] ( identifier[titlesAlignments] , identifier[by] , identifier[limit] = keyword[None] ):
literal[string]
identifier[out] =[]
keyword[for] identifier[i] , identifier[title] keyword[in] identifier[enumerate] ( identifier[titlesAlignments] . identifier[sortTitles] ( id... | def _sortHTML(titlesAlignments, by, limit=None):
"""
Return an C{IPython.display.HTML} object with the alignments sorted by the
given attribute.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param by: A C{str}, one of 'length', 'maxScore', 'medianScore',
'readCount',... |
def job_is_enabled(self, job_id):
"""
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
job_desc = self._jobs[job_id]
return job_desc['enabled'] | def function[job_is_enabled, parameter[self, job_id]]:
constant[
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
]
variable[job_id] assign[=] call[name[normalize_job_id], parameter[name[job_id]]]
variabl... | keyword[def] identifier[job_is_enabled] ( identifier[self] , identifier[job_id] ):
literal[string]
identifier[job_id] = identifier[normalize_job_id] ( identifier[job_id] )
identifier[job_desc] = identifier[self] . identifier[_jobs] [ identifier[job_id] ]
keyword[return] identifier[job_desc] [ literal[st... | def job_is_enabled(self, job_id):
"""
Check if a job is enabled.
:param job_id: Job identifier to check the status of.
:type job_id: :py:class:`uuid.UUID`
:rtype: bool
"""
job_id = normalize_job_id(job_id)
job_desc = self._jobs[job_id]
return job_desc['enabled'] |
def extract_ipv4(roster_order, ipv4):
'''
Extract the preferred IP address from the ipv4 grain
'''
for ip_type in roster_order:
for ip_ in ipv4:
if ':' in ip_:
continue
if not salt.utils.validate.net.ipv4_addr(ip_):
continue
if ... | def function[extract_ipv4, parameter[roster_order, ipv4]]:
constant[
Extract the preferred IP address from the ipv4 grain
]
for taget[name[ip_type]] in starred[name[roster_order]] begin[:]
for taget[name[ip_]] in starred[name[ipv4]] begin[:]
if compare[con... | keyword[def] identifier[extract_ipv4] ( identifier[roster_order] , identifier[ipv4] ):
literal[string]
keyword[for] identifier[ip_type] keyword[in] identifier[roster_order] :
keyword[for] identifier[ip_] keyword[in] identifier[ipv4] :
keyword[if] literal[string] keyword[in] i... | def extract_ipv4(roster_order, ipv4):
"""
Extract the preferred IP address from the ipv4 grain
"""
for ip_type in roster_order:
for ip_ in ipv4:
if ':' in ip_:
continue # depends on [control=['if'], data=[]]
if not salt.utils.validate.net.ipv4_addr(ip_):
... |
async def container(self, container=None, container_type=None, params=None):
"""
Loads/dumps container
:return:
"""
if hasattr(container_type, "serialize_archive"):
container = container_type() if container is None else container
return await container.ser... | <ast.AsyncFunctionDef object at 0x7da2047e9d20> | keyword[async] keyword[def] identifier[container] ( identifier[self] , identifier[container] = keyword[None] , identifier[container_type] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[container_type] , literal[string] ):
... | async def container(self, container=None, container_type=None, params=None):
"""
Loads/dumps container
:return:
"""
if hasattr(container_type, 'serialize_archive'):
container = container_type() if container is None else container
return await container.serialize_archive(s... |
def get_average_length_of_string(strings):
"""Computes average length of words
:param strings: list of words
:return: Average length of word on list
"""
if not strings:
return 0
return sum(len(word) for word in strings) / len(strings) | def function[get_average_length_of_string, parameter[strings]]:
constant[Computes average length of words
:param strings: list of words
:return: Average length of word on list
]
if <ast.UnaryOp object at 0x7da18f09e440> begin[:]
return[constant[0]]
return[binary_operation[call[n... | keyword[def] identifier[get_average_length_of_string] ( identifier[strings] ):
literal[string]
keyword[if] keyword[not] identifier[strings] :
keyword[return] literal[int]
keyword[return] identifier[sum] ( identifier[len] ( identifier[word] ) keyword[for] identifier[word] keyword[in] ... | def get_average_length_of_string(strings):
"""Computes average length of words
:param strings: list of words
:return: Average length of word on list
"""
if not strings:
return 0 # depends on [control=['if'], data=[]]
return sum((len(word) for word in strings)) / len(strings) |
def destroy(name):
'''
removes a container [stops a container if it's running and]
raises ContainerNotExists exception if the specified name is not created
'''
if not exists(name):
raise ContainerNotExists("The container (%s) does not exist!" % name)
cmd = ['lxc-destroy', '-f', '-... | def function[destroy, parameter[name]]:
constant[
removes a container [stops a container if it's running and]
raises ContainerNotExists exception if the specified name is not created
]
if <ast.UnaryOp object at 0x7da20c6ab010> begin[:]
<ast.Raise object at 0x7da20c6ab6d0>
var... | keyword[def] identifier[destroy] ( identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[exists] ( identifier[name] ):
keyword[raise] identifier[ContainerNotExists] ( literal[string] % identifier[name] )
identifier[cmd] =[ literal[string] , literal[string] , literal[s... | def destroy(name):
"""
removes a container [stops a container if it's running and]
raises ContainerNotExists exception if the specified name is not created
"""
if not exists(name):
raise ContainerNotExists('The container (%s) does not exist!' % name) # depends on [control=['if'], data=[]]
... |
def fill_off_diagonal(x, radius, value=0):
"""Sets all cells of a matrix to a given ``value``
if they lie outside a constraint region.
In this case, the constraint region is the
Sakoe-Chiba band which runs with a fixed ``radius``
along the main diagonal.
When ``x.shape[0] != x.shape[1]``, the ra... | def function[fill_off_diagonal, parameter[x, radius, value]]:
constant[Sets all cells of a matrix to a given ``value``
if they lie outside a constraint region.
In this case, the constraint region is the
Sakoe-Chiba band which runs with a fixed ``radius``
along the main diagonal.
When ``x.sha... | keyword[def] identifier[fill_off_diagonal] ( identifier[x] , identifier[radius] , identifier[value] = literal[int] ):
literal[string]
identifier[nx] , identifier[ny] = identifier[x] . identifier[shape]
identifier[radius] = identifier[np] . identifier[round] ( identifier[radius] * identifier[np]... | def fill_off_diagonal(x, radius, value=0):
"""Sets all cells of a matrix to a given ``value``
if they lie outside a constraint region.
In this case, the constraint region is the
Sakoe-Chiba band which runs with a fixed ``radius``
along the main diagonal.
When ``x.shape[0] != x.shape[1]``, the ra... |
def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
else:
fact.start_time = dt.datetime.now()
return fact | def function[localized_fact, parameter[self]]:
constant[Make sure fact has the correct start_time.]
variable[fact] assign[=] call[name[Fact], parameter[call[name[self].activity.get_text, parameter[]]]]
if name[fact].start_time begin[:]
name[fact].date assign[=] name[self].date
... | keyword[def] identifier[localized_fact] ( identifier[self] ):
literal[string]
identifier[fact] = identifier[Fact] ( identifier[self] . identifier[activity] . identifier[get_text] ())
keyword[if] identifier[fact] . identifier[start_time] :
identifier[fact] . identifier[date] =... | def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date # depends on [control=['if'], data=[]]
else:
fact.start_time = dt.datetime.now()
return fact |
def word_tokenize(self, text, include_punc=True):
"""The Treebank tokenizer uses regular expressions to tokenize text as
in Penn Treebank.
It assumes that the text has already been segmented into sentences,
e.g. using ``self.sent_tokenize()``.
This tokenizer performs the follow... | def function[word_tokenize, parameter[self, text, include_punc]]:
constant[The Treebank tokenizer uses regular expressions to tokenize text as
in Penn Treebank.
It assumes that the text has already been segmented into sentences,
e.g. using ``self.sent_tokenize()``.
This tokeniz... | keyword[def] identifier[word_tokenize] ( identifier[self] , identifier[text] , identifier[include_punc] = keyword[True] ):
literal[string]
keyword[if] identifier[text] . identifier[strip] ()== literal[string] :
keyword[return] []
identifier[_tokens] = identifier[self... | def word_tokenize(self, text, include_punc=True):
"""The Treebank tokenizer uses regular expressions to tokenize text as
in Penn Treebank.
It assumes that the text has already been segmented into sentences,
e.g. using ``self.sent_tokenize()``.
This tokenizer performs the following ... |
def clean_cache_key(key):
""" Replace spaces with '-' and hash if length is greater than 250.
"""
cache_key = re.sub(r'\s+', '-', key)
cache_key = smart_str(cache_key)
if len(cache_key) > 200:
cache_key = cache_key[:150] + '-' + hashlib.md5(cache_key).hexdigest()
return cache_key | def function[clean_cache_key, parameter[key]]:
constant[ Replace spaces with '-' and hash if length is greater than 250.
]
variable[cache_key] assign[=] call[name[re].sub, parameter[constant[\s+], constant[-], name[key]]]
variable[cache_key] assign[=] call[name[smart_str], parameter[name[cac... | keyword[def] identifier[clean_cache_key] ( identifier[key] ):
literal[string]
identifier[cache_key] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[key] )
identifier[cache_key] = identifier[smart_str] ( identifier[cache_key] )
keyword[if] identifier[len] ( id... | def clean_cache_key(key):
""" Replace spaces with '-' and hash if length is greater than 250.
"""
cache_key = re.sub('\\s+', '-', key)
cache_key = smart_str(cache_key)
if len(cache_key) > 200:
cache_key = cache_key[:150] + '-' + hashlib.md5(cache_key).hexdigest() # depends on [control=['if'... |
def comment_marker(self, value):
"""
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
... | def function[comment_marker, parameter[self, value]]:
constant[
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parameter[... | keyword[def] identifier[comment_marker] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[unicode] , literal[string] . ide... | def comment_marker(self, value):
"""
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format('comment_marker', valu... |
def disable_wx(self):
"""Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_WX):
self._apps[GUI_WX]._in_event_loop = False
self.clear_inputhook() | def function[disable_wx, parameter[self]]:
constant[Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
]
if call[name[self]._apps.has_key, parameter[name[GUI_WX]]] begin[:]
call[name[self]._apps][name[GUI_WX]]._in_event_loop assign[=] ... | keyword[def] identifier[disable_wx] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_apps] . identifier[has_key] ( identifier[GUI_WX] ):
identifier[self] . identifier[_apps] [ identifier[GUI_WX] ]. identifier[_in_event_loop] = keyword[False]
i... | def disable_wx(self):
"""Disable event loop integration with wxPython.
This merely sets PyOS_InputHook to NULL.
"""
if self._apps.has_key(GUI_WX):
self._apps[GUI_WX]._in_event_loop = False # depends on [control=['if'], data=[]]
self.clear_inputhook() |
def all(self, store_id, product_id, get_all=False, **queryparams):
"""
Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
... | def function[all, parameter[self, store_id, product_id, get_all]]:
constant[
Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
... | keyword[def] identifier[all] ( identifier[self] , identifier[store_id] , identifier[product_id] , identifier[get_all] = keyword[False] ,** identifier[queryparams] ):
literal[string]
identifier[self] . identifier[store_id] = identifier[store_id]
identifier[self] . identifier[product_id] = ... | def all(self, store_id, product_id, get_all=False, **queryparams):
"""
Get information about a product’s images.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param product_id: The id for the product of a store.
:type product_id: :py:class:`str`
:pa... |
def get_hotkey_name(names=None):
"""
Returns a string representation of hotkey from the given key names, or
the currently pressed keys if not given. This function:
- normalizes names;
- removes "left" and "right" prefixes;
- replaces the "+" key name with "plus" to avoid ambiguity;
- puts ... | def function[get_hotkey_name, parameter[names]]:
constant[
Returns a string representation of hotkey from the given key names, or
the currently pressed keys if not given. This function:
- normalizes names;
- removes "left" and "right" prefixes;
- replaces the "+" key name with "plus" to av... | keyword[def] identifier[get_hotkey_name] ( identifier[names] = keyword[None] ):
literal[string]
keyword[if] identifier[names] keyword[is] keyword[None] :
identifier[_listener] . identifier[start_if_necessary] ()
keyword[with] identifier[_pressed_events_lock] :
identifier[... | def get_hotkey_name(names=None):
"""
Returns a string representation of hotkey from the given key names, or
the currently pressed keys if not given. This function:
- normalizes names;
- removes "left" and "right" prefixes;
- replaces the "+" key name with "plus" to avoid ambiguity;
- puts ... |
def info(self, msg, indent=0, **kwargs):
"""invoke ``self.info.debug``"""
return self.logger.info(self._indent(msg, indent), **kwargs) | def function[info, parameter[self, msg, indent]]:
constant[invoke ``self.info.debug``]
return[call[name[self].logger.info, parameter[call[name[self]._indent, parameter[name[msg], name[indent]]]]]] | keyword[def] identifier[info] ( identifier[self] , identifier[msg] , identifier[indent] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[logger] . identifier[info] ( identifier[self] . identifier[_indent] ( identifier[msg] , identifier[indent] ... | def info(self, msg, indent=0, **kwargs):
"""invoke ``self.info.debug``"""
return self.logger.info(self._indent(msg, indent), **kwargs) |
def set(zpool, prop, value):
'''
Sets the given property on the specified pool
zpool : string
Name of storage pool
prop : string
Name of property to set
value : string
Value to set for the specified property
.. versionadded:: 2016.3.0
CLI Example:
.. code-bl... | def function[set, parameter[zpool, prop, value]]:
constant[
Sets the given property on the specified pool
zpool : string
Name of storage pool
prop : string
Name of property to set
value : string
Value to set for the specified property
.. versionadded:: 2016.3.0
... | keyword[def] identifier[set] ( identifier[zpool] , identifier[prop] , identifier[value] ):
literal[string]
identifier[ret] = identifier[OrderedDict] ()
identifier[res] = identifier[__salt__] [ literal[string] ](
identifier[__utils__] [ literal[string] ](
identifier[command] = literal[s... | def set(zpool, prop, value):
"""
Sets the given property on the specified pool
zpool : string
Name of storage pool
prop : string
Name of property to set
value : string
Value to set for the specified property
.. versionadded:: 2016.3.0
CLI Example:
.. code-bl... |
def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
ns = logevent.nscanned
nr = logevent.nreturned
if ns is not None and nr is not ... | def function[accept, parameter[self, logevent]]:
constant[
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
]
variable[ns] assign[=] name[logevent].nscanned
variable[nr] ass... | keyword[def] identifier[accept] ( identifier[self] , identifier[logevent] ):
literal[string]
identifier[ns] = identifier[logevent] . identifier[nscanned]
identifier[nr] = identifier[logevent] . identifier[nreturned]
keyword[if] identifier[ns] keyword[is] keyword[not] keywor... | def accept(self, logevent):
"""
Process line.
Overwrite BaseFilter.accept() and return True if the provided
logevent should be accepted (causing output), or False if not.
"""
ns = logevent.nscanned
nr = logevent.nreturned
if ns is not None and nr is not None:
if ... |
def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if ite... | def function[duplicates, parameter[base, items]]:
constant[Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
]
... | keyword[def] identifier[duplicates] ( identifier[base] , identifier[items] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[items] :
keyword[if] identifier[item] . identifier[similarity] ( identifier[base] ) keyword[and] keyword[not] identifier[item] . identifier[equal... | def duplicates(base, items):
"""Get an iterator of items similar but not equal to the base.
@param base: base item to perform comparison against
@param items: list of items to compare to the base
@return: generator of items sorted by similarity to the base
"""
for item in items:
if ite... |
def nvmlDeviceGetPowerManagementMode(handle):
r"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or higher.
*
* For from t... | def function[nvmlDeviceGetPowerManagementMode, parameter[handle]]:
constant[
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \a NVML_INFOROM_POWER version 3.0 or hi... | keyword[def] identifier[nvmlDeviceGetPowerManagementMode] ( identifier[handle] ):
literal[string]
identifier[c_pcapMode] = identifier[_nvmlEnableState_t] ()
identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] )
identifier[ret] = identifier[fn] ( identifier[handle] , identifier[... | def nvmlDeviceGetPowerManagementMode(handle):
"""
/**
* This API has been deprecated.
*
* Retrieves the power management mode associated with this device.
*
* For products from the Fermi family.
* - Requires \\a NVML_INFOROM_POWER version 3.0 or higher.
*
* For from t... |
def gauss_jordan(A, x, b):
"""Linear equation system Ax=b by Gauss-Jordan
:param A: n by m matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique,
2 otherwise
:co... | def function[gauss_jordan, parameter[A, x, b]]:
constant[Linear equation system Ax=b by Gauss-Jordan
:param A: n by m matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique... | keyword[def] identifier[gauss_jordan] ( identifier[A] , identifier[x] , identifier[b] ):
literal[string]
identifier[n] = identifier[len] ( identifier[x] )
identifier[m] = identifier[len] ( identifier[b] )
keyword[assert] identifier[len] ( identifier[A] )== identifier[m] keyword[and] identifier... | def gauss_jordan(A, x, b):
"""Linear equation system Ax=b by Gauss-Jordan
:param A: n by m matrix
:param x: table of size n
:param b: table of size m
:modifies: x will contain solution if any
:returns int:
0 if no solution,
1 if solution unique,
2 otherwise
:co... |
def _get_ln_a_n_max(self, C, n_sites, idx, rup):
"""
Defines the rock site amplification defined in equations 10a and 10b
"""
ln_a_n_max = C["lnSC1AM"] * np.ones(n_sites)
for i in [2, 3, 4]:
if np.any(idx[i]):
ln_a_n_max[idx[i]] += C["S{:g}".format(i)]... | def function[_get_ln_a_n_max, parameter[self, C, n_sites, idx, rup]]:
constant[
Defines the rock site amplification defined in equations 10a and 10b
]
variable[ln_a_n_max] assign[=] binary_operation[call[name[C]][constant[lnSC1AM]] * call[name[np].ones, parameter[name[n_sites]]]]
... | keyword[def] identifier[_get_ln_a_n_max] ( identifier[self] , identifier[C] , identifier[n_sites] , identifier[idx] , identifier[rup] ):
literal[string]
identifier[ln_a_n_max] = identifier[C] [ literal[string] ]* identifier[np] . identifier[ones] ( identifier[n_sites] )
keyword[for] ident... | def _get_ln_a_n_max(self, C, n_sites, idx, rup):
"""
Defines the rock site amplification defined in equations 10a and 10b
"""
ln_a_n_max = C['lnSC1AM'] * np.ones(n_sites)
for i in [2, 3, 4]:
if np.any(idx[i]):
ln_a_n_max[idx[i]] += C['S{:g}'.format(i)] # depends on [cont... |
def _apply_to_values(self, entity, function):
"""Apply a function to the property value/values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each of the values in the list. The... | def function[_apply_to_values, parameter[self, entity, function]]:
constant[Apply a function to the property value/values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each ... | keyword[def] identifier[_apply_to_values] ( identifier[self] , identifier[entity] , identifier[function] ):
literal[string]
identifier[value] = identifier[self] . identifier[_retrieve_value] ( identifier[entity] , identifier[self] . identifier[_default] )
keyword[if] identifier[self] . identifier[_re... | def _apply_to_values(self, entity, function):
"""Apply a function to the property value/values of a given entity.
This retrieves the property value, applies the function, and then
stores the value back. For a repeated property, the function is
applied separately to each of the values in the list. The... |
async def SetExternalControllerInfo(self, controllers):
'''
controllers : typing.Sequence[~SetExternalControllerInfoParams]
Returns -> typing.Sequence[~ErrorResult]
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='ExternalControllerUpdater',
... | <ast.AsyncFunctionDef object at 0x7da1b0ebc4c0> | keyword[async] keyword[def] identifier[SetExternalControllerInfo] ( identifier[self] , identifier[controllers] ):
literal[string]
identifier[_params] = identifier[dict] ()
identifier[msg] = identifier[dict] ( identifier[type] = literal[string] ,
identifier[request] = lit... | async def SetExternalControllerInfo(self, controllers):
"""
controllers : typing.Sequence[~SetExternalControllerInfoParams]
Returns -> typing.Sequence[~ErrorResult]
"""
# map input types to rpc msg
_params = dict()
msg = dict(type='ExternalControllerUpdater', request='SetExternal... |
def calcValueAtBirth(cLvlHist,BirthBool,PlvlHist,MrkvHist,DiscFac,CRRA):
'''
Calculate expected value of being born in each Markov state using the realizations
of consumption for a history of many consumers. The histories should already be
trimmed of the "burn in" periods.
Parameters
---------... | def function[calcValueAtBirth, parameter[cLvlHist, BirthBool, PlvlHist, MrkvHist, DiscFac, CRRA]]:
constant[
Calculate expected value of being born in each Markov state using the realizations
of consumption for a history of many consumers. The histories should already be
trimmed of the "burn in" pe... | keyword[def] identifier[calcValueAtBirth] ( identifier[cLvlHist] , identifier[BirthBool] , identifier[PlvlHist] , identifier[MrkvHist] , identifier[DiscFac] , identifier[CRRA] ):
literal[string]
identifier[J] = identifier[np] . identifier[max] ( identifier[MrkvHist] )+ literal[int]
identifier[T] = id... | def calcValueAtBirth(cLvlHist, BirthBool, PlvlHist, MrkvHist, DiscFac, CRRA):
"""
Calculate expected value of being born in each Markov state using the realizations
of consumption for a history of many consumers. The histories should already be
trimmed of the "burn in" periods.
Parameters
----... |
def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn,
customer_gateway_name=None, tags=None,
region=None, key=None, keyid=None, profile=None):
'''
Given a valid VPN connection type, a static IP address and a customer
gateway’s Border Ga... | def function[create_customer_gateway, parameter[vpn_connection_type, ip_address, bgp_asn, customer_gateway_name, tags, region, key, keyid, profile]]:
constant[
Given a valid VPN connection type, a static IP address and a customer
gateway’s Border Gateway Protocol (BGP) Autonomous System Number,
crea... | keyword[def] identifier[create_customer_gateway] ( identifier[vpn_connection_type] , identifier[ip_address] , identifier[bgp_asn] ,
identifier[customer_gateway_name] = keyword[None] , identifier[tags] = keyword[None] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keywor... | def create_customer_gateway(vpn_connection_type, ip_address, bgp_asn, customer_gateway_name=None, tags=None, region=None, key=None, keyid=None, profile=None):
"""
Given a valid VPN connection type, a static IP address and a customer
gateway’s Border Gateway Protocol (BGP) Autonomous System Number,
creat... |
def _pre_heat_deploy(self):
"""Setup before the Heat stack create or update has been done."""
clients = self.app.client_manager
compute_client = clients.compute
self.log.debug("Checking hypervisor stats")
if utils.check_hypervisor_stats(compute_client) is None:
raise... | def function[_pre_heat_deploy, parameter[self]]:
constant[Setup before the Heat stack create or update has been done.]
variable[clients] assign[=] name[self].app.client_manager
variable[compute_client] assign[=] name[clients].compute
call[name[self].log.debug, parameter[constant[Checking... | keyword[def] identifier[_pre_heat_deploy] ( identifier[self] ):
literal[string]
identifier[clients] = identifier[self] . identifier[app] . identifier[client_manager]
identifier[compute_client] = identifier[clients] . identifier[compute]
identifier[self] . identifier[log] . iden... | def _pre_heat_deploy(self):
"""Setup before the Heat stack create or update has been done."""
clients = self.app.client_manager
compute_client = clients.compute
self.log.debug('Checking hypervisor stats')
if utils.check_hypervisor_stats(compute_client) is None:
raise exceptions.DeploymentErr... |
def relabel_nodes(G, mapping, copy=True):
"""Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
copy : bool (optional, def... | def function[relabel_nodes, parameter[G, mapping, copy]]:
constant[Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
... | keyword[def] identifier[relabel_nodes] ( identifier[G] , identifier[mapping] , identifier[copy] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[mapping] , literal[string] ):
identifier[m] = identifier[dict] (( identifier[n] , identifier[mapp... | def relabel_nodes(G, mapping, copy=True):
"""Relabel the nodes of the graph G.
Parameters
----------
G : graph
A NetworkX graph
mapping : dictionary
A dictionary with the old labels as keys and new labels as values.
A partial mapping is allowed.
copy : bool (optional, def... |
def preprocess_na(sent, label_type):
"""Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
"""
if label_type == "phonemes_and_tones":
phonemes = True
tones = True
tgm = True
elif label_type == "phonemes_and_tones_no_tgm":
... | def function[preprocess_na, parameter[sent, label_type]]:
constant[Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
]
if compare[name[label_type] equal[==] constant[phonemes_and_tones]] begin[:]
variable[phonemes] assign[=] co... | keyword[def] identifier[preprocess_na] ( identifier[sent] , identifier[label_type] ):
literal[string]
keyword[if] identifier[label_type] == literal[string] :
identifier[phonemes] = keyword[True]
identifier[tones] = keyword[True]
identifier[tgm] = keyword[True]
keyword[el... | def preprocess_na(sent, label_type):
"""Preprocess Na sentences
Args:
sent: A sentence
label_type: The type of label provided
"""
if label_type == 'phonemes_and_tones':
phonemes = True
tones = True
tgm = True # depends on [control=['if'], data=[]]
elif label... |
def _check_jwt_claims(jwt_claims):
"""Checks whether the JWT claims should be accepted.
Specifically, this method checks the "exp" claim and the "nbf" claim (if
present), and raises UnauthenticatedException if 1) the current time is
before the time identified by the "nbf" claim, or 2) the current time ... | def function[_check_jwt_claims, parameter[jwt_claims]]:
constant[Checks whether the JWT claims should be accepted.
Specifically, this method checks the "exp" claim and the "nbf" claim (if
present), and raises UnauthenticatedException if 1) the current time is
before the time identified by the "nbf"... | keyword[def] identifier[_check_jwt_claims] ( identifier[jwt_claims] ):
literal[string]
identifier[current_time] = identifier[time] . identifier[time] ()
identifier[expiration] = identifier[jwt_claims] [ literal[string] ]
keyword[if] keyword[not] identifier[isinstance] ( identifier[expiration] ... | def _check_jwt_claims(jwt_claims):
"""Checks whether the JWT claims should be accepted.
Specifically, this method checks the "exp" claim and the "nbf" claim (if
present), and raises UnauthenticatedException if 1) the current time is
before the time identified by the "nbf" claim, or 2) the current time ... |
async def _analog_message(self, data):
"""
This is a private message handler method.
It is a message handler for analog messages.
:param data: message data
:returns: None - but saves the data in the pins structure
"""
pin = data[0]
value = (data[PrivateC... | <ast.AsyncFunctionDef object at 0x7da20c76d0f0> | keyword[async] keyword[def] identifier[_analog_message] ( identifier[self] , identifier[data] ):
literal[string]
identifier[pin] = identifier[data] [ literal[int] ]
identifier[value] =( identifier[data] [ identifier[PrivateConstants] . identifier[MSB] ]<< literal[int] )+ identifier[data] ... | async def _analog_message(self, data):
"""
This is a private message handler method.
It is a message handler for analog messages.
:param data: message data
:returns: None - but saves the data in the pins structure
"""
pin = data[0]
value = (data[PrivateConstants.MSB... |
def contains(self, key, counter_id):
"""
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError.
"""
with self._lock:
return counter_id in self._metadata[key] | def function[contains, parameter[self, key, counter_id]]:
constant[
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError.
]
with name[self]._lock begin[:]
return[compare[name[counter_id] in call[name[self]._met... | keyword[def] identifier[contains] ( identifier[self] , identifier[key] , identifier[counter_id] ):
literal[string]
keyword[with] identifier[self] . identifier[_lock] :
keyword[return] identifier[counter_id] keyword[in] identifier[self] . identifier[_metadata] [ identifier[key] ] | def contains(self, key, counter_id):
"""
Return whether a counter_id is present for a given instance key.
If the key is not in the cache, raises a KeyError.
"""
with self._lock:
return counter_id in self._metadata[key] # depends on [control=['with'], data=[]] |
def encrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"""Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... | def function[encrypt_python_item, parameter[item, crypto_config]]:
constant[Encrypt a dictionary for DynamoDB.
>>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item
>>> plaintext_item = {
... 'some': 'data',
... 'more': 5
... }
>>> encrypted_item = encrypt_p... | keyword[def] identifier[encrypt_python_item] ( identifier[item] , identifier[crypto_config] ):
literal[string]
identifier[ddb_item] = identifier[dict_to_ddb] ( identifier[item] )
identifier[encrypted_ddb_item] = identifier[encrypt_dynamodb_item] ( identifier[ddb_item] , identifier[crypto_config] )
... | def encrypt_python_item(item, crypto_config):
# type: (dynamodb_types.ITEM, CryptoConfig) -> dynamodb_types.ITEM
"Encrypt a dictionary for DynamoDB.\n\n >>> from dynamodb_encryption_sdk.encrypted.item import encrypt_python_item\n >>> plaintext_item = {\n ... 'some': 'data',\n ... 'more': 5\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.