code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def load_template():
"""Bail out if template is not found.
"""
cloudformation, found = load_cloudformation_template()
if not found:
print(colored.red('could not load cloudformation.py, bailing out...'))
sys.exit(1)
return cloudformation | def function[load_template, parameter[]]:
constant[Bail out if template is not found.
]
<ast.Tuple object at 0x7da20e956140> assign[=] call[name[load_cloudformation_template], parameter[]]
if <ast.UnaryOp object at 0x7da1b0e339d0> begin[:]
call[name[print], parameter[call[nam... | keyword[def] identifier[load_template] ():
literal[string]
identifier[cloudformation] , identifier[found] = identifier[load_cloudformation_template] ()
keyword[if] keyword[not] identifier[found] :
identifier[print] ( identifier[colored] . identifier[red] ( literal[string] ))
identi... | def load_template():
"""Bail out if template is not found.
"""
(cloudformation, found) = load_cloudformation_template()
if not found:
print(colored.red('could not load cloudformation.py, bailing out...'))
sys.exit(1) # depends on [control=['if'], data=[]]
return cloudformation |
def genomic_signal(fn, kind):
"""
Factory function that makes the right class for the file format.
Typically you'll only need this function to create a new genomic signal
object.
:param fn: Filename
:param kind:
String. Format of the file; see
metaseq.genomic_signal._registry.... | def function[genomic_signal, parameter[fn, kind]]:
constant[
Factory function that makes the right class for the file format.
Typically you'll only need this function to create a new genomic signal
object.
:param fn: Filename
:param kind:
String. Format of the file; see
me... | keyword[def] identifier[genomic_signal] ( identifier[fn] , identifier[kind] ):
literal[string]
keyword[try] :
identifier[klass] = identifier[_registry] [ identifier[kind] . identifier[lower] ()]
keyword[except] identifier[KeyError] :
keyword[raise] identifier[ValueError] (
... | def genomic_signal(fn, kind):
"""
Factory function that makes the right class for the file format.
Typically you'll only need this function to create a new genomic signal
object.
:param fn: Filename
:param kind:
String. Format of the file; see
metaseq.genomic_signal._registry.... |
def get(self, timeout=None): # pylint: disable=arguments-differ
"""Check a session out from the pool.
:type timeout: int
:param timeout: seconds to block waiting for an available session
:rtype: :class:`~google.cloud.spanner_v1.session.Session`
:returns: an existing session fr... | def function[get, parameter[self, timeout]]:
constant[Check a session out from the pool.
:type timeout: int
:param timeout: seconds to block waiting for an available session
:rtype: :class:`~google.cloud.spanner_v1.session.Session`
:returns: an existing session from the pool, o... | keyword[def] identifier[get] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[timeout] keyword[is] keyword[None] :
identifier[timeout] = identifier[self] . identifier[default_timeout]
identifier[session] = identifier[self]... | def get(self, timeout=None): # pylint: disable=arguments-differ
'Check a session out from the pool.\n\n :type timeout: int\n :param timeout: seconds to block waiting for an available session\n\n :rtype: :class:`~google.cloud.spanner_v1.session.Session`\n :returns: an existing session fr... |
def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = "hash_type_to_saml_name_id_format is deprecated and... | def function[hash_type_to_saml_name_id_format, parameter[hash_type]]:
constant[
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
]
variable[msg] assign[=] ... | keyword[def] identifier[hash_type_to_saml_name_id_format] ( identifier[hash_type] ):
literal[string]
identifier[msg] = literal[string]
identifier[_warnings] . identifier[warn] ( identifier[msg] , identifier[DeprecationWarning] )
identifier[hash_type_to_name_id_format] ={
identifier[UserIdH... | def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = 'hash_type_to_saml_name_id_format is deprecated and... |
def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i=0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i+1
d[k] = C[i]
else:
j = i \
+ reduce(operator.mul, s, 1)
d[k] = C[i... | def function[C_array2dict, parameter[C]]:
constant[Convert a 1D array containing C values to a dictionary.]
variable[d] assign[=] call[name[OrderedDict], parameter[]]
variable[i] assign[=] constant[0]
for taget[name[k]] in starred[name[C_keys]] begin[:]
variable[s] assign... | keyword[def] identifier[C_array2dict] ( identifier[C] ):
literal[string]
identifier[d] = identifier[OrderedDict] ()
identifier[i] = literal[int]
keyword[for] identifier[k] keyword[in] identifier[C_keys] :
identifier[s] = identifier[C_keys_shape] [ identifier[k] ]
keyword[if]... | def C_array2dict(C):
"""Convert a 1D array containing C values to a dictionary."""
d = OrderedDict()
i = 0
for k in C_keys:
s = C_keys_shape[k]
if s == 1:
j = i + 1
d[k] = C[i] # depends on [control=['if'], data=[]]
else:
j = i + reduce(operat... |
def injector_component_2_json(self, properties_only=False):
"""
transform this local object to JSON. If properties only ignore the component blob (awaited by Ariane Server)
:param properties_only: true or false
:return: the JSON from this local object
"""
LOGGER.debug("In... | def function[injector_component_2_json, parameter[self, properties_only]]:
constant[
transform this local object to JSON. If properties only ignore the component blob (awaited by Ariane Server)
:param properties_only: true or false
:return: the JSON from this local object
]
... | keyword[def] identifier[injector_component_2_json] ( identifier[self] , identifier[properties_only] = keyword[False] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] identifier[properties_only] :
identifier[json_obj] ={
li... | def injector_component_2_json(self, properties_only=False):
"""
transform this local object to JSON. If properties only ignore the component blob (awaited by Ariane Server)
:param properties_only: true or false
:return: the JSON from this local object
"""
LOGGER.debug('InjectorCa... |
def sort(self, axis=-1, kind='quicksort', order=None):
"""Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field.
... | def function[sort, parameter[self, axis, kind, order]]:
constant[Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field... | keyword[def] identifier[sort] ( identifier[self] , identifier[axis] =- literal[int] , identifier[kind] = literal[string] , identifier[order] = keyword[None] ):
literal[string]
keyword[try] :
identifier[numpy] . identifier[recarray] . identifier[sort] ( identifier[self] , identifier[axi... | def sort(self, axis=-1, kind='quicksort', order=None):
"""Sort an array, in-place.
This function extends the standard numpy record array in-place sort
to allow the basic use of Field array virtual fields. Only a single
field is currently supported when referencing a virtual field.
... |
def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event... | def function[sample, parameter[self, event, record_keepalive]]:
constant[
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a... | keyword[def] identifier[sample] ( identifier[self] , identifier[event] = keyword[None] , identifier[record_keepalive] = keyword[False] ):
literal[string]
identifier[url] = literal[string]
identifier[params] ={ literal[string] : keyword[True] }
identifier[headers] ={ literal[strin... | def sample(self, event=None, record_keepalive=False):
"""
Returns a small random sample of all public statuses. The Tweets
returned by the default access level are the same, so if two different
clients connect to this endpoint, they will see the same Tweets.
If a threading.Event is ... |
def _process_human_orthos(self, limit=None):
"""
This table provides ortholog mappings between zebrafish and humans.
ZFIN has their own process of creating orthology mappings,
that we take in addition to other orthology-calling sources
(like PANTHER). We ignore the omim ids, and ... | def function[_process_human_orthos, parameter[self, limit]]:
constant[
This table provides ortholog mappings between zebrafish and humans.
ZFIN has their own process of creating orthology mappings,
that we take in addition to other orthology-calling sources
(like PANTHER). We ign... | keyword[def] identifier[_process_human_orthos] ( identifier[self] , identifier[limit] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[test_mode] :
identifier[graph] = identifier[self] . identifier[testgraph]
keyword[else] :
identifi... | def _process_human_orthos(self, limit=None):
"""
This table provides ortholog mappings between zebrafish and humans.
ZFIN has their own process of creating orthology mappings,
that we take in addition to other orthology-calling sources
(like PANTHER). We ignore the omim ids, and only... |
def update_context(self,
context,
update_mask=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Updates the specified... | def function[update_context, parameter[self, context, update_mask, retry, timeout, metadata]]:
constant[
Updates the specified context.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.ContextsClient()
>>>
>>> # TODO: I... | keyword[def] identifier[update_context] ( identifier[self] ,
identifier[context] ,
identifier[update_mask] = keyword[None] ,
identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[timeout] = identifier[google] . identifier[api_c... | def update_context(self, context, update_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
"""
Updates the specified context.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2... |
def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to d... | def function[add, parameter[self, pattern, function, method, type_cast]]:
constant[Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): ... | keyword[def] identifier[add] ( identifier[self] , identifier[pattern] , identifier[function] , identifier[method] = keyword[None] , identifier[type_cast] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[type_cast] :
identifier[type_cast] ={}
keyword[wi... | def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to defin... |
def split_window(self, fpath, vertical=False, size=None, bufopts=None):
"""Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size... | def function[split_window, parameter[self, fpath, vertical, size, bufopts]]:
constant[Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
... | keyword[def] identifier[split_window] ( identifier[self] , identifier[fpath] , identifier[vertical] = keyword[False] , identifier[size] = keyword[None] , identifier[bufopts] = keyword[None] ):
literal[string]
identifier[command] = literal[string] . identifier[format] ( identifier[fpath] ) keyword[i... | def split_window(self, fpath, vertical=False, size=None, bufopts=None):
"""Open file in a new split window.
Args:
fpath (str): Path of the file to open. If ``None``, a new empty
split is created.
vertical (bool): Whether to open a vertical split.
size (Op... |
def abort_thread():
"""
This function checks to see if the user has indicated that they want the
currently running execution to stop prematurely by marking the running
thread as aborted. It only applies to operations that are run within
CauldronThreads and not the main thread.
"""
thread = ... | def function[abort_thread, parameter[]]:
constant[
This function checks to see if the user has indicated that they want the
currently running execution to stop prematurely by marking the running
thread as aborted. It only applies to operations that are run within
CauldronThreads and not the main... | keyword[def] identifier[abort_thread] ():
literal[string]
identifier[thread] = identifier[threading] . identifier[current_thread] ()
keyword[if] keyword[not] identifier[isinstance] ( identifier[thread] , identifier[CauldronThread] ):
keyword[return]
keyword[if] identifier[thread] ... | def abort_thread():
"""
This function checks to see if the user has indicated that they want the
currently running execution to stop prematurely by marking the running
thread as aborted. It only applies to operations that are run within
CauldronThreads and not the main thread.
"""
thread = t... |
def _find_resources(directory, excludes=[]):
"""Return a list of resource paths from the directory.
Ignore records via the list of `excludes`,
which are callables that take a file parameter (as a `Path` instance).
"""
return sorted([r for r in directory.glob('*')
if True not in [... | def function[_find_resources, parameter[directory, excludes]]:
constant[Return a list of resource paths from the directory.
Ignore records via the list of `excludes`,
which are callables that take a file parameter (as a `Path` instance).
]
return[call[name[sorted], parameter[<ast.ListComp objec... | keyword[def] identifier[_find_resources] ( identifier[directory] , identifier[excludes] =[]):
literal[string]
keyword[return] identifier[sorted] ([ identifier[r] keyword[for] identifier[r] keyword[in] identifier[directory] . identifier[glob] ( literal[string] )
keyword[if] keyword[True] keyword... | def _find_resources(directory, excludes=[]):
"""Return a list of resource paths from the directory.
Ignore records via the list of `excludes`,
which are callables that take a file parameter (as a `Path` instance).
"""
return sorted([r for r in directory.glob('*') if True not in [e(r) for e in exclu... |
def check_wlcalib_sp(sp, crpix1, crval1, cdelt1, wv_master,
coeff_ini=None, naxis1_ini=None,
min_nlines_to_refine=0,
interactive=False,
threshold=0,
nwinwidth_initial=7,
nwinwidth_refined=5,
... | def function[check_wlcalib_sp, parameter[sp, crpix1, crval1, cdelt1, wv_master, coeff_ini, naxis1_ini, min_nlines_to_refine, interactive, threshold, nwinwidth_initial, nwinwidth_refined, ntimes_match_wv, poldeg_residuals, times_sigma_reject, use_r, title, remove_null_borders, ylogscale, geometry, pdf, debugplot]]:
... | keyword[def] identifier[check_wlcalib_sp] ( identifier[sp] , identifier[crpix1] , identifier[crval1] , identifier[cdelt1] , identifier[wv_master] ,
identifier[coeff_ini] = keyword[None] , identifier[naxis1_ini] = keyword[None] ,
identifier[min_nlines_to_refine] = literal[int] ,
identifier[interactive] = keyword[Fa... | def check_wlcalib_sp(sp, crpix1, crval1, cdelt1, wv_master, coeff_ini=None, naxis1_ini=None, min_nlines_to_refine=0, interactive=False, threshold=0, nwinwidth_initial=7, nwinwidth_refined=5, ntimes_match_wv=2, poldeg_residuals=1, times_sigma_reject=5, use_r=False, title=None, remove_null_borders=True, ylogscale=False, ... |
def list(members, meta=None) -> List: # pylint:disable=redefined-builtin
"""Creates a new list."""
return List( # pylint: disable=abstract-class-instantiated
plist(iterable=members), meta=meta
) | def function[list, parameter[members, meta]]:
constant[Creates a new list.]
return[call[name[List], parameter[call[name[plist], parameter[]]]]] | keyword[def] identifier[list] ( identifier[members] , identifier[meta] = keyword[None] )-> identifier[List] :
literal[string]
keyword[return] identifier[List] (
identifier[plist] ( identifier[iterable] = identifier[members] ), identifier[meta] = identifier[meta]
) | def list(members, meta=None) -> List: # pylint:disable=redefined-builtin
'Creates a new list.' # pylint: disable=abstract-class-instantiated
return List(plist(iterable=members), meta=meta) |
def get(self, index, n_cols=70):
"""
Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n`
"""
if index < -1:
raise IndexError
elif index == -1:
data = self._submission_data
data['split_title... | def function[get, parameter[self, index, n_cols]]:
constant[
Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n`
]
if compare[name[index] less[<] <ast.UnaryOp object at 0x7da1b2344cd0>] begin[:]
<ast.Raise object at 0x7da1b2345... | keyword[def] identifier[get] ( identifier[self] , identifier[index] , identifier[n_cols] = literal[int] ):
literal[string]
keyword[if] identifier[index] <- literal[int] :
keyword[raise] identifier[IndexError]
keyword[elif] identifier[index] ==- literal[int] :
... | def get(self, index, n_cols=70):
"""
Grab the `i`th submission, with the title field formatted to fit inside
of a window of width `n`
"""
if index < -1:
raise IndexError # depends on [control=['if'], data=[]]
elif index == -1:
data = self._submission_data
dat... |
async def list_transactions(self, request):
"""Fetches list of txns from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of txn ids to include in results
Res... | <ast.AsyncFunctionDef object at 0x7da18bc73370> | keyword[async] keyword[def] identifier[list_transactions] ( identifier[self] , identifier[request] ):
literal[string]
identifier[paging_controls] = identifier[self] . identifier[_get_paging_controls] ( identifier[request] )
identifier[validator_query] = identifier[client_transaction_pb2] ... | async def list_transactions(self, request):
"""Fetches list of txns from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of txn ids to include in results
Respons... |
def get_nodes(self, request):
"""
Return menu's node for categories
"""
nodes = []
nodes.append(NavigationNode(_('Categories'),
reverse('zinnia:category_list'),
'categories'))
for category in Category... | def function[get_nodes, parameter[self, request]]:
constant[
Return menu's node for categories
]
variable[nodes] assign[=] list[[]]
call[name[nodes].append, parameter[call[name[NavigationNode], parameter[call[name[_], parameter[constant[Categories]]], call[name[reverse], paramete... | keyword[def] identifier[get_nodes] ( identifier[self] , identifier[request] ):
literal[string]
identifier[nodes] =[]
identifier[nodes] . identifier[append] ( identifier[NavigationNode] ( identifier[_] ( literal[string] ),
identifier[reverse] ( literal[string] ),
literal[s... | def get_nodes(self, request):
"""
Return menu's node for categories
"""
nodes = []
nodes.append(NavigationNode(_('Categories'), reverse('zinnia:category_list'), 'categories'))
for category in Category.objects.all():
nodes.append(NavigationNode(category.title, category.get_absolut... |
def decode_state(cls, state, param='user_state'):
"""
Decode state and return param.
:param str state:
state parameter passed through by provider
:param str param:
key to query from decoded state variable. Options include 'csrf'
and 'user_state'.
... | def function[decode_state, parameter[cls, state, param]]:
constant[
Decode state and return param.
:param str state:
state parameter passed through by provider
:param str param:
key to query from decoded state variable. Options include 'csrf'
and 'us... | keyword[def] identifier[decode_state] ( identifier[cls] , identifier[state] , identifier[param] = literal[string] ):
literal[string]
keyword[if] identifier[state] keyword[and] identifier[cls] . identifier[supports_user_state] :
keyword[return] identifier[... | def decode_state(cls, state, param='user_state'):
"""
Decode state and return param.
:param str state:
state parameter passed through by provider
:param str param:
key to query from decoded state variable. Options include 'csrf'
and 'user_state'.
... |
def configuration(t0: date, t1: Optional[date] = None,
steps_per_day: int = None) -> Tuple[np.ndarray, np.ndarray]:
"""
Get the positions and velocities of the sun and eight planets
Returned as a tuple q, v
q: Nx3 array of positions (x, y, z) in the J2000.0 coordinate frame.
"""
... | def function[configuration, parameter[t0, t1, steps_per_day]]:
constant[
Get the positions and velocities of the sun and eight planets
Returned as a tuple q, v
q: Nx3 array of positions (x, y, z) in the J2000.0 coordinate frame.
]
if compare[name[steps_per_day] is constant[None]] begin[:... | keyword[def] identifier[configuration] ( identifier[t0] : identifier[date] , identifier[t1] : identifier[Optional] [ identifier[date] ]= keyword[None] ,
identifier[steps_per_day] : identifier[int] = keyword[None] )-> identifier[Tuple] [ identifier[np] . identifier[ndarray] , identifier[np] . identifier[ndarray] ]:
... | def configuration(t0: date, t1: Optional[date]=None, steps_per_day: int=None) -> Tuple[np.ndarray, np.ndarray]:
"""
Get the positions and velocities of the sun and eight planets
Returned as a tuple q, v
q: Nx3 array of positions (x, y, z) in the J2000.0 coordinate frame.
"""
# Default steps_per_... |
def MetaOrdered(parallel, done, turnstile):
"""meta class for Ordered construct."""
class Ordered:
def __init__(self, iterref):
if parallel.master:
done[...] = 0
self.iterref = iterref
parallel.barrier()
@classmethod
def abort(self):
... | def function[MetaOrdered, parameter[parallel, done, turnstile]]:
constant[meta class for Ordered construct.]
class class[Ordered, parameter[]] begin[:]
def function[__init__, parameter[self, iterref]]:
if name[parallel].master begin[:]
... | keyword[def] identifier[MetaOrdered] ( identifier[parallel] , identifier[done] , identifier[turnstile] ):
literal[string]
keyword[class] identifier[Ordered] :
keyword[def] identifier[__init__] ( identifier[self] , identifier[iterref] ):
keyword[if] identifier[parallel] . identifier... | def MetaOrdered(parallel, done, turnstile):
"""meta class for Ordered construct."""
class Ordered:
def __init__(self, iterref):
if parallel.master:
done[...] = 0 # depends on [control=['if'], data=[]]
self.iterref = iterref
parallel.barrier()
... |
def load_file(self, cursor, target, fname, options):
"Parses and loads a single file into the target table."
with open(fname) as fin:
log.debug("opening {0} in {1} load_file".format(fname, __name__))
encoding = options.get('encoding', 'utf-8')
if target in self.proces... | def function[load_file, parameter[self, cursor, target, fname, options]]:
constant[Parses and loads a single file into the target table.]
with call[name[open], parameter[name[fname]]] begin[:]
call[name[log].debug, parameter[call[constant[opening {0} in {1} load_file].format, parameter[n... | keyword[def] identifier[load_file] ( identifier[self] , identifier[cursor] , identifier[target] , identifier[fname] , identifier[options] ):
literal[string]
keyword[with] identifier[open] ( identifier[fname] ) keyword[as] identifier[fin] :
identifier[log] . identifier[debug] ( litera... | def load_file(self, cursor, target, fname, options):
"""Parses and loads a single file into the target table."""
with open(fname) as fin:
log.debug('opening {0} in {1} load_file'.format(fname, __name__))
encoding = options.get('encoding', 'utf-8')
if target in self.processors:
... |
def configure(username=None, password=None, overwrite=None, config_file=None):
"""Configure IA Mine with your Archive.org credentials."""
username = input('Email address: ') if not username else username
password = getpass('Password: ') if not password else password
_config_file = write_config_file(user... | def function[configure, parameter[username, password, overwrite, config_file]]:
constant[Configure IA Mine with your Archive.org credentials.]
variable[username] assign[=] <ast.IfExp object at 0x7da18ede6dd0>
variable[password] assign[=] <ast.IfExp object at 0x7da18ede4790>
variable[_con... | keyword[def] identifier[configure] ( identifier[username] = keyword[None] , identifier[password] = keyword[None] , identifier[overwrite] = keyword[None] , identifier[config_file] = keyword[None] ):
literal[string]
identifier[username] = identifier[input] ( literal[string] ) keyword[if] keyword[not] ident... | def configure(username=None, password=None, overwrite=None, config_file=None):
"""Configure IA Mine with your Archive.org credentials."""
username = input('Email address: ') if not username else username
password = getpass('Password: ') if not password else password
_config_file = write_config_file(user... |
def getDigitalMaximum(self, chn=None):
"""
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> ... | def function[getDigitalMaximum, parameter[self, chn]]:
constant[
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_ge... | keyword[def] identifier[getDigitalMaximum] ( identifier[self] , identifier[chn] = keyword[None] ):
literal[string]
keyword[if] identifier[chn] keyword[is] keyword[not] keyword[None] :
keyword[if] literal[int] <= identifier[chn] < identifier[self] . identifier[signals_in_file] :
... | def getDigitalMaximum(self, chn=None):
"""
Returns the maximum digital value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.ge... |
def create_site(self, site, states=None):
"""Create a new site on an agent if it doesn't already exist."""
if site not in self.sites:
self.sites.append(site)
if states is not None:
self.site_states.setdefault(site, [])
try:
states = list(states... | def function[create_site, parameter[self, site, states]]:
constant[Create a new site on an agent if it doesn't already exist.]
if compare[name[site] <ast.NotIn object at 0x7da2590d7190> name[self].sites] begin[:]
call[name[self].sites.append, parameter[name[site]]]
if compare[nam... | keyword[def] identifier[create_site] ( identifier[self] , identifier[site] , identifier[states] = keyword[None] ):
literal[string]
keyword[if] identifier[site] keyword[not] keyword[in] identifier[self] . identifier[sites] :
identifier[self] . identifier[sites] . identifier[append] ... | def create_site(self, site, states=None):
"""Create a new site on an agent if it doesn't already exist."""
if site not in self.sites:
self.sites.append(site) # depends on [control=['if'], data=['site']]
if states is not None:
self.site_states.setdefault(site, [])
try:
st... |
def write_out(self, message, verbosity_level=1):
"""
Convenient method for outputing.
"""
if self.verbosity and self.verbosity >= verbosity_level:
sys.stdout.write(smart_str(message))
sys.stdout.flush() | def function[write_out, parameter[self, message, verbosity_level]]:
constant[
Convenient method for outputing.
]
if <ast.BoolOp object at 0x7da1b1d47b20> begin[:]
call[name[sys].stdout.write, parameter[call[name[smart_str], parameter[name[message]]]]]
call... | keyword[def] identifier[write_out] ( identifier[self] , identifier[message] , identifier[verbosity_level] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[verbosity] keyword[and] identifier[self] . identifier[verbosity] >= identifier[verbosity_level] :
ide... | def write_out(self, message, verbosity_level=1):
"""
Convenient method for outputing.
"""
if self.verbosity and self.verbosity >= verbosity_level:
sys.stdout.write(smart_str(message))
sys.stdout.flush() # depends on [control=['if'], data=[]] |
def network_deconvolution(mat, **kwargs):
"""Python implementation/translation of network deconvolution by MIT-KELLIS LAB.
.. note::
code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution)
LICENSE: MIT-KELLIS LAB
AUTHORS:
Algorithm was programmed by... | def function[network_deconvolution, parameter[mat]]:
constant[Python implementation/translation of network deconvolution by MIT-KELLIS LAB.
.. note::
code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution)
LICENSE: MIT-KELLIS LAB
AUTHORS:
Algori... | keyword[def] identifier[network_deconvolution] ( identifier[mat] ,** identifier[kwargs] ):
literal[string]
identifier[alpha] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
identifier[beta] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
identif... | def network_deconvolution(mat, **kwargs):
"""Python implementation/translation of network deconvolution by MIT-KELLIS LAB.
.. note::
code author:gidonro [Github username](https://github.com/gidonro/Network-Deconvolution)
LICENSE: MIT-KELLIS LAB
AUTHORS:
Algorithm was programmed by... |
def corr(self, method='pearson', min_periods=1):
"""
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
* pearson : standard correlation coefficient
* kendall : ... | def function[corr, parameter[self, method, min_periods]]:
constant[
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
* pearson : standard correlation coefficient
... | keyword[def] identifier[corr] ( identifier[self] , identifier[method] = literal[string] , identifier[min_periods] = literal[int] ):
literal[string]
identifier[numeric_df] = identifier[self] . identifier[_get_numeric_data] ()
identifier[cols] = identifier[numeric_df] . identifier[columns]
... | def corr(self, method='pearson', min_periods=1):
"""
Compute pairwise correlation of columns, excluding NA/null values.
Parameters
----------
method : {'pearson', 'kendall', 'spearman'} or callable
* pearson : standard correlation coefficient
* kendall : Kend... |
def adduser(name, username):
'''
Add a user in the group.
CLI Example:
.. code-block:: bash
salt '*' group.adduser foo bar
Verifies if a valid username 'bar' as a member of an existing group 'foo',
if not then adds it.
'''
# Note: pw exits with code 65 if group is unknown
... | def function[adduser, parameter[name, username]]:
constant[
Add a user in the group.
CLI Example:
.. code-block:: bash
salt '*' group.adduser foo bar
Verifies if a valid username 'bar' as a member of an existing group 'foo',
if not then adds it.
]
variable[retcode] a... | keyword[def] identifier[adduser] ( identifier[name] , identifier[username] ):
literal[string]
identifier[retcode] = identifier[__salt__] [ literal[string] ]( literal[string] . identifier[format] (
identifier[name] , identifier[username] ), identifier[python_shell] = keyword[False] )
keyword... | def adduser(name, username):
"""
Add a user in the group.
CLI Example:
.. code-block:: bash
salt '*' group.adduser foo bar
Verifies if a valid username 'bar' as a member of an existing group 'foo',
if not then adds it.
"""
# Note: pw exits with code 65 if group is unknown
... |
def _save_cache(self):
"""Save data to the cache file."""
# Create the cache directory
safe_makedirs(self.cache_dir)
# Create/overwrite the cache file
try:
with open(self.cache_file, 'wb') as f:
pickle.dump(self.data, f)
except Exception as e:... | def function[_save_cache, parameter[self]]:
constant[Save data to the cache file.]
call[name[safe_makedirs], parameter[name[self].cache_dir]]
<ast.Try object at 0x7da1b21e2bf0> | keyword[def] identifier[_save_cache] ( identifier[self] ):
literal[string]
identifier[safe_makedirs] ( identifier[self] . identifier[cache_dir] )
keyword[try] :
keyword[with] identifier[open] ( identifier[self] . identifier[cache_file] , literal[string] ) k... | def _save_cache(self):
"""Save data to the cache file."""
# Create the cache directory
safe_makedirs(self.cache_dir)
# Create/overwrite the cache file
try:
with open(self.cache_file, 'wb') as f:
pickle.dump(self.data, f) # depends on [control=['with'], data=['f']] # depends on ... |
def chempot_vs_gamma(self, ref_delu, chempot_range, miller_index=(),
delu_dict={}, delu_default=0, JPERM2=False,
show_unstable=False, ylim=[], plt=None,
no_clean=False, no_doped=False,
use_entry_labels=False, no_label=Fa... | def function[chempot_vs_gamma, parameter[self, ref_delu, chempot_range, miller_index, delu_dict, delu_default, JPERM2, show_unstable, ylim, plt, no_clean, no_doped, use_entry_labels, no_label]]:
constant[
Plots the surface energy as a function of chemical potential.
Each facet will be associ... | keyword[def] identifier[chempot_vs_gamma] ( identifier[self] , identifier[ref_delu] , identifier[chempot_range] , identifier[miller_index] =(),
identifier[delu_dict] ={}, identifier[delu_default] = literal[int] , identifier[JPERM2] = keyword[False] ,
identifier[show_unstable] = keyword[False] , identifier[ylim] =[]... | def chempot_vs_gamma(self, ref_delu, chempot_range, miller_index=(), delu_dict={}, delu_default=0, JPERM2=False, show_unstable=False, ylim=[], plt=None, no_clean=False, no_doped=False, use_entry_labels=False, no_label=False):
"""
Plots the surface energy as a function of chemical potential.
Each... |
def _query_http(self, dl_path, repo_info):
'''
Download files via http
'''
query = None
response = None
try:
if 'username' in repo_info:
try:
if 'password' in repo_info:
query = http.query(
... | def function[_query_http, parameter[self, dl_path, repo_info]]:
constant[
Download files via http
]
variable[query] assign[=] constant[None]
variable[response] assign[=] constant[None]
<ast.Try object at 0x7da20cabed70>
<ast.Try object at 0x7da2047e8b80>
return[name[r... | keyword[def] identifier[_query_http] ( identifier[self] , identifier[dl_path] , identifier[repo_info] ):
literal[string]
identifier[query] = keyword[None]
identifier[response] = keyword[None]
keyword[try] :
keyword[if] literal[string] keyword[in] identifier[repo... | def _query_http(self, dl_path, repo_info):
"""
Download files via http
"""
query = None
response = None
try:
if 'username' in repo_info:
try:
if 'password' in repo_info:
query = http.query(dl_path, text=True, username=repo_info['use... |
def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
'''Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... | def function[evert, parameter[iterable]]:
constant[Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ]``
The resulting iterable con... | keyword[def] identifier[evert] ( identifier[iterable] : identifier[Iterable] [ identifier[Dict] [ identifier[str] , identifier[Tuple] ]])-> identifier[Iterable] [ identifier[Iterable] [ identifier[Dict] [ identifier[str] , identifier[Any] ]]]:
literal[string]
identifier[keys] = identifier[list] ( identifi... | def evert(iterable: Iterable[Dict[str, Tuple]]) -> Iterable[Iterable[Dict[str, Any]]]:
"""Evert dictionaries with tuples.
Iterates over the list of dictionaries and everts them with their tuple
values. For example:
``[ { 'a': ( 1, 2, ), }, ]``
becomes
``[ ( { 'a': 1, }, ), ( { 'a', 2, }, ) ... |
def get_gmn_version(base_url):
"""Return the version currently running on a GMN instance.
(is_gmn, version_or_error)
"""
home_url = d1_common.url.joinPathElements(base_url, 'home')
try:
response = requests.get(home_url, verify=False)
except requests.exceptions.ConnectionError as e:
... | def function[get_gmn_version, parameter[base_url]]:
constant[Return the version currently running on a GMN instance.
(is_gmn, version_or_error)
]
variable[home_url] assign[=] call[name[d1_common].url.joinPathElements, parameter[name[base_url], constant[home]]]
<ast.Try object at 0x7da18c4c... | keyword[def] identifier[get_gmn_version] ( identifier[base_url] ):
literal[string]
identifier[home_url] = identifier[d1_common] . identifier[url] . identifier[joinPathElements] ( identifier[base_url] , literal[string] )
keyword[try] :
identifier[response] = identifier[requests] . identifier[g... | def get_gmn_version(base_url):
"""Return the version currently running on a GMN instance.
(is_gmn, version_or_error)
"""
home_url = d1_common.url.joinPathElements(base_url, 'home')
try:
response = requests.get(home_url, verify=False) # depends on [control=['try'], data=[]]
except requ... |
def subtags(subtags):
"""
Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s).
:param subtags: string subtag or list of string subtags.
:return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The return list can be empty.
... | def function[subtags, parameter[subtags]]:
constant[
Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s).
:param subtags: string subtag or list of string subtags.
:return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The retu... | keyword[def] identifier[subtags] ( identifier[subtags] ):
literal[string]
identifier[result] =[]
keyword[if] keyword[not] identifier[isinstance] ( identifier[subtags] , identifier[list] ):
identifier[subtags] =[ identifier[subtags] ]
keyword[for] identifier[subta... | def subtags(subtags):
"""
Get a list of existing :class:`language_tags.Subtag.Subtag` objects given the input subtag(s).
:param subtags: string subtag or list of string subtags.
:return: a list of existing :class:`language_tags.Subtag.Subtag` objects. The return list can be empty.
"... |
def bitop_and(self, dest, key, *keys):
"""Perform bitwise AND operations between strings."""
return self.execute(b'BITOP', b'AND', dest, key, *keys) | def function[bitop_and, parameter[self, dest, key]]:
constant[Perform bitwise AND operations between strings.]
return[call[name[self].execute, parameter[constant[b'BITOP'], constant[b'AND'], name[dest], name[key], <ast.Starred object at 0x7da1b2358160>]]] | keyword[def] identifier[bitop_and] ( identifier[self] , identifier[dest] , identifier[key] ,* identifier[keys] ):
literal[string]
keyword[return] identifier[self] . identifier[execute] ( literal[string] , literal[string] , identifier[dest] , identifier[key] ,* identifier[keys] ) | def bitop_and(self, dest, key, *keys):
"""Perform bitwise AND operations between strings."""
return self.execute(b'BITOP', b'AND', dest, key, *keys) |
def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, ... | def function[unload, parameter[self]]:
constant[Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`... | keyword[def] identifier[unload] ( identifier[self] ):
literal[string]
identifier[unloaded] = keyword[False]
keyword[if] identifier[self] . identifier[_lib] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[_winlib] keyword[is] keyword[... | def unload(self):
"""Unloads the library's DLL if it has been loaded.
This additionally cleans up the temporary DLL file that was created
when the library was loaded.
Args:
self (Library): the ``Library`` instance
Returns:
``True`` if the DLL was unloaded, othe... |
def md5(self):
"""
MD5 of scene which will change when meshes or
transforms are changed
Returns
--------
hashed: str, MD5 hash of scene
"""
# start with transforms hash
hashes = [self.graph.md5()]
for g in self.geometry.values():
... | def function[md5, parameter[self]]:
constant[
MD5 of scene which will change when meshes or
transforms are changed
Returns
--------
hashed: str, MD5 hash of scene
]
variable[hashes] assign[=] list[[<ast.Call object at 0x7da1b22ba2c0>]]
for taget[n... | keyword[def] identifier[md5] ( identifier[self] ):
literal[string]
identifier[hashes] =[ identifier[self] . identifier[graph] . identifier[md5] ()]
keyword[for] identifier[g] keyword[in] identifier[self] . identifier[geometry] . identifier[values] ():
keyword[if] ... | def md5(self):
"""
MD5 of scene which will change when meshes or
transforms are changed
Returns
--------
hashed: str, MD5 hash of scene
"""
# start with transforms hash
hashes = [self.graph.md5()]
for g in self.geometry.values():
if hasattr(g, 'md... |
def get_reply_visibility(self, status_dict):
"""Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default.
"""
# Visibility rankings (higher is more limited)
visibility = ("public", "unlisted", "private", "direct")
default... | def function[get_reply_visibility, parameter[self, status_dict]]:
constant[Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default.
]
variable[visibility] assign[=] tuple[[<ast.Constant object at 0x7da1b05f2f50>, <ast.Constant object at ... | keyword[def] identifier[get_reply_visibility] ( identifier[self] , identifier[status_dict] ):
literal[string]
identifier[visibility] =( literal[string] , literal[string] , literal[string] , literal[string] )
identifier[default_visibility] = identifier[visibility] . identifier[ind... | def get_reply_visibility(self, status_dict):
"""Given a status dict, return the visibility that should be used.
This behaves like Mastodon does by default.
"""
# Visibility rankings (higher is more limited)
visibility = ('public', 'unlisted', 'private', 'direct')
default_visibility = vis... |
def do_run(self, line):
"""run Perform each operation in the queue of write operations."""
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().execute()
self._print_info_if_verbose(
"All operations in the write queue were successfully executed"
... | def function[do_run, parameter[self, line]]:
constant[run Perform each operation in the queue of write operations.]
call[name[self]._split_args, parameter[name[line], constant[0], constant[0]]]
call[call[name[self]._command_processor.get_operation_queue, parameter[]].execute, parameter[]]
... | keyword[def] identifier[do_run] ( identifier[self] , identifier[line] ):
literal[string]
identifier[self] . identifier[_split_args] ( identifier[line] , literal[int] , literal[int] )
identifier[self] . identifier[_command_processor] . identifier[get_operation_queue] (). identifier[execute]... | def do_run(self, line):
"""run Perform each operation in the queue of write operations."""
self._split_args(line, 0, 0)
self._command_processor.get_operation_queue().execute()
self._print_info_if_verbose('All operations in the write queue were successfully executed') |
def pause(self, container):
"""
Pauses all processes within a container.
Args:
container (str): The container to pause
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/containers/{0}... | def function[pause, parameter[self, container]]:
constant[
Pauses all processes within a container.
Args:
container (str): The container to pause
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
]
variabl... | keyword[def] identifier[pause] ( identifier[self] , identifier[container] ):
literal[string]
identifier[url] = identifier[self] . identifier[_url] ( literal[string] , identifier[container] )
identifier[res] = identifier[self] . identifier[_post] ( identifier[url] )
identifier[self... | def pause(self, container):
"""
Pauses all processes within a container.
Args:
container (str): The container to pause
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
url = self._url('/containers/{0}/pause',... |
def show_window_options(self, option=None, g=False):
"""
Return a dict of options for the window.
For familiarity with tmux, the option ``option`` param forwards to
pick a single option, forwarding to :meth:`Window.show_window_option`.
Parameters
----------
opti... | def function[show_window_options, parameter[self, option, g]]:
constant[
Return a dict of options for the window.
For familiarity with tmux, the option ``option`` param forwards to
pick a single option, forwarding to :meth:`Window.show_window_option`.
Parameters
-------... | keyword[def] identifier[show_window_options] ( identifier[self] , identifier[option] = keyword[None] , identifier[g] = keyword[False] ):
literal[string]
identifier[tmux_args] = identifier[tuple] ()
keyword[if] identifier[g] :
identifier[tmux_args] +=( literal[string] ,)
... | def show_window_options(self, option=None, g=False):
"""
Return a dict of options for the window.
For familiarity with tmux, the option ``option`` param forwards to
pick a single option, forwarding to :meth:`Window.show_window_option`.
Parameters
----------
option :... |
def read_hotkey(suppress=True):
"""
Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p"
"""
queue = _queue.Queue()
fn = lambda e:... | def function[read_hotkey, parameter[suppress]]:
constant[
Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p"
]
variable[queu... | keyword[def] identifier[read_hotkey] ( identifier[suppress] = keyword[True] ):
literal[string]
identifier[queue] = identifier[_queue] . identifier[Queue] ()
identifier[fn] = keyword[lambda] identifier[e] : identifier[queue] . identifier[put] ( identifier[e] ) keyword[or] identifier[e] . identifier[e... | def read_hotkey(suppress=True):
"""
Similar to `read_key()`, but blocks until the user presses and releases a
hotkey (or single key), then returns a string representing the hotkey
pressed.
Example:
read_hotkey()
# "ctrl+shift+p"
"""
queue = _queue.Queue()
fn = lambda e:... |
def validate_current_versions(self): # type: () -> bool
"""
Can a version be found? Are all versions currently the same? Are they valid sem ver?
:return:
"""
versions = self.all_current_versions()
for _, version in versions.items():
if "Invalid Semantic Versi... | def function[validate_current_versions, parameter[self]]:
constant[
Can a version be found? Are all versions currently the same? Are they valid sem ver?
:return:
]
variable[versions] assign[=] call[name[self].all_current_versions, parameter[]]
for taget[tuple[[<ast.Name o... | keyword[def] identifier[validate_current_versions] ( identifier[self] ):
literal[string]
identifier[versions] = identifier[self] . identifier[all_current_versions] ()
keyword[for] identifier[_] , identifier[version] keyword[in] identifier[versions] . identifier[items] ():
k... | def validate_current_versions(self): # type: () -> bool
'\n Can a version be found? Are all versions currently the same? Are they valid sem ver?\n :return:\n '
versions = self.all_current_versions()
for (_, version) in versions.items():
if 'Invalid Semantic Version' in version:... |
def update_attrs(self, old, new):
""" Update any `attr` members.
Parameters
-----------
old: Declarative
The existing view instance that needs to be updated
new: Declarative
The new view instance that should be used for updating
... | def function[update_attrs, parameter[self, old, new]]:
constant[ Update any `attr` members.
Parameters
-----------
old: Declarative
The existing view instance that needs to be updated
new: Declarative
The new view instance that sho... | keyword[def] identifier[update_attrs] ( identifier[self] , identifier[old] , identifier[new] ):
literal[string]
keyword[if] identifier[new] . identifier[_d_storage] :
identifier[old] . identifier[_d_storage] = identifier[new] . identifier[_d_storage] | def update_attrs(self, old, new):
""" Update any `attr` members.
Parameters
-----------
old: Declarative
The existing view instance that needs to be updated
new: Declarative
The new view instance that should be used for updating
... |
def save_to_disk(self, filename_pattern=None):
"""Returns a callback to convert test record to proto and save to disk."""
if not self._converter:
raise RuntimeError(
'Must set _converter on subclass or via set_converter before calling '
'save_to_disk.')
pattern = filename_pattern ... | def function[save_to_disk, parameter[self, filename_pattern]]:
constant[Returns a callback to convert test record to proto and save to disk.]
if <ast.UnaryOp object at 0x7da1b18aadd0> begin[:]
<ast.Raise object at 0x7da1b18aa6b0>
variable[pattern] assign[=] <ast.BoolOp object at 0x7da1b1... | keyword[def] identifier[save_to_disk] ( identifier[self] , identifier[filename_pattern] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_converter] :
keyword[raise] identifier[RuntimeError] (
literal[string]
literal[string] )
identifi... | def save_to_disk(self, filename_pattern=None):
"""Returns a callback to convert test record to proto and save to disk."""
if not self._converter:
raise RuntimeError('Must set _converter on subclass or via set_converter before calling save_to_disk.') # depends on [control=['if'], data=[]]
pattern = ... |
def clouds(opts):
'''
Return the cloud functions
'''
# Let's bring __active_provider_name__, defaulting to None, to all cloud
# drivers. This will get temporarily updated/overridden with a context
# manager when needed.
functions = LazyLoader(
_module_dirs(opts,
... | def function[clouds, parameter[opts]]:
constant[
Return the cloud functions
]
variable[functions] assign[=] call[name[LazyLoader], parameter[call[name[_module_dirs], parameter[name[opts], constant[clouds], constant[cloud]]], name[opts]]]
for taget[name[funcname]] in starred[name[LIBCLOUD... | keyword[def] identifier[clouds] ( identifier[opts] ):
literal[string]
identifier[functions] = identifier[LazyLoader] (
identifier[_module_dirs] ( identifier[opts] ,
literal[string] ,
literal[string] ,
identifier[base_path] = identifier[os] . identifier[path] . identifier[... | def clouds(opts):
"""
Return the cloud functions
"""
# Let's bring __active_provider_name__, defaulting to None, to all cloud
# drivers. This will get temporarily updated/overridden with a context
# manager when needed.
functions = LazyLoader(_module_dirs(opts, 'clouds', 'cloud', base_path=o... |
def install(self, filepath):
''' TODO(ssx): not tested. '''
if not os.path.exists(filepath):
raise EnvironmentError('file "%s" not exists.' % filepath)
ideviceinstaller = must_look_exec('ideviceinstaller')
os.system(subprocess.list2cmdline([ideviceinstaller, '-u', self.udid,... | def function[install, parameter[self, filepath]]:
constant[ TODO(ssx): not tested. ]
if <ast.UnaryOp object at 0x7da204564220> begin[:]
<ast.Raise object at 0x7da204565090>
variable[ideviceinstaller] assign[=] call[name[must_look_exec], parameter[constant[ideviceinstaller]]]
call... | keyword[def] identifier[install] ( identifier[self] , identifier[filepath] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[filepath] ):
keyword[raise] identifier[EnvironmentError] ( literal[string] % identifier[filepath... | def install(self, filepath):
""" TODO(ssx): not tested. """
if not os.path.exists(filepath):
raise EnvironmentError('file "%s" not exists.' % filepath) # depends on [control=['if'], data=[]]
ideviceinstaller = must_look_exec('ideviceinstaller')
os.system(subprocess.list2cmdline([ideviceinstalle... |
async def send_message(self, event=None):
"""
Sends a message. Does nothing if the client is not connected.
"""
if not self.cl.is_connected():
return
# The user needs to configure a chat where the message should be sent.
#
# If the chat ID does not ex... | <ast.AsyncFunctionDef object at 0x7da1b218bfa0> | keyword[async] keyword[def] identifier[send_message] ( identifier[self] , identifier[event] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[cl] . identifier[is_connected] ():
keyword[return]
... | async def send_message(self, event=None):
"""
Sends a message. Does nothing if the client is not connected.
"""
if not self.cl.is_connected():
return # depends on [control=['if'], data=[]]
# The user needs to configure a chat where the message should be sent.
#
# If the chat... |
def to_str(s):
"""
Convert bytes and non-string into Python 3 str
"""
if isinstance(s, bytes):
s = s.decode('utf-8')
elif not isinstance(s, str):
s = str(s)
return s | def function[to_str, parameter[s]]:
constant[
Convert bytes and non-string into Python 3 str
]
if call[name[isinstance], parameter[name[s], name[bytes]]] begin[:]
variable[s] assign[=] call[name[s].decode, parameter[constant[utf-8]]]
return[name[s]] | keyword[def] identifier[to_str] ( identifier[s] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[s] , identifier[bytes] ):
identifier[s] = identifier[s] . identifier[decode] ( literal[string] )
keyword[elif] keyword[not] identifier[isinstance] ( identifier[s] , identifier... | def to_str(s):
"""
Convert bytes and non-string into Python 3 str
"""
if isinstance(s, bytes):
s = s.decode('utf-8') # depends on [control=['if'], data=[]]
elif not isinstance(s, str):
s = str(s) # depends on [control=['if'], data=[]]
return s |
def dump(obj, fp, **kw):
r"""Dump python object to file.
>>> import lazyxml
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> lazyxml.dump(data, 'dump.xml')
>>> with open('dump-fp.xml', 'w') as fp:
>>> lazyxml.dump(data, fp)
>>> from cStringIO import StringIO
>>> data = {'demo': {'foo'... | def function[dump, parameter[obj, fp]]:
constant[Dump python object to file.
>>> import lazyxml
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> lazyxml.dump(data, 'dump.xml')
>>> with open('dump-fp.xml', 'w') as fp:
>>> lazyxml.dump(data, fp)
>>> from cStringIO import StringIO
>>... | keyword[def] identifier[dump] ( identifier[obj] , identifier[fp] ,** identifier[kw] ):
literal[string]
identifier[xml] = identifier[dumps] ( identifier[obj] ,** identifier[kw] )
keyword[if] identifier[isinstance] ( identifier[fp] , identifier[basestring] ):
keyword[with] identifier[open] ( ... | def dump(obj, fp, **kw):
"""Dump python object to file.
>>> import lazyxml
>>> data = {'demo': {'foo': 1, 'bar': 2}}
>>> lazyxml.dump(data, 'dump.xml')
>>> with open('dump-fp.xml', 'w') as fp:
>>> lazyxml.dump(data, fp)
>>> from cStringIO import StringIO
>>> data = {'demo': {'foo':... |
def set_nweight(self, node_from, node_to, weight_there, weight_back):
r"""
Set a single n-weight / edge-weight.
Parameters
----------
node_from : int
Node-id from the first node of the edge.
node_to : int
Node-id from the second node of th... | def function[set_nweight, parameter[self, node_from, node_to, weight_there, weight_back]]:
constant[
Set a single n-weight / edge-weight.
Parameters
----------
node_from : int
Node-id from the first node of the edge.
node_to : int
Node-id ... | keyword[def] identifier[set_nweight] ( identifier[self] , identifier[node_from] , identifier[node_to] , identifier[weight_there] , identifier[weight_back] ):
literal[string]
keyword[if] identifier[node_from] >= identifier[self] . identifier[__nodes] keyword[or] identifier[node_from] < literal[in... | def set_nweight(self, node_from, node_to, weight_there, weight_back):
"""
Set a single n-weight / edge-weight.
Parameters
----------
node_from : int
Node-id from the first node of the edge.
node_to : int
Node-id from the second node of the edg... |
def reset_mode(self):
"""Send a Reset command to set the operation mode to 0."""
self.command(0x18, b"\x01", timeout=0.1)
self.transport.write(Chipset.ACK)
time.sleep(0.010) | def function[reset_mode, parameter[self]]:
constant[Send a Reset command to set the operation mode to 0.]
call[name[self].command, parameter[constant[24], constant[b'\x01']]]
call[name[self].transport.write, parameter[name[Chipset].ACK]]
call[name[time].sleep, parameter[constant[0.01]]] | keyword[def] identifier[reset_mode] ( identifier[self] ):
literal[string]
identifier[self] . identifier[command] ( literal[int] , literal[string] , identifier[timeout] = literal[int] )
identifier[self] . identifier[transport] . identifier[write] ( identifier[Chipset] . identifier[ACK] )
... | def reset_mode(self):
"""Send a Reset command to set the operation mode to 0."""
self.command(24, b'\x01', timeout=0.1)
self.transport.write(Chipset.ACK)
time.sleep(0.01) |
def notifyReady(self):
"""
Returns a deferred that will fire when the factory has created a
protocol that can be used to communicate with a Mongo server.
Note that this will not fire until we have connected to a Mongo
master, unless slaveOk was specified in the M... | def function[notifyReady, parameter[self]]:
constant[
Returns a deferred that will fire when the factory has created a
protocol that can be used to communicate with a Mongo server.
Note that this will not fire until we have connected to a Mongo
master, unless sla... | keyword[def] identifier[notifyReady] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[instance] :
keyword[return] identifier[defer] . identifier[succeed] ( identifier[self] . identifier[instance] )
keyword[def] identifier[on_cancel] ( identif... | def notifyReady(self):
"""
Returns a deferred that will fire when the factory has created a
protocol that can be used to communicate with a Mongo server.
Note that this will not fire until we have connected to a Mongo
master, unless slaveOk was specified in the Mongo... |
def from_any_pb(pb_type, any_pb):
"""Converts an ``Any`` protobuf to the specified message type.
Args:
pb_type (type): the type of the message that any_pb stores an instance
of.
any_pb (google.protobuf.any_pb2.Any): the object to be converted.
Returns:
pb_type: An insta... | def function[from_any_pb, parameter[pb_type, any_pb]]:
constant[Converts an ``Any`` protobuf to the specified message type.
Args:
pb_type (type): the type of the message that any_pb stores an instance
of.
any_pb (google.protobuf.any_pb2.Any): the object to be converted.
Ret... | keyword[def] identifier[from_any_pb] ( identifier[pb_type] , identifier[any_pb] ):
literal[string]
identifier[msg] = identifier[pb_type] ()
keyword[if] identifier[callable] ( identifier[getattr] ( identifier[pb_type] , literal[string] , keyword[None] )):
identifier[msg_pb] = identifier... | def from_any_pb(pb_type, any_pb):
"""Converts an ``Any`` protobuf to the specified message type.
Args:
pb_type (type): the type of the message that any_pb stores an instance
of.
any_pb (google.protobuf.any_pb2.Any): the object to be converted.
Returns:
pb_type: An insta... |
def prepare(args):
"""
%prog prepare [--options] folder [--bam rnaseq.coordSorted.bam]
Run Trinity on a folder of reads. When paired-end (--paired) mode is on,
filenames will be scanned based on whether they contain the patterns
("_1_" and "_2_") or (".1." and ".2.") or ("_1." and "_2.").
By ... | def function[prepare, parameter[args]]:
constant[
%prog prepare [--options] folder [--bam rnaseq.coordSorted.bam]
Run Trinity on a folder of reads. When paired-end (--paired) mode is on,
filenames will be scanned based on whether they contain the patterns
("_1_" and "_2_") or (".1." and ".2.")... | keyword[def] identifier[prepare] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[prepare] . identifier[__doc__] )
identifier[p] . identifier[add_option] ( literal[string] , identifier[default] = keyword[False] , identifier[action] = literal[string] ,
id... | def prepare(args):
"""
%prog prepare [--options] folder [--bam rnaseq.coordSorted.bam]
Run Trinity on a folder of reads. When paired-end (--paired) mode is on,
filenames will be scanned based on whether they contain the patterns
("_1_" and "_2_") or (".1." and ".2.") or ("_1." and "_2.").
By ... |
def optplot(modes=('absorption',), filenames=None, prefix=None, directory=None,
gaussian=None, band_gaps=None, labels=None, average=True, height=6,
width=6, xmin=0, xmax=None, ymin=0, ymax=1e5, colours=None,
style=None, no_base_style=None,
image_format='pdf', dpi=400, plt... | def function[optplot, parameter[modes, filenames, prefix, directory, gaussian, band_gaps, labels, average, height, width, xmin, xmax, ymin, ymax, colours, style, no_base_style, image_format, dpi, plt, fonts]]:
constant[A script to plot optical absorption spectra from VASP calculations.
Args:
modes ... | keyword[def] identifier[optplot] ( identifier[modes] =( literal[string] ,), identifier[filenames] = keyword[None] , identifier[prefix] = keyword[None] , identifier[directory] = keyword[None] ,
identifier[gaussian] = keyword[None] , identifier[band_gaps] = keyword[None] , identifier[labels] = keyword[None] , identifi... | def optplot(modes=('absorption',), filenames=None, prefix=None, directory=None, gaussian=None, band_gaps=None, labels=None, average=True, height=6, width=6, xmin=0, xmax=None, ymin=0, ymax=100000.0, colours=None, style=None, no_base_style=None, image_format='pdf', dpi=400, plt=None, fonts=None):
"""A script to plot... |
def __remove_queue_logging_handler():
'''
This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers.
'''
global LOGGING_STORE_HANDLER
if LOGGING_STORE_HANDLER is None:
# Already removed
return
... | def function[__remove_queue_logging_handler, parameter[]]:
constant[
This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers.
]
<ast.Global object at 0x7da1b215d420>
if compare[name[LOGGING_STORE_HANDLER... | keyword[def] identifier[__remove_queue_logging_handler] ():
literal[string]
keyword[global] identifier[LOGGING_STORE_HANDLER]
keyword[if] identifier[LOGGING_STORE_HANDLER] keyword[is] keyword[None] :
keyword[return]
identifier[root_logger] = identifier[logging] . identifier[g... | def __remove_queue_logging_handler():
"""
This function will run once the additional loggers have been synchronized.
It just removes the QueueLoggingHandler from the logging handlers.
"""
global LOGGING_STORE_HANDLER
if LOGGING_STORE_HANDLER is None:
# Already removed
return # d... |
def adaptive_graph_lasso(X, model_selector, method):
"""Run QuicGraphicalLassoCV or QuicGraphicalLassoEBIC as a two step adaptive fit
with method of choice (currently: 'binary', 'inverse', 'inverse_squared').
Compare the support and values to the model-selection estimator.
"""
metric = "log_likelih... | def function[adaptive_graph_lasso, parameter[X, model_selector, method]]:
constant[Run QuicGraphicalLassoCV or QuicGraphicalLassoEBIC as a two step adaptive fit
with method of choice (currently: 'binary', 'inverse', 'inverse_squared').
Compare the support and values to the model-selection estimator.
... | keyword[def] identifier[adaptive_graph_lasso] ( identifier[X] , identifier[model_selector] , identifier[method] ):
literal[string]
identifier[metric] = literal[string]
identifier[print] ( literal[string] . identifier[format] ( identifier[model_selector] ))
identifier[print] ( literal[string] . i... | def adaptive_graph_lasso(X, model_selector, method):
"""Run QuicGraphicalLassoCV or QuicGraphicalLassoEBIC as a two step adaptive fit
with method of choice (currently: 'binary', 'inverse', 'inverse_squared').
Compare the support and values to the model-selection estimator.
"""
metric = 'log_likelih... |
def get_tagged_version(self):
"""
Get the version of the local working set as a StrictVersion or
None if no viable tag exists. If the local working set is itself
the tagged commit and the tip and there are no local
modifications, use the tag on the parent changeset.
"""
tags = list(self.get_tags())
if '... | def function[get_tagged_version, parameter[self]]:
constant[
Get the version of the local working set as a StrictVersion or
None if no viable tag exists. If the local working set is itself
the tagged commit and the tip and there are no local
modifications, use the tag on the parent changeset.
]
... | keyword[def] identifier[get_tagged_version] ( identifier[self] ):
literal[string]
identifier[tags] = identifier[list] ( identifier[self] . identifier[get_tags] ())
keyword[if] literal[string] keyword[in] identifier[tags] keyword[and] keyword[not] identifier[self] . identifier[is_modified] ():
iden... | def get_tagged_version(self):
"""
Get the version of the local working set as a StrictVersion or
None if no viable tag exists. If the local working set is itself
the tagged commit and the tip and there are no local
modifications, use the tag on the parent changeset.
"""
tags = list(self.get_tags())
... |
def _callInTransaction(self, func, *args, **kwargs):
"""Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back."""
# No nesting of transactions
self.conn.rollback()
try:... | def function[_callInTransaction, parameter[self, func]]:
constant[Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back.]
call[name[self].conn.rollback, parameter[]]
<ast.Try object... | keyword[def] identifier[_callInTransaction] ( identifier[self] , identifier[func] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[conn] . identifier[rollback] ()
keyword[try] :
identifier[self] . identifier[cur] = identifie... | def _callInTransaction(self, func, *args, **kwargs):
"""Execute the given function inside of a transaction, with an
open cursor. If no exception is raised, the transaction is
comitted, otherwise it is rolled back."""
# No nesting of transactions
self.conn.rollback()
try:
self.cur... |
def emit(self, record):
"""
Function inserts log messages to list_view
"""
msg = record.getMessage()
list_store = self.list_view.get_model()
Gdk.threads_enter()
if msg:
# Underline URLs in the record message
msg = replace_markup_chars(recor... | def function[emit, parameter[self, record]]:
constant[
Function inserts log messages to list_view
]
variable[msg] assign[=] call[name[record].getMessage, parameter[]]
variable[list_store] assign[=] call[name[self].list_view.get_model, parameter[]]
call[name[Gdk].threads_e... | keyword[def] identifier[emit] ( identifier[self] , identifier[record] ):
literal[string]
identifier[msg] = identifier[record] . identifier[getMessage] ()
identifier[list_store] = identifier[self] . identifier[list_view] . identifier[get_model] ()
identifier[Gdk] . identifier[threa... | def emit(self, record):
"""
Function inserts log messages to list_view
"""
msg = record.getMessage()
list_store = self.list_view.get_model()
Gdk.threads_enter()
if msg:
# Underline URLs in the record message
msg = replace_markup_chars(record.getMessage())
reco... |
def update_thesis_information(self):
"""501 degree info - move subfields."""
fields_501 = record_get_field_instances(self.record, '502')
for idx, field in enumerate(fields_501):
new_subs = []
for key, value in field[0]:
if key == 'a':
n... | def function[update_thesis_information, parameter[self]]:
constant[501 degree info - move subfields.]
variable[fields_501] assign[=] call[name[record_get_field_instances], parameter[name[self].record, constant[502]]]
for taget[tuple[[<ast.Name object at 0x7da207f00280>, <ast.Name object at 0x7da... | keyword[def] identifier[update_thesis_information] ( identifier[self] ):
literal[string]
identifier[fields_501] = identifier[record_get_field_instances] ( identifier[self] . identifier[record] , literal[string] )
keyword[for] identifier[idx] , identifier[field] keyword[in] identifier[en... | def update_thesis_information(self):
"""501 degree info - move subfields."""
fields_501 = record_get_field_instances(self.record, '502')
for (idx, field) in enumerate(fields_501):
new_subs = []
for (key, value) in field[0]:
if key == 'a':
new_subs.append(('b', val... |
def parse_unix(self, lines):
'''Parse listings from a Unix ls command format.'''
# This method uses some Filezilla parsing algorithms
for line in lines:
original_line = line
fields = line.split(' ')
after_perm_index = 0
# Search for the permissio... | def function[parse_unix, parameter[self, lines]]:
constant[Parse listings from a Unix ls command format.]
for taget[name[line]] in starred[name[lines]] begin[:]
variable[original_line] assign[=] name[line]
variable[fields] assign[=] call[name[line].split, parameter[consta... | keyword[def] identifier[parse_unix] ( identifier[self] , identifier[lines] ):
literal[string]
keyword[for] identifier[line] keyword[in] identifier[lines] :
identifier[original_line] = identifier[line]
identifier[fields] = identifier[line] . identifier[split] ... | def parse_unix(self, lines):
"""Parse listings from a Unix ls command format."""
# This method uses some Filezilla parsing algorithms
for line in lines:
original_line = line
fields = line.split(' ')
after_perm_index = 0
# Search for the permissions field by checking the file ... |
def _set_member_bridge_domain(self, v, load=False):
"""
Setter method for member_bridge_domain, mapped from YANG variable /topology_group/member_bridge_domain (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_bridge_domain is considered as a private
... | def function[_set_member_bridge_domain, parameter[self, v, load]]:
constant[
Setter method for member_bridge_domain, mapped from YANG variable /topology_group/member_bridge_domain (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_bridge_domain is con... | keyword[def] identifier[_set_member_bridge_domain] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_member_bridge_domain(self, v, load=False):
"""
Setter method for member_bridge_domain, mapped from YANG variable /topology_group/member_bridge_domain (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_member_bridge_domain is considered as a private
... |
def build_header(self, plugin, attribute, stat):
"""Build and return the header line"""
line = ''
if attribute is not None:
line += '{}.{}{}'.format(plugin, attribute, self.separator)
else:
if isinstance(stat, dict):
for k in stat.keys():
... | def function[build_header, parameter[self, plugin, attribute, stat]]:
constant[Build and return the header line]
variable[line] assign[=] constant[]
if compare[name[attribute] is_not constant[None]] begin[:]
<ast.AugAssign object at 0x7da18ede7df0>
return[name[line]] | keyword[def] identifier[build_header] ( identifier[self] , identifier[plugin] , identifier[attribute] , identifier[stat] ):
literal[string]
identifier[line] = literal[string]
keyword[if] identifier[attribute] keyword[is] keyword[not] keyword[None] :
identifier[line] += l... | def build_header(self, plugin, attribute, stat):
"""Build and return the header line"""
line = ''
if attribute is not None:
line += '{}.{}{}'.format(plugin, attribute, self.separator) # depends on [control=['if'], data=['attribute']]
elif isinstance(stat, dict):
for k in stat.keys():
... |
def _get(self, item):
"""
Helper function to keep the __getattr__ and __getitem__ calls
KISSish
"""
if item not in object.__getattribute__(self, "_protectedItems") \
and item[0] != "_":
data = object.__getattribute__(self, "_data")
if item ... | def function[_get, parameter[self, item]]:
constant[
Helper function to keep the __getattr__ and __getitem__ calls
KISSish
]
if <ast.BoolOp object at 0x7da20c7cb7c0> begin[:]
variable[data] assign[=] call[name[object].__getattribute__, parameter[name[self], consta... | keyword[def] identifier[_get] ( identifier[self] , identifier[item] ):
literal[string]
keyword[if] identifier[item] keyword[not] keyword[in] identifier[object] . identifier[__getattribute__] ( identifier[self] , literal[string] ) keyword[and] identifier[item] [ literal[int] ]!= literal[string]... | def _get(self, item):
"""
Helper function to keep the __getattr__ and __getitem__ calls
KISSish
"""
if item not in object.__getattribute__(self, '_protectedItems') and item[0] != '_':
data = object.__getattribute__(self, '_data')
if item in data:
return data[i... |
def groups(self, user, include=None):
"""
Retrieve the groups for this user.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param user: User object or id
"""
return sel... | def function[groups, parameter[self, user, include]]:
constant[
Retrieve the groups for this user.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param user: User object or id
... | keyword[def] identifier[groups] ( identifier[self] , identifier[user] , identifier[include] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_query_zendesk] ( identifier[self] . identifier[endpoint] . identifier[groups] , literal[string] , identifier[id] = identifie... | def groups(self, user, include=None):
"""
Retrieve the groups for this user.
:param include: list of objects to sideload. `Side-loading API Docs
<https://developer.zendesk.com/rest_api/docs/core/side_loading>`__.
:param user: User object or id
"""
return self._query... |
def accept_line(event):
" Accept the line regardless of where the cursor is. "
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) | def function[accept_line, parameter[event]]:
constant[ Accept the line regardless of where the cursor is. ]
variable[b] assign[=] name[event].current_buffer
call[name[b].accept_action.validate_and_handle, parameter[name[event].cli, name[b]]] | keyword[def] identifier[accept_line] ( identifier[event] ):
literal[string]
identifier[b] = identifier[event] . identifier[current_buffer]
identifier[b] . identifier[accept_action] . identifier[validate_and_handle] ( identifier[event] . identifier[cli] , identifier[b] ) | def accept_line(event):
""" Accept the line regardless of where the cursor is. """
b = event.current_buffer
b.accept_action.validate_and_handle(event.cli, b) |
def install_readline(hook):
'''Set up things for the interpreter to call
our function like GNU readline.'''
global readline_hook, readline_ref
# save the hook so the wrapper can call it
readline_hook = hook
# get the address of PyOS_ReadlineFunctionPointer so we can update it
PyOS_RF... | def function[install_readline, parameter[hook]]:
constant[Set up things for the interpreter to call
our function like GNU readline.]
<ast.Global object at 0x7da1b27e1d80>
variable[readline_hook] assign[=] name[hook]
variable[PyOS_RFP] assign[=] call[name[c_void_p].from_address, paramete... | keyword[def] identifier[install_readline] ( identifier[hook] ):
literal[string]
keyword[global] identifier[readline_hook] , identifier[readline_ref]
identifier[readline_hook] = identifier[hook]
identifier[PyOS_RFP] = identifier[c_void_p] . identifier[from_address] ( identifier[... | def install_readline(hook):
"""Set up things for the interpreter to call
our function like GNU readline."""
global readline_hook, readline_ref # save the hook so the wrapper can call it
readline_hook = hook # get the address of PyOS_ReadlineFunctionPointer so we can update it
PyOS_RFP = c_void_p.... |
def read_mac(self):
""" Read MAC from EFUSE region """
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack(">II", *words)
bitstring = bitstring[2:8] # trim the 2 byte CRC
try:
return tuple(ord(b) for b in bitstring)
except TypeError: # P... | def function[read_mac, parameter[self]]:
constant[ Read MAC from EFUSE region ]
variable[words] assign[=] list[[<ast.Call object at 0x7da18f00c4f0>, <ast.Call object at 0x7da1b23475e0>]]
variable[bitstring] assign[=] call[name[struct].pack, parameter[constant[>II], <ast.Starred object at 0x7da1b... | keyword[def] identifier[read_mac] ( identifier[self] ):
literal[string]
identifier[words] =[ identifier[self] . identifier[read_efuse] ( literal[int] ), identifier[self] . identifier[read_efuse] ( literal[int] )]
identifier[bitstring] = identifier[struct] . identifier[pack] ( literal[strin... | def read_mac(self):
""" Read MAC from EFUSE region """
words = [self.read_efuse(2), self.read_efuse(1)]
bitstring = struct.pack('>II', *words)
bitstring = bitstring[2:8] # trim the 2 byte CRC
try:
return tuple((ord(b) for b in bitstring)) # depends on [control=['try'], data=[]]
except ... |
def extract_audio_video_enabled(param, resp):
"""Extract if any audio/video stream enabled from response."""
return 'true' in [part.split('=')[1] for part in resp.split()
if '.{}Enable='.format(param) in part] | def function[extract_audio_video_enabled, parameter[param, resp]]:
constant[Extract if any audio/video stream enabled from response.]
return[compare[constant[true] in <ast.ListComp object at 0x7da1b106e2c0>]] | keyword[def] identifier[extract_audio_video_enabled] ( identifier[param] , identifier[resp] ):
literal[string]
keyword[return] literal[string] keyword[in] [ identifier[part] . identifier[split] ( literal[string] )[ literal[int] ] keyword[for] identifier[part] keyword[in] identifier[resp] . identifier[... | def extract_audio_video_enabled(param, resp):
"""Extract if any audio/video stream enabled from response."""
return 'true' in [part.split('=')[1] for part in resp.split() if '.{}Enable='.format(param) in part] |
def dkron(A,dA,B,dB, operation='prod'):
"""
Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (or 2... | def function[dkron, parameter[A, dA, B, dB, operation]]:
constant[
Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
S... | keyword[def] identifier[dkron] ( identifier[A] , identifier[dA] , identifier[B] , identifier[dB] , identifier[operation] = literal[string] ):
literal[string]
keyword[if] identifier[dA] keyword[is] keyword[None] :
identifier[dA_param_num] = literal[int]
identifier[dA] = identifier[np]... | def dkron(A, dA, B, dB, operation='prod'):
"""
Function computes the derivative of Kronecker product A*B
(or Kronecker sum A+B).
Input:
-----------------------
A: 2D matrix
Some matrix
dA: 3D (or 2D matrix)
Derivarives of A
B: 2D matrix
Some matrix
dB: 3D (o... |
def _check_first_arg_for_type(self, node, metaclass=0):
"""check the name of first argument, expect:
* 'self' for a regular method
* 'cls' for a class method or a metaclass regular method (actually
valid-classmethod-first-arg value)
* 'mcs' for a metaclass class method (actual... | def function[_check_first_arg_for_type, parameter[self, node, metaclass]]:
constant[check the name of first argument, expect:
* 'self' for a regular method
* 'cls' for a class method or a metaclass regular method (actually
valid-classmethod-first-arg value)
* 'mcs' for a metac... | keyword[def] identifier[_check_first_arg_for_type] ( identifier[self] , identifier[node] , identifier[metaclass] = literal[int] ):
literal[string]
keyword[if] identifier[node] . identifier[args] . identifier[args] keyword[is] keyword[None] :
keyword[return]
identi... | def _check_first_arg_for_type(self, node, metaclass=0):
"""check the name of first argument, expect:
* 'self' for a regular method
* 'cls' for a class method or a metaclass regular method (actually
valid-classmethod-first-arg value)
* 'mcs' for a metaclass class method (actually
... |
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
geometry_field = options.get("geometry_field", "geom")
def FeatureToPython(dictobj):
properties = dictobj['properties']
model_name = options.get("model_name") or properties.pop('mode... | def function[Deserializer, parameter[stream_or_string]]:
constant[
Deserialize a stream or string of JSON data.
]
variable[geometry_field] assign[=] call[name[options].get, parameter[constant[geometry_field], constant[geom]]]
def function[FeatureToPython, parameter[dictobj]]:
... | keyword[def] identifier[Deserializer] ( identifier[stream_or_string] ,** identifier[options] ):
literal[string]
identifier[geometry_field] = identifier[options] . identifier[get] ( literal[string] , literal[string] )
keyword[def] identifier[FeatureToPython] ( identifier[dictobj] ):
identif... | def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
geometry_field = options.get('geometry_field', 'geom')
def FeatureToPython(dictobj):
properties = dictobj['properties']
model_name = options.get('model_name') or properties.pop('model... |
def start_transfer(self):
''' pass the transfer spec to the Aspera sdk and start the transfer '''
try:
if not self.is_done():
faspmanager2.startTransfer(self.get_transfer_id(),
None,
self.ge... | def function[start_transfer, parameter[self]]:
constant[ pass the transfer spec to the Aspera sdk and start the transfer ]
<ast.Try object at 0x7da18eb54160> | keyword[def] identifier[start_transfer] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[if] keyword[not] identifier[self] . identifier[is_done] ():
identifier[faspmanager2] . identifier[startTransfer] ( identifier[self] . identifier[get_transfer_id] (),
... | def start_transfer(self):
""" pass the transfer spec to the Aspera sdk and start the transfer """
try:
if not self.is_done():
faspmanager2.startTransfer(self.get_transfer_id(), None, self.get_transfer_spec(), self) # depends on [control=['if'], data=[]] # depends on [control=['try'], data=... |
def mgmt_request(self, message, operation, op_type=None, node=None, callback=None, **kwargs):
"""Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the target... | def function[mgmt_request, parameter[self, message, operation, op_type, node, callback]]:
constant[Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the targ... | keyword[def] identifier[mgmt_request] ( identifier[self] , identifier[message] , identifier[operation] , identifier[op_type] = keyword[None] , identifier[node] = keyword[None] , identifier[callback] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[while] keyword[not] identifier[s... | def mgmt_request(self, message, operation, op_type=None, node=None, callback=None, **kwargs):
"""Run a request/response operation. These are frequently used for management
tasks against a $management node, however any node name can be specified
and the available options will depend on the target ser... |
def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
token, secret, expires_at = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
p... | def function[request, parameter[self, method, url]]:
constant[Build remote url request. Constructs necessary auth.]
variable[user_token] assign[=] call[name[kwargs].pop, parameter[constant[token], name[self].token]]
<ast.Tuple object at 0x7da1b2651bd0> assign[=] call[name[self].parse_raw_token, ... | keyword[def] identifier[request] ( identifier[self] , identifier[method] , identifier[url] ,** identifier[kwargs] ):
literal[string]
identifier[user_token] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[token] )
identifier[token] , identifier[secre... | def request(self, method, url, **kwargs):
"""Build remote url request. Constructs necessary auth."""
user_token = kwargs.pop('token', self.token)
(token, secret, expires_at) = self.parse_raw_token(user_token)
if token is not None:
params = kwargs.get('params', {})
params['access_token'] ... |
def ttv(self, v, modes=[], without=False):
"""
Tensor times vector product
Parameters
----------
v : 1-d array or tuple of 1-d arrays
Vector to be multiplied with tensor.
modes : array_like of integers, optional
Modes in which the vectors should b... | def function[ttv, parameter[self, v, modes, without]]:
constant[
Tensor times vector product
Parameters
----------
v : 1-d array or tuple of 1-d arrays
Vector to be multiplied with tensor.
modes : array_like of integers, optional
Modes in which th... | keyword[def] identifier[ttv] ( identifier[self] , identifier[v] , identifier[modes] =[], identifier[without] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[v] , identifier[tuple] ):
identifier[v] =( identifier[v] ,)
identifie... | def ttv(self, v, modes=[], without=False):
"""
Tensor times vector product
Parameters
----------
v : 1-d array or tuple of 1-d arrays
Vector to be multiplied with tensor.
modes : array_like of integers, optional
Modes in which the vectors should be mu... |
def set_data(self, data):
"""Sets this parameter's value on all contexts."""
self.shape = data.shape
if self._data is None:
assert self._deferred_init, \
"Parameter '%s' has not been initialized"%self.name
self._deferred_init = self._deferred_init[:3] + (... | def function[set_data, parameter[self, data]]:
constant[Sets this parameter's value on all contexts.]
name[self].shape assign[=] name[data].shape
if compare[name[self]._data is constant[None]] begin[:]
assert[name[self]._deferred_init]
name[self]._deferred_init assign[=] ... | keyword[def] identifier[set_data] ( identifier[self] , identifier[data] ):
literal[string]
identifier[self] . identifier[shape] = identifier[data] . identifier[shape]
keyword[if] identifier[self] . identifier[_data] keyword[is] keyword[None] :
keyword[assert] identifier[... | def set_data(self, data):
"""Sets this parameter's value on all contexts."""
self.shape = data.shape
if self._data is None:
assert self._deferred_init, "Parameter '%s' has not been initialized" % self.name
self._deferred_init = self._deferred_init[:3] + (data,)
return # depends on [... |
def scan(self):
"""Analyze state and queue tasks."""
log.debug("scanning machine: %s..." % self.name)
deployed = set()
services = yield self.client.get_children(self.path + "/services")
for name in services:
log.debug("checking service: '%s'..." % name)
... | def function[scan, parameter[self]]:
constant[Analyze state and queue tasks.]
call[name[log].debug, parameter[binary_operation[constant[scanning machine: %s...] <ast.Mod object at 0x7da2590d6920> name[self].name]]]
variable[deployed] assign[=] call[name[set], parameter[]]
variable[servic... | keyword[def] identifier[scan] ( identifier[self] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] % identifier[self] . identifier[name] )
identifier[deployed] = identifier[set] ()
identifier[services] = keyword[yield] identifier[self] . identifier[client... | def scan(self):
"""Analyze state and queue tasks."""
log.debug('scanning machine: %s...' % self.name)
deployed = set()
services = (yield self.client.get_children(self.path + '/services'))
for name in services:
log.debug("checking service: '%s'..." % name)
try:
(value, met... |
def add_worksheet(self):
"""Add a worksheet to the workbook."""
wsh = self.workbook.add_worksheet()
if self.vars.fld2col_widths is not None:
self.set_xlsx_colwidths(wsh, self.vars.fld2col_widths, self.wbfmtobj.get_prt_flds())
return wsh | def function[add_worksheet, parameter[self]]:
constant[Add a worksheet to the workbook.]
variable[wsh] assign[=] call[name[self].workbook.add_worksheet, parameter[]]
if compare[name[self].vars.fld2col_widths is_not constant[None]] begin[:]
call[name[self].set_xlsx_colwidths, para... | keyword[def] identifier[add_worksheet] ( identifier[self] ):
literal[string]
identifier[wsh] = identifier[self] . identifier[workbook] . identifier[add_worksheet] ()
keyword[if] identifier[self] . identifier[vars] . identifier[fld2col_widths] keyword[is] keyword[not] keyword[None] :
... | def add_worksheet(self):
"""Add a worksheet to the workbook."""
wsh = self.workbook.add_worksheet()
if self.vars.fld2col_widths is not None:
self.set_xlsx_colwidths(wsh, self.vars.fld2col_widths, self.wbfmtobj.get_prt_flds()) # depends on [control=['if'], data=[]]
return wsh |
def write_short(self, n):
"""Write an integer as an unsigned 16-bit value."""
if n < 0 or n > 65535:
raise FrameSyntaxError(
'Octet {0!r} out of range 0..65535'.format(n))
self._flushbits()
self.out.write(pack('>H', int(n))) | def function[write_short, parameter[self, n]]:
constant[Write an integer as an unsigned 16-bit value.]
if <ast.BoolOp object at 0x7da18eb54100> begin[:]
<ast.Raise object at 0x7da18f812230>
call[name[self]._flushbits, parameter[]]
call[name[self].out.write, parameter[call[name[pa... | keyword[def] identifier[write_short] ( identifier[self] , identifier[n] ):
literal[string]
keyword[if] identifier[n] < literal[int] keyword[or] identifier[n] > literal[int] :
keyword[raise] identifier[FrameSyntaxError] (
literal[string] . identifier[format] ( identifie... | def write_short(self, n):
"""Write an integer as an unsigned 16-bit value."""
if n < 0 or n > 65535:
raise FrameSyntaxError('Octet {0!r} out of range 0..65535'.format(n)) # depends on [control=['if'], data=[]]
self._flushbits()
self.out.write(pack('>H', int(n))) |
def predict(self, x, *args, **kwargs):
"""
Parameters
----------
x: ndarray
array of Points, (x, y) pairs of shape (N, 2) for 2d kriging
array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging
Returns
-------
Prediction array
... | def function[predict, parameter[self, x]]:
constant[
Parameters
----------
x: ndarray
array of Points, (x, y) pairs of shape (N, 2) for 2d kriging
array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging
Returns
-------
Prediction a... | keyword[def] identifier[predict] ( identifier[self] , identifier[x] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[model] :
keyword[raise] identifier[Exception] ( literal[string] )
identifier[points] = i... | def predict(self, x, *args, **kwargs):
"""
Parameters
----------
x: ndarray
array of Points, (x, y) pairs of shape (N, 2) for 2d kriging
array of Points, (x, y, z) pairs of shape (N, 3) for 3d kriging
Returns
-------
Prediction array
"... |
def write_stilde(self, stilde_dict, group=None):
"""Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the strain to. If No... | def function[write_stilde, parameter[self, stilde_dict, group]]:
constant[Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to writ... | keyword[def] identifier[write_stilde] ( identifier[self] , identifier[stilde_dict] , identifier[group] = keyword[None] ):
literal[string]
identifier[subgroup] = identifier[self] . identifier[data_group] + literal[string]
keyword[if] identifier[group] keyword[is] keyword[None] :
... | def write_stilde(self, stilde_dict, group=None):
"""Writes stilde for each IFO to file.
Parameters
-----------
stilde : {dict, FrequencySeries}
A dict of FrequencySeries where the key is the IFO.
group : {None, str}
The group to write the strain to. If None, ... |
def _publish(self):
"""
Process a publish action on the related object, returns a boolean if a change is made.
Only objects where a version change is needed will be updated.
"""
obj = self.content_object
version = self.get_version()
actioned = False
# On... | def function[_publish, parameter[self]]:
constant[
Process a publish action on the related object, returns a boolean if a change is made.
Only objects where a version change is needed will be updated.
]
variable[obj] assign[=] name[self].content_object
variable[version] ... | keyword[def] identifier[_publish] ( identifier[self] ):
literal[string]
identifier[obj] = identifier[self] . identifier[content_object]
identifier[version] = identifier[self] . identifier[get_version] ()
identifier[actioned] = keyword[False]
keyword[if] ident... | def _publish(self):
"""
Process a publish action on the related object, returns a boolean if a change is made.
Only objects where a version change is needed will be updated.
"""
obj = self.content_object
version = self.get_version()
actioned = False
# Only update if needed
... |
def build_available_time_string(availabilities):
"""
Build a string eliciting for a possible time slot among at least two availabilities.
"""
prefix = 'We have availabilities at '
if len(availabilities) > 3:
prefix = 'We have plenty of availability, including '
prefix += build_time_outp... | def function[build_available_time_string, parameter[availabilities]]:
constant[
Build a string eliciting for a possible time slot among at least two availabilities.
]
variable[prefix] assign[=] constant[We have availabilities at ]
if compare[call[name[len], parameter[name[availabilities]... | keyword[def] identifier[build_available_time_string] ( identifier[availabilities] ):
literal[string]
identifier[prefix] = literal[string]
keyword[if] identifier[len] ( identifier[availabilities] )> literal[int] :
identifier[prefix] = literal[string]
identifier[prefix] += identifier[b... | def build_available_time_string(availabilities):
"""
Build a string eliciting for a possible time slot among at least two availabilities.
"""
prefix = 'We have availabilities at '
if len(availabilities) > 3:
prefix = 'We have plenty of availability, including ' # depends on [control=['if'],... |
def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
"""
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in productio... | def function[create_keyspace_network_topology, parameter[name, dc_replication_map, durable_writes, connections]]:
constant[
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, es... | keyword[def] identifier[create_keyspace_network_topology] ( identifier[name] , identifier[dc_replication_map] , identifier[durable_writes] = keyword[True] , identifier[connections] = keyword[None] ):
literal[string]
identifier[_create_keyspace] ( identifier[name] , identifier[durable_writes] , literal[stri... | def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
"""
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in productio... |
def query(pattern_path, dict_, max_length=None, strip=False,
case_sensitive=False, unique=False, deduplicate=False,
string_transformations=None, hyperlink=False,
return_multiple_columns=False):
"""Query the given dict with the given pattern path and return the result.
The ``patter... | def function[query, parameter[pattern_path, dict_, max_length, strip, case_sensitive, unique, deduplicate, string_transformations, hyperlink, return_multiple_columns]]:
constant[Query the given dict with the given pattern path and return the result.
The ``pattern_path`` is a either a single regular express... | keyword[def] identifier[query] ( identifier[pattern_path] , identifier[dict_] , identifier[max_length] = keyword[None] , identifier[strip] = keyword[False] ,
identifier[case_sensitive] = keyword[False] , identifier[unique] = keyword[False] , identifier[deduplicate] = keyword[False] ,
identifier[string_transformatio... | def query(pattern_path, dict_, max_length=None, strip=False, case_sensitive=False, unique=False, deduplicate=False, string_transformations=None, hyperlink=False, return_multiple_columns=False):
"""Query the given dict with the given pattern path and return the result.
The ``pattern_path`` is a either a single ... |
def hilbert_chip_order(machine):
"""A generator which iterates over a set of chips in a machine in a hilbert
path.
For use as a chip ordering for the sequential placer.
"""
max_dimen = max(machine.width, machine.height)
hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0
... | def function[hilbert_chip_order, parameter[machine]]:
constant[A generator which iterates over a set of chips in a machine in a hilbert
path.
For use as a chip ordering for the sequential placer.
]
variable[max_dimen] assign[=] call[name[max], parameter[name[machine].width, name[machine].he... | keyword[def] identifier[hilbert_chip_order] ( identifier[machine] ):
literal[string]
identifier[max_dimen] = identifier[max] ( identifier[machine] . identifier[width] , identifier[machine] . identifier[height] )
identifier[hilbert_levels] = identifier[int] ( identifier[ceil] ( identifier[log] ( identi... | def hilbert_chip_order(machine):
"""A generator which iterates over a set of chips in a machine in a hilbert
path.
For use as a chip ordering for the sequential placer.
"""
max_dimen = max(machine.width, machine.height)
hilbert_levels = int(ceil(log(max_dimen, 2.0))) if max_dimen >= 1 else 0
... |
def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'):
"""
Return a version of the ASCII map showing reached crop cells.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist... | def function[map_sprinkler, parameter[self, sx, sy, watered_crop, watered_field, dry_field, dry_crop]]:
constant[
Return a version of the ASCII map showing reached crop cells.
]
variable[maplist] assign[=] <ast.ListComp object at 0x7da18dc04400>
for taget[tuple[[<ast.Name object ... | keyword[def] identifier[map_sprinkler] ( identifier[self] , identifier[sx] , identifier[sy] , identifier[watered_crop] = literal[string] , identifier[watered_field] = literal[string] , identifier[dry_field] = literal[string] , identifier[dry_crop] = literal[string] ):
literal[string]
ident... | def map_sprinkler(self, sx, sy, watered_crop='^', watered_field='_', dry_field=' ', dry_crop='x'):
"""
Return a version of the ASCII map showing reached crop cells.
"""
# convert strings (rows) to lists of characters for easier map editing
maplist = [list(s) for s in self.maplist]
for (y... |
async def move_to(self, channel: discord.VoiceChannel):
"""
Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel
"""
if channel.guild != self.channel.guild:
raise TypeError("Cannot move to a different guild.")
... | <ast.AsyncFunctionDef object at 0x7da20c76f940> | keyword[async] keyword[def] identifier[move_to] ( identifier[self] , identifier[channel] : identifier[discord] . identifier[VoiceChannel] ):
literal[string]
keyword[if] identifier[channel] . identifier[guild] != identifier[self] . identifier[channel] . identifier[guild] :
keyword[rai... | async def move_to(self, channel: discord.VoiceChannel):
"""
Moves this player to a voice channel.
Parameters
----------
channel : discord.VoiceChannel
"""
if channel.guild != self.channel.guild:
raise TypeError('Cannot move to a different guild.') # depends on [... |
def from_payload(self, payload):
"""Init frame from binary data."""
self.status = NodeInformationStatus(payload[0])
self.node_id = payload[1] | def function[from_payload, parameter[self, payload]]:
constant[Init frame from binary data.]
name[self].status assign[=] call[name[NodeInformationStatus], parameter[call[name[payload]][constant[0]]]]
name[self].node_id assign[=] call[name[payload]][constant[1]] | keyword[def] identifier[from_payload] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[self] . identifier[status] = identifier[NodeInformationStatus] ( identifier[payload] [ literal[int] ])
identifier[self] . identifier[node_id] = identifier[payload] [ literal[int] ] | def from_payload(self, payload):
"""Init frame from binary data."""
self.status = NodeInformationStatus(payload[0])
self.node_id = payload[1] |
def gammalnStirling(z):
"""
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
"""
return (0.5 * (np.log(2. * np.pi) - np.log(z))) \
+ (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.)) | def function[gammalnStirling, parameter[z]]:
constant[
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
]
return[binary_operation[binary_operation[constant[0.5] * binary_operation[call[name[np].log, parameter[binary_operation[constant[2.0] * name[np].pi]]] - cal... | keyword[def] identifier[gammalnStirling] ( identifier[z] ):
literal[string]
keyword[return] ( literal[int] *( identifier[np] . identifier[log] ( literal[int] * identifier[np] . identifier[pi] )- identifier[np] . identifier[log] ( identifier[z] )))+( identifier[z] *( identifier[np] . identifier[log] ( ident... | def gammalnStirling(z):
"""
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
"""
return 0.5 * (np.log(2.0 * np.pi) - np.log(z)) + z * (np.log(z + 1.0 / (12.0 * z - 1.0 / (10.0 * z))) - 1.0) |
def split_full_path(path):
"""Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> ... | def function[split_full_path, parameter[path]]:
constant[Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
... | keyword[def] identifier[split_full_path] ( identifier[path] ):
literal[string]
keyword[if] identifier[path] . identifier[startswith] ( literal[string] ):
identifier[path] = identifier[path] [ literal[int] :]
keyword[elif] identifier[path] . identifier[startswith] ( literal[string] ):
... | def split_full_path(path):
"""Return pair of bucket without protocol and path
Arguments:
path - valid S3 path, such as s3://somebucket/events
>>> split_full_path('s3://mybucket/path-to-events')
('mybucket', 'path-to-events/')
>>> split_full_path('s3://mybucket')
('mybucket', None)
>>> ... |
def backpropagate_2d(uSin, angles, res, nm, lD=0, coords=None,
weight_angles=True,
onlyreal=False, padding=True, padval=0,
count=None, max_count=None, verbose=0):
r"""2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffracti... | def function[backpropagate_2d, parameter[uSin, angles, res, nm, lD, coords, weight_angles, onlyreal, padding, padval, count, max_count, verbose]]:
constant[2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a plane w... | keyword[def] identifier[backpropagate_2d] ( identifier[uSin] , identifier[angles] , identifier[res] , identifier[nm] , identifier[lD] = literal[int] , identifier[coords] = keyword[None] ,
identifier[weight_angles] = keyword[True] ,
identifier[onlyreal] = keyword[False] , identifier[padding] = keyword[True] , identi... | def backpropagate_2d(uSin, angles, res, nm, lD=0, coords=None, weight_angles=True, onlyreal=False, padding=True, padval=0, count=None, max_count=None, verbose=0):
"""2D backpropagation with the Fourier diffraction theorem
Two-dimensional diffraction tomography reconstruction
algorithm for scattering of a p... |
def bulk_update_resourcedata(scenario_ids, resource_scenarios,**kwargs):
"""
Update the data associated with a list of scenarios.
"""
user_id = kwargs.get('user_id')
res = None
res = {}
net_ids = db.DBSession.query(Scenario.network_id).filter(Scenario.id.in_(scenario_ids)).all()
i... | def function[bulk_update_resourcedata, parameter[scenario_ids, resource_scenarios]]:
constant[
Update the data associated with a list of scenarios.
]
variable[user_id] assign[=] call[name[kwargs].get, parameter[constant[user_id]]]
variable[res] assign[=] constant[None]
variab... | keyword[def] identifier[bulk_update_resourcedata] ( identifier[scenario_ids] , identifier[resource_scenarios] ,** identifier[kwargs] ):
literal[string]
identifier[user_id] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[res] = keyword[None]
identifier[res] ={}
identi... | def bulk_update_resourcedata(scenario_ids, resource_scenarios, **kwargs):
"""
Update the data associated with a list of scenarios.
"""
user_id = kwargs.get('user_id')
res = None
res = {}
net_ids = db.DBSession.query(Scenario.network_id).filter(Scenario.id.in_(scenario_ids)).all()
if ... |
def encode_all_features(dataset, vocabulary):
"""Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset
"""
def my_fn(features):
ret = {}
for k, v in features.items():
v = vocabulary.encode_tf(v)
v = tf.concat([tf.t... | def function[encode_all_features, parameter[dataset, vocabulary]]:
constant[Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset
]
def function[my_fn, parameter[features]]:
variable[ret] assign[=] dictiona... | keyword[def] identifier[encode_all_features] ( identifier[dataset] , identifier[vocabulary] ):
literal[string]
keyword[def] identifier[my_fn] ( identifier[features] ):
identifier[ret] ={}
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[features] . identifier[items] ():
id... | def encode_all_features(dataset, vocabulary):
"""Encode all features.
Args:
dataset: a tf.data.Dataset
vocabulary: a vocabulary.Vocabulary
Returns:
a tf.data.Dataset
"""
def my_fn(features):
ret = {}
for (k, v) in features.items():
v = vocabulary.encode_tf(v)
... |
def _create_external_tool(self, context, context_id, json_data):
"""
Create an external tool using the passed json_data.
context is either COURSES_API or ACCOUNTS_API.
context_id is the Canvas course_id or account_id, depending on context.
https://canvas.instructure.com/doc/api... | def function[_create_external_tool, parameter[self, context, context_id, json_data]]:
constant[
Create an external tool using the passed json_data.
context is either COURSES_API or ACCOUNTS_API.
context_id is the Canvas course_id or account_id, depending on context.
https://can... | keyword[def] identifier[_create_external_tool] ( identifier[self] , identifier[context] , identifier[context_id] , identifier[json_data] ):
literal[string]
identifier[url] = identifier[context] . identifier[format] ( identifier[context_id] )+ literal[string]
keyword[return] identifier[se... | def _create_external_tool(self, context, context_id, json_data):
"""
Create an external tool using the passed json_data.
context is either COURSES_API or ACCOUNTS_API.
context_id is the Canvas course_id or account_id, depending on context.
https://canvas.instructure.com/doc/api/ext... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.