code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def cone(self, plunge, bearing, angle, segments=100, bidirectional=True,
**kwargs):
"""
Plot a polygon of a small circle (a.k.a. a cone) with an angular radius
of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword
arguments are passed on to the ``PathCollec... | def function[cone, parameter[self, plunge, bearing, angle, segments, bidirectional]]:
constant[
Plot a polygon of a small circle (a.k.a. a cone) with an angular radius
of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword
arguments are passed on to the ``PathCollection`... | keyword[def] identifier[cone] ( identifier[self] , identifier[plunge] , identifier[bearing] , identifier[angle] , identifier[segments] = literal[int] , identifier[bidirectional] = keyword[True] ,
** identifier[kwargs] ):
literal[string]
identifier[plunge] , identifier[bearing] , identifier[angle] =... | def cone(self, plunge, bearing, angle, segments=100, bidirectional=True, **kwargs):
"""
Plot a polygon of a small circle (a.k.a. a cone) with an angular radius
of *angle* centered at a p/b of *plunge*, *bearing*. Additional keyword
arguments are passed on to the ``PathCollection``. (e.g. to... |
def container_unfreeze(name, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Unfreeze a container
name :
Name of the container to unfreeze
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr... | def function[container_unfreeze, parameter[name, remote_addr, cert, key, verify_cert]]:
constant[
Unfreeze a container
name :
Name of the container to unfreeze
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a T... | keyword[def] identifier[container_unfreeze] ( identifier[name] , identifier[remote_addr] = keyword[None] ,
identifier[cert] = keyword[None] , identifier[key] = keyword[None] , identifier[verify_cert] = keyword[True] ):
literal[string]
identifier[container] = identifier[container_get] (
identifier[nam... | def container_unfreeze(name, remote_addr=None, cert=None, key=None, verify_cert=True):
"""
Unfreeze a container
name :
Name of the container to unfreeze
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!... |
def _GetRoutingMap(self, router):
"""Returns a routing map for a given router instance."""
try:
routing_map = self._routing_maps_cache.Get(router.__class__)
except KeyError:
routing_map = self._BuildHttpRoutingMap(router.__class__)
self._routing_maps_cache.Put(router.__class__, routing_ma... | def function[_GetRoutingMap, parameter[self, router]]:
constant[Returns a routing map for a given router instance.]
<ast.Try object at 0x7da1b1c3f160>
return[name[routing_map]] | keyword[def] identifier[_GetRoutingMap] ( identifier[self] , identifier[router] ):
literal[string]
keyword[try] :
identifier[routing_map] = identifier[self] . identifier[_routing_maps_cache] . identifier[Get] ( identifier[router] . identifier[__class__] )
keyword[except] identifier[KeyError] ... | def _GetRoutingMap(self, router):
"""Returns a routing map for a given router instance."""
try:
routing_map = self._routing_maps_cache.Get(router.__class__) # depends on [control=['try'], data=[]]
except KeyError:
routing_map = self._BuildHttpRoutingMap(router.__class__)
self._routi... |
async def deregister(self, service):
"""Deregisters a local service
Parameters:
service (ObjectID): Service ID
Returns:
bool: ``True`` on success
The deregister endpoint is used to remove a service from the local
agent. The agent will take care of deregi... | <ast.AsyncFunctionDef object at 0x7da2054a71c0> | keyword[async] keyword[def] identifier[deregister] ( identifier[self] , identifier[service] ):
literal[string]
identifier[service_id] = identifier[extract_attr] ( identifier[service] , identifier[keys] =[ literal[string] , literal[string] ])
identifier[response] = keyword[await] identifi... | async def deregister(self, service):
"""Deregisters a local service
Parameters:
service (ObjectID): Service ID
Returns:
bool: ``True`` on success
The deregister endpoint is used to remove a service from the local
agent. The agent will take care of deregister... |
def root_open(filename, mode=''):
"""
Open a ROOT file via ROOT's static ROOT.TFile.Open [1] function and return
an asrootpy'd File.
Parameters
----------
filename : string
The absolute or relative path to the ROOT file.
mode : string, optional (default='')
Mode indicating... | def function[root_open, parameter[filename, mode]]:
constant[
Open a ROOT file via ROOT's static ROOT.TFile.Open [1] function and return
an asrootpy'd File.
Parameters
----------
filename : string
The absolute or relative path to the ROOT file.
mode : string, optional (default... | keyword[def] identifier[root_open] ( identifier[filename] , identifier[mode] = literal[string] ):
literal[string]
identifier[mode_map] ={ literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
literal[string] : literal[string] ,
liter... | def root_open(filename, mode=''):
"""
Open a ROOT file via ROOT's static ROOT.TFile.Open [1] function and return
an asrootpy'd File.
Parameters
----------
filename : string
The absolute or relative path to the ROOT file.
mode : string, optional (default='')
Mode indicating... |
def from_yang(self, text: str) -> ScalarValue:
"""Parse value specified in a YANG module.
Args:
text: String representation of the value.
Raises:
InvalidArgument: If the receiver type cannot parse the text.
"""
res = self.parse_value(text)
if res... | def function[from_yang, parameter[self, text]]:
constant[Parse value specified in a YANG module.
Args:
text: String representation of the value.
Raises:
InvalidArgument: If the receiver type cannot parse the text.
]
variable[res] assign[=] call[name[self... | keyword[def] identifier[from_yang] ( identifier[self] , identifier[text] : identifier[str] )-> identifier[ScalarValue] :
literal[string]
identifier[res] = identifier[self] . identifier[parse_value] ( identifier[text] )
keyword[if] identifier[res] keyword[is] keyword[None] :
... | def from_yang(self, text: str) -> ScalarValue:
"""Parse value specified in a YANG module.
Args:
text: String representation of the value.
Raises:
InvalidArgument: If the receiver type cannot parse the text.
"""
res = self.parse_value(text)
if res is None:
... |
def construct_txt_file(self):
"""Construct the header of the txt file"""
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ]
textlines.append("=" * len(textlines[0]))
textlines.append('Created on %s using PLIP v%s\n' % (time.strftim... | def function[construct_txt_file, parameter[self]]:
constant[Construct the header of the txt file]
variable[textlines] assign[=] list[[<ast.BinOp object at 0x7da18f00d150>]]
call[name[textlines].append, parameter[binary_operation[constant[=] * call[name[len], parameter[call[name[textlines]][const... | keyword[def] identifier[construct_txt_file] ( identifier[self] ):
literal[string]
identifier[textlines] =[ literal[string] % identifier[self] . identifier[mol] . identifier[pymol_name] . identifier[upper] (),]
identifier[textlines] . identifier[append] ( literal[string] * identifier[len] (... | def construct_txt_file(self):
"""Construct the header of the txt file"""
textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper()]
textlines.append('=' * len(textlines[0]))
textlines.append('Created on %s using PLIP v%s\n' % (time.strftime('%Y/%m/%d'), __v... |
def _reset_seaborn(gallery_conf, fname):
"""Reset seaborn."""
# Horrible code to 'unload' seaborn, so that it resets
# its default when is load
# Python does not support unloading of modules
# https://bugs.python.org/issue9072
for module in list(sys.modules.keys()):
if 'seaborn' in modul... | def function[_reset_seaborn, parameter[gallery_conf, fname]]:
constant[Reset seaborn.]
for taget[name[module]] in starred[call[name[list], parameter[call[name[sys].modules.keys, parameter[]]]]] begin[:]
if compare[constant[seaborn] in name[module]] begin[:]
<ast.Delete object... | keyword[def] identifier[_reset_seaborn] ( identifier[gallery_conf] , identifier[fname] ):
literal[string]
keyword[for] identifier[module] keyword[in] identifier[list] ( identifier[sys] . identifier[modules] . identifier[keys] ()):
keyword[if] literal[string] keyword[in] i... | def _reset_seaborn(gallery_conf, fname):
"""Reset seaborn."""
# Horrible code to 'unload' seaborn, so that it resets
# its default when is load
# Python does not support unloading of modules
# https://bugs.python.org/issue9072
for module in list(sys.modules.keys()):
if 'seaborn' in modul... |
def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
def locate():
"""Locate the image file/index if decode fails."""
if self.seq is not None:
idx = self.seq[(self.cur % self.num_image) - 1]
... | def function[imdecode, parameter[self, s]]:
constant[Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details.]
def function[locate, parameter[]]:
constant[Locate the image file/index if decode fails.]
if compare[name[self].seq is_not co... | keyword[def] identifier[imdecode] ( identifier[self] , identifier[s] ):
literal[string]
keyword[def] identifier[locate] ():
literal[string]
keyword[if] identifier[self] . identifier[seq] keyword[is] keyword[not] keyword[None] :
identifier[idx] = iden... | def imdecode(self, s):
"""Decodes a string or byte string to an NDArray.
See mx.img.imdecode for more details."""
def locate():
"""Locate the image file/index if decode fails."""
if self.seq is not None:
idx = self.seq[self.cur % self.num_image - 1] # depends on [control=['... |
def get_month(self):
"""
Return the month from the database in the format expected by the URL.
"""
year = super(BuildableDayArchiveView, self).get_year()
month = super(BuildableDayArchiveView, self).get_month()
fmt = self.get_month_format()
dt = date(int(year), in... | def function[get_month, parameter[self]]:
constant[
Return the month from the database in the format expected by the URL.
]
variable[year] assign[=] call[call[name[super], parameter[name[BuildableDayArchiveView], name[self]]].get_year, parameter[]]
variable[month] assign[=] call[... | keyword[def] identifier[get_month] ( identifier[self] ):
literal[string]
identifier[year] = identifier[super] ( identifier[BuildableDayArchiveView] , identifier[self] ). identifier[get_year] ()
identifier[month] = identifier[super] ( identifier[BuildableDayArchiveView] , identifier[self] )... | def get_month(self):
"""
Return the month from the database in the format expected by the URL.
"""
year = super(BuildableDayArchiveView, self).get_year()
month = super(BuildableDayArchiveView, self).get_month()
fmt = self.get_month_format()
dt = date(int(year), int(month), 1)
ret... |
def construct_pipeline_block(env='',
generated=None,
previous_env='',
region='us-east-1',
settings=None,
pipeline_data=None,
region_subnets=None,
... | def function[construct_pipeline_block, parameter[env, generated, previous_env, region, settings, pipeline_data, region_subnets]]:
constant[Create the Pipeline JSON from template.
This handles the common repeatable patterns in a pipeline, such as
judgement, infrastructure, tagger and qe.
Note:
... | keyword[def] identifier[construct_pipeline_block] ( identifier[env] = literal[string] ,
identifier[generated] = keyword[None] ,
identifier[previous_env] = literal[string] ,
identifier[region] = literal[string] ,
identifier[settings] = keyword[None] ,
identifier[pipeline_data] = keyword[None] ,
identifier[region... | def construct_pipeline_block(env='', generated=None, previous_env='', region='us-east-1', settings=None, pipeline_data=None, region_subnets=None, **kwargs):
"""Create the Pipeline JSON from template.
This handles the common repeatable patterns in a pipeline, such as
judgement, infrastructure, tagger and qe... |
def delete(self, alert_condition_nrql_id):
"""
This API endpoint allows you to delete an alert condition nrql
:type alert_condition_nrql_id: integer
:param alert_condition_nrql_id: Alert Condition ID
:rtype: dict
:return: The JSON response of the API
::
... | def function[delete, parameter[self, alert_condition_nrql_id]]:
constant[
This API endpoint allows you to delete an alert condition nrql
:type alert_condition_nrql_id: integer
:param alert_condition_nrql_id: Alert Condition ID
:rtype: dict
:return: The JSON response of ... | keyword[def] identifier[delete] ( identifier[self] , identifier[alert_condition_nrql_id] ):
literal[string]
keyword[return] identifier[self] . identifier[_delete] (
identifier[url] = literal[string] . identifier[format] ( identifier[self] . identifier[URL] , identifier[alert_condition_nr... | def delete(self, alert_condition_nrql_id):
"""
This API endpoint allows you to delete an alert condition nrql
:type alert_condition_nrql_id: integer
:param alert_condition_nrql_id: Alert Condition ID
:rtype: dict
:return: The JSON response of the API
::
{
... |
def is_descendant_of_catalog(self, id_, catalog_id):
"""Tests if an ``Id`` is a descendant of a catalog.
arg: id (osid.id.Id): an ``Id``
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``catalo... | def function[is_descendant_of_catalog, parameter[self, id_, catalog_id]]:
constant[Tests if an ``Id`` is a descendant of a catalog.
arg: id (osid.id.Id): an ``Id``
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
return: (boolean) - ``true`` if the ``id`` is a descendant of
... | keyword[def] identifier[is_descendant_of_catalog] ( identifier[self] , identifier[id_] , identifier[catalog_id] ):
literal[string]
keyword[if] identifier[self] . identifier[_catalog_session] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self... | def is_descendant_of_catalog(self, id_, catalog_id):
"""Tests if an ``Id`` is a descendant of a catalog.
arg: id (osid.id.Id): an ``Id``
arg: catalog_id (osid.id.Id): the ``Id`` of a catalog
return: (boolean) - ``true`` if the ``id`` is a descendant of
the ``catalog_id... |
def download(self, temp_ver, store_metadata=True):
"""
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved on... | def function[download, parameter[self, temp_ver, store_metadata]]:
constant[
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata... | keyword[def] identifier[download] ( identifier[self] , identifier[temp_ver] , identifier[store_metadata] = keyword[True] ):
literal[string]
identifier[dest] = identifier[self] . identifier[_prefixed] ( identifier[temp_ver] . identifier[name] )
identifier[temp_dest] = literal[string] % iden... | def download(self, temp_ver, store_metadata=True):
"""
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved one
... |
def simxCreateDummy(clientID, size, color, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if color != None:
c_color = (ct.c_ubyte*12)(*color)
else:
c_color = None
return c_CreateDummy(clientID... | def function[simxCreateDummy, parameter[clientID, size, color, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[handle] assign[=] call[name[ct].c_int, parameter[]]
if compare[name[color] not_equal[!=] constant[Non... | keyword[def] identifier[simxCreateDummy] ( identifier[clientID] , identifier[size] , identifier[color] , identifier[operationMode] ):
literal[string]
identifier[handle] = identifier[ct] . identifier[c_int] ()
keyword[if] identifier[color] != keyword[None] :
identifier[c_color] =( identifier... | def simxCreateDummy(clientID, size, color, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
handle = ct.c_int()
if color != None:
c_color = (ct.c_ubyte * 12)(*color) # depends on [control=['if'], data=['color']]
else:
... |
def _mod_run_check(cmd_kwargs, onlyif, unless):
'''
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
'''
if onlyif:
if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
retu... | def function[_mod_run_check, parameter[cmd_kwargs, onlyif, unless]]:
constant[
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
]
if name[onlyif] begin[:]
if compare[call[... | keyword[def] identifier[_mod_run_check] ( identifier[cmd_kwargs] , identifier[onlyif] , identifier[unless] ):
literal[string]
keyword[if] identifier[onlyif] :
keyword[if] identifier[__salt__] [ literal[string] ]( identifier[onlyif] ,** identifier[cmd_kwargs] )!= literal[int] :
keywo... | def _mod_run_check(cmd_kwargs, onlyif, unless):
"""
Execute the onlyif and unless logic.
Return a result dict if:
* onlyif failed (onlyif != 0)
* unless succeeded (unless == 0)
else return True
"""
if onlyif:
if __salt__['cmd.retcode'](onlyif, **cmd_kwargs) != 0:
retu... |
def close(self):
""" Prompt the objects to output pdf code, and save to file. """
self.document._set_page_numbers()
# Places header, pages, page content first.
self._put_header()
self._put_pages()
self._put_resources()
# Information object
self._pu... | def function[close, parameter[self]]:
constant[ Prompt the objects to output pdf code, and save to file. ]
call[name[self].document._set_page_numbers, parameter[]]
call[name[self]._put_header, parameter[]]
call[name[self]._put_pages, parameter[]]
call[name[self]._put_resources, p... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[document] . identifier[_set_page_numbers] ()
identifier[self] . identifier[_put_header] ()
identifier[self] . identifier[_put_pages] ()
identifier[self] . ide... | def close(self):
""" Prompt the objects to output pdf code, and save to file. """
self.document._set_page_numbers() # Places header, pages, page content first.
self._put_header()
self._put_pages()
self._put_resources() # Information object
self._put_information() # Catalog object
self._pu... |
def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of... | def function[build_vocab, parameter[self]]:
constant[Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents ... | keyword[def] identifier[build_vocab] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[counter] = identifier[Counter] ()
identifier[sources] =[]
keyword[for] identifier[arg] keyword[in] identifier[args] :
keyword[if] ident... | def build_vocab(self, *args, **kwargs):
"""Construct the Vocab object for this field from one or more datasets.
Arguments:
Positional arguments: Dataset objects or other iterable data
sources from which to construct the Vocab object that
represents the set of pos... |
def get_one(self, schema, query=None, **kwargs):
"""
get one row from the db matching filters set in query
schema -- Schema()
query -- Query()
return -- dict -- the matching row
"""
ret = self._get_query(self._get_one, schema, query, **kwargs)
if not ret... | def function[get_one, parameter[self, schema, query]]:
constant[
get one row from the db matching filters set in query
schema -- Schema()
query -- Query()
return -- dict -- the matching row
]
variable[ret] assign[=] call[name[self]._get_query, parameter[name[sel... | keyword[def] identifier[get_one] ( identifier[self] , identifier[schema] , identifier[query] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[ret] = identifier[self] . identifier[_get_query] ( identifier[self] . identifier[_get_one] , identifier[schema] , identifier[query] ,** i... | def get_one(self, schema, query=None, **kwargs):
"""
get one row from the db matching filters set in query
schema -- Schema()
query -- Query()
return -- dict -- the matching row
"""
ret = self._get_query(self._get_one, schema, query, **kwargs)
if not ret:
re... |
def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
key, value = line.split('=', 1)
try:
result[key] = json.loa... | def function[read_config, parameter[config_path]]:
constant[read config_path and return options as dictionary]
variable[result] assign[=] dictionary[[], []]
with call[name[open], parameter[name[config_path], constant[r]]] begin[:]
for taget[name[line]] in starred[call[name[fd].re... | keyword[def] identifier[read_config] ( identifier[config_path] ):
literal[string]
identifier[result] ={}
keyword[with] identifier[open] ( identifier[config_path] , literal[string] ) keyword[as] identifier[fd] :
keyword[for] identifier[line] keyword[in] identifier[fd] . identifier[readlin... | def read_config(config_path):
"""read config_path and return options as dictionary"""
result = {}
with open(config_path, 'r') as fd:
for line in fd.readlines():
if '=' in line:
(key, value) = line.split('=', 1)
try:
result[key] = json.l... |
def DEFINE_multi( # pylint: disable=g-bad-name,redefined-builtin
parser, serializer, name, default, help, flag_values=FLAGS,
module_name=None, **args):
"""Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who... | def function[DEFINE_multi, parameter[parser, serializer, name, default, help, flag_values, module_name]]:
constant[Registers a generic MultiFlag that parses its args with a given parser.
Auxiliary function. Normal users should NOT use it directly.
Developers who need to create their own 'Parser' classes ... | keyword[def] identifier[DEFINE_multi] (
identifier[parser] , identifier[serializer] , identifier[name] , identifier[default] , identifier[help] , identifier[flag_values] = identifier[FLAGS] ,
identifier[module_name] = keyword[None] ,** identifier[args] ):
literal[string]
identifier[DEFINE_flag] ( identifier[... | def DEFINE_multi(parser, serializer, name, default, help, flag_values=FLAGS, module_name=None, **args): # pylint: disable=g-bad-name,redefined-builtin
"Registers a generic MultiFlag that parses its args with a given parser.\n\n Auxiliary function. Normal users should NOT use it directly.\n\n Developers who need... |
def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_rang... | def function[square_off, parameter[series, time_delta, transition_seconds]]:
constant[Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(rang... | keyword[def] identifier[square_off] ( identifier[series] , identifier[time_delta] = keyword[None] , identifier[transition_seconds] = literal[int] ):
literal[string]
keyword[if] identifier[time_delta] :
keyword[if] identifier[isinstance] ( identifier[time_delta] ,( identifier[int] , identifi... | def square_off(series, time_delta=None, transition_seconds=1):
"""Insert samples in regularly sampled data to produce stairsteps from ramps when plotted.
New samples are 1 second (1e9 ns) before each existing samples, to facilitate plotting and sorting
>>> square_off(pd.Series(range(3), index=pd.date_rang... |
def run(self, *args):
"""Merge two identities.
When <from_uuid> or <to_uuid> are empty the command does not have
any effect. The same happens when both <from_uuid> and <to_uuid>
are the same unique identity.
"""
params = self.parser.parse_args(args)
from_uuid = ... | def function[run, parameter[self]]:
constant[Merge two identities.
When <from_uuid> or <to_uuid> are empty the command does not have
any effect. The same happens when both <from_uuid> and <to_uuid>
are the same unique identity.
]
variable[params] assign[=] call[name[self... | keyword[def] identifier[run] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[params] = identifier[self] . identifier[parser] . identifier[parse_args] ( identifier[args] )
identifier[from_uuid] = identifier[params] . identifier[from_uuid]
identifier[to_uuid] ... | def run(self, *args):
"""Merge two identities.
When <from_uuid> or <to_uuid> are empty the command does not have
any effect. The same happens when both <from_uuid> and <to_uuid>
are the same unique identity.
"""
params = self.parser.parse_args(args)
from_uuid = params.from_u... |
def resize(widthWindow, heightWindow):
"""Setup 3D projection for window"""
glViewport(0, 0, widthWindow, heightWindow)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0*widthWindow/heightWindow, 0.001, 10000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() | def function[resize, parameter[widthWindow, heightWindow]]:
constant[Setup 3D projection for window]
call[name[glViewport], parameter[constant[0], constant[0], name[widthWindow], name[heightWindow]]]
call[name[glMatrixMode], parameter[name[GL_PROJECTION]]]
call[name[glLoadIdentity], para... | keyword[def] identifier[resize] ( identifier[widthWindow] , identifier[heightWindow] ):
literal[string]
identifier[glViewport] ( literal[int] , literal[int] , identifier[widthWindow] , identifier[heightWindow] )
identifier[glMatrixMode] ( identifier[GL_PROJECTION] )
identifier[glLoadIdentity] ()
identifier... | def resize(widthWindow, heightWindow):
"""Setup 3D projection for window"""
glViewport(0, 0, widthWindow, heightWindow)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(70, 1.0 * widthWindow / heightWindow, 0.001, 10000.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() |
def __tokenize_segments(self):
"""
tokenizes every RS3 segment (i.e. an RST nucleus or satellite).
for each token, a node is added to the graph, as well as an edge from
the segment node to the token node. the token node IDs are also added
to ``self.tokens``.
"""
f... | def function[__tokenize_segments, parameter[self]]:
constant[
tokenizes every RS3 segment (i.e. an RST nucleus or satellite).
for each token, a node is added to the graph, as well as an edge from
the segment node to the token node. the token node IDs are also added
to ``self.toke... | keyword[def] identifier[__tokenize_segments] ( identifier[self] ):
literal[string]
keyword[for] identifier[seg_node_id] keyword[in] identifier[self] . identifier[segments] :
identifier[segment_toks] = identifier[self] . identifier[node] [ identifier[seg_node_id] ][ identifier[self] ... | def __tokenize_segments(self):
"""
tokenizes every RS3 segment (i.e. an RST nucleus or satellite).
for each token, a node is added to the graph, as well as an edge from
the segment node to the token node. the token node IDs are also added
to ``self.tokens``.
"""
for seg_n... |
def _add_grid_attributes(self, ds):
"""Add model grid attributes to a dataset"""
for name_int, names_ext in self._grid_attrs.items():
ds_coord_name = set(names_ext).intersection(set(ds.coords) |
set(ds.data_vars))
model_attr... | def function[_add_grid_attributes, parameter[self, ds]]:
constant[Add model grid attributes to a dataset]
for taget[tuple[[<ast.Name object at 0x7da1b04f5240>, <ast.Name object at 0x7da1b04f5b10>]]] in starred[call[name[self]._grid_attrs.items, parameter[]]] begin[:]
variable[ds_coord_na... | keyword[def] identifier[_add_grid_attributes] ( identifier[self] , identifier[ds] ):
literal[string]
keyword[for] identifier[name_int] , identifier[names_ext] keyword[in] identifier[self] . identifier[_grid_attrs] . identifier[items] ():
identifier[ds_coord_name] = identifier[set] (... | def _add_grid_attributes(self, ds):
"""Add model grid attributes to a dataset"""
for (name_int, names_ext) in self._grid_attrs.items():
ds_coord_name = set(names_ext).intersection(set(ds.coords) | set(ds.data_vars))
model_attr = getattr(self.model, name_int, None)
if ds_coord_name and mo... |
def get_cluster_info(host, port, ignore_cluster_errors=False):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'v... | def function[get_cluster_info, parameter[host, port, ignore_cluster_errors]]:
constant[
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
]
variable[client] assign[=]... | keyword[def] identifier[get_cluster_info] ( identifier[host] , identifier[port] , identifier[ignore_cluster_errors] = keyword[False] ):
literal[string]
identifier[client] = identifier[Telnet] ( identifier[host] , identifier[int] ( identifier[port] ))
identifier[client] . identifier[write] ( literal[st... | def get_cluster_info(host, port, ignore_cluster_errors=False):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'v... |
def set_game_score(
self,
user_id: Union[int, str],
score: int,
force: bool = None,
disable_edit_message: bool = None,
chat_id: Union[int, str] = None,
message_id: int = None
):
# inline_message_id: str = None): TODO Add inline_message_id
"""U... | def function[set_game_score, parameter[self, user_id, score, force, disable_edit_message, chat_id, message_id]]:
constant[Use this method to set the score of the specified user in a game.
Args:
user_id (``int`` | ``str``):
Unique identifier (int) or username (str) of the tar... | keyword[def] identifier[set_game_score] (
identifier[self] ,
identifier[user_id] : identifier[Union] [ identifier[int] , identifier[str] ],
identifier[score] : identifier[int] ,
identifier[force] : identifier[bool] = keyword[None] ,
identifier[disable_edit_message] : identifier[bool] = keyword[None] ,
identifie... | def set_game_score(self, user_id: Union[int, str], score: int, force: bool=None, disable_edit_message: bool=None, chat_id: Union[int, str]=None, message_id: int=None):
# inline_message_id: str = None): TODO Add inline_message_id
'Use this method to set the score of the specified user in a game.\n\n Args... |
def labelForAction(self, action):
"""
Returns the label that contains the inputed action.
:return <XDockActionLabel> || None
"""
for label in self.actionLabels():
if label.action() == action:
return label
return None | def function[labelForAction, parameter[self, action]]:
constant[
Returns the label that contains the inputed action.
:return <XDockActionLabel> || None
]
for taget[name[label]] in starred[call[name[self].actionLabels, parameter[]]] begin[:]
if compare... | keyword[def] identifier[labelForAction] ( identifier[self] , identifier[action] ):
literal[string]
keyword[for] identifier[label] keyword[in] identifier[self] . identifier[actionLabels] ():
keyword[if] identifier[label] . identifier[action] ()== identifier[action] :
... | def labelForAction(self, action):
"""
Returns the label that contains the inputed action.
:return <XDockActionLabel> || None
"""
for label in self.actionLabels():
if label.action() == action:
return label # depends on [control=['if'], data=[]] # depends... |
def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Ar... | def function[send, parameter[self, sender]]:
constant[
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is r... | keyword[def] identifier[send] ( identifier[self] , identifier[sender] ,** identifier[named] ):
literal[string]
identifier[responses] =[]
keyword[if] keyword[not] identifier[self] . identifier[receivers] keyword[or] identifier[self] . identifier[sender_receivers_cache] . identifier[get]... | def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Argume... |
def search(self, **kwargs):
"""Search.
:return:
An :class:`~.AmazonSearch` iterable.
"""
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
return AmazonSearch(self.api, self.aws_associate_tag, **kwargs) | def function[search, parameter[self]]:
constant[Search.
:return:
An :class:`~.AmazonSearch` iterable.
]
variable[region] assign[=] call[name[kwargs].get, parameter[constant[region], name[self].region]]
call[name[kwargs].update, parameter[dictionary[[<ast.Constant obj... | keyword[def] identifier[search] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[region] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[self] . identifier[region] )
identifier[kwargs] . identifier[update] ({ literal[string] : identifier[region]... | def search(self, **kwargs):
"""Search.
:return:
An :class:`~.AmazonSearch` iterable.
"""
region = kwargs.get('region', self.region)
kwargs.update({'region': region})
return AmazonSearch(self.api, self.aws_associate_tag, **kwargs) |
def createLearningRateScheduler(self, optimizer):
"""
Creates the learning rate scheduler and attach the optimizer
"""
return torch.optim.lr_scheduler.StepLR(optimizer,
step_size=1,
gamma=self.lr_scheduler_gamma) | def function[createLearningRateScheduler, parameter[self, optimizer]]:
constant[
Creates the learning rate scheduler and attach the optimizer
]
return[call[name[torch].optim.lr_scheduler.StepLR, parameter[name[optimizer]]]] | keyword[def] identifier[createLearningRateScheduler] ( identifier[self] , identifier[optimizer] ):
literal[string]
keyword[return] identifier[torch] . identifier[optim] . identifier[lr_scheduler] . identifier[StepLR] ( identifier[optimizer] ,
identifier[step_size] = literal[int] ,
identifier[gam... | def createLearningRateScheduler(self, optimizer):
"""
Creates the learning rate scheduler and attach the optimizer
"""
return torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=self.lr_scheduler_gamma) |
def ac_factory(path=""):
"""Attribute Converter factory
:param path: The path to a directory where the attribute maps are expected
to reside.
:return: A AttributeConverter instance
"""
acs = []
if path:
if path not in sys.path:
sys.path.insert(0, path)
for ... | def function[ac_factory, parameter[path]]:
constant[Attribute Converter factory
:param path: The path to a directory where the attribute maps are expected
to reside.
:return: A AttributeConverter instance
]
variable[acs] assign[=] list[[]]
if name[path] begin[:]
... | keyword[def] identifier[ac_factory] ( identifier[path] = literal[string] ):
literal[string]
identifier[acs] =[]
keyword[if] identifier[path] :
keyword[if] identifier[path] keyword[not] keyword[in] identifier[sys] . identifier[path] :
identifier[sys] . identifier[path] . ide... | def ac_factory(path=''):
"""Attribute Converter factory
:param path: The path to a directory where the attribute maps are expected
to reside.
:return: A AttributeConverter instance
"""
acs = []
if path:
if path not in sys.path:
sys.path.insert(0, path) # depends on ... |
def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state["t"] = 0.
optim_state["m"] = [tf.zeros_like(v) for v in x]
optim_state["u"] = [tf.zeros_like(v) for v in x]
return optim_state | def function[init_state, parameter[self, x]]:
constant[
Initialize t, m, and u
]
variable[optim_state] assign[=] dictionary[[], []]
call[name[optim_state]][constant[t]] assign[=] constant[0.0]
call[name[optim_state]][constant[m]] assign[=] <ast.ListComp object at 0x7da20c7946d0>
... | keyword[def] identifier[init_state] ( identifier[self] , identifier[x] ):
literal[string]
identifier[optim_state] ={}
identifier[optim_state] [ literal[string] ]= literal[int]
identifier[optim_state] [ literal[string] ]=[ identifier[tf] . identifier[zeros_like] ( identifier[v] ) keyword[for] id... | def init_state(self, x):
"""
Initialize t, m, and u
"""
optim_state = {}
optim_state['t'] = 0.0
optim_state['m'] = [tf.zeros_like(v) for v in x]
optim_state['u'] = [tf.zeros_like(v) for v in x]
return optim_state |
def which_lease_to_steal(self, stealable_leases, have_lease_count):
"""
Determines and return which lease to steal
If the number of leases is a multiple of the number of hosts, then the desired
configuration is that all hosts own the name number of leases, and the
difference betw... | def function[which_lease_to_steal, parameter[self, stealable_leases, have_lease_count]]:
constant[
Determines and return which lease to steal
If the number of leases is a multiple of the number of hosts, then the desired
configuration is that all hosts own the name number of leases, and ... | keyword[def] identifier[which_lease_to_steal] ( identifier[self] , identifier[stealable_leases] , identifier[have_lease_count] ):
literal[string]
identifier[counts_by_owner] = identifier[self] . identifier[count_leases_by_owner] ( identifier[stealable_leases] )
identifier[biggest_owner] =(... | def which_lease_to_steal(self, stealable_leases, have_lease_count):
"""
Determines and return which lease to steal
If the number of leases is a multiple of the number of hosts, then the desired
configuration is that all hosts own the name number of leases, and the
difference between ... |
def forwards(self, orm):
"Write your forwards methods here."
for qde_xtf in orm['xtf.QualifiedDublinCoreElement'].objects.all().order_by('id'):
qde = orm.QualifiedDublinCoreElement()
qde.content = qde_xtf.content
qde.term = qde_xtf.term
qde.qualifier = qde... | def function[forwards, parameter[self, orm]]:
constant[Write your forwards methods here.]
for taget[name[qde_xtf]] in starred[call[call[call[name[orm]][constant[xtf.QualifiedDublinCoreElement]].objects.all, parameter[]].order_by, parameter[constant[id]]]] begin[:]
variable[qde] assign[=]... | keyword[def] identifier[forwards] ( identifier[self] , identifier[orm] ):
literal[string]
keyword[for] identifier[qde_xtf] keyword[in] identifier[orm] [ literal[string] ]. identifier[objects] . identifier[all] (). identifier[order_by] ( literal[string] ):
identifier[qde] = identifie... | def forwards(self, orm):
"""Write your forwards methods here."""
for qde_xtf in orm['xtf.QualifiedDublinCoreElement'].objects.all().order_by('id'):
qde = orm.QualifiedDublinCoreElement()
qde.content = qde_xtf.content
qde.term = qde_xtf.term
qde.qualifier = qde_xtf.qualifier
... |
def bind(self, func: Callable[[Any], IO]) -> 'Put':
"""IO a -> (a -> IO b) -> IO b"""
text, a = self._value
return Put(text, a.bind(func)) | def function[bind, parameter[self, func]]:
constant[IO a -> (a -> IO b) -> IO b]
<ast.Tuple object at 0x7da1b0bdafe0> assign[=] name[self]._value
return[call[name[Put], parameter[name[text], call[name[a].bind, parameter[name[func]]]]]] | keyword[def] identifier[bind] ( identifier[self] , identifier[func] : identifier[Callable] [[ identifier[Any] ], identifier[IO] ])-> literal[string] :
literal[string]
identifier[text] , identifier[a] = identifier[self] . identifier[_value]
keyword[return] identifier[Put] ( identifier[te... | def bind(self, func: Callable[[Any], IO]) -> 'Put':
"""IO a -> (a -> IO b) -> IO b"""
(text, a) = self._value
return Put(text, a.bind(func)) |
def ends(self, s):
length = len(s)
""" True iff 0...k ends with string s """
res = (self.b[self.k-length+1:self.k+1] == s)
if res:
self.j = self.k - length
return res | def function[ends, parameter[self, s]]:
variable[length] assign[=] call[name[len], parameter[name[s]]]
constant[ True iff 0...k ends with string s ]
variable[res] assign[=] compare[call[name[self].b][<ast.Slice object at 0x7da1b1da31c0>] equal[==] name[s]]
if name[res] begin[:]
... | keyword[def] identifier[ends] ( identifier[self] , identifier[s] ):
identifier[length] = identifier[len] ( identifier[s] )
literal[string]
identifier[res] =( identifier[self] . identifier[b] [ identifier[self] . identifier[k] - identifier[length] + literal[int] : identifier[self] . identif... | def ends(self, s):
length = len(s)
' True iff 0...k ends with string s '
res = self.b[self.k - length + 1:self.k + 1] == s
if res:
self.j = self.k - length # depends on [control=['if'], data=[]]
return res |
def sanitize_unicode(item):
"""Safely pass string values to the CASA tools.
item
A value to be passed to a CASA tool.
In Python 2, the bindings to CASA tasks expect to receive all string values
as binary data (:class:`str`) and not Unicode. But :mod:`pwkit` often uses
the ``from __future__ i... | def function[sanitize_unicode, parameter[item]]:
constant[Safely pass string values to the CASA tools.
item
A value to be passed to a CASA tool.
In Python 2, the bindings to CASA tasks expect to receive all string values
as binary data (:class:`str`) and not Unicode. But :mod:`pwkit` often u... | keyword[def] identifier[sanitize_unicode] ( identifier[item] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[item] , identifier[text_type] ):
keyword[return] identifier[item] . identifier[encode] ( literal[string] )
keyword[if] identifier[isinstance] ( identifier[item] ,... | def sanitize_unicode(item):
"""Safely pass string values to the CASA tools.
item
A value to be passed to a CASA tool.
In Python 2, the bindings to CASA tasks expect to receive all string values
as binary data (:class:`str`) and not Unicode. But :mod:`pwkit` often uses
the ``from __future__ i... |
def packages(ctx, opts, owner_repo, page, page_size, query):
"""
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query)... | def function[packages, parameter[ctx, opts, owner_repo, page, page_size, query]]:
constant[
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can us... | keyword[def] identifier[packages] ( identifier[ctx] , identifier[opts] , identifier[owner_repo] , identifier[page] , identifier[page_size] , identifier[query] ):
literal[string]
identifier[owner] , identifier[repo] = identifier[owner_repo]
identifier[use_stderr] = identifier[opts] . identifier[... | def packages(ctx, opts, owner_repo, page, page_size, query):
"""
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query)... |
def set_notify_dispatch_request(self, notify_dispatch_request, *args):
"""Set function to call just before requests are dispatched
Args:
notify_dispatch_request (callable): function will be called
with request as single arg just before request is dispatched
"""
... | def function[set_notify_dispatch_request, parameter[self, notify_dispatch_request]]:
constant[Set function to call just before requests are dispatched
Args:
notify_dispatch_request (callable): function will be called
with request as single arg just before request is dispatch... | keyword[def] identifier[set_notify_dispatch_request] ( identifier[self] , identifier[notify_dispatch_request] ,* identifier[args] ):
literal[string]
identifier[self] . identifier[_notify_dispatch_request] = identifier[notify_dispatch_request]
identifier[self] . identifier[_notify_args] = ... | def set_notify_dispatch_request(self, notify_dispatch_request, *args):
"""Set function to call just before requests are dispatched
Args:
notify_dispatch_request (callable): function will be called
with request as single arg just before request is dispatched
"""
self.... |
def __retrieve_updates(self, timeout=20):
"""
Retrieves any updates from the Telegram API.
Registered listeners and applicable message handlers will be notified when a new message arrives.
:raises ApiException when a call has failed.
"""
if self.skip_pending:
... | def function[__retrieve_updates, parameter[self, timeout]]:
constant[
Retrieves any updates from the Telegram API.
Registered listeners and applicable message handlers will be notified when a new message arrives.
:raises ApiException when a call has failed.
]
if name[self... | keyword[def] identifier[__retrieve_updates] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[skip_pending] :
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifie... | def __retrieve_updates(self, timeout=20):
"""
Retrieves any updates from the Telegram API.
Registered listeners and applicable message handlers will be notified when a new message arrives.
:raises ApiException when a call has failed.
"""
if self.skip_pending:
logger.debug... |
def copy(self):
"""Return a copy of this `Fact`."""
content = [(k, v) for k, v in self.items()]
intidx = [(k, v) for k, v in content if isinstance(k, int)]
args = [v for k, v in sorted(intidx)]
kwargs = {k: v
for k, v in content
if not isinst... | def function[copy, parameter[self]]:
constant[Return a copy of this `Fact`.]
variable[content] assign[=] <ast.ListComp object at 0x7da1b1e64550>
variable[intidx] assign[=] <ast.ListComp object at 0x7da1b1e666e0>
variable[args] assign[=] <ast.ListComp object at 0x7da1b1e67910>
var... | keyword[def] identifier[copy] ( identifier[self] ):
literal[string]
identifier[content] =[( identifier[k] , identifier[v] ) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[items] ()]
identifier[intidx] =[( identifier[k] , identifier[v] ) keyword[for... | def copy(self):
"""Return a copy of this `Fact`."""
content = [(k, v) for (k, v) in self.items()]
intidx = [(k, v) for (k, v) in content if isinstance(k, int)]
args = [v for (k, v) in sorted(intidx)]
kwargs = {k: v for (k, v) in content if not isinstance(k, int) and (not self.is_special(k))}
ret... |
def get_random_distorted_bottlenecks(
sess, image_lists, how_many, category, image_dir, input_jpeg_tensor,
distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we ha... | def function[get_random_distorted_bottlenecks, parameter[sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tensor]]:
constant[Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops,... | keyword[def] identifier[get_random_distorted_bottlenecks] (
identifier[sess] , identifier[image_lists] , identifier[how_many] , identifier[category] , identifier[image_dir] , identifier[input_jpeg_tensor] ,
identifier[distorted_image] , identifier[resized_input_tensor] , identifier[bottleneck_tensor] ):
literal[... | def get_random_distorted_bottlenecks(sess, image_lists, how_many, category, image_dir, input_jpeg_tensor, distorted_image, resized_input_tensor, bottleneck_tensor):
"""Retrieves bottleneck values for training images, after distortions.
If we're training with distortions like crops, scales, or flips, we have to
... |
def get_string(self):
"""A string representation of the junction
:return: string represnetation
:rtype: string
"""
return self.left.chr+':'+str(self.left.end)+'-'+self.right.chr+':'+str(self.right.start) | def function[get_string, parameter[self]]:
constant[A string representation of the junction
:return: string represnetation
:rtype: string
]
return[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[binary_operation[name[self].left.chr + constant[:]] + call[name... | keyword[def] identifier[get_string] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[left] . identifier[chr] + literal[string] + identifier[str] ( identifier[self] . identifier[left] . identifier[end] )+ literal[string] + identifier[self] . identifier[right] . identifier... | def get_string(self):
"""A string representation of the junction
:return: string represnetation
:rtype: string
"""
return self.left.chr + ':' + str(self.left.end) + '-' + self.right.chr + ':' + str(self.right.start) |
def prep_stream_data(data):
"""Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO
"""
if isinstance(data, (six.string_types, six.binary_type)):
stream = io.BytesIO(to_bytes(data))
else:
stream = ... | def function[prep_stream_data, parameter[data]]:
constant[Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO
]
if call[name[isinstance], parameter[name[data], tuple[[<ast.Attribute object at 0x7da18fe93010>,... | keyword[def] identifier[prep_stream_data] ( identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] ,( identifier[six] . identifier[string_types] , identifier[six] . identifier[binary_type] )):
identifier[stream] = identifier[io] . identifier[BytesIO] ( identifie... | def prep_stream_data(data):
"""Take an input and prepare it for use as a stream.
:param data: Input data
:returns: Prepared stream
:rtype: InsistentReaderBytesIO
"""
if isinstance(data, (six.string_types, six.binary_type)):
stream = io.BytesIO(to_bytes(data)) # depends on [control=['if... |
def _transform(self, W):
for t in range(16, 80):
W.append(_rotateLeft(
W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1) & 0xffffffff)
A = self.H0
B = self.H1
C = self.H2
D = self.H3
E = self.H4
"""
This loop was unrolled to gain about... | def function[_transform, parameter[self, W]]:
for taget[name[t]] in starred[call[name[range], parameter[constant[16], constant[80]]]] begin[:]
call[name[W].append, parameter[binary_operation[call[name[_rotateLeft], parameter[binary_operation[binary_operation[binary_operation[call[name[W]][binary... | keyword[def] identifier[_transform] ( identifier[self] , identifier[W] ):
keyword[for] identifier[t] keyword[in] identifier[range] ( literal[int] , literal[int] ):
identifier[W] . identifier[append] ( identifier[_rotateLeft] (
identifier[W] [ identifier[t] - literal[int] ]^ iden... | def _transform(self, W):
for t in range(16, 80):
W.append(_rotateLeft(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1) & 4294967295) # depends on [control=['for'], data=['t']]
A = self.H0
B = self.H1
C = self.H2
D = self.H3
E = self.H4
'\n This loop was unrolled to gain about ... |
def init_defaults(self):
"""
Sets a query instance variable to the table value
"""
super(QueryTable, self).init_defaults()
self.query = self.table
self.query.is_inner = True | def function[init_defaults, parameter[self]]:
constant[
Sets a query instance variable to the table value
]
call[call[name[super], parameter[name[QueryTable], name[self]]].init_defaults, parameter[]]
name[self].query assign[=] name[self].table
name[self].query.is_inner as... | keyword[def] identifier[init_defaults] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[QueryTable] , identifier[self] ). identifier[init_defaults] ()
identifier[self] . identifier[query] = identifier[self] . identifier[table]
identifier[self] . identifier[que... | def init_defaults(self):
"""
Sets a query instance variable to the table value
"""
super(QueryTable, self).init_defaults()
self.query = self.table
self.query.is_inner = True |
def wait_for_completion(report, interval=10):
"""Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job iden... | def function[wait_for_completion, parameter[report, interval]]:
constant[Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: l... | keyword[def] identifier[wait_for_completion] ( identifier[report] , identifier[interval] = literal[int] ):
literal[string]
keyword[for] identifier[jobid] keyword[in] identifier[report] . identifier[collect] ( literal[string] ):
keyword[try] :
keyword[if] keyword[not] identifier[J... | def wait_for_completion(report, interval=10):
"""Wait for asynchronous jobs stil running in the given campaign.
:param report: memory representation of a campaign report
:type campaign: ReportNode
:param interval: wait interval
:type interval: int or float
:return: list of asynchronous job iden... |
def chunks(f):
"""Split read PNG image data into chunks"""
while 1:
try:
length = struct.unpack(b"!I", f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack(b"!I", f.read(4))[0]
except struct.error:... | def function[chunks, parameter[f]]:
constant[Split read PNG image data into chunks]
while constant[1] begin[:]
<ast.Try object at 0x7da1b094a4a0>
if compare[binary_operation[call[name[zlib].crc32, parameter[binary_operation[name[tag] + name[data]]]] <ast.BitAnd object at 0x7da259... | keyword[def] identifier[chunks] ( identifier[f] ):
literal[string]
keyword[while] literal[int] :
keyword[try] :
identifier[length] = identifier[struct] . identifier[unpack] ( literal[string] , identifier[f] . identifier[read] ( literal[int] ))[ literal[int] ]
... | def chunks(f):
"""Split read PNG image data into chunks"""
while 1:
try:
length = struct.unpack(b'!I', f.read(4))[0]
tag = f.read(4)
data = f.read(length)
crc = struct.unpack(b'!I', f.read(4))[0] # depends on [control=['try'], data=[]]
except stru... |
def make_mesh_file(
self,
labels=None,
):
""" Make one mesh (vtk or stl) file
:param label: labels from prev use of set_labels are used if None
:return: filename of output file
Funkce vrací trojrozměrné porobné jako data['segmentation']
v da... | def function[make_mesh_file, parameter[self, labels]]:
constant[ Make one mesh (vtk or stl) file
:param label: labels from prev use of set_labels are used if None
:return: filename of output file
Funkce vrací trojrozměrné porobné jako data['segmentation']
v data['slab'] je pop... | keyword[def] identifier[make_mesh_file] (
identifier[self] ,
identifier[labels] = keyword[None] ,
):
literal[string]
keyword[if] identifier[labels] keyword[is] keyword[None] :
identifier[labels] = identifier[self] . identifier[labels]
identifier[strlabel] = identifier[... | def make_mesh_file(self, labels=None):
""" Make one mesh (vtk or stl) file
:param label: labels from prev use of set_labels are used if None
:return: filename of output file
Funkce vrací trojrozměrné porobné jako data['segmentation']
v data['slab'] je popsáno, co která hodnota zna... |
async def _set_wallets(an_data: dict) -> dict:
"""
Set wallets as configured for setnym operation.
:param an_data: dict mapping profiles to anchor data
:return: dict mapping anchor names to wallet objects
"""
w_mgr = WalletManager()
rv = {}
for profile in an_data:
w_cfg = {'id'... | <ast.AsyncFunctionDef object at 0x7da18c4cef50> | keyword[async] keyword[def] identifier[_set_wallets] ( identifier[an_data] : identifier[dict] )-> identifier[dict] :
literal[string]
identifier[w_mgr] = identifier[WalletManager] ()
identifier[rv] ={}
keyword[for] identifier[profile] keyword[in] identifier[an_data] :
identifier[w_cf... | async def _set_wallets(an_data: dict) -> dict:
"""
Set wallets as configured for setnym operation.
:param an_data: dict mapping profiles to anchor data
:return: dict mapping anchor names to wallet objects
"""
w_mgr = WalletManager()
rv = {}
for profile in an_data:
w_cfg = {'id':... |
def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
self.stdout.write(style.format_command('Removing', addon))
removed = dependencies.remo... | def function[remove, parameter[self, addon, dev]]:
constant[Remove a dependency and uninstall it.]
variable[dependencies] assign[=] call[name[self].get_dependency_manager, parameter[]]
variable[other_dependencies] assign[=] call[name[self].get_dependency_manager, parameter[]]
call[name[s... | keyword[def] identifier[remove] ( identifier[self] , identifier[addon] , identifier[dev] = keyword[False] ):
literal[string]
identifier[dependencies] = identifier[self] . identifier[get_dependency_manager] ( identifier[dev] = identifier[dev] )
identifier[other_dependencies] = identifier[se... | def remove(self, addon, dev=False):
"""Remove a dependency and uninstall it."""
dependencies = self.get_dependency_manager(dev=dev)
other_dependencies = self.get_dependency_manager(dev=not dev)
self.stdout.write(style.format_command('Removing', addon))
removed = dependencies.remove(addon, warn=False... |
def serve_assets(path):
"""Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
"""
res = os.path.join(app.config['NIKOLA_ROOT'],
_site.config["OUTPU... | def function[serve_assets, parameter[path]]:
constant[Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
]
variable[res] assign[=] call[name[os].path.join, parame... | keyword[def] identifier[serve_assets] ( identifier[path] ):
literal[string]
identifier[res] = identifier[os] . identifier[path] . identifier[join] ( identifier[app] . identifier[config] [ literal[string] ],
identifier[_site] . identifier[config] [ literal[string] ], literal[string] )
keyword[retu... | def serve_assets(path):
"""Serve Nikola assets.
This is meant to be used ONLY by the internal dev server.
Please configure your web server to handle requests to this URL::
/assets/ => output/assets
"""
res = os.path.join(app.config['NIKOLA_ROOT'], _site.config['OUTPUT_FOLDER'], 'assets')
... |
def rotate_grid_from_profile(self, grid_elliptical):
""" Rotate a grid of elliptical (y,x) coordinates from the reference frame of the profile back to the \
unrotated coordinate grid reference frame (coordinates are not shifted back to their original centre).
This routine is used after computin... | def function[rotate_grid_from_profile, parameter[self, grid_elliptical]]:
constant[ Rotate a grid of elliptical (y,x) coordinates from the reference frame of the profile back to the unrotated coordinate grid reference frame (coordinates are not shifted back to their original centre).
This routi... | keyword[def] identifier[rotate_grid_from_profile] ( identifier[self] , identifier[grid_elliptical] ):
literal[string]
identifier[y] = identifier[np] . identifier[add] ( identifier[np] . identifier[multiply] ( identifier[grid_elliptical] [:, literal[int] ], identifier[self] . identifier[sin_phi] ), ... | def rotate_grid_from_profile(self, grid_elliptical):
""" Rotate a grid of elliptical (y,x) coordinates from the reference frame of the profile back to the unrotated coordinate grid reference frame (coordinates are not shifted back to their original centre).
This routine is used after computing defl... |
def _set_node_state(self, v, load=False):
"""
Setter method for node_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_state (node-state-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_node_state is considered as a priva... | def function[_set_node_state, parameter[self, v, load]]:
constant[
Setter method for node_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_state (node-state-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_node_state... | keyword[def] identifier[_set_node_state] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
ide... | def _set_node_state(self, v, load=False):
"""
Setter method for node_state, mapped from YANG variable /brocade_vcs_rpc/show_vcs/output/vcs_nodes/vcs_node_info/node_state (node-state-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_node_state is considered as a priva... |
def from_taxdb(cls, con, root=None):
"""
Generate a TaxNode from a taxonomy database
"""
cursor = con.cursor()
if root is None:
cursor.execute(
"SELECT tax_id, rank FROM nodes WHERE tax_id = parent_id")
else:
cursor.execute(
... | def function[from_taxdb, parameter[cls, con, root]]:
constant[
Generate a TaxNode from a taxonomy database
]
variable[cursor] assign[=] call[name[con].cursor, parameter[]]
if compare[name[root] is constant[None]] begin[:]
call[name[cursor].execute, parameter[const... | keyword[def] identifier[from_taxdb] ( identifier[cls] , identifier[con] , identifier[root] = keyword[None] ):
literal[string]
identifier[cursor] = identifier[con] . identifier[cursor] ()
keyword[if] identifier[root] keyword[is] keyword[None] :
identifier[cursor] . identifie... | def from_taxdb(cls, con, root=None):
"""
Generate a TaxNode from a taxonomy database
"""
cursor = con.cursor()
if root is None:
cursor.execute('SELECT tax_id, rank FROM nodes WHERE tax_id = parent_id') # depends on [control=['if'], data=[]]
else:
cursor.execute('SELECT t... |
def divide(iterable, n): # pylint: disable=invalid-name
"""Evenly divide elements.
Arguments
---------
iterable : iterable
n : integer
The number of buckets in which to divide the elements
Returns
-------
The generator produces *n* tuples, each cont... | def function[divide, parameter[iterable, n]]:
constant[Evenly divide elements.
Arguments
---------
iterable : iterable
n : integer
The number of buckets in which to divide the elements
Returns
-------
The generator produces *n* tuples, each containing a number... | keyword[def] identifier[divide] ( identifier[iterable] , identifier[n] ):
literal[string]
keyword[if] identifier[n] <= literal[int] :
keyword[return] []
identifier[data] = identifier[list] ( identifier[iterable] )
identifier[base] , identifier[rem] = identifier[divmod] ( identifier[len]... | def divide(iterable, n): # pylint: disable=invalid-name
'Evenly divide elements.\n\n Arguments\n ---------\n iterable : iterable\n n : integer\n The number of buckets in which to divide the elements\n\n Returns\n -------\n The generator produces *n* tuples, each containing... |
def get_section_metrics(cls):
"""
Get the mapping between metrics and sections in Manuscripts report
:return: a dict with the mapping between metrics and sections in Manuscripts report
"""
return {
"overview": {
"activity_metrics": [Closed, Submitted]... | def function[get_section_metrics, parameter[cls]]:
constant[
Get the mapping between metrics and sections in Manuscripts report
:return: a dict with the mapping between metrics and sections in Manuscripts report
]
return[dictionary[[<ast.Constant object at 0x7da1b268ea40>, <ast.Const... | keyword[def] identifier[get_section_metrics] ( identifier[cls] ):
literal[string]
keyword[return] {
literal[string] :{
literal[string] :[ identifier[Closed] , identifier[Submitted] ],
literal[string] : keyword[None] ,
literal[string] :[ identifier[BMI] ],
... | def get_section_metrics(cls):
"""
Get the mapping between metrics and sections in Manuscripts report
:return: a dict with the mapping between metrics and sections in Manuscripts report
"""
return {'overview': {'activity_metrics': [Closed, Submitted], 'author_metrics': None, 'bmi_metrics'... |
def prompt_y_or_n(self, prompt):
"""
Wrapper around prompt_input for simple yes/no queries.
"""
ch = self.prompt_input(prompt, key=True)
if ch in (ord('Y'), ord('y')):
return True
elif ch in (ord('N'), ord('n'), None):
return False
else:
... | def function[prompt_y_or_n, parameter[self, prompt]]:
constant[
Wrapper around prompt_input for simple yes/no queries.
]
variable[ch] assign[=] call[name[self].prompt_input, parameter[name[prompt]]]
if compare[name[ch] in tuple[[<ast.Call object at 0x7da18fe91240>, <ast.Call obje... | keyword[def] identifier[prompt_y_or_n] ( identifier[self] , identifier[prompt] ):
literal[string]
identifier[ch] = identifier[self] . identifier[prompt_input] ( identifier[prompt] , identifier[key] = keyword[True] )
keyword[if] identifier[ch] keyword[in] ( identifier[ord] ( literal[stri... | def prompt_y_or_n(self, prompt):
"""
Wrapper around prompt_input for simple yes/no queries.
"""
ch = self.prompt_input(prompt, key=True)
if ch in (ord('Y'), ord('y')):
return True # depends on [control=['if'], data=[]]
elif ch in (ord('N'), ord('n'), None):
return False ... |
def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str] = None, fill_values: Dict[str, np.ndarray] = None) -> None:
"""
**DEPRECATED** - Use `new` instead; see https://gith... | def function[create_append, parameter[filename, layers, row_attrs, col_attrs]]:
constant[
**DEPRECATED** - Use `new` instead; see https://github.com/linnarsson-lab/loompy/issues/42
]
call[name[deprecated], parameter[constant['create_append' is deprecated. See https://github.com/linnarsson-lab/loompy/i... | keyword[def] identifier[create_append] ( identifier[filename] : identifier[str] , identifier[layers] : identifier[Union] [ identifier[np] . identifier[ndarray] , identifier[Dict] [ identifier[str] , identifier[np] . identifier[ndarray] ], identifier[loompy] . identifier[LayerManager] ], identifier[row_attrs] : identi... | def create_append(filename: str, layers: Union[np.ndarray, Dict[str, np.ndarray], loompy.LayerManager], row_attrs: Dict[str, np.ndarray], col_attrs: Dict[str, np.ndarray], *, file_attrs: Dict[str, str]=None, fill_values: Dict[str, np.ndarray]=None) -> None:
"""
**DEPRECATED** - Use `new` instead; see https://githu... |
def main(**kwargs):
"""
if not _IRC3_INSTALLED:
logging.error('vexbot_irc requires `irc3` to be installed. Please install '
'using `pip install irc3`')
sys.exit(1)
"""
config = _from_argv(irc3.IrcBot, kwargs=kwargs)
if not 'includes' in config:
config[... | def function[main, parameter[]]:
constant[
if not _IRC3_INSTALLED:
logging.error('vexbot_irc requires `irc3` to be installed. Please install '
'using `pip install irc3`')
sys.exit(1)
]
variable[config] assign[=] call[name[_from_argv], parameter[name[irc3].I... | keyword[def] identifier[main] (** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[_from_argv] ( identifier[irc3] . identifier[IrcBot] , identifier[kwargs] = identifier[kwargs] )
keyword[if] keyword[not] literal[string] keyword[in] identifier[config] :
identifier[con... | def main(**kwargs):
"""
if not _IRC3_INSTALLED:
logging.error('vexbot_irc requires `irc3` to be installed. Please install '
'using `pip install irc3`')
sys.exit(1)
"""
config = _from_argv(irc3.IrcBot, kwargs=kwargs)
if not 'includes' in config:
config['... |
async def download_cot_artifact(chain, task_id, path):
"""Download an artifact and verify its SHA against the chain of trust.
Args:
chain (ChainOfTrust): the chain of trust object
task_id (str): the task ID to download from
path (str): the relative path to the artifact to download
... | <ast.AsyncFunctionDef object at 0x7da18dc99330> | keyword[async] keyword[def] identifier[download_cot_artifact] ( identifier[chain] , identifier[task_id] , identifier[path] ):
literal[string]
identifier[link] = identifier[chain] . identifier[get_link] ( identifier[task_id] )
identifier[log] . identifier[debug] ( literal[string] . identifier[format] ... | async def download_cot_artifact(chain, task_id, path):
"""Download an artifact and verify its SHA against the chain of trust.
Args:
chain (ChainOfTrust): the chain of trust object
task_id (str): the task ID to download from
path (str): the relative path to the artifact to download
... |
def currentContentsWidget( self, autoadd = False ):
"""
Returns the current contents widget based on the cached index. If \
no widget is specified and autoadd is True, then a new widget will \
be added to the tab.
:param autoadd | <bool>
:r... | def function[currentContentsWidget, parameter[self, autoadd]]:
constant[
Returns the current contents widget based on the cached index. If no widget is specified and autoadd is True, then a new widget will be added to the tab.
:param autoadd | <bool>
... | keyword[def] identifier[currentContentsWidget] ( identifier[self] , identifier[autoadd] = keyword[False] ):
literal[string]
identifier[widget] = identifier[self] . identifier[uiContentsTAB] . identifier[widget] ( identifier[self] . identifier[currentContentsIndex] ())
keyword[if] ( keywo... | def currentContentsWidget(self, autoadd=False):
"""
Returns the current contents widget based on the cached index. If no widget is specified and autoadd is True, then a new widget will be added to the tab.
:param autoadd | <bool>
:return <QWebView>... |
def basic_addresses_write(self, cycles, last_op_address, address, word):
"""
0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM
0114 001B VARTAB RMB 2 *PV START OF VARIABLES
0115 001D ARYTAB RMB 2 *PV START OF ARRAYS
0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1)
0117 0... | def function[basic_addresses_write, parameter[self, cycles, last_op_address, address, word]]:
constant[
0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM
0114 001B VARTAB RMB 2 *PV START OF VARIABLES
0115 001D ARYTAB RMB 2 *PV START OF ARRAYS
0116 001F ARYEND RMB 2 *PV END OF... | keyword[def] identifier[basic_addresses_write] ( identifier[self] , identifier[cycles] , identifier[last_op_address] , identifier[address] , identifier[word] ):
literal[string]
identifier[log] . identifier[critical] ( literal[string] , identifier[last_op_address] , identifier[word] , identifier[add... | def basic_addresses_write(self, cycles, last_op_address, address, word):
"""
0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM
0114 001B VARTAB RMB 2 *PV START OF VARIABLES
0115 001D ARYTAB RMB 2 *PV START OF ARRAYS
0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1)
0117 0021 ... |
def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """
db_fields = self.mongokat_collection.find_one({"_id": self["_id"]}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return
... | def function[refetch_fields, parameter[self, missing_fields]]:
constant[ Refetches a list of fields from the DB ]
variable[db_fields] assign[=] call[name[self].mongokat_collection.find_one, parameter[dictionary[[<ast.Constant object at 0x7da1b265fa30>], [<ast.Subscript object at 0x7da1b265fcd0>]]]]
... | keyword[def] identifier[refetch_fields] ( identifier[self] , identifier[missing_fields] ):
literal[string]
identifier[db_fields] = identifier[self] . identifier[mongokat_collection] . identifier[find_one] ({ literal[string] : identifier[self] [ literal[string] ]}, identifier[fields] ={ identifier[k... | def refetch_fields(self, missing_fields):
""" Refetches a list of fields from the DB """
db_fields = self.mongokat_collection.find_one({'_id': self['_id']}, fields={k: 1 for k in missing_fields})
self._fetched_fields += tuple(missing_fields)
if not db_fields:
return # depends on [control=['if']... |
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for category in orm['document_library.DocumentCategory'].objects.all():
category.slug = category.documentcategorytitle_set.all()[0].title... | def function[forwards, parameter[self, orm]]:
constant[Write your forwards methods here.]
for taget[name[category]] in starred[call[call[name[orm]][constant[document_library.DocumentCategory]].objects.all, parameter[]]] begin[:]
name[category].slug assign[=] call[call[call[name[category]... | keyword[def] identifier[forwards] ( identifier[self] , identifier[orm] ):
literal[string]
keyword[for] identifier[category] keyword[in] identifier[orm] [ literal[string] ]. identifier[objects] . identifier[all] ():
identifier[category] . identifier[slug] = identifier[catego... | def forwards(self, orm):
"""Write your forwards methods here."""
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for category in orm['document_library.DocumentCategory'].objects.all():
category.slug = category.documentcategorytitle_set.all()[0].title.lower()
... |
def _normalize_args(args):
'''
Return args as a list of strings
'''
if isinstance(args, six.string_types):
return shlex.split(args)
if isinstance(args, (tuple, list)):
return [six.text_type(arg) for arg in args]
else:
return [six.text_type(args)] | def function[_normalize_args, parameter[args]]:
constant[
Return args as a list of strings
]
if call[name[isinstance], parameter[name[args], name[six].string_types]] begin[:]
return[call[name[shlex].split, parameter[name[args]]]]
if call[name[isinstance], parameter[name[args], tu... | keyword[def] identifier[_normalize_args] ( identifier[args] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[args] , identifier[six] . identifier[string_types] ):
keyword[return] identifier[shlex] . identifier[split] ( identifier[args] )
keyword[if] identifier[isinstance... | def _normalize_args(args):
"""
Return args as a list of strings
"""
if isinstance(args, six.string_types):
return shlex.split(args) # depends on [control=['if'], data=[]]
if isinstance(args, (tuple, list)):
return [six.text_type(arg) for arg in args] # depends on [control=['if'], d... |
def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
"""
spec = cls.find_spec(fullname, path)
if spec is None:
return None
elif spec.loa... | def function[find_module, parameter[cls, fullname, path]]:
constant[find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
]
variable[spec] assign[=] call[name[cls].find_spec, parameter[name[fullname], name[path]... | keyword[def] identifier[find_module] ( identifier[cls] , identifier[fullname] , identifier[path] = keyword[None] ):
literal[string]
identifier[spec] = identifier[cls] . identifier[find_spec] ( identifier[fullname] , identifier[path] )
keyword[if] identifier[spec] keyword[is] keyword[Non... | def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.
This method is for python2 only
"""
spec = cls.find_spec(fullname, path)
if spec is None:
return None # depends on [control=['if'], data=[... |
def rollback(self, date):
"""Roll date backward to nearest end of quarter"""
if self.onOffset(date):
return date
else:
return date - QuarterEnd(month=self.month) | def function[rollback, parameter[self, date]]:
constant[Roll date backward to nearest end of quarter]
if call[name[self].onOffset, parameter[name[date]]] begin[:]
return[name[date]] | keyword[def] identifier[rollback] ( identifier[self] , identifier[date] ):
literal[string]
keyword[if] identifier[self] . identifier[onOffset] ( identifier[date] ):
keyword[return] identifier[date]
keyword[else] :
keyword[return] identifier[date] - identifier[... | def rollback(self, date):
"""Roll date backward to nearest end of quarter"""
if self.onOffset(date):
return date # depends on [control=['if'], data=[]]
else:
return date - QuarterEnd(month=self.month) |
def clear_recovery_range(working_dir):
"""
Clear out our recovery hint
"""
recovery_range_path = os.path.join(working_dir, '.recovery')
if os.path.exists(recovery_range_path):
os.unlink(recovery_range_path) | def function[clear_recovery_range, parameter[working_dir]]:
constant[
Clear out our recovery hint
]
variable[recovery_range_path] assign[=] call[name[os].path.join, parameter[name[working_dir], constant[.recovery]]]
if call[name[os].path.exists, parameter[name[recovery_range_path]]] begi... | keyword[def] identifier[clear_recovery_range] ( identifier[working_dir] ):
literal[string]
identifier[recovery_range_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[working_dir] , literal[string] )
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifi... | def clear_recovery_range(working_dir):
"""
Clear out our recovery hint
"""
recovery_range_path = os.path.join(working_dir, '.recovery')
if os.path.exists(recovery_range_path):
os.unlink(recovery_range_path) # depends on [control=['if'], data=[]] |
def _http_call(the_url, method, authorization, **kw):
'''
send an http request and return a json object if no error occurred.
'''
params = None
boundary = None
if method == _HTTP_UPLOAD:
# fix sina upload url:
the_url = the_url.replace('https://api.', 'https://upload.api.')
... | def function[_http_call, parameter[the_url, method, authorization]]:
constant[
send an http request and return a json object if no error occurred.
]
variable[params] assign[=] constant[None]
variable[boundary] assign[=] constant[None]
if compare[name[method] equal[==] name[_HTTP_... | keyword[def] identifier[_http_call] ( identifier[the_url] , identifier[method] , identifier[authorization] ,** identifier[kw] ):
literal[string]
identifier[params] = keyword[None]
identifier[boundary] = keyword[None]
keyword[if] identifier[method] == identifier[_HTTP_UPLOAD] :
id... | def _http_call(the_url, method, authorization, **kw):
"""
send an http request and return a json object if no error occurred.
"""
params = None
boundary = None
if method == _HTTP_UPLOAD:
# fix sina upload url:
the_url = the_url.replace('https://api.', 'https://upload.api.')
... |
def group_records(records, groupby='week'):
"""
Group records by year, month, week, or day.
Parameters
----------
records : iterator
An iterator over records
groupby : Default is 'week':
* 'week': group all records by year and week
* None: records are not grouped. This ... | def function[group_records, parameter[records, groupby]]:
constant[
Group records by year, month, week, or day.
Parameters
----------
records : iterator
An iterator over records
groupby : Default is 'week':
* 'week': group all records by year and week
* None: record... | keyword[def] identifier[group_records] ( identifier[records] , identifier[groupby] = literal[string] ):
literal[string]
keyword[def] identifier[_group_date] ( identifier[records] , identifier[_fun] ):
keyword[for] identifier[_] , identifier[chunk] keyword[in] identifier[itertools] . identifie... | def group_records(records, groupby='week'):
"""
Group records by year, month, week, or day.
Parameters
----------
records : iterator
An iterator over records
groupby : Default is 'week':
* 'week': group all records by year and week
* None: records are not grouped. This ... |
def luhn_validate(number):
""" Source code from: https://en.wikipedia.org/wiki/Luhn_algorithm"""
sum = 0
parity = len(number) % 2
for i, digit in enumerate([int(x) for x in number]):
if i % 2 == parity:
digit *= 2
if digit > 9:
digit -= 9
sum += d... | def function[luhn_validate, parameter[number]]:
constant[ Source code from: https://en.wikipedia.org/wiki/Luhn_algorithm]
variable[sum] assign[=] constant[0]
variable[parity] assign[=] binary_operation[call[name[len], parameter[name[number]]] <ast.Mod object at 0x7da2590d6920> constant[2]]
... | keyword[def] identifier[luhn_validate] ( identifier[number] ):
literal[string]
identifier[sum] = literal[int]
identifier[parity] = identifier[len] ( identifier[number] )% literal[int]
keyword[for] identifier[i] , identifier[digit] keyword[in] identifier[enumerate] ([ identifier[int] ( ident... | def luhn_validate(number):
""" Source code from: https://en.wikipedia.org/wiki/Luhn_algorithm"""
sum = 0
parity = len(number) % 2
for (i, digit) in enumerate([int(x) for x in number]):
if i % 2 == parity:
digit *= 2
if digit > 9:
digit -= 9 # depends on [... |
def is_installed(pkg_name):
"""
Check if an RPM package is installed.
"""
manager = MANAGER
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = run("rpm --query %(pkg_name)s" % locals())
if res.succeeded:
return True
return False | def function[is_installed, parameter[pkg_name]]:
constant[
Check if an RPM package is installed.
]
variable[manager] assign[=] name[MANAGER]
with call[name[settings], parameter[call[name[hide], parameter[constant[running], constant[stdout], constant[stderr], constant[warnings]]]]] begin[... | keyword[def] identifier[is_installed] ( identifier[pkg_name] ):
literal[string]
identifier[manager] = identifier[MANAGER]
keyword[with] identifier[settings] ( identifier[hide] ( literal[string] , literal[string] , literal[string] , literal[string] ), identifier[warn_only] = keyword[True] ):
... | def is_installed(pkg_name):
"""
Check if an RPM package is installed.
"""
manager = MANAGER
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = run('rpm --query %(pkg_name)s' % locals())
if res.succeeded:
return True # depends on [contro... |
def nvmlShutdown():
r"""
/**
* Shut down NVML by releasing all GPU resources previously allocated with \ref nvmlInit().
*
* For all products.
*
* This method should be called after NVML work is done, once for each call to \ref nvmlInit()
* A reference count of the number of initial... | def function[nvmlShutdown, parameter[]]:
constant[
/**
* Shut down NVML by releasing all GPU resources previously allocated with \ref nvmlInit().
*
* For all products.
*
* This method should be called after NVML work is done, once for each call to \ref nvmlInit()
* A reference ... | keyword[def] identifier[nvmlShutdown] ():
literal[string]
identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] )
identifier[ret] = identifier[fn] ()
identifier[_nvmlCheckReturn] ( identifier[ret] )
keyword[global] identifier[_nvmlLib_refcount]
id... | def nvmlShutdown():
"""
/**
* Shut down NVML by releasing all GPU resources previously allocated with \\ref nvmlInit().
*
* For all products.
*
* This method should be called after NVML work is done, once for each call to \\ref nvmlInit()
* A reference count of the number of initia... |
def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: ... | def function[find_keys, parameter[self, regex, bucket_name]]:
constant[Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
... | keyword[def] identifier[find_keys] ( identifier[self] , identifier[regex] , identifier[bucket_name] = keyword[None] ):
literal[string]
identifier[log] = identifier[logging] . identifier[getLogger] ( identifier[self] . identifier[cls_logger] + literal[string] )
identifier[matched_keys] =[]
... | def find_keys(self, regex, bucket_name=None):
"""Finds a list of S3 keys matching the passed regex
Given a regular expression, this method searches the S3 bucket
for matching keys, and returns an array of strings for matched
keys, an empty array if non are found.
:param regex: (str... |
def before(point):
""" True if point datetime specification is before now """
if not point:
return True
if isinstance(point, str):
point = str_to_time(point)
elif isinstance(point, int):
point = time.gmtime(point)
return time.gmtime() < point | def function[before, parameter[point]]:
constant[ True if point datetime specification is before now ]
if <ast.UnaryOp object at 0x7da18fe92560> begin[:]
return[constant[True]]
if call[name[isinstance], parameter[name[point], name[str]]] begin[:]
variable[point] assign[=]... | keyword[def] identifier[before] ( identifier[point] ):
literal[string]
keyword[if] keyword[not] identifier[point] :
keyword[return] keyword[True]
keyword[if] identifier[isinstance] ( identifier[point] , identifier[str] ):
identifier[point] = identifier[str_to_time] ( identifier... | def before(point):
""" True if point datetime specification is before now """
if not point:
return True # depends on [control=['if'], data=[]]
if isinstance(point, str):
point = str_to_time(point) # depends on [control=['if'], data=[]]
elif isinstance(point, int):
point = time.... |
def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim)
if rep == 'Operator':
return _from_operator('Kraus', da... | def function[_to_kraus, parameter[rep, data, input_dim, output_dim]]:
constant[Transform a QuantumChannel to the Kraus representation.]
if compare[name[rep] equal[==] constant[Kraus]] begin[:]
return[name[data]]
if compare[name[rep] equal[==] constant[Stinespring]] begin[:]
retur... | keyword[def] identifier[_to_kraus] ( identifier[rep] , identifier[data] , identifier[input_dim] , identifier[output_dim] ):
literal[string]
keyword[if] identifier[rep] == literal[string] :
keyword[return] identifier[data]
keyword[if] identifier[rep] == literal[string] :
keyword[r... | def _to_kraus(rep, data, input_dim, output_dim):
"""Transform a QuantumChannel to the Kraus representation."""
if rep == 'Kraus':
return data # depends on [control=['if'], data=[]]
if rep == 'Stinespring':
return _stinespring_to_kraus(data, input_dim, output_dim) # depends on [control=['if... |
def reindex(args):
"""
%prog agpfile
assume the component line order is correct, modify coordinates, this is
necessary mostly due to manual edits (insert/delete) that disrupts
the target coordinates.
"""
p = OptionParser(reindex.__doc__)
p.add_option("--nogaps", default=False, action="s... | def function[reindex, parameter[args]]:
constant[
%prog agpfile
assume the component line order is correct, modify coordinates, this is
necessary mostly due to manual edits (insert/delete) that disrupts
the target coordinates.
]
variable[p] assign[=] call[name[OptionParser], paramet... | keyword[def] identifier[reindex] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[reindex] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = keyword[False] , identifier[action] = literal[string] ,
id... | def reindex(args):
"""
%prog agpfile
assume the component line order is correct, modify coordinates, this is
necessary mostly due to manual edits (insert/delete) that disrupts
the target coordinates.
"""
p = OptionParser(reindex.__doc__)
p.add_option('--nogaps', default=False, action='s... |
def append(self, hcont, value, score = None):
""" If sort_field is specified, score must be None.
If sort_field is not specified, score is mandatory. """
assert (score is None) != (self.field.sort_field is None)
if score is None:
score = getattr(value, self.field.sort_fie... | def function[append, parameter[self, hcont, value, score]]:
constant[ If sort_field is specified, score must be None.
If sort_field is not specified, score is mandatory. ]
assert[compare[compare[name[score] is constant[None]] not_equal[!=] compare[name[self].field.sort_field is constant[None]]]]... | keyword[def] identifier[append] ( identifier[self] , identifier[hcont] , identifier[value] , identifier[score] = keyword[None] ):
literal[string]
keyword[assert] ( identifier[score] keyword[is] keyword[None] )!=( identifier[self] . identifier[field] . identifier[sort_field] keyword[is] keyword[... | def append(self, hcont, value, score=None):
""" If sort_field is specified, score must be None.
If sort_field is not specified, score is mandatory. """
assert (score is None) != (self.field.sort_field is None)
if score is None:
score = getattr(value, self.field.sort_field.name) # depend... |
def set(self, section, option, value):
"""
Set method that (1) auto-saves if possible and (2) auto-creates
sections.
"""
try:
super(ExactOnlineConfig, self).set(section, option, value)
except NoSectionError:
self.add_section(section)
su... | def function[set, parameter[self, section, option, value]]:
constant[
Set method that (1) auto-saves if possible and (2) auto-creates
sections.
]
<ast.Try object at 0x7da1b0243e50>
call[name[self].save, parameter[]] | keyword[def] identifier[set] ( identifier[self] , identifier[section] , identifier[option] , identifier[value] ):
literal[string]
keyword[try] :
identifier[super] ( identifier[ExactOnlineConfig] , identifier[self] ). identifier[set] ( identifier[section] , identifier[option] , identifi... | def set(self, section, option, value):
"""
Set method that (1) auto-saves if possible and (2) auto-creates
sections.
"""
try:
super(ExactOnlineConfig, self).set(section, option, value) # depends on [control=['try'], data=[]]
except NoSectionError:
self.add_section(se... |
def clear_session_cookies(self):
"""Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
"""
self._cookies_lock.acquire()
try:
for cookie in self:
... | def function[clear_session_cookies, parameter[self]]:
constant[Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
]
call[name[self]._cookies_lock.acquire, parameter[]]
... | keyword[def] identifier[clear_session_cookies] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_cookies_lock] . identifier[acquire] ()
keyword[try] :
keyword[for] identifier[cookie] keyword[in] identifier[self] :
keyword[if] identifier[... | def clear_session_cookies(self):
"""Discard all session cookies.
Note that the .save() method won't save session cookies anyway, unless
you ask otherwise by passing a true ignore_discard argument.
"""
self._cookies_lock.acquire()
try:
for cookie in self:
if cook... |
def error(self):
"""Returns the error for this barrier and all work items, if any."""
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and... | def function[error, parameter[self]]:
constant[Returns the error for this barrier and all work items, if any.]
for taget[name[item]] in starred[name[self]] begin[:]
if <ast.BoolOp object at 0x7da204566350> begin[:]
return[name[item].error]
return[constant[None]] | keyword[def] identifier[error] ( identifier[self] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[self] :
keyword[if] identifier[isinstance] ( identifier[item] , identifier[WorkItem] ) keyword[and] identifier[item] . iden... | def error(self):
"""Returns the error for this barrier and all work items, if any."""
# Copy the error from any failed item to be the error for the whole
# barrier. The first error seen "wins". Also handles the case where
# the WorkItems passed into the barrier have already completed and
# been mark... |
def _get(self, url, params={}):
"""Wrapper around request.get() to use the API prefix. Returns a JSON response."""
r = requests.get(self._api_prefix + url,
params=params,
headers=self.headers,
auth=self.auth,
)
return self._action(r) | def function[_get, parameter[self, url, params]]:
constant[Wrapper around request.get() to use the API prefix. Returns a JSON response.]
variable[r] assign[=] call[name[requests].get, parameter[binary_operation[name[self]._api_prefix + name[url]]]]
return[call[name[self]._action, parameter[name[r]]]... | keyword[def] identifier[_get] ( identifier[self] , identifier[url] , identifier[params] ={}):
literal[string]
identifier[r] = identifier[requests] . identifier[get] ( identifier[self] . identifier[_api_prefix] + identifier[url] ,
identifier[params] = identifier[params] ,
identifie... | def _get(self, url, params={}):
"""Wrapper around request.get() to use the API prefix. Returns a JSON response."""
r = requests.get(self._api_prefix + url, params=params, headers=self.headers, auth=self.auth)
return self._action(r) |
def setValidityErrorHandler(self, err_func, warn_func, arg=None):
"""
Register error and warning handlers for DTD validation.
These will be called back as f(msg,arg)
"""
libxml2mod.xmlSetValidErrors(self._o, err_func, warn_func, arg) | def function[setValidityErrorHandler, parameter[self, err_func, warn_func, arg]]:
constant[
Register error and warning handlers for DTD validation.
These will be called back as f(msg,arg)
]
call[name[libxml2mod].xmlSetValidErrors, parameter[name[self]._o, name[err_func], name[war... | keyword[def] identifier[setValidityErrorHandler] ( identifier[self] , identifier[err_func] , identifier[warn_func] , identifier[arg] = keyword[None] ):
literal[string]
identifier[libxml2mod] . identifier[xmlSetValidErrors] ( identifier[self] . identifier[_o] , identifier[err_func] , identifier[warn... | def setValidityErrorHandler(self, err_func, warn_func, arg=None):
"""
Register error and warning handlers for DTD validation.
These will be called back as f(msg,arg)
"""
libxml2mod.xmlSetValidErrors(self._o, err_func, warn_func, arg) |
def _decode_key(self, key):
"""Decode key using hex_codec to retrieve the original key.
Keys are returned as :class:`str` if serialization is enabled.
Keys are returned as :class:`bytes` if serialization is disabled.
"""
bkey = codecs.decode(key.encode(self._keyencoding), 'hex_... | def function[_decode_key, parameter[self, key]]:
constant[Decode key using hex_codec to retrieve the original key.
Keys are returned as :class:`str` if serialization is enabled.
Keys are returned as :class:`bytes` if serialization is disabled.
]
variable[bkey] assign[=] call[na... | keyword[def] identifier[_decode_key] ( identifier[self] , identifier[key] ):
literal[string]
identifier[bkey] = identifier[codecs] . identifier[decode] ( identifier[key] . identifier[encode] ( identifier[self] . identifier[_keyencoding] ), literal[string] )
keyword[return] identifier[bkey... | def _decode_key(self, key):
"""Decode key using hex_codec to retrieve the original key.
Keys are returned as :class:`str` if serialization is enabled.
Keys are returned as :class:`bytes` if serialization is disabled.
"""
bkey = codecs.decode(key.encode(self._keyencoding), 'hex_codec')
... |
def pip_remove(self, name=None, prefix=None, pkgs=None):
"""Remove a pip package in given environment by `name` or `prefix`."""
logger.debug(str((prefix, pkgs)))
if isinstance(pkgs, (list, tuple)):
pkg = ' '.join(pkgs)
else:
pkg = pkgs
extra_args = ['uni... | def function[pip_remove, parameter[self, name, prefix, pkgs]]:
constant[Remove a pip package in given environment by `name` or `prefix`.]
call[name[logger].debug, parameter[call[name[str], parameter[tuple[[<ast.Name object at 0x7da1b2765120>, <ast.Name object at 0x7da1b2767220>]]]]]]
if call[nam... | keyword[def] identifier[pip_remove] ( identifier[self] , identifier[name] = keyword[None] , identifier[prefix] = keyword[None] , identifier[pkgs] = keyword[None] ):
literal[string]
identifier[logger] . identifier[debug] ( identifier[str] (( identifier[prefix] , identifier[pkgs] )))
keywor... | def pip_remove(self, name=None, prefix=None, pkgs=None):
"""Remove a pip package in given environment by `name` or `prefix`."""
logger.debug(str((prefix, pkgs)))
if isinstance(pkgs, (list, tuple)):
pkg = ' '.join(pkgs) # depends on [control=['if'], data=[]]
else:
pkg = pkgs
extra_ar... |
def from_seed(cls, seed, encoder=encoding.RawEncoder):
"""
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
r... | def function[from_seed, parameter[cls, seed, encoder]]:
constant[
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
... | keyword[def] identifier[from_seed] ( identifier[cls] , identifier[seed] , identifier[encoder] = identifier[encoding] . identifier[RawEncoder] ):
literal[string]
identifier[seed] = identifier[encoder] . identifier[decode] ( identifier[seed] )
keyword[if] keyword[not] ( id... | def from_seed(cls, seed, encoder=encoding.RawEncoder):
"""
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
rando... |
def read(self, size=None):
""" Read `size` of bytes."""
if size is None:
return self.buf.read() + self.open_file.read()
contents = self.buf.read(size)
if len(contents) < size:
contents += self.open_file.read(size - len(contents))
return contents | def function[read, parameter[self, size]]:
constant[ Read `size` of bytes.]
if compare[name[size] is constant[None]] begin[:]
return[binary_operation[call[name[self].buf.read, parameter[]] + call[name[self].open_file.read, parameter[]]]]
variable[contents] assign[=] call[name[self].buf.r... | keyword[def] identifier[read] ( identifier[self] , identifier[size] = keyword[None] ):
literal[string]
keyword[if] identifier[size] keyword[is] keyword[None] :
keyword[return] identifier[self] . identifier[buf] . identifier[read] ()+ identifier[self] . identifier[open_file] . identifier[read] ()... | def read(self, size=None):
""" Read `size` of bytes."""
if size is None:
return self.buf.read() + self.open_file.read() # depends on [control=['if'], data=[]]
contents = self.buf.read(size)
if len(contents) < size:
contents += self.open_file.read(size - len(contents)) # depends on [con... |
def is_rate_matrix(K, tol=1e-12):
r"""Check if the given matrix is a rate matrix.
Parameters
----------
K : (M, M) ndarray or scipy.sparse matrix
Matrix to check
tol : float (optional)
Floating point tolerance to check with
Returns
-------
is_rate_matrix : bool
... | def function[is_rate_matrix, parameter[K, tol]]:
constant[Check if the given matrix is a rate matrix.
Parameters
----------
K : (M, M) ndarray or scipy.sparse matrix
Matrix to check
tol : float (optional)
Floating point tolerance to check with
Returns
-------
is_rat... | keyword[def] identifier[is_rate_matrix] ( identifier[K] , identifier[tol] = literal[int] ):
literal[string]
identifier[K] = identifier[_types] . identifier[ensure_ndarray_or_sparse] ( identifier[K] , identifier[ndim] = literal[int] , identifier[uniform] = keyword[True] , identifier[kind] = literal[string] ... | def is_rate_matrix(K, tol=1e-12):
"""Check if the given matrix is a rate matrix.
Parameters
----------
K : (M, M) ndarray or scipy.sparse matrix
Matrix to check
tol : float (optional)
Floating point tolerance to check with
Returns
-------
is_rate_matrix : bool
T... |
def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
... | def function[wait_for_and_switch_to_alert, parameter[driver, timeout]]:
constant[
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (requi... | keyword[def] identifier[wait_for_and_switch_to_alert] ( identifier[driver] , identifier[timeout] = identifier[settings] . identifier[LARGE_TIMEOUT] ):
literal[string]
identifier[start_ms] = identifier[time] . identifier[time] ()* literal[int]
identifier[stop_ms] = identifier[start_ms] +( identifier[... | def wait_for_and_switch_to_alert(driver, timeout=settings.LARGE_TIMEOUT):
"""
Wait for a browser alert to appear, and switch to it. This should be usable
as a drop-in replacement for driver.switch_to.alert when the alert box
may not exist yet.
@Params
driver - the webdriver object (required)
... |
def drawBezier(page, p1, p2, p3, p4, color=None, fill=None,
dashes=None, width=1, morph=None,
closePath=False, roundCap=False, overlay=True):
"""Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3.
"""
img = page.newShape()
Q = img.drawBezier(Poin... | def function[drawBezier, parameter[page, p1, p2, p3, p4, color, fill, dashes, width, morph, closePath, roundCap, overlay]]:
constant[Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3.
]
variable[img] assign[=] call[name[page].newShape, parameter[]]
variable[Q] as... | keyword[def] identifier[drawBezier] ( identifier[page] , identifier[p1] , identifier[p2] , identifier[p3] , identifier[p4] , identifier[color] = keyword[None] , identifier[fill] = keyword[None] ,
identifier[dashes] = keyword[None] , identifier[width] = literal[int] , identifier[morph] = keyword[None] ,
identifier[c... | def drawBezier(page, p1, p2, p3, p4, color=None, fill=None, dashes=None, width=1, morph=None, closePath=False, roundCap=False, overlay=True):
"""Draw a general cubic Bezier curve from p1 to p4 using control points p2 and p3.
"""
img = page.newShape()
Q = img.drawBezier(Point(p1), Point(p2), Point(p3), P... |
def draw(self, renderer):
"""
Draw the children
"""
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
for c in self._children:
c.draw(renderer)
self.stale = False | def function[draw, parameter[self, renderer]]:
constant[
Draw the children
]
variable[dpi_cor] assign[=] call[name[renderer].points_to_pixels, parameter[constant[1.0]]]
call[name[self].dpi_transform.clear, parameter[]]
call[name[self].dpi_transform.scale, parameter[name[d... | keyword[def] identifier[draw] ( identifier[self] , identifier[renderer] ):
literal[string]
identifier[dpi_cor] = identifier[renderer] . identifier[points_to_pixels] ( literal[int] )
identifier[self] . identifier[dpi_transform] . identifier[clear] ()
identifier[self] . identifier[d... | def draw(self, renderer):
"""
Draw the children
"""
dpi_cor = renderer.points_to_pixels(1.0)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
for c in self._children:
c.draw(renderer) # depends on [control=['for'], data=['c']]
self.stale = False |
def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reaso... | def function[verify, parameter[self, obj]]:
constant[Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thr... | keyword[def] identifier[verify] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] identifier[obj] != identifier[self] . identifier[_literal] :
keyword[raise] identifier[ValidationError] ( literal[string] ,
identifier[reason] = literal[string] %( identi... | def verify(self, obj):
"""Verify that the object conforms to this verifier's schema
Args:
obj (object): A python object to verify
Raises:
ValidationError: If there is a problem verifying the dictionary, a
ValidationError is thrown with at least the reason ke... |
def foldx_dir(self):
"""str: FoldX folder"""
if self.root_dir:
return op.join(self.root_dir, self._foldx_dirname)
else:
log.warning('Root directory not set')
return None | def function[foldx_dir, parameter[self]]:
constant[str: FoldX folder]
if name[self].root_dir begin[:]
return[call[name[op].join, parameter[name[self].root_dir, name[self]._foldx_dirname]]] | keyword[def] identifier[foldx_dir] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[root_dir] :
keyword[return] identifier[op] . identifier[join] ( identifier[self] . identifier[root_dir] , identifier[self] . identifier[_foldx_dirname] )
keywor... | def foldx_dir(self):
"""str: FoldX folder"""
if self.root_dir:
return op.join(self.root_dir, self._foldx_dirname) # depends on [control=['if'], data=[]]
else:
log.warning('Root directory not set')
return None |
def _get_measure_outcome(self, qubit):
"""Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcom... | def function[_get_measure_outcome, parameter[self, qubit]]:
constant[Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probabi... | keyword[def] identifier[_get_measure_outcome] ( identifier[self] , identifier[qubit] ):
literal[string]
identifier[axis] = identifier[list] ( identifier[range] ( identifier[self] . identifier[_number_of_qubits] ))
identifier[axis] . identifier[remove] ( identifier[self] . identifi... | def _get_measure_outcome(self, qubit):
"""Simulate the outcome of measurement of a qubit.
Args:
qubit (int): the qubit to measure
Return:
tuple: pair (outcome, probability) where outcome is '0' or '1' and
probability is the probability of the returned outcome.
... |
def append(self, other, ignore_index=False):
"""Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
... | def function[append, parameter[self, other, ignore_index]]:
constant[Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is... | keyword[def] identifier[append] ( identifier[self] , identifier[other] , identifier[ignore_index] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[other] , identifier[self] . identifier[__class__] ):
keyword[raise] identifier[ValueErro... | def append(self, other, ignore_index=False):
"""Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
... |
def get_expected_image_size(module_or_spec, signature=None, input_name=None):
"""Returns expected [height, width] dimensions of an image input.
Args:
module_or_spec: a Module or ModuleSpec that accepts image inputs.
signature: a string with the key of the signature in question.
If None, the default s... | def function[get_expected_image_size, parameter[module_or_spec, signature, input_name]]:
constant[Returns expected [height, width] dimensions of an image input.
Args:
module_or_spec: a Module or ModuleSpec that accepts image inputs.
signature: a string with the key of the signature in question.
... | keyword[def] identifier[get_expected_image_size] ( identifier[module_or_spec] , identifier[signature] = keyword[None] , identifier[input_name] = keyword[None] ):
literal[string]
identifier[image_module_info] = identifier[get_image_module_info] ( identifier[module_or_spec] )
keyword[if] identifier[image_... | def get_expected_image_size(module_or_spec, signature=None, input_name=None):
"""Returns expected [height, width] dimensions of an image input.
Args:
module_or_spec: a Module or ModuleSpec that accepts image inputs.
signature: a string with the key of the signature in question.
If None, the default... |
def ar1(rho, mu, sigma, size=1):
"""Return an autoregressive series of order one AR(1).
.. math::
X_t = \mu_t + \rho (X_{t-1}-\mu_{t-1} + \epsilon_t
If mu is a sequence and size > len(mu), the algorithm loops through
mu.
:Stochastics:
rho : scalar in [0,1]
mu : scalar or s... | def function[ar1, parameter[rho, mu, sigma, size]]:
constant[Return an autoregressive series of order one AR(1).
.. math::
X_t = \mu_t +
ho (X_{t-1}-\mu_{t-1} + \epsilon_t
If mu is a sequence and size > len(mu), the algorithm loops through
mu.
:Stochastics:
rho : scalar in [0... | keyword[def] identifier[ar1] ( identifier[rho] , identifier[mu] , identifier[sigma] , identifier[size] = literal[int] ):
literal[string]
keyword[return] identifier[np] . identifier[array] ([ identifier[x] keyword[for] identifier[x] keyword[in] identifier[ar1_gen] ( identifier[rho] , identifier[mu] , i... | def ar1(rho, mu, sigma, size=1):
"""Return an autoregressive series of order one AR(1).
.. math::
X_t = \\mu_t + \rho (X_{t-1}-\\mu_{t-1} + \\epsilon_t
If mu is a sequence and size > len(mu), the algorithm loops through
mu.
:Stochastics:
rho : scalar in [0,1]
mu : scalar o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.