code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _parse_boolean(value):
"""
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
"""
if not value:
return False
try:
# Lower string to check known "false" value
value = value.lower()
return value not... | def function[_parse_boolean, parameter[value]]:
constant[
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
]
if <ast.UnaryOp object at 0x7da1b0470ca0> begin[:]
return[constant[False]]
<ast.Try object at 0x7da1b04702... | keyword[def] identifier[_parse_boolean] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[value] :
keyword[return] keyword[False]
keyword[try] :
identifier[value] = identifier[value] . identifier[lower] ()
keyword[return] identifier[value]... | def _parse_boolean(value):
"""
Returns a boolean value corresponding to the given value.
:param value: Any value
:return: Its boolean value
"""
if not value:
return False # depends on [control=['if'], data=[]]
try:
# Lower string to check known "false" value
value =... |
def ds2n(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 0, x[1] + 2) for x in self.df.index]
values = self.s2n.values - self.s2n.loc[idx].values
return Table(df=pd.Series(values, index=self.df.... | def function[ds2n, parameter[self]]:
constant[Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
]
variable[idx] assign[=] <ast.ListComp object at 0x7da2054a5780>
variable[values] assign[=] binary_operation[name[self].s2n.values - cal... | keyword[def] identifier[ds2n] ( identifier[self] ):
literal[string]
identifier[idx] =[( identifier[x] [ literal[int] ]+ literal[int] , identifier[x] [ literal[int] ]+ literal[int] ) keyword[for] identifier[x] keyword[in] identifier[self] . identifier[df] . identifier[index] ]
identifier... | def ds2n(self):
"""Calculates the derivative of the neutron separation energies:
ds2n(Z,A) = s2n(Z,A) - s2n(Z,A+2)
"""
idx = [(x[0] + 0, x[1] + 2) for x in self.df.index]
values = self.s2n.values - self.s2n.loc[idx].values
return Table(df=pd.Series(values, index=self.df.index, name='ds2... |
def set_server_state(name,object=None,delete=False):
"""
Sets a simple 'state' on the server by creating a file
with the desired state's name and storing ``content`` as json strings if supplied
returns the filename used to store state
"""
with fab_settings(project_fullname=''):
r... | def function[set_server_state, parameter[name, object, delete]]:
constant[
Sets a simple 'state' on the server by creating a file
with the desired state's name and storing ``content`` as json strings if supplied
returns the filename used to store state
]
with call[name[fab_settin... | keyword[def] identifier[set_server_state] ( identifier[name] , identifier[object] = keyword[None] , identifier[delete] = keyword[False] ):
literal[string]
keyword[with] identifier[fab_settings] ( identifier[project_fullname] = literal[string] ):
keyword[return] identifier[set_version_state] ( id... | def set_server_state(name, object=None, delete=False):
"""
Sets a simple 'state' on the server by creating a file
with the desired state's name and storing ``content`` as json strings if supplied
returns the filename used to store state
"""
with fab_settings(project_fullname=''):
... |
def record_error(hostname, exc_info, preceding_stack=None, error_threshold=None, additional_info=None):
''' Helper function to record errors to the flawless backend '''
stack = []
exc_type, exc_value, sys_traceback = exc_info
while sys_traceback is not None:
stack.append(sys_traceback)
... | def function[record_error, parameter[hostname, exc_info, preceding_stack, error_threshold, additional_info]]:
constant[ Helper function to record errors to the flawless backend ]
variable[stack] assign[=] list[[]]
<ast.Tuple object at 0x7da20c6a90f0> assign[=] name[exc_info]
while compar... | keyword[def] identifier[record_error] ( identifier[hostname] , identifier[exc_info] , identifier[preceding_stack] = keyword[None] , identifier[error_threshold] = keyword[None] , identifier[additional_info] = keyword[None] ):
literal[string]
identifier[stack] =[]
identifier[exc_type] , identifier[exc_v... | def record_error(hostname, exc_info, preceding_stack=None, error_threshold=None, additional_info=None):
""" Helper function to record errors to the flawless backend """
stack = []
(exc_type, exc_value, sys_traceback) = exc_info
while sys_traceback is not None:
stack.append(sys_traceback)
... |
def getTotalCpuTimeAndMemoryUsage():
"""Gives the total cpu time and memory usage of itself and its children.
"""
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime+me.ru_stime+childs.ru_utime+childs.ru_stime
totalMemory... | def function[getTotalCpuTimeAndMemoryUsage, parameter[]]:
constant[Gives the total cpu time and memory usage of itself and its children.
]
variable[me] assign[=] call[name[resource].getrusage, parameter[name[resource].RUSAGE_SELF]]
variable[childs] assign[=] call[name[resource].getrusage, pa... | keyword[def] identifier[getTotalCpuTimeAndMemoryUsage] ():
literal[string]
identifier[me] = identifier[resource] . identifier[getrusage] ( identifier[resource] . identifier[RUSAGE_SELF] )
identifier[childs] = identifier[resource] . identifier[getrusage] ( identifier[resource] . identifier[RUSAGE_CHILD... | def getTotalCpuTimeAndMemoryUsage():
"""Gives the total cpu time and memory usage of itself and its children.
"""
me = resource.getrusage(resource.RUSAGE_SELF)
childs = resource.getrusage(resource.RUSAGE_CHILDREN)
totalCpuTime = me.ru_utime + me.ru_stime + childs.ru_utime + childs.ru_stime
total... |
def get_conn(opts, profile=None, host=None, port=None):
'''
Return a conn object for accessing memcached
'''
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
... | def function[get_conn, parameter[opts, profile, host, port]]:
constant[
Return a conn object for accessing memcached
]
if <ast.UnaryOp object at 0x7da1b1c65cc0> begin[:]
variable[opts_pillar] assign[=] call[name[opts].get, parameter[constant[pillar], dictionary[[], []]]]
... | keyword[def] identifier[get_conn] ( identifier[opts] , identifier[profile] = keyword[None] , identifier[host] = keyword[None] , identifier[port] = keyword[None] ):
literal[string]
keyword[if] keyword[not] ( identifier[host] keyword[and] identifier[port] ):
identifier[opts_pillar] = identifier[o... | def get_conn(opts, profile=None, host=None, port=None):
"""
Return a conn object for accessing memcached
"""
if not (host and port):
opts_pillar = opts.get('pillar', {})
opts_master = opts_pillar.get('master', {})
opts_merged = {}
opts_merged.update(opts_master)
o... |
def LeaseClientActionRequests(self,
client_id,
lease_time=None,
limit=sys.maxsize):
"""Leases available client action requests for a client."""
leased_requests = []
now = rdfvalue.RDFDatetime.Now()
expirati... | def function[LeaseClientActionRequests, parameter[self, client_id, lease_time, limit]]:
constant[Leases available client action requests for a client.]
variable[leased_requests] assign[=] list[[]]
variable[now] assign[=] call[name[rdfvalue].RDFDatetime.Now, parameter[]]
variable[expirati... | keyword[def] identifier[LeaseClientActionRequests] ( identifier[self] ,
identifier[client_id] ,
identifier[lease_time] = keyword[None] ,
identifier[limit] = identifier[sys] . identifier[maxsize] ):
literal[string]
identifier[leased_requests] =[]
identifier[now] = identifier[rdfvalue] . identifier... | def LeaseClientActionRequests(self, client_id, lease_time=None, limit=sys.maxsize):
"""Leases available client action requests for a client."""
leased_requests = []
now = rdfvalue.RDFDatetime.Now()
expiration_time = now + lease_time
process_id_str = utils.ProcessIdString()
leases = self.client_a... |
def open(self):
"""initialize visit variables"""
self.stats = self.linter.add_stats()
self._returns = []
self._branches = defaultdict(int)
self._stmts = [] | def function[open, parameter[self]]:
constant[initialize visit variables]
name[self].stats assign[=] call[name[self].linter.add_stats, parameter[]]
name[self]._returns assign[=] list[[]]
name[self]._branches assign[=] call[name[defaultdict], parameter[name[int]]]
name[self]._stmt... | keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[self] . identifier[stats] = identifier[self] . identifier[linter] . identifier[add_stats] ()
identifier[self] . identifier[_returns] =[]
identifier[self] . identifier[_branches] = identifier[defaultdict... | def open(self):
"""initialize visit variables"""
self.stats = self.linter.add_stats()
self._returns = []
self._branches = defaultdict(int)
self._stmts = [] |
def update_activity(self, activity_id, name=None, activity_type=None,
private=None, commute=None, trainer=None, gear_id=None,
description=None,device_name=None):
"""
Updates the properties of a specific activity.
http://strava.github.io/api/v3/act... | def function[update_activity, parameter[self, activity_id, name, activity_type, private, commute, trainer, gear_id, description, device_name]]:
constant[
Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: The ID of ... | keyword[def] identifier[update_activity] ( identifier[self] , identifier[activity_id] , identifier[name] = keyword[None] , identifier[activity_type] = keyword[None] ,
identifier[private] = keyword[None] , identifier[commute] = keyword[None] , identifier[trainer] = keyword[None] , identifier[gear_id] = keyword[None] ... | def update_activity(self, activity_id, name=None, activity_type=None, private=None, commute=None, trainer=None, gear_id=None, description=None, device_name=None):
"""
Updates the properties of a specific activity.
http://strava.github.io/api/v3/activities/#put-updates
:param activity_id: T... |
def generate_jackknife_replicates(self,
mnl_obj=None,
mnl_init_vals=None,
mnl_fit_kwargs=None,
extract_init_vals=None,
print_res=F... | def function[generate_jackknife_replicates, parameter[self, mnl_obj, mnl_init_vals, mnl_fit_kwargs, extract_init_vals, print_res, method, loss_tol, gradient_tol, maxiter, ridge, constrained_pos]]:
constant[
Generates the jackknife replicates for one's given model and dataset.
Parameters
... | keyword[def] identifier[generate_jackknife_replicates] ( identifier[self] ,
identifier[mnl_obj] = keyword[None] ,
identifier[mnl_init_vals] = keyword[None] ,
identifier[mnl_fit_kwargs] = keyword[None] ,
identifier[extract_init_vals] = keyword[None] ,
identifier[print_res] = keyword[False] ,
identifier[method] =... | def generate_jackknife_replicates(self, mnl_obj=None, mnl_init_vals=None, mnl_fit_kwargs=None, extract_init_vals=None, print_res=False, method='BFGS', loss_tol=1e-06, gradient_tol=1e-06, maxiter=1000, ridge=None, constrained_pos=None):
"""
Generates the jackknife replicates for one's given model and dataset... |
def _collection_json_response(cls, resources, start, stop, depth=0):
"""Return the JSON representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response`
"""
top_level_json_name = None
if cls.__top_level_json_n... | def function[_collection_json_response, parameter[cls, resources, start, stop, depth]]:
constant[Return the JSON representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response`
]
variable[top_level_json_na... | keyword[def] identifier[_collection_json_response] ( identifier[cls] , identifier[resources] , identifier[start] , identifier[stop] , identifier[depth] = literal[int] ):
literal[string]
identifier[top_level_json_name] = keyword[None]
keyword[if] identifier[cls] . identifier[__top_level_json_name__]... | def _collection_json_response(cls, resources, start, stop, depth=0):
"""Return the JSON representation of the collection *resources*.
:param list resources: list of :class:`sandman.model.Model`s to render
:rtype: :class:`flask.Response`
"""
top_level_json_name = None
if cls.__top_level_json_na... |
def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
"""
if will_print(level):
printer(("WARNING: " if prefix else "") + msg, "yellow") | def function[warn, parameter[msg, level, prefix]]:
constant[Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
]
if call[name[will_print], parameter[name[level]]] begin[:]
call[name[printer], parameter[binary_operation[<ast.IfEx... | keyword[def] identifier[warn] ( identifier[msg] , identifier[level] = literal[int] , identifier[prefix] = keyword[True] ):
literal[string]
keyword[if] identifier[will_print] ( identifier[level] ):
identifier[printer] (( literal[string] keyword[if] identifier[prefix] keyword[else] literal[stri... | def warn(msg, level=0, prefix=True):
"""Prints the specified message as a warning; prepends "WARNING" to
the message, so that can be left off.
"""
if will_print(level):
printer(('WARNING: ' if prefix else '') + msg, 'yellow') # depends on [control=['if'], data=[]] |
def post(self, url, postParameters=None, urlParameters=None):
"""
Implement libgreader's interface for authenticated POST request
"""
if self._action_token == None:
self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL)
if self._http == None:
self._set... | def function[post, parameter[self, url, postParameters, urlParameters]]:
constant[
Implement libgreader's interface for authenticated POST request
]
if compare[name[self]._action_token equal[==] constant[None]] begin[:]
name[self]._action_token assign[=] call[name[self].g... | keyword[def] identifier[post] ( identifier[self] , identifier[url] , identifier[postParameters] = keyword[None] , identifier[urlParameters] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_action_token] == keyword[None] :
identifier[self] . identifier[_act... | def post(self, url, postParameters=None, urlParameters=None):
"""
Implement libgreader's interface for authenticated POST request
"""
if self._action_token == None:
self._action_token = self.get(ReaderUrl.ACTION_TOKEN_URL) # depends on [control=['if'], data=[]]
if self._http == None... |
def highstate(test=None, queue=False, **kwargs):
'''
Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
... | def function[highstate, parameter[test, queue]]:
constant[
Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
... | keyword[def] identifier[highstate] ( identifier[test] = keyword[None] , identifier[queue] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[_disabled] ([ literal[string] ]):
identifier[log] . identifier[debug] ( literal[string] )
identifier[ret] ={
... | def highstate(test=None, queue=False, **kwargs):
"""
Retrieve the state data from the salt master for this minion and execute it
test
Run states in test-only (dry-run) mode
pillar
Custom Pillar values, passed as a dictionary of key-value pairs
.. code-block:: bash
... |
def push_new_themes(catalog, portal_url, apikey):
"""Toma un catálogo y escribe los temas de la taxonomía que no están
presentes.
Args:
catalog (DataJson): El catálogo de origen que contiene la
taxonomía.
portal_url (str): La URL del portal CKAN de destino.
... | def function[push_new_themes, parameter[catalog, portal_url, apikey]]:
constant[Toma un catálogo y escribe los temas de la taxonomía que no están
presentes.
Args:
catalog (DataJson): El catálogo de origen que contiene la
taxonomía.
portal_url (str): La URL de... | keyword[def] identifier[push_new_themes] ( identifier[catalog] , identifier[portal_url] , identifier[apikey] ):
literal[string]
identifier[ckan_portal] = identifier[RemoteCKAN] ( identifier[portal_url] , identifier[apikey] = identifier[apikey] )
identifier[existing_themes] = identifier[ckan_portal] . ... | def push_new_themes(catalog, portal_url, apikey):
"""Toma un catálogo y escribe los temas de la taxonomía que no están
presentes.
Args:
catalog (DataJson): El catálogo de origen que contiene la
taxonomía.
portal_url (str): La URL del portal CKAN de destino.
... |
def run(self):
"""Keep running this thread until it's stopped"""
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0) | def function[run, parameter[self]]:
constant[Keep running this thread until it's stopped]
while <ast.UnaryOp object at 0x7da20e963610> begin[:]
call[name[self]._func, parameter[name[self]._reference]]
call[name[self]._finished.wait, parameter[binary_operation[name[self]._... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[_finished] . identifier[isSet] ():
identifier[self] . identifier[_func] ( identifier[self] . identifier[_reference] )
identifier[self] . identifie... | def run(self):
"""Keep running this thread until it's stopped"""
while not self._finished.isSet():
self._func(self._reference)
self._finished.wait(self._func._interval / 1000.0) # depends on [control=['while'], data=[]] |
def _get_security_context(self):
"""Defines the security context"""
security_context = {}
if self.kube_config.worker_run_as_user:
security_context['runAsUser'] = self.kube_config.worker_run_as_user
if self.kube_config.worker_fs_group:
security_context['fsGroup']... | def function[_get_security_context, parameter[self]]:
constant[Defines the security context]
variable[security_context] assign[=] dictionary[[], []]
if name[self].kube_config.worker_run_as_user begin[:]
call[name[security_context]][constant[runAsUser]] assign[=] name[self].kube_c... | keyword[def] identifier[_get_security_context] ( identifier[self] ):
literal[string]
identifier[security_context] ={}
keyword[if] identifier[self] . identifier[kube_config] . identifier[worker_run_as_user] :
identifier[security_context] [ literal[string] ]= identifier[self] ... | def _get_security_context(self):
"""Defines the security context"""
security_context = {}
if self.kube_config.worker_run_as_user:
security_context['runAsUser'] = self.kube_config.worker_run_as_user # depends on [control=['if'], data=[]]
if self.kube_config.worker_fs_group:
security_cont... |
def sendcommand(self, cmd, opt=None):
"Send a telnet command (IAC)"
if cmd in [DO, DONT]:
if not self.DOOPTS.has_key(opt):
self.DOOPTS[opt] = None
if (((cmd == DO) and (self.DOOPTS[opt] != True))
or ((cmd == DONT) and (self.DOOPTS[opt] != False))):
... | def function[sendcommand, parameter[self, cmd, opt]]:
constant[Send a telnet command (IAC)]
if compare[name[cmd] in list[[<ast.Name object at 0x7da20c6e78b0>, <ast.Name object at 0x7da20c6e6110>]]] begin[:]
if <ast.UnaryOp object at 0x7da20c6e7f70> begin[:]
call[n... | keyword[def] identifier[sendcommand] ( identifier[self] , identifier[cmd] , identifier[opt] = keyword[None] ):
literal[string]
keyword[if] identifier[cmd] keyword[in] [ identifier[DO] , identifier[DONT] ]:
keyword[if] keyword[not] identifier[self] . identifier[DOOPTS] . identifier[... | def sendcommand(self, cmd, opt=None):
"""Send a telnet command (IAC)"""
if cmd in [DO, DONT]:
if not self.DOOPTS.has_key(opt):
self.DOOPTS[opt] = None # depends on [control=['if'], data=[]]
if cmd == DO and self.DOOPTS[opt] != True or (cmd == DONT and self.DOOPTS[opt] != False):
... |
def readme():
"""Try to read README.rst or return empty string if failed.
:return: File contents.
:rtype: str
"""
path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'README.rst'))
handle = None
try:
handle = codecs.open(path, encoding='utf-8')
return handle.read... | def function[readme, parameter[]]:
constant[Try to read README.rst or return empty string if failed.
:return: File contents.
:rtype: str
]
variable[path] assign[=] call[name[os].path.realpath, parameter[call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]... | keyword[def] identifier[readme] ():
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), literal[string] ))
identifier[handl... | def readme():
"""Try to read README.rst or return empty string if failed.
:return: File contents.
:rtype: str
"""
path = os.path.realpath(os.path.join(os.path.dirname(__file__), 'README.rst'))
handle = None
try:
handle = codecs.open(path, encoding='utf-8')
return handle.read... |
def add_output_arg(self, out):
""" Add an output as an argument
"""
self.add_arg(out._dax_repr())
self._add_output(out) | def function[add_output_arg, parameter[self, out]]:
constant[ Add an output as an argument
]
call[name[self].add_arg, parameter[call[name[out]._dax_repr, parameter[]]]]
call[name[self]._add_output, parameter[name[out]]] | keyword[def] identifier[add_output_arg] ( identifier[self] , identifier[out] ):
literal[string]
identifier[self] . identifier[add_arg] ( identifier[out] . identifier[_dax_repr] ())
identifier[self] . identifier[_add_output] ( identifier[out] ) | def add_output_arg(self, out):
""" Add an output as an argument
"""
self.add_arg(out._dax_repr())
self._add_output(out) |
def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | def function[list_motors, parameter[name_pattern]]:
constant[
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*'.
keyw... | keyword[def] identifier[list_motors] ( identifier[name_pattern] = identifier[Motor] . identifier[SYSTEM_DEVICE_NAME_CONVENTION] ,** identifier[kwargs] ):
literal[string]
identifier[class_path] = identifier[abspath] ( identifier[Device] . identifier[DEVICE_ROOT_PATH] + literal[string] + identifier[Motor] . ... | def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... |
def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
"""
if typ... | def function[add_option, parameter[self, value, label]]:
constant[Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`... | keyword[def] identifier[add_option] ( identifier[self] , identifier[value] , identifier[label] ):
literal[string]
keyword[if] identifier[type] ( identifier[value] ) keyword[is] identifier[list] :
identifier[warnings] . identifier[warn] ( literal[string] , identifier[DeprecationWarnin... | def add_option(self, value, label):
"""Add an option for the field.
:Parameters:
- `value`: option values.
- `label`: option label (human-readable description).
:Types:
- `value`: `list` of `unicode`
- `label`: `unicode`
"""
if type(value)... |
def is_attribute_valid(attribute_key, attribute_value):
""" Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one o... | def function[is_attribute_valid, parameter[attribute_key, attribute_value]]:
constant[ Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
Fals... | keyword[def] identifier[is_attribute_valid] ( identifier[attribute_key] , identifier[attribute_value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[attribute_key] , identifier[string_types] ):
keyword[return] keyword[False]
keyword[if] identifier[isinstance] ( i... | def is_attribute_valid(attribute_key, attribute_value):
""" Determine if given attribute is valid.
Args:
attribute_key: Variable which needs to be validated
attribute_value: Variable which needs to be validated
Returns:
False if attribute_key is not a string
False if attribute_value is not one... |
def dalignbed2dalignbedqueriesseq(cfg):
"""
Get sequences from BED file
step#6
:param cfg: configuration dict
"""
datatmpd=cfg['datatmpd']
dalignbedqueries=del_Unnamed(pd.read_csv(cfg['dalignbedqueriesp'],sep='\t'))
dalignedfasta=del_Unnamed(pd.read_csv(cfg['dalignedfastap'],sep='\t'))
... | def function[dalignbed2dalignbedqueriesseq, parameter[cfg]]:
constant[
Get sequences from BED file
step#6
:param cfg: configuration dict
]
variable[datatmpd] assign[=] call[name[cfg]][constant[datatmpd]]
variable[dalignbedqueries] assign[=] call[name[del_Unnamed], parameter[call... | keyword[def] identifier[dalignbed2dalignbedqueriesseq] ( identifier[cfg] ):
literal[string]
identifier[datatmpd] = identifier[cfg] [ literal[string] ]
identifier[dalignbedqueries] = identifier[del_Unnamed] ( identifier[pd] . identifier[read_csv] ( identifier[cfg] [ literal[string] ], identifier[sep] =... | def dalignbed2dalignbedqueriesseq(cfg):
"""
Get sequences from BED file
step#6
:param cfg: configuration dict
"""
datatmpd = cfg['datatmpd']
dalignbedqueries = del_Unnamed(pd.read_csv(cfg['dalignbedqueriesp'], sep='\t'))
dalignedfasta = del_Unnamed(pd.read_csv(cfg['dalignedfastap'], sep... |
def conn_handler(self, session: ClientSession, proxy: str = None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param session: AIOHTTP client session instance
:param proxy: Proxy url
:return:
"""
return ConnectionHandler("https", ... | def function[conn_handler, parameter[self, session, proxy]]:
constant[
Return connection handler instance for the endpoint
:param session: AIOHTTP client session instance
:param proxy: Proxy url
:return:
]
return[call[name[ConnectionHandler], parameter[constant[https... | keyword[def] identifier[conn_handler] ( identifier[self] , identifier[session] : identifier[ClientSession] , identifier[proxy] : identifier[str] = keyword[None] )-> identifier[ConnectionHandler] :
literal[string]
keyword[return] identifier[ConnectionHandler] ( literal[string] , literal[string] , i... | def conn_handler(self, session: ClientSession, proxy: str=None) -> ConnectionHandler:
"""
Return connection handler instance for the endpoint
:param session: AIOHTTP client session instance
:param proxy: Proxy url
:return:
"""
return ConnectionHandler('https', 'wss', sel... |
def _parse_pet_record(self, root):
"""
Given a <pet> Element from a pet.get or pet.getRandom response, pluck
out the pet record.
:param lxml.etree._Element root: A <pet> tag Element.
:rtype: dict
:returns: An assembled pet record.
"""
record = {
... | def function[_parse_pet_record, parameter[self, root]]:
constant[
Given a <pet> Element from a pet.get or pet.getRandom response, pluck
out the pet record.
:param lxml.etree._Element root: A <pet> tag Element.
:rtype: dict
:returns: An assembled pet record.
]
... | keyword[def] identifier[_parse_pet_record] ( identifier[self] , identifier[root] ):
literal[string]
identifier[record] ={
literal[string] :[],
literal[string] :[],
literal[string] :[],
literal[string] :{},
}
identifier[straight... | def _parse_pet_record(self, root):
"""
Given a <pet> Element from a pet.get or pet.getRandom response, pluck
out the pet record.
:param lxml.etree._Element root: A <pet> tag Element.
:rtype: dict
:returns: An assembled pet record.
"""
record = {'breeds': [], 'pho... |
def addRnaQuantMetadata(self, fields):
"""
data elements are:
Id, annotations, description, name, readGroupId
where annotations is a comma separated list
"""
self._featureSetIds = fields["feature_set_ids"].split(',')
self._description = fields["description"]
... | def function[addRnaQuantMetadata, parameter[self, fields]]:
constant[
data elements are:
Id, annotations, description, name, readGroupId
where annotations is a comma separated list
]
name[self]._featureSetIds assign[=] call[call[name[fields]][constant[feature_set_ids]].sp... | keyword[def] identifier[addRnaQuantMetadata] ( identifier[self] , identifier[fields] ):
literal[string]
identifier[self] . identifier[_featureSetIds] = identifier[fields] [ literal[string] ]. identifier[split] ( literal[string] )
identifier[self] . identifier[_description] = identifier[fie... | def addRnaQuantMetadata(self, fields):
"""
data elements are:
Id, annotations, description, name, readGroupId
where annotations is a comma separated list
"""
self._featureSetIds = fields['feature_set_ids'].split(',')
self._description = fields['description']
self._name = ... |
def release(self):
""" Release the lock. """
if self.valid():
with self._db_conn() as conn:
affected_rows = conn.query('''
DELETE FROM %s
WHERE id = %%s AND lock_hash = %%s
''' % self._manager.table_name, self._lock_id, ... | def function[release, parameter[self]]:
constant[ Release the lock. ]
if call[name[self].valid, parameter[]] begin[:]
with call[name[self]._db_conn, parameter[]] begin[:]
variable[affected_rows] assign[=] call[name[conn].query, parameter[binary_operation[constant[... | keyword[def] identifier[release] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[valid] ():
keyword[with] identifier[self] . identifier[_db_conn] () keyword[as] identifier[conn] :
identifier[affected_rows] = identifier[conn] . identif... | def release(self):
""" Release the lock. """
if self.valid():
with self._db_conn() as conn:
affected_rows = conn.query('\n DELETE FROM %s\n WHERE id = %%s AND lock_hash = %%s\n ' % self._manager.table_name, self._lock_id, self._lock_hash) ... |
def add_in_filter(self, *values):
"""
Add a filter using "IN" logic. This is typically the primary filter
that will be used to find a match and generally combines other
filters to get more granular. An example of usage would be searching
for an IP address (or addresses) in a spec... | def function[add_in_filter, parameter[self]]:
constant[
Add a filter using "IN" logic. This is typically the primary filter
that will be used to find a match and generally combines other
filters to get more granular. An example of usage would be searching
for an IP address (or ad... | keyword[def] identifier[add_in_filter] ( identifier[self] ,* identifier[values] ):
literal[string]
identifier[filt] = identifier[InFilter] (* identifier[values] )
identifier[self] . identifier[update_filter] ( identifier[filt] )
keyword[return] identifier[filt] | def add_in_filter(self, *values):
"""
Add a filter using "IN" logic. This is typically the primary filter
that will be used to find a match and generally combines other
filters to get more granular. An example of usage would be searching
for an IP address (or addresses) in a specific... |
def georgian_day(date):
""" Returns the number of days passed since the start of the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> georgian_day('05/1/2015')
121
"""
try:
fmt = '%m... | def function[georgian_day, parameter[date]]:
constant[ Returns the number of days passed since the start of the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> georgian_day('05/1/2015')
121
... | keyword[def] identifier[georgian_day] ( identifier[date] ):
literal[string]
keyword[try] :
identifier[fmt] = literal[string]
keyword[return] identifier[datetime] . identifier[strptime] ( identifier[date] , identifier[fmt] ). identifier[timetuple] (). identifier[tm_yday]
keyword[ex... | def georgian_day(date):
""" Returns the number of days passed since the start of the year.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:returns:
int
:example:
>>> georgian_day('05/1/2015')
121
"""
try:
fmt = '%m... |
def get_interesting_members(base_class, cls):
"""Returns a list of methods that can be routed to"""
base_members = dir(base_class)
predicate = inspect.ismethod if _py2 else inspect.isfunction
all_members = inspect.getmembers(cls, predicate=predicate)
return [member for member in all_members
... | def function[get_interesting_members, parameter[base_class, cls]]:
constant[Returns a list of methods that can be routed to]
variable[base_members] assign[=] call[name[dir], parameter[name[base_class]]]
variable[predicate] assign[=] <ast.IfExp object at 0x7da1b209e140>
variable[all_membe... | keyword[def] identifier[get_interesting_members] ( identifier[base_class] , identifier[cls] ):
literal[string]
identifier[base_members] = identifier[dir] ( identifier[base_class] )
identifier[predicate] = identifier[inspect] . identifier[ismethod] keyword[if] identifier[_py2] keyword[else] identi... | def get_interesting_members(base_class, cls):
"""Returns a list of methods that can be routed to"""
base_members = dir(base_class)
predicate = inspect.ismethod if _py2 else inspect.isfunction
all_members = inspect.getmembers(cls, predicate=predicate)
return [member for member in all_members if not m... |
def itemComments(self):
""" returns all comments for a given item """
url = "%s/comments/" % self.root
params = {
"f": "json"
}
return self._get(url,
params,
securityHandler=self._securityHandler,
... | def function[itemComments, parameter[self]]:
constant[ returns all comments for a given item ]
variable[url] assign[=] binary_operation[constant[%s/comments/] <ast.Mod object at 0x7da2590d6920> name[self].root]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b12f1120>], [<as... | keyword[def] identifier[itemComments] ( identifier[self] ):
literal[string]
identifier[url] = literal[string] % identifier[self] . identifier[root]
identifier[params] ={
literal[string] : literal[string]
}
keyword[return] identifier[self] . identifier[_get] ( i... | def itemComments(self):
""" returns all comments for a given item """
url = '%s/comments/' % self.root
params = {'f': 'json'}
return self._get(url, params, securityHandler=self._securityHandler, proxy_port=self._proxy_port, proxy_url=self._proxy_url) |
def create_ipython_exports(self):
"""
.. warning:: this feature is experimental and is currently not enabled by default! Use with caution!
Creates attributes for all classes, methods and fields on the Analysis object itself.
This makes it easier to work with Analysis module in an iPytho... | def function[create_ipython_exports, parameter[self]]:
constant[
.. warning:: this feature is experimental and is currently not enabled by default! Use with caution!
Creates attributes for all classes, methods and fields on the Analysis object itself.
This makes it easier to work with A... | keyword[def] identifier[create_ipython_exports] ( identifier[self] ):
literal[string]
keyword[for] identifier[cls] keyword[in] identifier[self] . identifier[get_classes] ():
identifier[name] = literal[string] + identifier[bytecode] . identifier[FormatClassToPython] ( identi... | def create_ipython_exports(self):
"""
.. warning:: this feature is experimental and is currently not enabled by default! Use with caution!
Creates attributes for all classes, methods and fields on the Analysis object itself.
This makes it easier to work with Analysis module in an iPython sh... |
def getNextRecord(self):
""" Returns combined data from all sources (values only).
:returns: None on EOF; empty sequence on timeout.
"""
# Keep reading from the raw input till we get enough for an aggregated
# record
while True:
# Reached EOF due to lastRow constraint?
if self._... | def function[getNextRecord, parameter[self]]:
constant[ Returns combined data from all sources (values only).
:returns: None on EOF; empty sequence on timeout.
]
while constant[True] begin[:]
if <ast.BoolOp object at 0x7da20c990ee0> begin[:]
variable[preA... | keyword[def] identifier[getNextRecord] ( identifier[self] ):
literal[string]
keyword[while] keyword[True] :
keyword[if] identifier[self] . identifier[_sourceLastRecordIdx] keyword[is] keyword[not] keyword[None] keyword[and] identifier[self] . identifier[_recordStore] . ident... | def getNextRecord(self):
""" Returns combined data from all sources (values only).
:returns: None on EOF; empty sequence on timeout.
"""
# Keep reading from the raw input till we get enough for an aggregated
# record
while True:
# Reached EOF due to lastRow constraint?
if self.... |
def reprkwargs(kwargs, sep=', ', fmt="{0!s}={1!r}"):
"""Display kwargs."""
return sep.join(fmt.format(k, v) for k, v in kwargs.iteritems()) | def function[reprkwargs, parameter[kwargs, sep, fmt]]:
constant[Display kwargs.]
return[call[name[sep].join, parameter[<ast.GeneratorExp object at 0x7da20e957250>]]] | keyword[def] identifier[reprkwargs] ( identifier[kwargs] , identifier[sep] = literal[string] , identifier[fmt] = literal[string] ):
literal[string]
keyword[return] identifier[sep] . identifier[join] ( identifier[fmt] . identifier[format] ( identifier[k] , identifier[v] ) keyword[for] identifier[k] , iden... | def reprkwargs(kwargs, sep=', ', fmt='{0!s}={1!r}'):
"""Display kwargs."""
return sep.join((fmt.format(k, v) for (k, v) in kwargs.iteritems())) |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
# One iteration changes the opinion of several voters using the following procedure:
# - select randomly one voter (sp... | def function[iteration, parameter[self, node_status]]:
constant[
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
]
call[name[self].clean_initial_status, parameter[call[name[self].available_statuses.values, parameter[]]]]
... | keyword[def] identifier[iteration] ( identifier[self] , identifier[node_status] = keyword[True] ):
literal[string]
identifier[self] . identifier[clean_initial_status] ( identifier[self] . identifier[available_statuses] . identifier[values] ())
keyword[... | def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
# One iteration changes the opinion of several voters using the following procedure:
# - select randomly one voter (speaker 1)
... |
def modify_request(self, request):
"""
Apply common path conventions eg. / > /index.html, /foobar > /foobar.html
"""
filename = URL.build(path=request.match_info['filename'], encoded=True).path
raw_path = self._directory.joinpath(filename)
try:
filepath = raw_... | def function[modify_request, parameter[self, request]]:
constant[
Apply common path conventions eg. / > /index.html, /foobar > /foobar.html
]
variable[filename] assign[=] call[name[URL].build, parameter[]].path
variable[raw_path] assign[=] call[name[self]._directory.joinpath, par... | keyword[def] identifier[modify_request] ( identifier[self] , identifier[request] ):
literal[string]
identifier[filename] = identifier[URL] . identifier[build] ( identifier[path] = identifier[request] . identifier[match_info] [ literal[string] ], identifier[encoded] = keyword[True] ). identifier[pat... | def modify_request(self, request):
"""
Apply common path conventions eg. / > /index.html, /foobar > /foobar.html
"""
filename = URL.build(path=request.match_info['filename'], encoded=True).path
raw_path = self._directory.joinpath(filename)
try:
filepath = raw_path.resolve()
... |
def select_line(self):
"""
Select the entire line but starts at the first non whitespace character
and stops at the non-whitespace character.
:return:
"""
self.cursor.movePosition(self.cursor.StartOfBlock)
text = self.cursor.block().text()
lindent = len(te... | def function[select_line, parameter[self]]:
constant[
Select the entire line but starts at the first non whitespace character
and stops at the non-whitespace character.
:return:
]
call[name[self].cursor.movePosition, parameter[name[self].cursor.StartOfBlock]]
vari... | keyword[def] identifier[select_line] ( identifier[self] ):
literal[string]
identifier[self] . identifier[cursor] . identifier[movePosition] ( identifier[self] . identifier[cursor] . identifier[StartOfBlock] )
identifier[text] = identifier[self] . identifier[cursor] . identifier[block] (). ... | def select_line(self):
"""
Select the entire line but starts at the first non whitespace character
and stops at the non-whitespace character.
:return:
"""
self.cursor.movePosition(self.cursor.StartOfBlock)
text = self.cursor.block().text()
lindent = len(text) - len(text.l... |
def parse_transaction_id(self, data):
"return transaction_id"
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data)
t, data = _parse_byte(data)
assert t == TDS_ENVCHANGE_TOKEN
_, data = _parse_int(data, 2) # packet length
e, data = _parse_by... | def function[parse_transaction_id, parameter[self, data]]:
constant[return transaction_id]
if compare[call[name[data]][constant[0]] equal[==] name[TDS_ERROR_TOKEN]] begin[:]
<ast.Raise object at 0x7da20c6c76a0>
<ast.Tuple object at 0x7da20c6c4e80> assign[=] call[name[_parse_byte], parame... | keyword[def] identifier[parse_transaction_id] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[data] [ literal[int] ]== identifier[TDS_ERROR_TOKEN] :
keyword[raise] identifier[self] . identifier[parse_error] ( literal[string] , identifier[data] )
... | def parse_transaction_id(self, data):
"""return transaction_id"""
if data[0] == TDS_ERROR_TOKEN:
raise self.parse_error('begin()', data) # depends on [control=['if'], data=[]]
(t, data) = _parse_byte(data)
assert t == TDS_ENVCHANGE_TOKEN
(_, data) = _parse_int(data, 2) # packet length
... |
def get_host_system_failfast(
self,
name,
verbose=False,
host_system_term='HS'
):
"""
Get a HostSystem object
fail fast if the object isn't a valid reference
"""
if verbose:
print("Finding HostSystem named %s..." % n... | def function[get_host_system_failfast, parameter[self, name, verbose, host_system_term]]:
constant[
Get a HostSystem object
fail fast if the object isn't a valid reference
]
if name[verbose] begin[:]
call[name[print], parameter[binary_operation[constant[Finding Ho... | keyword[def] identifier[get_host_system_failfast] (
identifier[self] ,
identifier[name] ,
identifier[verbose] = keyword[False] ,
identifier[host_system_term] = literal[string]
):
literal[string]
keyword[if] identifier[verbose] :
identifier[print] ( literal[string] % identifier[na... | def get_host_system_failfast(self, name, verbose=False, host_system_term='HS'):
"""
Get a HostSystem object
fail fast if the object isn't a valid reference
"""
if verbose:
print('Finding HostSystem named %s...' % name) # depends on [control=['if'], data=[]]
hs = self.get_hos... |
def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
module_name, attr_name = module_path.split(':', 1)
except ValueError: # noqa
... | def function[_load_module, parameter[self, module_path]]:
constant[Load the module.]
variable[module_path] assign[=] call[name[str], parameter[name[module_path]]]
<ast.Try object at 0x7da1b0e14940>
<ast.Try object at 0x7da1b0e15540>
if <ast.UnaryOp object at 0x7da1b0e153c0> begin[:]
... | keyword[def] identifier[_load_module] ( identifier[self] , identifier[module_path] ):
literal[string]
identifier[module_path] = identifier[str] ( identifier[module_path] )
keyword[try] :
identifier[module_name] , identifier[attr_name] = identifier[module_pat... | def _load_module(self, module_path):
"""Load the module."""
# __import__ will fail on unicode,
# so we ensure module path is a string here.
module_path = str(module_path)
try:
(module_name, attr_name) = module_path.split(':', 1) # depends on [control=['try'], data=[]]
except ValueError:... |
def copy(self, name=None):
"""
shallow copy of the instruction.
Args:
name (str): name to be given to the copied circuit,
if None then the name stays the same
Returns:
Instruction: a shallow copy of the current instruction, with the name
upda... | def function[copy, parameter[self, name]]:
constant[
shallow copy of the instruction.
Args:
name (str): name to be given to the copied circuit,
if None then the name stays the same
Returns:
Instruction: a shallow copy of the current instruction, with the... | keyword[def] identifier[copy] ( identifier[self] , identifier[name] = keyword[None] ):
literal[string]
identifier[cpy] = identifier[copy] . identifier[copy] ( identifier[self] )
keyword[if] identifier[name] :
identifier[cpy] . identifier[name] = identifier[name]
key... | def copy(self, name=None):
"""
shallow copy of the instruction.
Args:
name (str): name to be given to the copied circuit,
if None then the name stays the same
Returns:
Instruction: a shallow copy of the current instruction, with the name
updated ... |
def readme():
"""Live reload readme"""
from livereload import Server
server = Server()
server.watch("README.rst", "py cute.py readme_build")
server.serve(open_url_delay=1, root="build/readme") | def function[readme, parameter[]]:
constant[Live reload readme]
from relative_module[livereload] import module[Server]
variable[server] assign[=] call[name[Server], parameter[]]
call[name[server].watch, parameter[constant[README.rst], constant[py cute.py readme_build]]]
call[name[ser... | keyword[def] identifier[readme] ():
literal[string]
keyword[from] identifier[livereload] keyword[import] identifier[Server]
identifier[server] = identifier[Server] ()
identifier[server] . identifier[watch] ( literal[string] , literal[string] )
identifier[server] . identifier[serve] ( identifier[open_ur... | def readme():
"""Live reload readme"""
from livereload import Server
server = Server()
server.watch('README.rst', 'py cute.py readme_build')
server.serve(open_url_delay=1, root='build/readme') |
def load_default_tc_plugins(self):
"""
Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins.
:return: Nothing
"""
for plugin_name, plugin_class in default_plugins.items():
if issubclass(plugin_class, PluginBase):
try:
... | def function[load_default_tc_plugins, parameter[self]]:
constant[
Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins.
:return: Nothing
]
for taget[tuple[[<ast.Name object at 0x7da1b0ebe2f0>, <ast.Name object at 0x7da1b0ebc460>]]] in starred[call[... | keyword[def] identifier[load_default_tc_plugins] ( identifier[self] ):
literal[string]
keyword[for] identifier[plugin_name] , identifier[plugin_class] keyword[in] identifier[default_plugins] . identifier[items] ():
keyword[if] identifier[issubclass] ( identifier[plugin_class] , ide... | def load_default_tc_plugins(self):
"""
Load default test case level plugins from icetea_lib.Plugin.plugins.default_plugins.
:return: Nothing
"""
for (plugin_name, plugin_class) in default_plugins.items():
if issubclass(plugin_class, PluginBase):
try:
... |
def get_mem_total(self):
"""Calculate the total memory in the current service unit."""
with open('/proc/meminfo') as meminfo_file:
for line in meminfo_file:
key, mem = line.split(':', 2)
if key == 'MemTotal':
mtot, modifier = mem.strip().sp... | def function[get_mem_total, parameter[self]]:
constant[Calculate the total memory in the current service unit.]
with call[name[open], parameter[constant[/proc/meminfo]]] begin[:]
for taget[name[line]] in starred[name[meminfo_file]] begin[:]
<ast.Tuple object at 0x... | keyword[def] identifier[get_mem_total] ( identifier[self] ):
literal[string]
keyword[with] identifier[open] ( literal[string] ) keyword[as] identifier[meminfo_file] :
keyword[for] identifier[line] keyword[in] identifier[meminfo_file] :
identifier[key] , identifier... | def get_mem_total(self):
"""Calculate the total memory in the current service unit."""
with open('/proc/meminfo') as meminfo_file:
for line in meminfo_file:
(key, mem) = line.split(':', 2)
if key == 'MemTotal':
(mtot, modifier) = mem.strip().split(' ')
... |
def delete_resource(self, resource_id):
"""Link a resource to an individual."""
resource_obj = self.resource(resource_id)
logger.debug("Deleting resource {0}".format(resource_obj.name))
self.session.delete(resource_obj)
self.save() | def function[delete_resource, parameter[self, resource_id]]:
constant[Link a resource to an individual.]
variable[resource_obj] assign[=] call[name[self].resource, parameter[name[resource_id]]]
call[name[logger].debug, parameter[call[constant[Deleting resource {0}].format, parameter[name[resourc... | keyword[def] identifier[delete_resource] ( identifier[self] , identifier[resource_id] ):
literal[string]
identifier[resource_obj] = identifier[self] . identifier[resource] ( identifier[resource_id] )
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier... | def delete_resource(self, resource_id):
"""Link a resource to an individual."""
resource_obj = self.resource(resource_id)
logger.debug('Deleting resource {0}'.format(resource_obj.name))
self.session.delete(resource_obj)
self.save() |
def MapParamNames(params, request_type):
"""Reverse parameter remappings for URL construction."""
return [encoding.GetCustomJsonFieldMapping(request_type, json_name=p) or p
for p in params] | def function[MapParamNames, parameter[params, request_type]]:
constant[Reverse parameter remappings for URL construction.]
return[<ast.ListComp object at 0x7da1b0718c40>] | keyword[def] identifier[MapParamNames] ( identifier[params] , identifier[request_type] ):
literal[string]
keyword[return] [ identifier[encoding] . identifier[GetCustomJsonFieldMapping] ( identifier[request_type] , identifier[json_name] = identifier[p] ) keyword[or] identifier[p]
keyword[for] identi... | def MapParamNames(params, request_type):
"""Reverse parameter remappings for URL construction."""
return [encoding.GetCustomJsonFieldMapping(request_type, json_name=p) or p for p in params] |
def tree(node, formatter=None, prefix=None, postfix=None, _depth=1):
"""Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict` objects for su... | def function[tree, parameter[node, formatter, prefix, postfix, _depth]]:
constant[Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict... | keyword[def] identifier[tree] ( identifier[node] , identifier[formatter] = keyword[None] , identifier[prefix] = keyword[None] , identifier[postfix] = keyword[None] , identifier[_depth] = literal[int] ):
literal[string]
identifier[current] = literal[int]
identifier[length] = identifier[len] ( identifier[nod... | def tree(node, formatter=None, prefix=None, postfix=None, _depth=1):
"""Print a tree.
Sometimes it's useful to print datastructures as a tree. This function prints
out a pretty tree with root `node`. A tree is represented as a :class:`dict`,
whose keys are node names and values are :class:`dict` objects for ... |
def create_form_data(self, **kwargs):
"""Create groupings of form elements."""
# Get the specified keyword arguments.
children = kwargs.get('children', [])
sort_order = kwargs.get('sort_order', None)
solr_response = kwargs.get('solr_response', None)
superuser = kwargs.get... | def function[create_form_data, parameter[self]]:
constant[Create groupings of form elements.]
variable[children] assign[=] call[name[kwargs].get, parameter[constant[children], list[[]]]]
variable[sort_order] assign[=] call[name[kwargs].get, parameter[constant[sort_order], constant[None]]]
... | keyword[def] identifier[create_form_data] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[children] = identifier[kwargs] . identifier[get] ( literal[string] ,[])
identifier[sort_order] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None]... | def create_form_data(self, **kwargs):
"""Create groupings of form elements."""
# Get the specified keyword arguments.
children = kwargs.get('children', [])
sort_order = kwargs.get('sort_order', None)
solr_response = kwargs.get('solr_response', None)
superuser = kwargs.get('superuser', False)
... |
def dry_run_scan(self, scan_id, targets):
""" Dry runs a scan. """
os.setsid()
for _, target in enumerate(targets):
host = resolve_hostname(target[0])
if host is None:
logger.info("Couldn't resolve %s.", target[0])
continue
por... | def function[dry_run_scan, parameter[self, scan_id, targets]]:
constant[ Dry runs a scan. ]
call[name[os].setsid, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da20c76e8f0>, <ast.Name object at 0x7da20c76c490>]]] in starred[call[name[enumerate], parameter[name[targets]]]] begin[:]
... | keyword[def] identifier[dry_run_scan] ( identifier[self] , identifier[scan_id] , identifier[targets] ):
literal[string]
identifier[os] . identifier[setsid] ()
keyword[for] identifier[_] , identifier[target] keyword[in] identifier[enumerate] ( identifier[targets] ):
identif... | def dry_run_scan(self, scan_id, targets):
""" Dry runs a scan. """
os.setsid()
for (_, target) in enumerate(targets):
host = resolve_hostname(target[0])
if host is None:
logger.info("Couldn't resolve %s.", target[0])
continue # depends on [control=['if'], data=[]]
... |
def set_mac_addr(self, mac_addr):
"""
Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
"""
yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform,
... | def function[set_mac_addr, parameter[self, mac_addr]]:
constant[
Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
]
<ast.YieldFrom object at 0x7da20c991b70>
call[name[log].info, parameter[call[constant[Router "{name}" [{id}]: M... | keyword[def] identifier[set_mac_addr] ( identifier[self] , identifier[mac_addr] ):
literal[string]
keyword[yield] keyword[from] identifier[self] . identifier[_hypervisor] . identifier[send] ( literal[string] . identifier[format] ( identifier[platform] = identifier[self] . identifier[_platform] ,... | def set_mac_addr(self, mac_addr):
"""
Sets the MAC address.
:param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh)
"""
yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform, name=self._name, mac_addr=mac_addr))
... |
def new_credentials():
"""Generate a new identifier and seed for authentication.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
"""
identifier = binascii.b2a_hex(os.urandom(8... | def function[new_credentials, parameter[]]:
constant[Generate a new identifier and seed for authentication.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
]
variable[... | keyword[def] identifier[new_credentials] ():
literal[string]
identifier[identifier] = identifier[binascii] . identifier[b2a_hex] ( identifier[os] . identifier[urandom] ( literal[int] )). identifier[decode] (). identifier[upper] ()
identifier[seed] = identifier[binascii] . identifier[b2a_hex] ( identif... | def new_credentials():
"""Generate a new identifier and seed for authentication.
Use the returned values in the following way:
* The identifier shall be passed as username to SRPAuthHandler.step1
* Seed shall be passed to SRPAuthHandler constructor
"""
identifier = binascii.b2a_hex(os.urandom(8... |
def domain_name_left_cuts(domain):
'''returns a list of strings created by splitting the domain on
'.' and successively cutting off the left most portion
'''
cuts = []
if domain:
parts = domain.split('.')
for i in range(len(parts)):
cuts.append( '.'.join(parts[i:]))
r... | def function[domain_name_left_cuts, parameter[domain]]:
constant[returns a list of strings created by splitting the domain on
'.' and successively cutting off the left most portion
]
variable[cuts] assign[=] list[[]]
if name[domain] begin[:]
variable[parts] assign[=] call... | keyword[def] identifier[domain_name_left_cuts] ( identifier[domain] ):
literal[string]
identifier[cuts] =[]
keyword[if] identifier[domain] :
identifier[parts] = identifier[domain] . identifier[split] ( literal[string] )
keyword[for] identifier[i] keyword[in] identifier[range] ( i... | def domain_name_left_cuts(domain):
"""returns a list of strings created by splitting the domain on
'.' and successively cutting off the left most portion
"""
cuts = []
if domain:
parts = domain.split('.')
for i in range(len(parts)):
cuts.append('.'.join(parts[i:])) # dep... |
def inner_contains(self, time_point):
"""
Returns ``True`` if this interval contains the given time point,
excluding its extrema (begin and end).
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:rtype: bool
"""
... | def function[inner_contains, parameter[self, time_point]]:
constant[
Returns ``True`` if this interval contains the given time point,
excluding its extrema (begin and end).
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
... | keyword[def] identifier[inner_contains] ( identifier[self] , identifier[time_point] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[time_point] , identifier[TimeValue] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[return... | def inner_contains(self, time_point):
"""
Returns ``True`` if this interval contains the given time point,
excluding its extrema (begin and end).
:param time_point: the time point to test
:type time_point: :class:`~aeneas.exacttiming.TimeValue`
:rtype: bool
"""
... |
def parse_headerline(self, line):
#Process incoming header line
"""11/03/2014 14:46:46
PANalytical
Results quantitative - Omnian 2013,
Selected archive:,Omnian 2013
Number of results selected:,4
"""
# Save each header field (that we know) and its... | def function[parse_headerline, parameter[self, line]]:
constant[11/03/2014 14:46:46
PANalytical
Results quantitative - Omnian 2013,
Selected archive:,Omnian 2013
Number of results selected:,4
]
if call[name[line].startswith, parameter[constant[Results quantitativ... | keyword[def] identifier[parse_headerline] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] identifier[line] . identifier[startswith] ( literal[string] ):
identifier[line] = identifier[to_unicode] ( identifier[line] )
keyword[if] identifier[... | def parse_headerline(self, line):
#Process incoming header line
'11/03/2014 14:46:46\n PANalytical\n Results quantitative - Omnian 2013,\n\n Selected archive:,Omnian 2013\n Number of results selected:,4\n ' # Save each header field (that we know) and its own value in the dict... |
def iteritems(self):
"""
Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping)
"""
for m in self.mappings:
yield self.indexes[m.clause][m.target], m | def function[iteritems, parameter[self]]:
constant[
Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping)
]
for taget[name[m]] in starred[name[self].mappings] begin[:]
<ast.Yield object at 0x7da1b0b3485... | keyword[def] identifier[iteritems] ( identifier[self] ):
literal[string]
keyword[for] identifier[m] keyword[in] identifier[self] . identifier[mappings] :
keyword[yield] identifier[self] . identifier[indexes] [ identifier[m] . identifier[clause] ][ identifier[m] . identifier[target]... | def iteritems(self):
"""
Iterates over all mappings
Yields
------
(int,Mapping)
The next pair (index, mapping)
"""
for m in self.mappings:
yield (self.indexes[m.clause][m.target], m) # depends on [control=['for'], data=['m']] |
def _call_vecfield_p(self, vf, out):
"""Implement ``self(vf, out)`` for exponent 1 < p < ``inf``."""
# Optimization for 1 component - just absolute value (maybe weighted)
if len(self.domain) == 1:
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out *= ... | def function[_call_vecfield_p, parameter[self, vf, out]]:
constant[Implement ``self(vf, out)`` for exponent 1 < p < ``inf``.]
if compare[call[name[len], parameter[name[self].domain]] equal[==] constant[1]] begin[:]
call[call[name[vf]][constant[0]].ufuncs.absolute, parameter[]]
... | keyword[def] identifier[_call_vecfield_p] ( identifier[self] , identifier[vf] , identifier[out] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[domain] )== literal[int] :
identifier[vf] [ literal[int] ]. identifier[ufuncs] . identifier[absolute]... | def _call_vecfield_p(self, vf, out):
"""Implement ``self(vf, out)`` for exponent 1 < p < ``inf``."""
# Optimization for 1 component - just absolute value (maybe weighted)
if len(self.domain) == 1:
vf[0].ufuncs.absolute(out=out)
if self.is_weighted:
out *= self.weights[0] ** (1 / ... |
def get_vnetwork_portgroups_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, "... | def function[get_vnetwork_portgroups_input_last_rcvd_instance, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_portgroups] assign[=] call[name[ET].Element, parameter[constant[get_vnetwor... | keyword[def] identifier[get_vnetwork_portgroups_input_last_rcvd_instance] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_portgroups] = identifier[ET] . identifier[Element] ( ... | def get_vnetwork_portgroups_input_last_rcvd_instance(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_portgroups = ET.Element('get_vnetwork_portgroups')
config = get_vnetwork_portgroups
input = ET.SubElement(get_vnetwork_portgroups, 'input')
last_rcv... |
def validate_bot_config(config_bundle) -> None:
"""
Checks the config bundle to see whether it has all required attributes.
"""
if not config_bundle.name:
bot_config = os.path.join(config_bundle.config_directory, config_bundle.config_file_name or '')
raise AttributeError(f"Bot config {bo... | def function[validate_bot_config, parameter[config_bundle]]:
constant[
Checks the config bundle to see whether it has all required attributes.
]
if <ast.UnaryOp object at 0x7da2044c3f70> begin[:]
variable[bot_config] assign[=] call[name[os].path.join, parameter[name[config_bundle... | keyword[def] identifier[validate_bot_config] ( identifier[config_bundle] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[config_bundle] . identifier[name] :
identifier[bot_config] = identifier[os] . identifier[path] . identifier[join] ( identifier[config_bundle] . identif... | def validate_bot_config(config_bundle) -> None:
"""
Checks the config bundle to see whether it has all required attributes.
"""
if not config_bundle.name:
bot_config = os.path.join(config_bundle.config_directory, config_bundle.config_file_name or '')
raise AttributeError(f'Bot config {bo... |
def create_sheet(self):
'''
create an editable grid showing demag_orient.txt
'''
#--------------------------------
# orient.txt supports many other headers
# but we will only initialize with
# the essential headers for
# sample orientation and headers pres... | def function[create_sheet, parameter[self]]:
constant[
create an editable grid showing demag_orient.txt
]
variable[samples_list] assign[=] call[name[list], parameter[call[name[self].orient_data.keys, parameter[]]]]
call[name[samples_list].sort, parameter[]]
name[self].sam... | keyword[def] identifier[create_sheet] ( identifier[self] ):
literal[string]
identifier[samples_list] = identifier[list] ( identifier[self] . identifier[orient_data] . identifier[keys] ())
identifie... | def create_sheet(self):
"""
create an editable grid showing demag_orient.txt
"""
#--------------------------------
# orient.txt supports many other headers
# but we will only initialize with
# the essential headers for
# sample orientation and headers present
# in existing de... |
def formatex(ex, msg='[!?] Caught exception',
prefix=None, key_list=[], locals_=None, iswarning=False, tb=False,
N=0, keys=None, colored=None):
r"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to displa... | def function[formatex, parameter[ex, msg, prefix, key_list, locals_, iswarning, tb, N, keys, colored]]:
constant[
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'[!?] Caught exception')
... | keyword[def] identifier[formatex] ( identifier[ex] , identifier[msg] = literal[string] ,
identifier[prefix] = keyword[None] , identifier[key_list] =[], identifier[locals_] = keyword[None] , identifier[iswarning] = keyword[False] , identifier[tb] = keyword[False] ,
identifier[N] = literal[int] , identifier[keys] = k... | def formatex(ex, msg='[!?] Caught exception', prefix=None, key_list=[], locals_=None, iswarning=False, tb=False, N=0, keys=None, colored=None):
"""
Formats an exception with relevant info
Args:
ex (Exception): exception to print
msg (unicode): a message to display to the user (default = u'... |
def zip_and_upload(app_dir, bucket, key, session=None):
"""Zip built static site and upload to S3."""
if session:
s3_client = session.client('s3')
else:
s3_client = boto3.client('s3')
transfer = S3Transfer(s3_client)
filedes, temp_file = tempfile.mkstemp()
os.close(filedes)
... | def function[zip_and_upload, parameter[app_dir, bucket, key, session]]:
constant[Zip built static site and upload to S3.]
if name[session] begin[:]
variable[s3_client] assign[=] call[name[session].client, parameter[constant[s3]]]
variable[transfer] assign[=] call[name[S3Transfer]... | keyword[def] identifier[zip_and_upload] ( identifier[app_dir] , identifier[bucket] , identifier[key] , identifier[session] = keyword[None] ):
literal[string]
keyword[if] identifier[session] :
identifier[s3_client] = identifier[session] . identifier[client] ( literal[string] )
keyword[else] :... | def zip_and_upload(app_dir, bucket, key, session=None):
"""Zip built static site and upload to S3."""
if session:
s3_client = session.client('s3') # depends on [control=['if'], data=[]]
else:
s3_client = boto3.client('s3')
transfer = S3Transfer(s3_client)
(filedes, temp_file) = temp... |
def get_psf_scalar(x, y, z, kfki=1., zint=100.0, normalize=False, **kwargs):
"""
Calculates a scalar (non-vectorial light) approximation to a confocal PSF
The calculation is approximate, since it ignores the effects of
polarization and apodization, but should be ~3x faster.
Parameters
--------... | def function[get_psf_scalar, parameter[x, y, z, kfki, zint, normalize]]:
constant[
Calculates a scalar (non-vectorial light) approximation to a confocal PSF
The calculation is approximate, since it ignores the effects of
polarization and apodization, but should be ~3x faster.
Parameters
--... | keyword[def] identifier[get_psf_scalar] ( identifier[x] , identifier[y] , identifier[z] , identifier[kfki] = literal[int] , identifier[zint] = literal[int] , identifier[normalize] = keyword[False] ,** identifier[kwargs] ):
literal[string]
identifier[rho] = identifier[np] . identifier[sqrt] ( identifier[x]... | def get_psf_scalar(x, y, z, kfki=1.0, zint=100.0, normalize=False, **kwargs):
"""
Calculates a scalar (non-vectorial light) approximation to a confocal PSF
The calculation is approximate, since it ignores the effects of
polarization and apodization, but should be ~3x faster.
Parameters
-------... |
def load_nietzsche_dataset(path='data'):
"""Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
... | def function[load_nietzsche_dataset, parameter[path]]:
constant[Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tu... | keyword[def] identifier[load_nietzsche_dataset] ( identifier[path] = literal[string] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[path] ))
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[path] , liter... | def load_nietzsche_dataset(path='data'):
"""Load Nietzsche dataset.
Parameters
----------
path : str
The path that the data is downloaded to, defaults is ``data/nietzsche/``.
Returns
--------
str
The content.
Examples
--------
>>> see tutorial_generate_text.py
... |
def keyReleaseEvent(self, event):
"""
Overrides keyReleaseEvent to emit the key_released signal.
:param event: QKeyEvent
"""
if self.isReadOnly():
return
initial_state = event.isAccepted()
event.ignore()
self.key_released.emit(event)
i... | def function[keyReleaseEvent, parameter[self, event]]:
constant[
Overrides keyReleaseEvent to emit the key_released signal.
:param event: QKeyEvent
]
if call[name[self].isReadOnly, parameter[]] begin[:]
return[None]
variable[initial_state] assign[=] call[name[eve... | keyword[def] identifier[keyReleaseEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[isReadOnly] ():
keyword[return]
identifier[initial_state] = identifier[event] . identifier[isAccepted] ()
identifier[event] .... | def keyReleaseEvent(self, event):
"""
Overrides keyReleaseEvent to emit the key_released signal.
:param event: QKeyEvent
"""
if self.isReadOnly():
return # depends on [control=['if'], data=[]]
initial_state = event.isAccepted()
event.ignore()
self.key_released.emit(... |
def AddAC(self, device_name, model_name):
'''Convenience method to add an AC object
You have to specify a device name which must be a valid part of an object
path, e. g. "mock_ac", and an arbitrary model name.
Please note that this does not set any global properties such as
"on-battery".
Retu... | def function[AddAC, parameter[self, device_name, model_name]]:
constant[Convenience method to add an AC object
You have to specify a device name which must be a valid part of an object
path, e. g. "mock_ac", and an arbitrary model name.
Please note that this does not set any global properties such... | keyword[def] identifier[AddAC] ( identifier[self] , identifier[device_name] , identifier[model_name] ):
literal[string]
identifier[path] = literal[string] + identifier[device_name]
identifier[self] . identifier[AddObject] ( identifier[path] ,
identifier[DEVICE_IFACE] ,
{
literal[string]... | def AddAC(self, device_name, model_name):
"""Convenience method to add an AC object
You have to specify a device name which must be a valid part of an object
path, e. g. "mock_ac", and an arbitrary model name.
Please note that this does not set any global properties such as
"on-battery".
Retu... |
def configs(self):
"""Returns a map of run paths to `ProjectorConfig` protos."""
run_path_pairs = list(self.run_paths.items())
self._append_plugin_asset_directories(run_path_pairs)
# If there are no summary event files, the projector should still work,
# treating the `logdir` as the model checkpoint... | def function[configs, parameter[self]]:
constant[Returns a map of run paths to `ProjectorConfig` protos.]
variable[run_path_pairs] assign[=] call[name[list], parameter[call[name[self].run_paths.items, parameter[]]]]
call[name[self]._append_plugin_asset_directories, parameter[name[run_path_pairs]... | keyword[def] identifier[configs] ( identifier[self] ):
literal[string]
identifier[run_path_pairs] = identifier[list] ( identifier[self] . identifier[run_paths] . identifier[items] ())
identifier[self] . identifier[_append_plugin_asset_directories] ( identifier[run_path_pairs] )
keyword[... | def configs(self):
"""Returns a map of run paths to `ProjectorConfig` protos."""
run_path_pairs = list(self.run_paths.items())
self._append_plugin_asset_directories(run_path_pairs)
# If there are no summary event files, the projector should still work,
# treating the `logdir` as the model checkpoint... |
def unload_module(modname):
"""
WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK
References:
http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
CommandLine:
python -m utool.util_cplat --test-unload_module
Example:
>>> # DISABLE_DOCTEST
>... | def function[unload_module, parameter[modname]]:
constant[
WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK
References:
http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
CommandLine:
python -m utool.util_cplat --test-unload_module
Example:
... | keyword[def] identifier[unload_module] ( identifier[modname] ):
literal[string]
keyword[import] identifier[sys]
keyword[import] identifier[gc]
keyword[if] identifier[modname] keyword[in] identifier[sys] . identifier[modules] :
identifier[referrer_list] = identifier[gc] . identifie... | def unload_module(modname):
"""
WARNING POTENTIALLY DANGEROUS AND MAY NOT WORK
References:
http://stackoverflow.com/questions/437589/how-do-i-unload-reload-a-python-module
CommandLine:
python -m utool.util_cplat --test-unload_module
Example:
>>> # DISABLE_DOCTEST
>... |
def save(self, where=None, fetch_when_save=None):
"""
将对象数据保存至服务器
:return: None
:rtype: None
"""
if where and not isinstance(where, leancloud.Query):
raise TypeError('where param type should be leancloud.Query, got %s', type(where))
if where and wher... | def function[save, parameter[self, where, fetch_when_save]]:
constant[
将对象数据保存至服务器
:return: None
:rtype: None
]
if <ast.BoolOp object at 0x7da1b0c66050> begin[:]
<ast.Raise object at 0x7da1b0c65d50>
if <ast.BoolOp object at 0x7da1b0c65a20> begin[:]
... | keyword[def] identifier[save] ( identifier[self] , identifier[where] = keyword[None] , identifier[fetch_when_save] = keyword[None] ):
literal[string]
keyword[if] identifier[where] keyword[and] keyword[not] identifier[isinstance] ( identifier[where] , identifier[leancloud] . identifier[Query] ):... | def save(self, where=None, fetch_when_save=None):
"""
将对象数据保存至服务器
:return: None
:rtype: None
"""
if where and (not isinstance(where, leancloud.Query)):
raise TypeError('where param type should be leancloud.Query, got %s', type(where)) # depends on [control=['if'], data=... |
def DAS(cpu):
"""
Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
the CF and AF flags are set accor... | def function[DAS, parameter[cpu]]:
constant[
Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
the CF... | keyword[def] identifier[DAS] ( identifier[cpu] ):
literal[string]
identifier[oldAL] = identifier[cpu] . identifier[AL]
identifier[oldCF] = identifier[cpu] . identifier[CF]
identifier[cpu] . identifier[AF] = identifier[Operators] . identifier[OR] (( identifier[cpu] . identifier[... | def DAS(cpu):
"""
Decimal adjusts AL after subtraction.
Adjusts the result of the subtraction of two packed BCD values to create a packed BCD result.
The AL register is the implied source and destination operand. If a decimal borrow is detected,
the CF and AF flags are set according... |
def mechanism_indices(self, direction):
"""The indices of nodes in the mechanism system."""
return {
Direction.CAUSE: self.effect_indices,
Direction.EFFECT: self.cause_indices
}[direction] | def function[mechanism_indices, parameter[self, direction]]:
constant[The indices of nodes in the mechanism system.]
return[call[dictionary[[<ast.Attribute object at 0x7da20cabfe20>, <ast.Attribute object at 0x7da20cabc7c0>], [<ast.Attribute object at 0x7da20cabcb50>, <ast.Attribute object at 0x7da20cabcee0... | keyword[def] identifier[mechanism_indices] ( identifier[self] , identifier[direction] ):
literal[string]
keyword[return] {
identifier[Direction] . identifier[CAUSE] : identifier[self] . identifier[effect_indices] ,
identifier[Direction] . identifier[EFFECT] : identifier[self] . id... | def mechanism_indices(self, direction):
"""The indices of nodes in the mechanism system."""
return {Direction.CAUSE: self.effect_indices, Direction.EFFECT: self.cause_indices}[direction] |
def last_component_continued(self):
# type: () -> bool
'''
Determines whether the previous component of this SL record is a
continued one or not.
Parameters:
None.
Returns:
True if the previous component of this SL record is continued, False otherwise.
... | def function[last_component_continued, parameter[self]]:
constant[
Determines whether the previous component of this SL record is a
continued one or not.
Parameters:
None.
Returns:
True if the previous component of this SL record is continued, False otherwise.
... | keyword[def] identifier[last_component_continued] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] )
keyword[if] k... | def last_component_continued(self):
# type: () -> bool
'\n Determines whether the previous component of this SL record is a\n continued one or not.\n\n Parameters:\n None.\n Returns:\n True if the previous component of this SL record is continued, False otherwise.\n ... |
def confusion_performance(mat, fn):
"""Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function
"""
if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2):
raise TypeError('{} is not a confusion ... | def function[confusion_performance, parameter[mat, fn]]:
constant[Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function
]
if <ast.BoolOp object at 0x7da1b28c7a30> begin[:]
<ast.Raise ... | keyword[def] identifier[confusion_performance] ( identifier[mat] , identifier[fn] ):
literal[string]
keyword[if] identifier[mat] . identifier[shape] [ literal[int] ]!= identifier[mat] . identifier[shape] [ literal[int] ] keyword[or] identifier[mat] . identifier[shape] <( literal[int] , literal[int] ):
... | def confusion_performance(mat, fn):
"""Apply a performance function to a confusion matrix
:param mat: confusion matrix
:type mat: square matrix
:param function fn: performance function
"""
if mat.shape[0] != mat.shape[1] or mat.shape < (2, 2):
raise TypeError('{} is not a confusion ... |
def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10
self.current_line = ... | def function[line, parameter[self, sentences, line_number]]:
constant[ Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
]
if compare[name[line_number] is constant[None]] begin[:]
variable... | keyword[def] identifier[line] ( identifier[self] , identifier[sentences] , identifier[line_number] = keyword[None] ):
literal[string]
keyword[if] identifier[line_number] keyword[is] keyword[None] :
identifier[line_number] = identifier[self] . identifier[current_line] + literal[int] ... | def line(self, sentences, line_number=None):
""" Return the bytes for a basic line.
If no line number is given, current one + 10 will be used
Sentences if a list of sentences
"""
if line_number is None:
line_number = self.current_line + 10 # depends on [control=['if'], data=['li... |
def depth_first_iter(self, self_first=True):
"""
Iterate over nodes below this node, optionally yielding children before
self.
"""
if self_first:
yield self
for child in list(self.children):
for i in child.depth_first_iter(self_first):
... | def function[depth_first_iter, parameter[self, self_first]]:
constant[
Iterate over nodes below this node, optionally yielding children before
self.
]
if name[self_first] begin[:]
<ast.Yield object at 0x7da1b198d2a0>
for taget[name[child]] in starred[call[... | keyword[def] identifier[depth_first_iter] ( identifier[self] , identifier[self_first] = keyword[True] ):
literal[string]
keyword[if] identifier[self_first] :
keyword[yield] identifier[self]
keyword[for] identifier[child] keyword[in] identifier[list] ( identifier[self] . ... | def depth_first_iter(self, self_first=True):
"""
Iterate over nodes below this node, optionally yielding children before
self.
"""
if self_first:
yield self # depends on [control=['if'], data=[]]
for child in list(self.children):
for i in child.depth_first_iter(self_... |
def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" builtin function
"""
if getattr(node, "name", None) == "super" and node.root().name == BUILTINS_NAME:
return True
return False | def function[is_super, parameter[node]]:
constant[return True if the node is referencing the "super" builtin function
]
if <ast.BoolOp object at 0x7da1b020d420> begin[:]
return[constant[True]]
return[constant[False]] | keyword[def] identifier[is_super] ( identifier[node] : identifier[astroid] . identifier[node_classes] . identifier[NodeNG] )-> identifier[bool] :
literal[string]
keyword[if] identifier[getattr] ( identifier[node] , literal[string] , keyword[None] )== literal[string] keyword[and] identifier[node] . ident... | def is_super(node: astroid.node_classes.NodeNG) -> bool:
"""return True if the node is referencing the "super" builtin function
"""
if getattr(node, 'name', None) == 'super' and node.root().name == BUILTINS_NAME:
return True # depends on [control=['if'], data=[]]
return False |
def dtypes(self):
"""Gives a Pandas series object containing all numpy dtypes of all columns (except hidden)."""
from pandas import Series
return Series({column_name:self.dtype(column_name) for column_name in self.get_column_names()}) | def function[dtypes, parameter[self]]:
constant[Gives a Pandas series object containing all numpy dtypes of all columns (except hidden).]
from relative_module[pandas] import module[Series]
return[call[name[Series], parameter[<ast.DictComp object at 0x7da18ede5360>]]] | keyword[def] identifier[dtypes] ( identifier[self] ):
literal[string]
keyword[from] identifier[pandas] keyword[import] identifier[Series]
keyword[return] identifier[Series] ({ identifier[column_name] : identifier[self] . identifier[dtype] ( identifier[column_name] ) keyword[for] iden... | def dtypes(self):
"""Gives a Pandas series object containing all numpy dtypes of all columns (except hidden)."""
from pandas import Series
return Series({column_name: self.dtype(column_name) for column_name in self.get_column_names()}) |
def feed_numpy(batch_size, *arrays):
"""Given a set of numpy arrays, produce slices of batch_size.
Note: You can use itertools.cycle to have this repeat forever.
Args:
batch_size: The batch_size for each array.
*arrays: A list of arrays.
Yields:
A list of slices from the arrays of length batch_siz... | def function[feed_numpy, parameter[batch_size]]:
constant[Given a set of numpy arrays, produce slices of batch_size.
Note: You can use itertools.cycle to have this repeat forever.
Args:
batch_size: The batch_size for each array.
*arrays: A list of arrays.
Yields:
A list of slices from the ar... | keyword[def] identifier[feed_numpy] ( identifier[batch_size] ,* identifier[arrays] ):
literal[string]
keyword[if] keyword[not] identifier[arrays] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[size] = identifier[len] ( identifier[arrays] [ literal[int] ])
keyword[for] ide... | def feed_numpy(batch_size, *arrays):
"""Given a set of numpy arrays, produce slices of batch_size.
Note: You can use itertools.cycle to have this repeat forever.
Args:
batch_size: The batch_size for each array.
*arrays: A list of arrays.
Yields:
A list of slices from the arrays of length batch_s... |
def add_vip(
self,
id,
real_name_sufixo,
id_vlan,
descricao_vlan,
id_vlan_real,
descricao_vlan_real,
balanceadores,
id_healthcheck_expect,
finalidade,
cliente,
ambiente,
... | def function[add_vip, parameter[self, id, real_name_sufixo, id_vlan, descricao_vlan, id_vlan_real, descricao_vlan_real, balanceadores, id_healthcheck_expect, finalidade, cliente, ambiente, cache, metodo_bal, persistencia, healthcheck_type, healthcheck, timeout, host, maxcon, dsr, bal_ativo, transbordos, portas, real_ma... | keyword[def] identifier[add_vip] (
identifier[self] ,
identifier[id] ,
identifier[real_name_sufixo] ,
identifier[id_vlan] ,
identifier[descricao_vlan] ,
identifier[id_vlan_real] ,
identifier[descricao_vlan_real] ,
identifier[balanceadores] ,
identifier[id_healthcheck_expect] ,
identifier[finalidade] ,
iden... | def add_vip(self, id, real_name_sufixo, id_vlan, descricao_vlan, id_vlan_real, descricao_vlan_real, balanceadores, id_healthcheck_expect, finalidade, cliente, ambiente, cache, metodo_bal, persistencia, healthcheck_type, healthcheck, timeout, host, maxcon, dsr, bal_ativo, transbordos, portas, real_maps, id_requisicao_vi... |
def get_transformation(self, coordinates):
"""Construct a transformation object"""
atom1, atom2 = self.hinge_atoms
direction = coordinates[atom1] - coordinates[atom2]
direction /= np.linalg.norm(direction)
direction *= np.random.uniform(-self.max_amplitude, self.max_amplitude)
... | def function[get_transformation, parameter[self, coordinates]]:
constant[Construct a transformation object]
<ast.Tuple object at 0x7da20c6a83a0> assign[=] name[self].hinge_atoms
variable[direction] assign[=] binary_operation[call[name[coordinates]][name[atom1]] - call[name[coordinates]][name[ato... | keyword[def] identifier[get_transformation] ( identifier[self] , identifier[coordinates] ):
literal[string]
identifier[atom1] , identifier[atom2] = identifier[self] . identifier[hinge_atoms]
identifier[direction] = identifier[coordinates] [ identifier[atom1] ]- identifier[coordinates] [ i... | def get_transformation(self, coordinates):
"""Construct a transformation object"""
(atom1, atom2) = self.hinge_atoms
direction = coordinates[atom1] - coordinates[atom2]
direction /= np.linalg.norm(direction)
direction *= np.random.uniform(-self.max_amplitude, self.max_amplitude)
result = Transla... |
def dup_idx(arr):
"""Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from ... | def function[dup_idx, parameter[arr]]:
constant[Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Exam... | keyword[def] identifier[dup_idx] ( identifier[arr] ):
literal[string]
identifier[_] , identifier[b] = identifier[np] . identifier[unique] ( identifier[arr] , identifier[return_inverse] = keyword[True] )
keyword[return] identifier[np] . identifier[nonzero] ( identifier[np] . identifier[logical_or] . i... | def dup_idx(arr):
"""Return the indices of all duplicated array elements.
Parameters
----------
arr : array-like object
An array-like object
Returns
-------
idx : NumPy array
An array containing the indices of the duplicated elements
Examples
--------
>>> from ... |
def _write(self, session, openFile, replaceParamFile):
"""
Precipitation File Write to File Method
"""
# Retrieve the events associated with this PrecipFile
events = self.precipEvents
# Write each event to file
for event in events:
openFile.write('EVE... | def function[_write, parameter[self, session, openFile, replaceParamFile]]:
constant[
Precipitation File Write to File Method
]
variable[events] assign[=] name[self].precipEvents
for taget[name[event]] in starred[name[events]] begin[:]
call[name[openFile].write, p... | keyword[def] identifier[_write] ( identifier[self] , identifier[session] , identifier[openFile] , identifier[replaceParamFile] ):
literal[string]
identifier[events] = identifier[self] . identifier[precipEvents]
keyword[for] identifier[event] keyword[in] identifier[ev... | def _write(self, session, openFile, replaceParamFile):
"""
Precipitation File Write to File Method
"""
# Retrieve the events associated with this PrecipFile
events = self.precipEvents
# Write each event to file
for event in events:
openFile.write('EVENT "%s"\nNRGAG %s\nNRPDS ... |
def rgb_to_html(r, g=None, b=None):
"""Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> rg... | def function[rgb_to_html, parameter[r, g, b]]:
constant[Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this col... | keyword[def] identifier[rgb_to_html] ( identifier[r] , identifier[g] = keyword[None] , identifier[b] = keyword[None] ):
literal[string]
keyword[if] identifier[type] ( identifier[r] ) keyword[in] [ identifier[list] , identifier[tuple] ]:
identifier[r] , identifier[g] , identifier[b] = identifier[r]
ke... | def rgb_to_html(r, g=None, b=None):
"""Convert the color from (r, g, b) to #RRGGBB.
Parameters:
:r:
The Red component value [0...1]
:g:
The Green component value [0...1]
:b:
The Blue component value [0...1]
Returns:
A CSS string representation of this color (#RRGGBB).
>>> ... |
def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... | def function[log_response, parameter[self, response]]:
constant[
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.respon... | keyword[def] identifier[log_response] ( identifier[self] , identifier[response] ):
literal[string]
keyword[if] identifier[self] . identifier[access_log] :
identifier[extra] ={ literal[string] : identifier[getattr] ( identifier[response] , literal[string] , literal[int] )}
... | def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... |
def to_td(frame, name, con, if_exists='fail', time_col=None, time_index=None, index=True, index_label=None, chunksize=10000, date_format=None):
'''Write a DataFrame to a Treasure Data table.
This method converts the dataframe into a series of key-value pairs
and send them using the Treasure Data streaming ... | def function[to_td, parameter[frame, name, con, if_exists, time_col, time_index, index, index_label, chunksize, date_format]]:
constant[Write a DataFrame to a Treasure Data table.
This method converts the dataframe into a series of key-value pairs
and send them using the Treasure Data streaming API. Th... | keyword[def] identifier[to_td] ( identifier[frame] , identifier[name] , identifier[con] , identifier[if_exists] = literal[string] , identifier[time_col] = keyword[None] , identifier[time_index] = keyword[None] , identifier[index] = keyword[True] , identifier[index_label] = keyword[None] , identifier[chunksize] = lite... | def to_td(frame, name, con, if_exists='fail', time_col=None, time_index=None, index=True, index_label=None, chunksize=10000, date_format=None):
"""Write a DataFrame to a Treasure Data table.
This method converts the dataframe into a series of key-value pairs
and send them using the Treasure Data streaming ... |
def set_I(self, I=None):
""" Set the current circulating on the coil (A) """
C0 = I is None
C1 = type(I) in [int,float,np.int64,np.float64]
C2 = type(I) in [list,tuple,np.ndarray]
msg = "Arg I must be None, a float or an 1D np.ndarray !"
assert C0 or C1 or C2, msg
... | def function[set_I, parameter[self, I]]:
constant[ Set the current circulating on the coil (A) ]
variable[C0] assign[=] compare[name[I] is constant[None]]
variable[C1] assign[=] compare[call[name[type], parameter[name[I]]] in list[[<ast.Name object at 0x7da1b2346f20>, <ast.Name object at 0x7da1b... | keyword[def] identifier[set_I] ( identifier[self] , identifier[I] = keyword[None] ):
literal[string]
identifier[C0] = identifier[I] keyword[is] keyword[None]
identifier[C1] = identifier[type] ( identifier[I] ) keyword[in] [ identifier[int] , identifier[float] , identifier[np] . identifi... | def set_I(self, I=None):
""" Set the current circulating on the coil (A) """
C0 = I is None
C1 = type(I) in [int, float, np.int64, np.float64]
C2 = type(I) in [list, tuple, np.ndarray]
msg = 'Arg I must be None, a float or an 1D np.ndarray !'
assert C0 or C1 or C2, msg
if C1:
I = np.... |
def _action_add(self, ids):
"""Add IDs to the group
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to add
Returns
-------
list of dict
The details of the added jobs
"""
return self._action_get((se... | def function[_action_add, parameter[self, ids]]:
constant[Add IDs to the group
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to add
Returns
-------
list of dict
The details of the added jobs
]
return... | keyword[def] identifier[_action_add] ( identifier[self] , identifier[ids] ):
literal[string]
keyword[return] identifier[self] . identifier[_action_get] (( identifier[self] . identifier[listen_to_node] ( identifier[id_] ) keyword[for] identifier[id_] keyword[in] identifier[ids] )) | def _action_add(self, ids):
"""Add IDs to the group
Parameters
----------
ids : {list, set, tuple, generator} of str
The IDs to add
Returns
-------
list of dict
The details of the added jobs
"""
return self._action_get((self.liste... |
def _series_feedback(series, out_port, in_port):
"""Invert a series self-feedback twice to get rid of unnecessary
permutations."""
series_s = series.series_inverse().series_inverse()
if series_s == series:
raise CannotSimplify()
return series_s.feedback(out_port=out_port, in_port=in_port) | def function[_series_feedback, parameter[series, out_port, in_port]]:
constant[Invert a series self-feedback twice to get rid of unnecessary
permutations.]
variable[series_s] assign[=] call[call[name[series].series_inverse, parameter[]].series_inverse, parameter[]]
if compare[name[series_s] ... | keyword[def] identifier[_series_feedback] ( identifier[series] , identifier[out_port] , identifier[in_port] ):
literal[string]
identifier[series_s] = identifier[series] . identifier[series_inverse] (). identifier[series_inverse] ()
keyword[if] identifier[series_s] == identifier[series] :
key... | def _series_feedback(series, out_port, in_port):
"""Invert a series self-feedback twice to get rid of unnecessary
permutations."""
series_s = series.series_inverse().series_inverse()
if series_s == series:
raise CannotSimplify() # depends on [control=['if'], data=[]]
return series_s.feedbac... |
def _flag_is_registered(self, flag_obj):
"""Checks whether a Flag object is registered under long name or short name.
Args:
flag_obj: Flag, the Flag instance to check for.
Returns:
bool, True iff flag_obj is registered under long name or short name.
"""
flag_dict = self._flags()
# ... | def function[_flag_is_registered, parameter[self, flag_obj]]:
constant[Checks whether a Flag object is registered under long name or short name.
Args:
flag_obj: Flag, the Flag instance to check for.
Returns:
bool, True iff flag_obj is registered under long name or short name.
]
... | keyword[def] identifier[_flag_is_registered] ( identifier[self] , identifier[flag_obj] ):
literal[string]
identifier[flag_dict] = identifier[self] . identifier[_flags] ()
identifier[name] = identifier[flag_obj] . identifier[name]
keyword[if] identifier[flag_dict] . identifier[get] ( identi... | def _flag_is_registered(self, flag_obj):
"""Checks whether a Flag object is registered under long name or short name.
Args:
flag_obj: Flag, the Flag instance to check for.
Returns:
bool, True iff flag_obj is registered under long name or short name.
"""
flag_dict = self._flags()
# ... |
def update_configuration(self, **kwargs):
"""
Update the OSPF configuration using kwargs that match the
`enable` constructor.
:param dict kwargs: keyword arguments matching enable constructor.
:return: whether change was made
:rtype: bool
"""
upda... | def function[update_configuration, parameter[self]]:
constant[
Update the OSPF configuration using kwargs that match the
`enable` constructor.
:param dict kwargs: keyword arguments matching enable constructor.
:return: whether change was made
:rtype: bool
... | keyword[def] identifier[update_configuration] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[updated] = keyword[False]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[kwargs] . identifier[update] ( identifier[ospfv2_profile_... | def update_configuration(self, **kwargs):
"""
Update the OSPF configuration using kwargs that match the
`enable` constructor.
:param dict kwargs: keyword arguments matching enable constructor.
:return: whether change was made
:rtype: bool
"""
updated = Fa... |
def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = query.one()
except NoResultFound:
raise WorkflowsMissingObject("No object for for id {0}".... | def function[get, parameter[cls, id_]]:
constant[Return a workflow object from id.]
with name[db].session.no_autoflush begin[:]
variable[query] assign[=] call[name[cls].dbmodel.query.filter_by, parameter[]]
<ast.Try object at 0x7da20c6e5750>
return[call[name[cls], paramet... | keyword[def] identifier[get] ( identifier[cls] , identifier[id_] ):
literal[string]
keyword[with] identifier[db] . identifier[session] . identifier[no_autoflush] :
identifier[query] = identifier[cls] . identifier[dbmodel] . identifier[query] . identifier[filter_by] ( identifier[id] = ... | def get(cls, id_):
"""Return a workflow object from id."""
with db.session.no_autoflush:
query = cls.dbmodel.query.filter_by(id=id_)
try:
model = query.one() # depends on [control=['try'], data=[]]
except NoResultFound:
raise WorkflowsMissingObject('No object for... |
def _CaptureException(f, *args, **kwargs):
"""Decorator implementation for capturing exceptions."""
from ambry.dbexceptions import LoggedException
b = args[0] # The 'self' argument
try:
return f(*args, **kwargs)
except Exception as e:
raise
try:
b.set_error_sta... | def function[_CaptureException, parameter[f]]:
constant[Decorator implementation for capturing exceptions.]
from relative_module[ambry.dbexceptions] import module[LoggedException]
variable[b] assign[=] call[name[args]][constant[0]]
<ast.Try object at 0x7da20c991120> | keyword[def] identifier[_CaptureException] ( identifier[f] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[ambry] . identifier[dbexceptions] keyword[import] identifier[LoggedException]
identifier[b] = identifier[args] [ literal[int] ]
keyword[try] :
... | def _CaptureException(f, *args, **kwargs):
"""Decorator implementation for capturing exceptions."""
from ambry.dbexceptions import LoggedException
b = args[0] # The 'self' argument
try:
return f(*args, **kwargs) # depends on [control=['try'], data=[]]
except Exception as e:
raise
... |
def __error(self,stanza):
"""Handle disco error response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
self.error(stanza.get_error())
except ProtocolError:
from ..error import Sta... | def function[__error, parameter[self, stanza]]:
constant[Handle disco error response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`]
<ast.Try object at 0x7da2043448e0> | keyword[def] identifier[__error] ( identifier[self] , identifier[stanza] ):
literal[string]
keyword[try] :
identifier[self] . identifier[error] ( identifier[stanza] . identifier[get_error] ())
keyword[except] identifier[ProtocolError] :
keyword[from] .. identifie... | def __error(self, stanza):
"""Handle disco error response.
:Parameters:
- `stanza`: the stanza received.
:Types:
- `stanza`: `pyxmpp.stanza.Stanza`"""
try:
self.error(stanza.get_error()) # depends on [control=['try'], data=[]]
except ProtocolError:
f... |
def to_yellow(self, on: bool=False):
"""
Change the LED to yellow (on or off)
:param on: True or False
:return: None
"""
self._on = on
if on:
self._load_new(led_yellow_on)
if self._toggle_on_click:
self._canvas.bind('<Butto... | def function[to_yellow, parameter[self, on]]:
constant[
Change the LED to yellow (on or off)
:param on: True or False
:return: None
]
name[self]._on assign[=] name[on]
if name[on] begin[:]
call[name[self]._load_new, parameter[name[led_yellow_on]]]
... | keyword[def] identifier[to_yellow] ( identifier[self] , identifier[on] : identifier[bool] = keyword[False] ):
literal[string]
identifier[self] . identifier[_on] = identifier[on]
keyword[if] identifier[on] :
identifier[self] . identifier[_load_new] ( identifier[led_yellow_on]... | def to_yellow(self, on: bool=False):
"""
Change the LED to yellow (on or off)
:param on: True or False
:return: None
"""
self._on = on
if on:
self._load_new(led_yellow_on)
if self._toggle_on_click:
self._canvas.bind('<Button-1>', lambda x: self.to_... |
def read(self, pin, is_differential=False):
"""I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read.
"""
pin = pin if is_differential else pin + 0x04
... | def function[read, parameter[self, pin, is_differential]]:
constant[I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read.
]
variable[pin] assign[=] <ast.IfEx... | keyword[def] identifier[read] ( identifier[self] , identifier[pin] , identifier[is_differential] = keyword[False] ):
literal[string]
identifier[pin] = identifier[pin] keyword[if] identifier[is_differential] keyword[else] identifier[pin] + literal[int]
keyword[return] identifier[self]... | def read(self, pin, is_differential=False):
"""I2C Interface for ADS1x15-based ADCs reads.
params:
:param pin: individual or differential pin.
:param bool is_differential: single-ended or differential read.
"""
pin = pin if is_differential else pin + 4
return self._r... |
def listener(self, event, *args, **kwargs):
"""Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword argume... | def function[listener, parameter[self, event]]:
constant[Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyw... | keyword[def] identifier[listener] ( identifier[self] , identifier[event] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] keyword[and] identifier[callable] ( identifier[args] [ literal[int] ]):
keyword[rais... | def listener(self, event, *args, **kwargs):
"""Create a listener from a decorated function.
:param event: Event to listen to.
:type event: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:param kwargs: captures the keyword arguments ... |
def get_block_adjustments(crypto, points=None, intervals=None, **modes):
"""
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
"""
from moneywagon import get_block
all_points = []
if intervals:
latest_b... | def function[get_block_adjustments, parameter[crypto, points, intervals]]:
constant[
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
]
from relative_module[moneywagon] import module[get_block]
variable[all... | keyword[def] identifier[get_block_adjustments] ( identifier[crypto] , identifier[points] = keyword[None] , identifier[intervals] = keyword[None] ,** identifier[modes] ):
literal[string]
keyword[from] identifier[moneywagon] keyword[import] identifier[get_block]
identifier[all_points] =[]
keyw... | def get_block_adjustments(crypto, points=None, intervals=None, **modes):
"""
This utility is used to determine the actual block rate. The output can be
directly copied to the `blocktime_adjustments` setting.
"""
from moneywagon import get_block
all_points = []
if intervals:
latest_bl... |
def fit(self, X, y=None):
"""
Fits the JointPlot, creating a correlative visualization between the columns
specified during initialization and the data and target passed into fit:
- If self.columns is None then X and y must both be specified as 1D arrays
or X must be a... | def function[fit, parameter[self, X, y]]:
constant[
Fits the JointPlot, creating a correlative visualization between the columns
specified during initialization and the data and target passed into fit:
- If self.columns is None then X and y must both be specified as 1D arrays
... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[X] ,( identifier[list] , identifier[tuple] )):
identifier[X] = identifier[np] . identifier[array] ( identifier[X]... | def fit(self, X, y=None):
"""
Fits the JointPlot, creating a correlative visualization between the columns
specified during initialization and the data and target passed into fit:
- If self.columns is None then X and y must both be specified as 1D arrays
or X must be a 2D ... |
def _read_mode_unpack(self, size, kind):
"""Read options request unpack process.
Keyword arguments:
size - int, length of option
kind - int, option kind value
Returns:
* dict -- extracted option which unpacked
Structure of TCP options:
O... | def function[_read_mode_unpack, parameter[self, size, kind]]:
constant[Read options request unpack process.
Keyword arguments:
size - int, length of option
kind - int, option kind value
Returns:
* dict -- extracted option which unpacked
Structure of... | keyword[def] identifier[_read_mode_unpack] ( identifier[self] , identifier[size] , identifier[kind] ):
literal[string]
identifier[data] = identifier[dict] (
identifier[kind] = identifier[kind] ,
identifier[length] = identifier[size] ,
identifier[data] = identifier[self] .... | def _read_mode_unpack(self, size, kind):
"""Read options request unpack process.
Keyword arguments:
size - int, length of option
kind - int, option kind value
Returns:
* dict -- extracted option which unpacked
Structure of TCP options:
Octet... |
def scan_dir_for_template_files(search_dir):
"""
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
"""
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
... | def function[scan_dir_for_template_files, parameter[search_dir]]:
constant[
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
]
variable[template_files] assign[=] dictionary[[], []]
variable[cf_dir] as... | keyword[def] identifier[scan_dir_for_template_files] ( identifier[search_dir] ):
literal[string]
identifier[template_files] ={}
identifier[cf_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[search_dir] , literal[string] )
keyword[for] identifier[type] keyword[in] ident... | def scan_dir_for_template_files(search_dir):
"""
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
"""
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.