code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def nsx_controller_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nsx_controller = ET.SubElement(config, "nsx-controller", xmlns="urn:brocade.com:mgmt:brocade-tunnels")
name_key = ET.SubElement(nsx_controller, "name")
name_key.text = kw... | def function[nsx_controller_activate, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[nsx_controller] assign[=] call[name[ET].SubElement, parameter[name[config], constant[nsx-controller]]]
va... | keyword[def] identifier[nsx_controller_activate] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[nsx_controller] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[st... | def nsx_controller_activate(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
nsx_controller = ET.SubElement(config, 'nsx-controller', xmlns='urn:brocade.com:mgmt:brocade-tunnels')
name_key = ET.SubElement(nsx_controller, 'name')
name_key.text = kwargs.pop('name')
... |
def is_valid_ip(ip_address):
"""
Check Validity of an IP address
"""
valid = True
try:
socket.inet_aton(ip_address.strip())
except:
valid = False
return valid | def function[is_valid_ip, parameter[ip_address]]:
constant[
Check Validity of an IP address
]
variable[valid] assign[=] constant[True]
<ast.Try object at 0x7da1b1080d60>
return[name[valid]] | keyword[def] identifier[is_valid_ip] ( identifier[ip_address] ):
literal[string]
identifier[valid] = keyword[True]
keyword[try] :
identifier[socket] . identifier[inet_aton] ( identifier[ip_address] . identifier[strip] ())
keyword[except] :
identifier[valid] = keyword[False]
... | def is_valid_ip(ip_address):
"""
Check Validity of an IP address
"""
valid = True
try:
socket.inet_aton(ip_address.strip()) # depends on [control=['try'], data=[]]
except:
valid = False # depends on [control=['except'], data=[]]
return valid |
def join(self, timeout=None):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all ... | def function[join, parameter[self, timeout]]:
constant[Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item ... | keyword[def] identifier[join] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[self] . identifier[all_tasks_done] . identifier[acquire] ()
keyword[try] :
keyword[while] identifier[self] . identifier[unfinished_tasks] :
id... | def join(self, timeout=None):
"""Blocks until all items in the Queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer thread calls task_done()
to indicate the item was retrieved and all work... |
def query_series_episodes(self, id, absolute_number=None, aired_season=None, aired_episode=None, dvd_season=None,
dvd_episode=None, imdb_id=None, page=1):
"""Query series episodes"""
# perform the request
params = {'absoluteNumber': absolute_number, 'airedSeason': a... | def function[query_series_episodes, parameter[self, id, absolute_number, aired_season, aired_episode, dvd_season, dvd_episode, imdb_id, page]]:
constant[Query series episodes]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b1eb5e40>, <ast.Constant object at 0x7da1b1eb4070>, <ast.Co... | keyword[def] identifier[query_series_episodes] ( identifier[self] , identifier[id] , identifier[absolute_number] = keyword[None] , identifier[aired_season] = keyword[None] , identifier[aired_episode] = keyword[None] , identifier[dvd_season] = keyword[None] ,
identifier[dvd_episode] = keyword[None] , identifier[imdb_... | def query_series_episodes(self, id, absolute_number=None, aired_season=None, aired_episode=None, dvd_season=None, dvd_episode=None, imdb_id=None, page=1):
"""Query series episodes"""
# perform the request
params = {'absoluteNumber': absolute_number, 'airedSeason': aired_season, 'airedEpisode': aired_episode... |
def predict(self, quadruplets):
"""Predicts the ordering between sample distances in input quadruplets.
For each quadruplet, returns 1 if the quadruplet is in the right order (
first pair is more similar than second pair), and -1 if not.
Parameters
----------
quadruplets : array-like, shape=(n... | def function[predict, parameter[self, quadruplets]]:
constant[Predicts the ordering between sample distances in input quadruplets.
For each quadruplet, returns 1 if the quadruplet is in the right order (
first pair is more similar than second pair), and -1 if not.
Parameters
----------
qua... | keyword[def] identifier[predict] ( identifier[self] , identifier[quadruplets] ):
literal[string]
identifier[check_is_fitted] ( identifier[self] , literal[string] )
identifier[quadruplets] = identifier[check_input] ( identifier[quadruplets] , identifier[type_of_inputs] = literal[string] ,
identifi... | def predict(self, quadruplets):
"""Predicts the ordering between sample distances in input quadruplets.
For each quadruplet, returns 1 if the quadruplet is in the right order (
first pair is more similar than second pair), and -1 if not.
Parameters
----------
quadruplets : array-like, shape=(n... |
def start(**kwargs):
''' Start KodeDrive daemon. '''
output, err = cli_syncthing_adapter.start(**kwargs)
click.echo("%s" % output, err=err) | def function[start, parameter[]]:
constant[ Start KodeDrive daemon. ]
<ast.Tuple object at 0x7da1b209e7a0> assign[=] call[name[cli_syncthing_adapter].start, parameter[]]
call[name[click].echo, parameter[binary_operation[constant[%s] <ast.Mod object at 0x7da2590d6920> name[output]]]] | keyword[def] identifier[start] (** identifier[kwargs] ):
literal[string]
identifier[output] , identifier[err] = identifier[cli_syncthing_adapter] . identifier[start] (** identifier[kwargs] )
identifier[click] . identifier[echo] ( literal[string] % identifier[output] , identifier[err] = identifier[err] ) | def start(**kwargs):
""" Start KodeDrive daemon. """
(output, err) = cli_syncthing_adapter.start(**kwargs)
click.echo('%s' % output, err=err) |
def run(self, inputs, **kwargs):
"""Run model inference and return the result
Parameters
----------
inputs : numpy array
input to run a layer on
Returns
-------
params : numpy array
result obtained after running the inference on mxnet
... | def function[run, parameter[self, inputs]]:
constant[Run model inference and return the result
Parameters
----------
inputs : numpy array
input to run a layer on
Returns
-------
params : numpy array
result obtained after running the infer... | keyword[def] identifier[run] ( identifier[self] , identifier[inputs] ,** identifier[kwargs] ):
literal[string]
identifier[input_data] = identifier[np] . identifier[asarray] ( identifier[inputs] [ literal[int] ], identifier[dtype] = literal[string] )
keyword[if] identifier[self] ... | def run(self, inputs, **kwargs):
"""Run model inference and return the result
Parameters
----------
inputs : numpy array
input to run a layer on
Returns
-------
params : numpy array
result obtained after running the inference on mxnet
... |
def apply_rectwv_coeff(reduced_image,
rectwv_coeff,
args_resampling=2,
args_ignore_dtu_configuration=True,
debugplot=0):
"""Compute rectification and wavelength calibration coefficients.
Parameters
----------
re... | def function[apply_rectwv_coeff, parameter[reduced_image, rectwv_coeff, args_resampling, args_ignore_dtu_configuration, debugplot]]:
constant[Compute rectification and wavelength calibration coefficients.
Parameters
----------
reduced_image : HDUList object
Image with preliminary basic redu... | keyword[def] identifier[apply_rectwv_coeff] ( identifier[reduced_image] ,
identifier[rectwv_coeff] ,
identifier[args_resampling] = literal[int] ,
identifier[args_ignore_dtu_configuration] = keyword[True] ,
identifier[debugplot] = literal[int] ):
literal[string]
identifier[logger] = identifier[logging]... | def apply_rectwv_coeff(reduced_image, rectwv_coeff, args_resampling=2, args_ignore_dtu_configuration=True, debugplot=0):
"""Compute rectification and wavelength calibration coefficients.
Parameters
----------
reduced_image : HDUList object
Image with preliminary basic reduction: bpm, bias, dark... |
def _fullCloneOrFallback(self):
"""Wrapper for _fullClone(). In the case of failure, if clobberOnFailure
is set to True remove the build directory and try a full clone again.
"""
res = yield self._fullClone()
if res != RC_SUCCESS:
if not self.clobberOnFailure:
... | def function[_fullCloneOrFallback, parameter[self]]:
constant[Wrapper for _fullClone(). In the case of failure, if clobberOnFailure
is set to True remove the build directory and try a full clone again.
]
variable[res] assign[=] <ast.Yield object at 0x7da1b21e31f0>
if compare[n... | keyword[def] identifier[_fullCloneOrFallback] ( identifier[self] ):
literal[string]
identifier[res] = keyword[yield] identifier[self] . identifier[_fullClone] ()
keyword[if] identifier[res] != identifier[RC_SUCCESS] :
keyword[if] keyword[not] identifier[self] . identifier... | def _fullCloneOrFallback(self):
"""Wrapper for _fullClone(). In the case of failure, if clobberOnFailure
is set to True remove the build directory and try a full clone again.
"""
res = (yield self._fullClone())
if res != RC_SUCCESS:
if not self.clobberOnFailure:
raise ... |
def _set_as_int(self, addr, val, numBytes = 1):
"""Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes."""
if not isinstance(v... | def function[_set_as_int, parameter[self, addr, val, numBytes]]:
constant[Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes.]
... | keyword[def] identifier[_set_as_int] ( identifier[self] , identifier[addr] , identifier[val] , identifier[numBytes] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[val] , identifier[int] ):
keyword[raise] identifier[ValueError] ( litera... | def _set_as_int(self, addr, val, numBytes=1):
"""Convenience method. Oftentimes we need to set a range of registers
to represent an int. This method will automatically set @numBytes registers
starting at @addr. It will convert the int @val into an array of bytes."""
if not isinstance(val, int):
... |
def import_name(modulename, name=None):
""" Import identifier ``name`` from module ``modulename``.
If ``name`` is omitted, ``modulename`` must contain the name after the
module path, delimited by a colon.
Parameters:
modulename (str): Fully qualified module name, e.g. ``x.y.z``... | def function[import_name, parameter[modulename, name]]:
constant[ Import identifier ``name`` from module ``modulename``.
If ``name`` is omitted, ``modulename`` must contain the name after the
module path, delimited by a colon.
Parameters:
modulename (str): Fully qualified m... | keyword[def] identifier[import_name] ( identifier[modulename] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[name] keyword[is] keyword[None] :
identifier[modulename] , identifier[name] = identifier[modulename] . identifier[rsplit] ( literal[string] , literal[int] )... | def import_name(modulename, name=None):
""" Import identifier ``name`` from module ``modulename``.
If ``name`` is omitted, ``modulename`` must contain the name after the
module path, delimited by a colon.
Parameters:
modulename (str): Fully qualified module name, e.g. ``x.y.z``... |
def remember_forever(self, key, callback):
"""
Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed
"""
# If the item e... | def function[remember_forever, parameter[self, key, callback]]:
constant[
Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed
... | keyword[def] identifier[remember_forever] ( identifier[self] , identifier[key] , identifier[callback] ):
literal[string]
identifier[val] = identifier[self] . identifier[get] ( identifier[key] )
keyword[if] identifier[val] keyword[is] keyword[not] keyword[None... | def remember_forever(self, key, callback):
"""
Get an item from the cache, or store the default value forever.
:param key: The cache key
:type key: str
:param callback: The default function
:type callback: mixed
:rtype: mixed
"""
# If the item exists in... |
def to_shapely_line_string(self, closed=False, interpolate=0):
"""
Convert this polygon to a Shapely LineString object.
Parameters
----------
closed : bool, optional
Whether to return the line string with the last point being identical to the first point.
in... | def function[to_shapely_line_string, parameter[self, closed, interpolate]]:
constant[
Convert this polygon to a Shapely LineString object.
Parameters
----------
closed : bool, optional
Whether to return the line string with the last point being identical to the first... | keyword[def] identifier[to_shapely_line_string] ( identifier[self] , identifier[closed] = keyword[False] , identifier[interpolate] = literal[int] ):
literal[string]
keyword[return] identifier[_convert_points_to_shapely_line_string] ( identifier[self] . identifier[exterior] , identifier[closed] = i... | def to_shapely_line_string(self, closed=False, interpolate=0):
"""
Convert this polygon to a Shapely LineString object.
Parameters
----------
closed : bool, optional
Whether to return the line string with the last point being identical to the first point.
interp... |
def _get_object(data, position, obj_end, opts, dummy):
"""Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
obj_size, end = _get_object_size(data, position, obj_end)
if _raw_document_class(opts.document_class):
return (opts.document_class(data[position:end + 1], opts),
... | def function[_get_object, parameter[data, position, obj_end, opts, dummy]]:
constant[Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef.]
<ast.Tuple object at 0x7da20c992620> assign[=] call[name[_get_object_size], parameter[name[data], name[position], name[obj_end]]]
if call[na... | keyword[def] identifier[_get_object] ( identifier[data] , identifier[position] , identifier[obj_end] , identifier[opts] , identifier[dummy] ):
literal[string]
identifier[obj_size] , identifier[end] = identifier[_get_object_size] ( identifier[data] , identifier[position] , identifier[obj_end] )
keyword... | def _get_object(data, position, obj_end, opts, dummy):
"""Decode a BSON subdocument to opts.document_class or bson.dbref.DBRef."""
(obj_size, end) = _get_object_size(data, position, obj_end)
if _raw_document_class(opts.document_class):
return (opts.document_class(data[position:end + 1], opts), posit... |
def __decode_data_time(self, payload):
"""Extract time and decode payload (based on mime type) from payload. Applies to E_FEEDDATA and E_RECENTDATA.
Returns tuple of data, mime, time."""
data, mime = self.__bytes_to_share_data(payload)
try:
time = datetime.strptime(payload.ge... | def function[__decode_data_time, parameter[self, payload]]:
constant[Extract time and decode payload (based on mime type) from payload. Applies to E_FEEDDATA and E_RECENTDATA.
Returns tuple of data, mime, time.]
<ast.Tuple object at 0x7da1b1b17070> assign[=] call[name[self].__bytes_to_share_data... | keyword[def] identifier[__decode_data_time] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[data] , identifier[mime] = identifier[self] . identifier[__bytes_to_share_data] ( identifier[payload] )
keyword[try] :
identifier[time] = identifier[datetime] . i... | def __decode_data_time(self, payload):
"""Extract time and decode payload (based on mime type) from payload. Applies to E_FEEDDATA and E_RECENTDATA.
Returns tuple of data, mime, time."""
(data, mime) = self.__bytes_to_share_data(payload)
try:
time = datetime.strptime(payload.get(P_TIME), sel... |
def on_background_image(self, *args):
"""When I get a new ``background_image``, store its texture in
``background_texture``.
"""
if self.background_image is not None:
self.background_texture = self.background_image.texture | def function[on_background_image, parameter[self]]:
constant[When I get a new ``background_image``, store its texture in
``background_texture``.
]
if compare[name[self].background_image is_not constant[None]] begin[:]
name[self].background_texture assign[=] name[self].ba... | keyword[def] identifier[on_background_image] ( identifier[self] ,* identifier[args] ):
literal[string]
keyword[if] identifier[self] . identifier[background_image] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[background_texture] = identifier[self] . identif... | def on_background_image(self, *args):
"""When I get a new ``background_image``, store its texture in
``background_texture``.
"""
if self.background_image is not None:
self.background_texture = self.background_image.texture # depends on [control=['if'], data=[]] |
def find(self, **kwargs):
"""Returns List(typeof=).
Executes collection's find method based on keyword args
maps results ( dict to list of entity instances).
Set max_limit parameter to limit the amount of data send back through network
Example::
manager = EntityMa... | def function[find, parameter[self]]:
constant[Returns List(typeof=).
Executes collection's find method based on keyword args
maps results ( dict to list of entity instances).
Set max_limit parameter to limit the amount of data send back through network
Example::
m... | keyword[def] identifier[find] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[max_limit] = keyword[None]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[max_limit] = identifier[kwargs] . identifier[pop] ( literal[string] )
... | def find(self, **kwargs):
"""Returns List(typeof=).
Executes collection's find method based on keyword args
maps results ( dict to list of entity instances).
Set max_limit parameter to limit the amount of data send back through network
Example::
manager = EntityManage... |
def update_event_source_mapping(UUID,
FunctionName=None, Enabled=None, BatchSize=None,
region=None, key=None, keyid=None, profile=None):
'''
Update the event source mapping identified by the UUID.
Returns {updated: true} if the alias was updat... | def function[update_event_source_mapping, parameter[UUID, FunctionName, Enabled, BatchSize, region, key, keyid, profile]]:
constant[
Update the event source mapping identified by the UUID.
Returns {updated: true} if the alias was updated and returns
{updated: False} if the alias was not updated.
... | keyword[def] identifier[update_event_source_mapping] ( identifier[UUID] ,
identifier[FunctionName] = keyword[None] , identifier[Enabled] = keyword[None] , identifier[BatchSize] = keyword[None] ,
identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[pro... | def update_event_source_mapping(UUID, FunctionName=None, Enabled=None, BatchSize=None, region=None, key=None, keyid=None, profile=None):
"""
Update the event source mapping identified by the UUID.
Returns {updated: true} if the alias was updated and returns
{updated: False} if the alias was not updated... |
def singleChoiceParam(parameters, name, type_converter = str):
""" single choice parameter value. Returns -1 if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a different type (e.g. str, ... | def function[singleChoiceParam, parameter[parameters, name, type_converter]]:
constant[ single choice parameter value. Returns -1 if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a d... | keyword[def] identifier[singleChoiceParam] ( identifier[parameters] , identifier[name] , identifier[type_converter] = identifier[str] ):
literal[string]
identifier[param] = identifier[parameters] . identifier[find] ( literal[string] . identifier[format] ( identifier[name] = identifier[name] ))
identif... | def singleChoiceParam(parameters, name, type_converter=str):
""" single choice parameter value. Returns -1 if no value was chosen.
:param parameters: the parameters tree.
:param name: the name of the parameter.
:param type_converter: function to convert the chosen value to a different type (e.g. str, fl... |
def _getJsonOrig(url):
'''internal'''
url = _URL_PREFIX + url
resp = requests.get(urlparse(url).geturl(), proxies=_PYEX_PROXIES)
if resp.status_code == 200:
return resp.json()
raise PyEXception('Response %d - ' % resp.status_code, resp.text) | def function[_getJsonOrig, parameter[url]]:
constant[internal]
variable[url] assign[=] binary_operation[name[_URL_PREFIX] + name[url]]
variable[resp] assign[=] call[name[requests].get, parameter[call[call[name[urlparse], parameter[name[url]]].geturl, parameter[]]]]
if compare[name[resp].... | keyword[def] identifier[_getJsonOrig] ( identifier[url] ):
literal[string]
identifier[url] = identifier[_URL_PREFIX] + identifier[url]
identifier[resp] = identifier[requests] . identifier[get] ( identifier[urlparse] ( identifier[url] ). identifier[geturl] (), identifier[proxies] = identifier[_PYEX_PR... | def _getJsonOrig(url):
"""internal"""
url = _URL_PREFIX + url
resp = requests.get(urlparse(url).geturl(), proxies=_PYEX_PROXIES)
if resp.status_code == 200:
return resp.json() # depends on [control=['if'], data=[]]
raise PyEXception('Response %d - ' % resp.status_code, resp.text) |
def i2c_bitrate(self):
"""I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz.
"""
ret = api.py_aa_i2c_bitrate(self.handle, 0)
_raise... | def function[i2c_bitrate, parameter[self]]:
constant[I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz.
]
variable[ret] assign[=] call[name[... | keyword[def] identifier[i2c_bitrate] ( identifier[self] ):
literal[string]
identifier[ret] = identifier[api] . identifier[py_aa_i2c_bitrate] ( identifier[self] . identifier[handle] , literal[int] )
identifier[_raise_error_if_negative] ( identifier[ret] )
keyword[return] identifi... | def i2c_bitrate(self):
"""I2C bitrate in kHz. Not every bitrate is supported by the host
adapter. Therefore, the actual bitrate may be less than the value which
is set.
The power-on default value is 100 kHz.
"""
ret = api.py_aa_i2c_bitrate(self.handle, 0)
_raise_error_if_neg... |
def get_history(self, exp, rep, tags):
""" returns the whole history for one experiment and one repetition.
tags can be a string or a list of strings. if tags is a string,
the history is returned as list of values, if tags is a list of
strings or 'all', history is returned a... | def function[get_history, parameter[self, exp, rep, tags]]:
constant[ returns the whole history for one experiment and one repetition.
tags can be a string or a list of strings. if tags is a string,
the history is returned as list of values, if tags is a list of
strings or '... | keyword[def] identifier[get_history] ( identifier[self] , identifier[exp] , identifier[rep] , identifier[tags] ):
literal[string]
identifier[params] = identifier[self] . identifier[get_params] ( identifier[exp] )
keyword[if] identifier[params] == keyword[None] :
keyword[rais... | def get_history(self, exp, rep, tags):
""" returns the whole history for one experiment and one repetition.
tags can be a string or a list of strings. if tags is a string,
the history is returned as list of values, if tags is a list of
strings or 'all', history is returned as a ... |
def select_features(cls, features_id, file_struct, annot_beats, framesync):
"""Selects the features from the given parameters.
Parameters
----------
features_id: str
The identifier of the features (it must be a key inside the
`features_registry`)
file_str... | def function[select_features, parameter[cls, features_id, file_struct, annot_beats, framesync]]:
constant[Selects the features from the given parameters.
Parameters
----------
features_id: str
The identifier of the features (it must be a key inside the
`features_... | keyword[def] identifier[select_features] ( identifier[cls] , identifier[features_id] , identifier[file_struct] , identifier[annot_beats] , identifier[framesync] ):
literal[string]
keyword[if] keyword[not] identifier[annot_beats] keyword[and] identifier[framesync] :
identifier[feat_... | def select_features(cls, features_id, file_struct, annot_beats, framesync):
"""Selects the features from the given parameters.
Parameters
----------
features_id: str
The identifier of the features (it must be a key inside the
`features_registry`)
file_struct:... |
def get_credentials(self):
"""Get read-only credentials.
Returns:
class: Read-only credentials.
"""
return ReadOnlyCredentials(
self.access_token, self.client_id, self.client_secret,
self.refresh_token
) | def function[get_credentials, parameter[self]]:
constant[Get read-only credentials.
Returns:
class: Read-only credentials.
]
return[call[name[ReadOnlyCredentials], parameter[name[self].access_token, name[self].client_id, name[self].client_secret, name[self].refresh_token]]] | keyword[def] identifier[get_credentials] ( identifier[self] ):
literal[string]
keyword[return] identifier[ReadOnlyCredentials] (
identifier[self] . identifier[access_token] , identifier[self] . identifier[client_id] , identifier[self] . identifier[client_secret] ,
identifier[self... | def get_credentials(self):
"""Get read-only credentials.
Returns:
class: Read-only credentials.
"""
return ReadOnlyCredentials(self.access_token, self.client_id, self.client_secret, self.refresh_token) |
def K2onSilicon_main(args=None):
"""Function called when `K2onSilicon` is executed on the command line."""
import argparse
parser = argparse.ArgumentParser(
description="Run K2onSilicon to find which targets in a "
"list call on active silicon for a given K2 campaign.")
parse... | def function[K2onSilicon_main, parameter[args]]:
constant[Function called when `K2onSilicon` is executed on the command line.]
import module[argparse]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].add_argument, parameter[constant[csv_file]]]
... | keyword[def] identifier[K2onSilicon_main] ( identifier[args] = keyword[None] ):
literal[string]
keyword[import] identifier[argparse]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string]
literal[string] )
identifier[parser]... | def K2onSilicon_main(args=None):
"""Function called when `K2onSilicon` is executed on the command line."""
import argparse
parser = argparse.ArgumentParser(description='Run K2onSilicon to find which targets in a list call on active silicon for a given K2 campaign.')
parser.add_argument('csv_file', type=... |
def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPy... | def function[get_ipython_module_path, parameter[module_str]]:
constant[Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
... | keyword[def] identifier[get_ipython_module_path] ( identifier[module_str] ):
literal[string]
keyword[if] identifier[module_str] == literal[string] :
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[get_ipython_package_dir] (), literal[string] )
identifier[mo... | def get_ipython_module_path(module_str):
"""Find the path to an IPython module in this version of IPython.
This will always find the version of the module that is in this importable
IPython package. This will always return the path to the ``.py``
version of the module.
"""
if module_str == 'IPy... |
def create_secgroup_rule(self, protocol, from_port, to_port,
source, target):
"""
Creates a new server security group rule.
:param str protocol: E.g. ``tcp``, ``icmp``, etc...
:param int from_port: E.g. ``1``
:param int to_port: E.g. ``65535``
:param str s... | def function[create_secgroup_rule, parameter[self, protocol, from_port, to_port, source, target]]:
constant[
Creates a new server security group rule.
:param str protocol: E.g. ``tcp``, ``icmp``, etc...
:param int from_port: E.g. ``1``
:param int to_port: E.g. ``65535``
... | keyword[def] identifier[create_secgroup_rule] ( identifier[self] , identifier[protocol] , identifier[from_port] , identifier[to_port] ,
identifier[source] , identifier[target] ):
literal[string]
identifier[nova] = identifier[self] . identifier[nova]
keyword[def] identifier[get_id] ( id... | def create_secgroup_rule(self, protocol, from_port, to_port, source, target):
"""
Creates a new server security group rule.
:param str protocol: E.g. ``tcp``, ``icmp``, etc...
:param int from_port: E.g. ``1``
:param int to_port: E.g. ``65535``
:param str source:
:... |
def execute(self, command, *args, **kwargs):
"""Execute sentinel command."""
# TODO: choose pool
# kwargs can be used to control which sentinel to use
if self.closed:
raise PoolClosedError("Sentinel pool is closed")
for pool in self._pools:
return pool.e... | def function[execute, parameter[self, command]]:
constant[Execute sentinel command.]
if name[self].closed begin[:]
<ast.Raise object at 0x7da18bc70340>
for taget[name[pool]] in starred[name[self]._pools] begin[:]
return[call[name[pool].execute, parameter[name[command], <ast.Starr... | keyword[def] identifier[execute] ( identifier[self] , identifier[command] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[closed] :
keyword[raise] identifier[PoolClosedError] ( literal[string] )
keywor... | def execute(self, command, *args, **kwargs):
"""Execute sentinel command."""
# TODO: choose pool
# kwargs can be used to control which sentinel to use
if self.closed:
raise PoolClosedError('Sentinel pool is closed') # depends on [control=['if'], data=[]]
for pool in self._pools:
r... |
def plot_return_on_dollar(rets, title='Return on $1', show_maxdd=0, figsize=None, ax=None, append=0, label=None, **plot_args):
""" Show the cumulative return of specified rets and max drawdowns if selected."""
crets = (1. + returns_cumulative(rets, expanding=1))
if isinstance(crets, pd.DataFrame):
t... | def function[plot_return_on_dollar, parameter[rets, title, show_maxdd, figsize, ax, append, label]]:
constant[ Show the cumulative return of specified rets and max drawdowns if selected.]
variable[crets] assign[=] binary_operation[constant[1.0] + call[name[returns_cumulative], parameter[name[rets]]]]
... | keyword[def] identifier[plot_return_on_dollar] ( identifier[rets] , identifier[title] = literal[string] , identifier[show_maxdd] = literal[int] , identifier[figsize] = keyword[None] , identifier[ax] = keyword[None] , identifier[append] = literal[int] , identifier[label] = keyword[None] ,** identifier[plot_args] ):
... | def plot_return_on_dollar(rets, title='Return on $1', show_maxdd=0, figsize=None, ax=None, append=0, label=None, **plot_args):
""" Show the cumulative return of specified rets and max drawdowns if selected."""
crets = 1.0 + returns_cumulative(rets, expanding=1)
if isinstance(crets, pd.DataFrame):
tm... |
def cli_info(data, title='Info'):
'''
Prints an info on CLI with the title.
Useful for infos, general errors etc.
:param data:
:param title:
:return:
'''
wrapper = textwrap.TextWrapper()
wrapper.initial_indent = ' ' * 4
wrapper.subsequent_indent = wrapper.initial_indent
re... | def function[cli_info, parameter[data, title]]:
constant[
Prints an info on CLI with the title.
Useful for infos, general errors etc.
:param data:
:param title:
:return:
]
variable[wrapper] assign[=] call[name[textwrap].TextWrapper, parameter[]]
name[wrapper].initial_ind... | keyword[def] identifier[cli_info] ( identifier[data] , identifier[title] = literal[string] ):
literal[string]
identifier[wrapper] = identifier[textwrap] . identifier[TextWrapper] ()
identifier[wrapper] . identifier[initial_indent] = literal[string] * literal[int]
identifier[wrapper] . identifie... | def cli_info(data, title='Info'):
"""
Prints an info on CLI with the title.
Useful for infos, general errors etc.
:param data:
:param title:
:return:
"""
wrapper = textwrap.TextWrapper()
wrapper.initial_indent = ' ' * 4
wrapper.subsequent_indent = wrapper.initial_indent
retu... |
def compute_Rk(L,A,n_samples):
# TODO: need to inspect more into compute Rk.
"""
Compute sparse L matrix and neighbors.
Returns
-------
Rk_tensor : array-like. Length = n
each component correspond to the sparse matrix of Lk, which is
generated by extracting the kth row of laplac... | def function[compute_Rk, parameter[L, A, n_samples]]:
constant[
Compute sparse L matrix and neighbors.
Returns
-------
Rk_tensor : array-like. Length = n
each component correspond to the sparse matrix of Lk, which is
generated by extracting the kth row of laplacian and removing ... | keyword[def] identifier[compute_Rk] ( identifier[L] , identifier[A] , identifier[n_samples] ):
literal[string]
identifier[laplacian_matrix] = identifier[L] . identifier[copy] ()
identifier[laplacian_matrix] . identifier[setdiag] ( literal[int] )
identifier[laplacian_matrix] . identifier[eliminat... | def compute_Rk(L, A, n_samples):
# TODO: need to inspect more into compute Rk.
'\n Compute sparse L matrix and neighbors.\n\n Returns\n -------\n Rk_tensor : array-like. Length = n\n each component correspond to the sparse matrix of Lk, which is\n generated by extracting the kth row of... |
def is_domain_class_collection_attribute(ent, attr_name):
"""
Checks if the given attribute name is a aggregate attribute of the given
registered resource.
"""
attr = get_domain_class_attribute(ent, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION | def function[is_domain_class_collection_attribute, parameter[ent, attr_name]]:
constant[
Checks if the given attribute name is a aggregate attribute of the given
registered resource.
]
variable[attr] assign[=] call[name[get_domain_class_attribute], parameter[name[ent], name[attr_name]]]
... | keyword[def] identifier[is_domain_class_collection_attribute] ( identifier[ent] , identifier[attr_name] ):
literal[string]
identifier[attr] = identifier[get_domain_class_attribute] ( identifier[ent] , identifier[attr_name] )
keyword[return] identifier[attr] . identifier[kind] == identifier[RESOURCE_A... | def is_domain_class_collection_attribute(ent, attr_name):
"""
Checks if the given attribute name is a aggregate attribute of the given
registered resource.
"""
attr = get_domain_class_attribute(ent, attr_name)
return attr.kind == RESOURCE_ATTRIBUTE_KINDS.COLLECTION |
def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info("Reading CONLL sentences from dataset files at: %s", file_path)
for root, _, files in list(os.walk(file_path))... | def function[dataset_path_iterator, parameter[file_path]]:
constant[
An iterator returning file_paths in a directory
containing CONLL-formatted files.
]
call[name[logger].info, parameter[constant[Reading CONLL sentences from dataset files at: %s], name[file_path]]]
for ta... | keyword[def] identifier[dataset_path_iterator] ( identifier[file_path] : identifier[str] )-> identifier[Iterator] [ identifier[str] ]:
literal[string]
identifier[logger] . identifier[info] ( literal[string] , identifier[file_path] )
keyword[for] identifier[root] , identifier[_] , identifi... | def dataset_path_iterator(file_path: str) -> Iterator[str]:
"""
An iterator returning file_paths in a directory
containing CONLL-formatted files.
"""
logger.info('Reading CONLL sentences from dataset files at: %s', file_path)
for (root, _, files) in list(os.walk(file_path)):
... |
def record_to_objects(self, preference=None):
"""Create objects from files, or merge the files into the objects. """
from ambry.orm.file import File
for f in self.list_records():
pref = preference if preference else f.record.preference
if pref == File.PREFERENCE.FILE:
... | def function[record_to_objects, parameter[self, preference]]:
constant[Create objects from files, or merge the files into the objects. ]
from relative_module[ambry.orm.file] import module[File]
for taget[name[f]] in starred[call[name[self].list_records, parameter[]]] begin[:]
variabl... | keyword[def] identifier[record_to_objects] ( identifier[self] , identifier[preference] = keyword[None] ):
literal[string]
keyword[from] identifier[ambry] . identifier[orm] . identifier[file] keyword[import] identifier[File]
keyword[for] identifier[f] keyword[in] identifier[self] . ... | def record_to_objects(self, preference=None):
"""Create objects from files, or merge the files into the objects. """
from ambry.orm.file import File
for f in self.list_records():
pref = preference if preference else f.record.preference
if pref == File.PREFERENCE.FILE:
self._bundl... |
def strip_escape(string='', encoding="utf-8"): # pylint: disable=redefined-outer-name
"""
Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string
"""
matches = []
try:
if hasattr(string, "... | def function[strip_escape, parameter[string, encoding]]:
constant[
Strip escape characters from string.
:param string: string to work on
:param encoding: string name of the encoding used.
:return: stripped string
]
variable[matches] assign[=] list[[]]
<ast.Try object at 0x7da1b0... | keyword[def] identifier[strip_escape] ( identifier[string] = literal[string] , identifier[encoding] = literal[string] ):
literal[string]
identifier[matches] =[]
keyword[try] :
keyword[if] identifier[hasattr] ( identifier[string] , literal[string] ):
identifier[string] = identifi... | def strip_escape(string='', encoding='utf-8'): # pylint: disable=redefined-outer-name
'\n Strip escape characters from string.\n\n :param string: string to work on\n :param encoding: string name of the encoding used.\n :return: stripped string\n '
matches = []
try:
if hasattr(string,... |
def read_namespaced_service_status(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_service_status # noqa: E501
read status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pas... | def function[read_namespaced_service_status, parameter[self, name, namespace]]:
constant[read_namespaced_service_status # noqa: E501
read status of the specified Service # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please ... | keyword[def] identifier[read_namespaced_service_status] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def read_namespaced_service_status(self, name, namespace, **kwargs): # noqa: E501
"read_namespaced_service_status # noqa: E501\n\n read status of the specified Service # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass ... |
def _get_folder(gi, folder_name, library, libitems):
"""Retrieve or create a folder inside the library with the specified name.
"""
for item in libitems:
if item["type"] == "folder" and item["name"] == "/%s" % folder_name:
return item
return gi.libraries.create_folder(library.id, fol... | def function[_get_folder, parameter[gi, folder_name, library, libitems]]:
constant[Retrieve or create a folder inside the library with the specified name.
]
for taget[name[item]] in starred[name[libitems]] begin[:]
if <ast.BoolOp object at 0x7da1b1849bd0> begin[:]
return[... | keyword[def] identifier[_get_folder] ( identifier[gi] , identifier[folder_name] , identifier[library] , identifier[libitems] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[libitems] :
keyword[if] identifier[item] [ literal[string] ]== literal[string] keyword[and] ide... | def _get_folder(gi, folder_name, library, libitems):
"""Retrieve or create a folder inside the library with the specified name.
"""
for item in libitems:
if item['type'] == 'folder' and item['name'] == '/%s' % folder_name:
return item # depends on [control=['if'], data=[]] # depends on... |
def _build(self, inputs):
"""Dynamic unroll across input objects.
Args:
inputs: tensor (batch x num_objects x feature). Objects to sort.
Returns:
Tensor (batch x num_objects); logits indicating the reference objects.
"""
batch_size = inputs.get_shape()[0]
output_sequence, _ = tf.nn... | def function[_build, parameter[self, inputs]]:
constant[Dynamic unroll across input objects.
Args:
inputs: tensor (batch x num_objects x feature). Objects to sort.
Returns:
Tensor (batch x num_objects); logits indicating the reference objects.
]
variable[batch_size] assign[=] c... | keyword[def] identifier[_build] ( identifier[self] , identifier[inputs] ):
literal[string]
identifier[batch_size] = identifier[inputs] . identifier[get_shape] ()[ literal[int] ]
identifier[output_sequence] , identifier[_] = identifier[tf] . identifier[nn] . identifier[dynamic_rnn] (
identifier[ce... | def _build(self, inputs):
"""Dynamic unroll across input objects.
Args:
inputs: tensor (batch x num_objects x feature). Objects to sort.
Returns:
Tensor (batch x num_objects); logits indicating the reference objects.
"""
batch_size = inputs.get_shape()[0]
(output_sequence, _) = tf.... |
def _serialize(cls, key, value, fields):
""" Marshal outgoing data into Taskwarrior's JSON format."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value) | def function[_serialize, parameter[cls, key, value, fields]]:
constant[ Marshal outgoing data into Taskwarrior's JSON format.]
variable[converter] assign[=] call[name[cls]._get_converter_for_field, parameter[name[key], constant[None], name[fields]]]
return[call[name[converter].serialize, parameter[n... | keyword[def] identifier[_serialize] ( identifier[cls] , identifier[key] , identifier[value] , identifier[fields] ):
literal[string]
identifier[converter] = identifier[cls] . identifier[_get_converter_for_field] ( identifier[key] , keyword[None] , identifier[fields] )
keyword[return] ident... | def _serialize(cls, key, value, fields):
""" Marshal outgoing data into Taskwarrior's JSON format."""
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value) |
def _get_search_page(
self,
query,
page,
per_page=1000,
mentions=3,
data=False,
):
"""
Retrieve one page of search results from the DocumentCloud API.
"""
if mentions > 10:
raise ValueError("You cannot search for more than 1... | def function[_get_search_page, parameter[self, query, page, per_page, mentions, data]]:
constant[
Retrieve one page of search results from the DocumentCloud API.
]
if compare[name[mentions] greater[>] constant[10]] begin[:]
<ast.Raise object at 0x7da1b0cff250>
variable[pa... | keyword[def] identifier[_get_search_page] (
identifier[self] ,
identifier[query] ,
identifier[page] ,
identifier[per_page] = literal[int] ,
identifier[mentions] = literal[int] ,
identifier[data] = keyword[False] ,
):
literal[string]
keyword[if] identifier[mentions] > literal[int] :
... | def _get_search_page(self, query, page, per_page=1000, mentions=3, data=False):
"""
Retrieve one page of search results from the DocumentCloud API.
"""
if mentions > 10:
raise ValueError('You cannot search for more than 10 mentions') # depends on [control=['if'], data=[]]
params = {... |
def cycle_dist(x, y, perimeter):
"""Find Distance between x, y by means of a n-length cycle.
:param x:
:param y:
:param perimeter:
Example:
>>> cycle_dist(1, 23, 24) = 2
>>> cycle_dist(5, 13, 24) = 8
>>> cycle_dist(0.0, 2.4, 1.0) = 0.4
>>> cycle_dist(0.0, 2.6, 1.0)... | def function[cycle_dist, parameter[x, y, perimeter]]:
constant[Find Distance between x, y by means of a n-length cycle.
:param x:
:param y:
:param perimeter:
Example:
>>> cycle_dist(1, 23, 24) = 2
>>> cycle_dist(5, 13, 24) = 8
>>> cycle_dist(0.0, 2.4, 1.0) = 0.4
... | keyword[def] identifier[cycle_dist] ( identifier[x] , identifier[y] , identifier[perimeter] ):
literal[string]
identifier[dist] = identifier[abs] ( identifier[x] - identifier[y] )% identifier[perimeter]
keyword[if] identifier[dist] > literal[int] * identifier[perimeter] :
identifier[dist] =... | def cycle_dist(x, y, perimeter):
"""Find Distance between x, y by means of a n-length cycle.
:param x:
:param y:
:param perimeter:
Example:
>>> cycle_dist(1, 23, 24) = 2
>>> cycle_dist(5, 13, 24) = 8
>>> cycle_dist(0.0, 2.4, 1.0) = 0.4
>>> cycle_dist(0.0, 2.6, 1.0)... |
def is_condition_met(self, hand, win_tile, melds, is_tsumo):
"""
Three closed pon sets, the other sets need not to be closed
:param hand: list of hand's sets
:param win_tile: 136 tiles format
:param melds: list Meld objects
:param is_tsumo:
:return: true|false
... | def function[is_condition_met, parameter[self, hand, win_tile, melds, is_tsumo]]:
constant[
Three closed pon sets, the other sets need not to be closed
:param hand: list of hand's sets
:param win_tile: 136 tiles format
:param melds: list Meld objects
:param is_tsumo:
... | keyword[def] identifier[is_condition_met] ( identifier[self] , identifier[hand] , identifier[win_tile] , identifier[melds] , identifier[is_tsumo] ):
literal[string]
identifier[win_tile] //= literal[int]
identifier[open_sets] =[ identifier[x] . identifier[tiles_34] keyword[for] identifi... | def is_condition_met(self, hand, win_tile, melds, is_tsumo):
"""
Three closed pon sets, the other sets need not to be closed
:param hand: list of hand's sets
:param win_tile: 136 tiles format
:param melds: list Meld objects
:param is_tsumo:
:return: true|false
... |
def _outer_distance_mod_n(ref, est, modulus=12):
"""Compute the absolute outer distance modulo n.
Using this distance, d(11, 0) = 1 (modulo 12)
Parameters
----------
ref : np.ndarray, shape=(n,)
Array of reference values.
est : np.ndarray, shape=(m,)
Array of estimated values.
... | def function[_outer_distance_mod_n, parameter[ref, est, modulus]]:
constant[Compute the absolute outer distance modulo n.
Using this distance, d(11, 0) = 1 (modulo 12)
Parameters
----------
ref : np.ndarray, shape=(n,)
Array of reference values.
est : np.ndarray, shape=(m,)
... | keyword[def] identifier[_outer_distance_mod_n] ( identifier[ref] , identifier[est] , identifier[modulus] = literal[int] ):
literal[string]
identifier[ref_mod_n] = identifier[np] . identifier[mod] ( identifier[ref] , identifier[modulus] )
identifier[est_mod_n] = identifier[np] . identifier[mod] ( ident... | def _outer_distance_mod_n(ref, est, modulus=12):
"""Compute the absolute outer distance modulo n.
Using this distance, d(11, 0) = 1 (modulo 12)
Parameters
----------
ref : np.ndarray, shape=(n,)
Array of reference values.
est : np.ndarray, shape=(m,)
Array of estimated values.
... |
def org_task(task_key, lock_timeout=None):
"""
Decorator to create an org task.
:param task_key: the task key used for state storage and locking, e.g. 'do-stuff'
:param lock_timeout: the lock timeout in seconds
"""
def _org_task(task_func):
def _decorator(org_id):
org = apps... | def function[org_task, parameter[task_key, lock_timeout]]:
constant[
Decorator to create an org task.
:param task_key: the task key used for state storage and locking, e.g. 'do-stuff'
:param lock_timeout: the lock timeout in seconds
]
def function[_org_task, parameter[task_func]]:
... | keyword[def] identifier[org_task] ( identifier[task_key] , identifier[lock_timeout] = keyword[None] ):
literal[string]
keyword[def] identifier[_org_task] ( identifier[task_func] ):
keyword[def] identifier[_decorator] ( identifier[org_id] ):
identifier[org] = identifier[apps] . iden... | def org_task(task_key, lock_timeout=None):
"""
Decorator to create an org task.
:param task_key: the task key used for state storage and locking, e.g. 'do-stuff'
:param lock_timeout: the lock timeout in seconds
"""
def _org_task(task_func):
def _decorator(org_id):
org = app... |
def help_string():
"""Generate help string with contents of registry."""
help_str = """
Registry contents:
------------------
Models:
%s
HParams:
%s
RangedHParams:
%s
Problems:
%s
Optimizers:
%s
Attacks:
%s
Attack HParams:
%s
Pruning HParams:
%s
Pruning Strategies:
%s
Env Problems:
%s
... | def function[help_string, parameter[]]:
constant[Generate help string with contents of registry.]
variable[help_str] assign[=] constant[
Registry contents:
------------------
Models:
%s
HParams:
%s
RangedHParams:
%s
Problems:
%s
Optimizers:
%s
Attacks:
%s
Attack HParams:
%s
Pruni... | keyword[def] identifier[help_string] ():
literal[string]
identifier[help_str] = literal[string]
identifier[lists] = identifier[tuple] (
identifier[display_list_by_prefix] ( identifier[entries] , identifier[starting_spaces] = literal[int] ) keyword[for] identifier[entries] keyword[in] [
identifier[l... | def help_string():
"""Generate help string with contents of registry."""
help_str = '\nRegistry contents:\n------------------\n\n Models:\n%s\n\n HParams:\n%s\n\n RangedHParams:\n%s\n\n Problems:\n%s\n\n Optimizers:\n%s\n\n Attacks:\n%s\n\n Attack HParams:\n%s\n\n Pruning HParams:\n%s\n\n Pruning Strat... |
def build_keyjar(key_conf, kid_template="", keyjar=None, owner=''):
"""
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
an existing KeyJar based on a key specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", ... | def function[build_keyjar, parameter[key_conf, kid_template, keyjar, owner]]:
constant[
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
an existing KeyJar based on a key specification.
An example of such a specification::
keys = [
{"type": "RSA", "key":... | keyword[def] identifier[build_keyjar] ( identifier[key_conf] , identifier[kid_template] = literal[string] , identifier[keyjar] = keyword[None] , identifier[owner] = literal[string] ):
literal[string]
keyword[if] identifier[keyjar] keyword[is] keyword[None] :
identifier[keyjar] = identifier[Key... | def build_keyjar(key_conf, kid_template='', keyjar=None, owner=''):
"""
Builds a :py:class:`oidcmsg.key_jar.KeyJar` instance or adds keys to
an existing KeyJar based on a key specification.
An example of such a specification::
keys = [
{"type": "RSA", "key": "cp_keys/key.pem", ... |
def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {
'start': {'line': message.lineno - 1, 'character': message.col},
'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])},
}
severity = lsp.Di... | def function[flake, parameter[self, message]]:
constant[ Get message like <filename>:<lineno>: <msg> ]
variable[err_range] assign[=] dictionary[[<ast.Constant object at 0x7da18c4ccfa0>, <ast.Constant object at 0x7da18c4cdc00>], [<ast.Dict object at 0x7da18c4cd9f0>, <ast.Dict object at 0x7da18c4cc910>]]
... | keyword[def] identifier[flake] ( identifier[self] , identifier[message] ):
literal[string]
identifier[err_range] ={
literal[string] :{ literal[string] : identifier[message] . identifier[lineno] - literal[int] , literal[string] : identifier[message] . identifier[col] },
literal[str... | def flake(self, message):
""" Get message like <filename>:<lineno>: <msg> """
err_range = {'start': {'line': message.lineno - 1, 'character': message.col}, 'end': {'line': message.lineno - 1, 'character': len(self.lines[message.lineno - 1])}}
severity = lsp.DiagnosticSeverity.Warning
for message_type in... |
def is_published(self):
"""Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
"""
field773 = record_get_field_instances(self.record, '773')
for f773 in field773:
if 'c' in field_get_subfields(f773):
... | def function[is_published, parameter[self]]:
constant[Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
]
variable[field773] assign[=] call[name[record_get_field_instances], parameter[name[self].record, constant[773]]]
... | keyword[def] identifier[is_published] ( identifier[self] ):
literal[string]
identifier[field773] = identifier[record_get_field_instances] ( identifier[self] . identifier[record] , literal[string] )
keyword[for] identifier[f773] keyword[in] identifier[field773] :
keyword[if]... | def is_published(self):
"""Check fields 980 and 773 to see if the record has already been published.
:return: True is published, else False
"""
field773 = record_get_field_instances(self.record, '773')
for f773 in field773:
if 'c' in field_get_subfields(f773):
return Tru... |
def keywords(self):
"""
Get the plot keywords for a specific movie id.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('keywords')
response = self._GET(path)
self._set_attrs_to_values(response)
r... | def function[keywords, parameter[self]]:
constant[
Get the plot keywords for a specific movie id.
Returns:
A dict representation of the JSON returned from the API.
]
variable[path] assign[=] call[name[self]._get_id_path, parameter[constant[keywords]]]
variabl... | keyword[def] identifier[keywords] ( identifier[self] ):
literal[string]
identifier[path] = identifier[self] . identifier[_get_id_path] ( literal[string] )
identifier[response] = identifier[self] . identifier[_GET] ( identifier[path] )
identifier[self] . identifier[_set_attrs_to_v... | def keywords(self):
"""
Get the plot keywords for a specific movie id.
Returns:
A dict representation of the JSON returned from the API.
"""
path = self._get_id_path('keywords')
response = self._GET(path)
self._set_attrs_to_values(response)
return response |
def restart(self, offset: int):
'''Send restart command.
Coroutine.
'''
yield from self._control_stream.write_command(Command('REST', str(offset)))
reply = yield from self._control_stream.read_reply()
self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_... | def function[restart, parameter[self, offset]]:
constant[Send restart command.
Coroutine.
]
<ast.YieldFrom object at 0x7da2054a49a0>
variable[reply] assign[=] <ast.YieldFrom object at 0x7da20e962860>
call[name[self].raise_if_not_match, parameter[constant[Restart], name[R... | keyword[def] identifier[restart] ( identifier[self] , identifier[offset] : identifier[int] ):
literal[string]
keyword[yield] keyword[from] identifier[self] . identifier[_control_stream] . identifier[write_command] ( identifier[Command] ( literal[string] , identifier[str] ( identifier[offset] )))
... | def restart(self, offset: int):
"""Send restart command.
Coroutine.
"""
yield from self._control_stream.write_command(Command('REST', str(offset)))
reply = (yield from self._control_stream.read_reply())
self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_pending_further_... |
def get_subdomains_owned_by_address(address, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomains for a given address
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return []
if db_path is None:
db_path = opts['subdomaindb... | def function[get_subdomains_owned_by_address, parameter[address, db_path, zonefiles_dir]]:
constant[
Static method for getting the list of subdomains for a given address
]
variable[opts] assign[=] call[name[get_blockstack_opts], parameter[]]
if <ast.UnaryOp object at 0x7da20e963ac0> begi... | keyword[def] identifier[get_subdomains_owned_by_address] ( identifier[address] , identifier[db_path] = keyword[None] , identifier[zonefiles_dir] = keyword[None] ):
literal[string]
identifier[opts] = identifier[get_blockstack_opts] ()
keyword[if] keyword[not] identifier[is_subdomains_enabled] ( ident... | def get_subdomains_owned_by_address(address, db_path=None, zonefiles_dir=None):
"""
Static method for getting the list of subdomains for a given address
"""
opts = get_blockstack_opts()
if not is_subdomains_enabled(opts):
return [] # depends on [control=['if'], data=[]]
if db_path is No... |
def log_request(handler):
"""
Logging request is opposite to response, sometime its necessary,
feel free to enable it.
"""
block = 'Request Infomations:\n' + _format_headers_log(handler.request.headers)
if handler.request.arguments:
block += '+----Arguments----+\n'
for k, v in h... | def function[log_request, parameter[handler]]:
constant[
Logging request is opposite to response, sometime its necessary,
feel free to enable it.
]
variable[block] assign[=] binary_operation[constant[Request Infomations:
] + call[name[_format_headers_log], parameter[name[handler].request.hea... | keyword[def] identifier[log_request] ( identifier[handler] ):
literal[string]
identifier[block] = literal[string] + identifier[_format_headers_log] ( identifier[handler] . identifier[request] . identifier[headers] )
keyword[if] identifier[handler] . identifier[request] . identifier[arguments] :
... | def log_request(handler):
"""
Logging request is opposite to response, sometime its necessary,
feel free to enable it.
"""
block = 'Request Infomations:\n' + _format_headers_log(handler.request.headers)
if handler.request.arguments:
block += '+----Arguments----+\n'
for (k, v) in ... |
def _read_mol(self):
"""-V3000"""
self.system = dict()
if self.file_content[2] != '\n':
self.system['remarks'] = self.file_content[2]
file_body = [i.split() for i in self.file_content]
elements = []
coordinates = []
atom_data = False
for line i... | def function[_read_mol, parameter[self]]:
constant[-V3000]
name[self].system assign[=] call[name[dict], parameter[]]
if compare[call[name[self].file_content][constant[2]] not_equal[!=] constant[
]] begin[:]
call[name[self].system][constant[remarks]] assign[=] call[name[self].file... | keyword[def] identifier[_read_mol] ( identifier[self] ):
literal[string]
identifier[self] . identifier[system] = identifier[dict] ()
keyword[if] identifier[self] . identifier[file_content] [ literal[int] ]!= literal[string] :
identifier[self] . identifier[system] [ literal[st... | def _read_mol(self):
"""-V3000"""
self.system = dict()
if self.file_content[2] != '\n':
self.system['remarks'] = self.file_content[2] # depends on [control=['if'], data=[]]
file_body = [i.split() for i in self.file_content]
elements = []
coordinates = []
atom_data = False
for li... |
def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) | def function[_hide_tick_lines_and_labels, parameter[axis]]:
constant[
Set visible property of ticklines and ticklabels of an axis to False
]
for taget[name[item]] in starred[binary_operation[call[name[axis].get_ticklines, parameter[]] + call[name[axis].get_ticklabels, parameter[]]]] begin[:]
... | keyword[def] identifier[_hide_tick_lines_and_labels] ( identifier[axis] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[axis] . identifier[get_ticklines] ()+ identifier[axis] . identifier[get_ticklabels] ():
identifier[item] . identifier[set_visible] ( keyword[False] ) | def _hide_tick_lines_and_labels(axis):
"""
Set visible property of ticklines and ticklabels of an axis to False
"""
for item in axis.get_ticklines() + axis.get_ticklabels():
item.set_visible(False) # depends on [control=['for'], data=['item']] |
def args_to_dict(args):
# type: (str) -> DictUpperBound[str,str]
"""Convert command line arguments in a comma separated string to a dictionary
Args:
args (str): Command line arguments
Returns:
DictUpperBound[str,str]: Dictionary of arguments
"""
arguments = dict()
for arg ... | def function[args_to_dict, parameter[args]]:
constant[Convert command line arguments in a comma separated string to a dictionary
Args:
args (str): Command line arguments
Returns:
DictUpperBound[str,str]: Dictionary of arguments
]
variable[arguments] assign[=] call[name[dic... | keyword[def] identifier[args_to_dict] ( identifier[args] ):
literal[string]
identifier[arguments] = identifier[dict] ()
keyword[for] identifier[arg] keyword[in] identifier[args] . identifier[split] ( literal[string] ):
identifier[key] , identifier[value] = identifier[arg] . identifier[spl... | def args_to_dict(args):
# type: (str) -> DictUpperBound[str,str]
'Convert command line arguments in a comma separated string to a dictionary\n\n Args:\n args (str): Command line arguments\n\n Returns:\n DictUpperBound[str,str]: Dictionary of arguments\n\n '
arguments = dict()
for ... |
def load_children(self, f):
"""Load the children of this section from a file-like object"""
while True:
line = self.readline(f)
if line[0] == '&':
if line[1:].startswith("END"):
check_name = line[4:].strip().upper()
if check... | def function[load_children, parameter[self, f]]:
constant[Load the children of this section from a file-like object]
while constant[True] begin[:]
variable[line] assign[=] call[name[self].readline, parameter[name[f]]]
if compare[call[name[line]][constant[0]] equal[==] con... | keyword[def] identifier[load_children] ( identifier[self] , identifier[f] ):
literal[string]
keyword[while] keyword[True] :
identifier[line] = identifier[self] . identifier[readline] ( identifier[f] )
keyword[if] identifier[line] [ literal[int] ]== literal[string] :
... | def load_children(self, f):
"""Load the children of this section from a file-like object"""
while True:
line = self.readline(f)
if line[0] == '&':
if line[1:].startswith('END'):
check_name = line[4:].strip().upper()
if check_name != self.__name:
... |
def _get_module_via_sys_modules(self, fullname):
"""
Attempt to fetch source code via sys.modules. This is specifically to
support __main__, but it may catch a few more cases.
"""
module = sys.modules.get(fullname)
LOG.debug('_get_module_via_sys_modules(%r) -> %r', fullna... | def function[_get_module_via_sys_modules, parameter[self, fullname]]:
constant[
Attempt to fetch source code via sys.modules. This is specifically to
support __main__, but it may catch a few more cases.
]
variable[module] assign[=] call[name[sys].modules.get, parameter[name[fulln... | keyword[def] identifier[_get_module_via_sys_modules] ( identifier[self] , identifier[fullname] ):
literal[string]
identifier[module] = identifier[sys] . identifier[modules] . identifier[get] ( identifier[fullname] )
identifier[LOG] . identifier[debug] ( literal[string] , identifier[fullnam... | def _get_module_via_sys_modules(self, fullname):
"""
Attempt to fetch source code via sys.modules. This is specifically to
support __main__, but it may catch a few more cases.
"""
module = sys.modules.get(fullname)
LOG.debug('_get_module_via_sys_modules(%r) -> %r', fullname, module)
... |
def conditional_expected_average_profit(self, frequency=None, monetary_value=None):
"""
Conditional expectation of the average profit.
This method computes the conditional expectation of the average profit
per transaction for a group of one or more customers.
Parameters
... | def function[conditional_expected_average_profit, parameter[self, frequency, monetary_value]]:
constant[
Conditional expectation of the average profit.
This method computes the conditional expectation of the average profit
per transaction for a group of one or more customers.
P... | keyword[def] identifier[conditional_expected_average_profit] ( identifier[self] , identifier[frequency] = keyword[None] , identifier[monetary_value] = keyword[None] ):
literal[string]
keyword[if] identifier[monetary_value] keyword[is] keyword[None] :
identifier[monetary_value] = ide... | def conditional_expected_average_profit(self, frequency=None, monetary_value=None):
"""
Conditional expectation of the average profit.
This method computes the conditional expectation of the average profit
per transaction for a group of one or more customers.
Parameters
---... |
def get_bucket_page(page):
"""
Returns all the keys in a s3 bucket paginator page.
"""
key_list = page.get('Contents', [])
logger.debug("Retrieving page with {} keys".format(
len(key_list),
))
return dict((k.get('Key'), k) for k in key_list) | def function[get_bucket_page, parameter[page]]:
constant[
Returns all the keys in a s3 bucket paginator page.
]
variable[key_list] assign[=] call[name[page].get, parameter[constant[Contents], list[[]]]]
call[name[logger].debug, parameter[call[constant[Retrieving page with {} keys].format... | keyword[def] identifier[get_bucket_page] ( identifier[page] ):
literal[string]
identifier[key_list] = identifier[page] . identifier[get] ( literal[string] ,[])
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] (
identifier[len] ( identifier[key_list] ),
))
key... | def get_bucket_page(page):
"""
Returns all the keys in a s3 bucket paginator page.
"""
key_list = page.get('Contents', [])
logger.debug('Retrieving page with {} keys'.format(len(key_list)))
return dict(((k.get('Key'), k) for k in key_list)) |
def get_objects(self, path, marker=None,
limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
"""Get objects.
Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object
for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an
extra +1 limit query... | def function[get_objects, parameter[self, path, marker, limit]]:
constant[Get objects.
Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object
for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an
extra +1 limit query and ignore any such file objects.
... | keyword[def] identifier[get_objects] ( identifier[self] , identifier[path] , identifier[marker] = keyword[None] ,
identifier[limit] = identifier[settings] . identifier[CLOUD_BROWSER_DEFAULT_LIST_LIMIT] ):
literal[string]
identifier[folder] = identifier[path] . identifier[split] ( identifi... | def get_objects(self, path, marker=None, limit=settings.CLOUD_BROWSER_DEFAULT_LIST_LIMIT):
"""Get objects.
Certain upload clients may add a 0-byte object (e.g., ``FOLDER`` object
for path ``path/to/FOLDER`` - ``path/to/FOLDER/FOLDER``). We add an
extra +1 limit query and ignore any such fil... |
def forward_ocr(self, img_):
"""Forward the image through the LSTM network model
Parameters
----------
img_: int of array
Returns
----------
label_list: string of list
"""
img_ = cv2.resize(img_, (80, 30))
img_ = img_.transpose(1, 0)
... | def function[forward_ocr, parameter[self, img_]]:
constant[Forward the image through the LSTM network model
Parameters
----------
img_: int of array
Returns
----------
label_list: string of list
]
variable[img_] assign[=] call[name[cv2].resize, p... | keyword[def] identifier[forward_ocr] ( identifier[self] , identifier[img_] ):
literal[string]
identifier[img_] = identifier[cv2] . identifier[resize] ( identifier[img_] ,( literal[int] , literal[int] ))
identifier[img_] = identifier[img_] . identifier[transpose] ( literal[int] , literal[in... | def forward_ocr(self, img_):
"""Forward the image through the LSTM network model
Parameters
----------
img_: int of array
Returns
----------
label_list: string of list
"""
img_ = cv2.resize(img_, (80, 30))
img_ = img_.transpose(1, 0)
print(img_.s... |
def render_field_error(self, obj_id, obj, exception, request):
"""
Default rendering for items in field where the the usual rendering
method raised an exception.
"""
if obj is None:
msg = 'No match for ID={0}'.format(obj_id)
else:
msg = unicode(exc... | def function[render_field_error, parameter[self, obj_id, obj, exception, request]]:
constant[
Default rendering for items in field where the the usual rendering
method raised an exception.
]
if compare[name[obj] is constant[None]] begin[:]
variable[msg] assign[=] ... | keyword[def] identifier[render_field_error] ( identifier[self] , identifier[obj_id] , identifier[obj] , identifier[exception] , identifier[request] ):
literal[string]
keyword[if] identifier[obj] keyword[is] keyword[None] :
identifier[msg] = literal[string] . identifier[format] ( ide... | def render_field_error(self, obj_id, obj, exception, request):
"""
Default rendering for items in field where the the usual rendering
method raised an exception.
"""
if obj is None:
msg = 'No match for ID={0}'.format(obj_id) # depends on [control=['if'], data=[]]
else:
... |
def sync_to(self):
"""Wrapper method that synchronizes configuration to DG.
Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd`
method to sync the configuration TO the device-group.
:note:: Both sync_to, and sync_from methods are convenience
methods wh... | def function[sync_to, parameter[self]]:
constant[Wrapper method that synchronizes configuration to DG.
Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd`
method to sync the configuration TO the device-group.
:note:: Both sync_to, and sync_from methods are convenience... | keyword[def] identifier[sync_to] ( identifier[self] ):
literal[string]
identifier[device_group_collection] = identifier[self] . identifier[_meta_data] [ literal[string] ]
identifier[cm] = identifier[device_group_collection] . identifier[_meta_data] [ literal[string] ]
identifier[s... | def sync_to(self):
"""Wrapper method that synchronizes configuration to DG.
Executes the containing object's cm :meth:`~f5.bigip.cm.Cm.exec_cmd`
method to sync the configuration TO the device-group.
:note:: Both sync_to, and sync_from methods are convenience
methods which ... |
def deleteable(self, request):
'''
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
'''
return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none... | def function[deleteable, parameter[self, request]]:
constant[
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
]
return[<ast.IfExp object at 0x7da20c991fc0>] | keyword[def] identifier[deleteable] ( identifier[self] , identifier[request] ):
literal[string]
keyword[return] identifier[self] . identifier[apply_deleteable] ( identifier[self] . identifier[get_queryset] (), identifier[request] ) keyword[if] identifier[self] . identifier[check_deleteable] ( ide... | def deleteable(self, request):
"""
Checks the both, check_deleteable and apply_deleteable, against the owned model and it's instance set
"""
return self.apply_deleteable(self.get_queryset(), request) if self.check_deleteable(self.model, request) is not False else self.get_queryset().none() |
def summarize_grading(samples, vkey="validate"):
"""Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level)
"""
samples = list(utils.flatten(samples))
if not _has_grading_info(samples, ... | def function[summarize_grading, parameter[samples, vkey]]:
constant[Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level)
]
variable[samples] assign[=] call[name[list], parameter[... | keyword[def] identifier[summarize_grading] ( identifier[samples] , identifier[vkey] = literal[string] ):
literal[string]
identifier[samples] = identifier[list] ( identifier[utils] . identifier[flatten] ( identifier[samples] ))
keyword[if] keyword[not] identifier[_has_grading_info] ( identifier[sampl... | def summarize_grading(samples, vkey='validate'):
"""Provide summaries of grading results across all samples.
Handles both traditional pipelines (validation part of variants) and CWL
pipelines (validation at top level)
"""
samples = list(utils.flatten(samples))
if not _has_grading_info(samples, ... |
def entries(self, query=None):
"""Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
:param query: (opt... | def function[entries, parameter[self, query]]:
constant[Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
... | keyword[def] identifier[entries] ( identifier[self] , identifier[query] = keyword[None] ):
literal[string]
keyword[if] identifier[query] keyword[is] keyword[None] :
identifier[query] ={}
identifier[self] . identifier[_normalize_select] ( identifier[query] )
keywo... | def entries(self, query=None):
"""Fetches all Entries from the Space (up to the set limit, can be modified in `query`).
API Reference: https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/entries/entries-collection/get-all-entries-of-a-space
:param query: (optiona... |
def fetch_page(cls, index, max_=None):
"""
Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :class:`int` or :data:`None... | def function[fetch_page, parameter[cls, index, max_]]:
constant[
Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :clas... | keyword[def] identifier[fetch_page] ( identifier[cls] , identifier[index] , identifier[max_] = keyword[None] ):
literal[string]
identifier[result] = identifier[cls] ()
identifier[result] . identifier[index] = identifier[index]
identifier[result] . identifier[max_] = identifier[m... | def fetch_page(cls, index, max_=None):
"""
Return a query set which requests a specific page.
:param index: Index of the first element of the page to fetch.
:type index: :class:`int`
:param max_: Maximum number of elements to fetch
:type max_: :class:`int` or :data:`None`
... |
def reference_pix_from_wcs(frames, pixref, origin=1):
"""Compute reference pixels between frames using WCS information.
The sky world coordinates are computed on *pixref* using
the WCS of the first frame in the sequence. Then, the
pixel coordinates of the reference sky world-coordinates
are compute... | def function[reference_pix_from_wcs, parameter[frames, pixref, origin]]:
constant[Compute reference pixels between frames using WCS information.
The sky world coordinates are computed on *pixref* using
the WCS of the first frame in the sequence. Then, the
pixel coordinates of the reference sky worl... | keyword[def] identifier[reference_pix_from_wcs] ( identifier[frames] , identifier[pixref] , identifier[origin] = literal[int] ):
literal[string]
identifier[result] =[]
keyword[with] identifier[frames] [ literal[int] ]. identifier[open] () keyword[as] identifier[hdulist] :
identifier[wcsh]... | def reference_pix_from_wcs(frames, pixref, origin=1):
"""Compute reference pixels between frames using WCS information.
The sky world coordinates are computed on *pixref* using
the WCS of the first frame in the sequence. Then, the
pixel coordinates of the reference sky world-coordinates
are compute... |
def validate_quota_change(self, quota_deltas, raise_exception=False):
"""
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
raise_exception - if True QuotaExceededException will be raised if validation fails
quota_deltas - dictio... | def function[validate_quota_change, parameter[self, quota_deltas, raise_exception]]:
constant[
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
raise_exception - if True QuotaExceededException will be raised if validation fails
... | keyword[def] identifier[validate_quota_change] ( identifier[self] , identifier[quota_deltas] , identifier[raise_exception] = keyword[False] ):
literal[string]
identifier[errors] =[]
keyword[for] identifier[name] , identifier[delta] keyword[in] identifier[six] . identifier[iteritems] ( i... | def validate_quota_change(self, quota_deltas, raise_exception=False):
"""
Get error messages about object and his ancestor quotas that will be exceeded if quota_delta will be added.
raise_exception - if True QuotaExceededException will be raised if validation fails
quota_deltas - dictionary... |
def api_key(api_key):
"""Authenticate via an api key."""
none()
_config.api_key_prefix["Authorization"] = "api-key"
_config.api_key["Authorization"] = "key=" + b64encode(api_key.encode()).decode() | def function[api_key, parameter[api_key]]:
constant[Authenticate via an api key.]
call[name[none], parameter[]]
call[name[_config].api_key_prefix][constant[Authorization]] assign[=] constant[api-key]
call[name[_config].api_key][constant[Authorization]] assign[=] binary_operation[constant... | keyword[def] identifier[api_key] ( identifier[api_key] ):
literal[string]
identifier[none] ()
identifier[_config] . identifier[api_key_prefix] [ literal[string] ]= literal[string]
identifier[_config] . identifier[api_key] [ literal[string] ]= literal[string] + identifier[b64encode] ( identifier[... | def api_key(api_key):
"""Authenticate via an api key."""
none()
_config.api_key_prefix['Authorization'] = 'api-key'
_config.api_key['Authorization'] = 'key=' + b64encode(api_key.encode()).decode() |
def list_(pkg=None, dir=None, runas=None, env=None, depth=None):
'''
List installed NPM packages.
If no directory is specified, this will return the list of globally-
installed packages.
pkg
Limit package listing by name
dir
The directory whose packages will be listed, or None... | def function[list_, parameter[pkg, dir, runas, env, depth]]:
constant[
List installed NPM packages.
If no directory is specified, this will return the list of globally-
installed packages.
pkg
Limit package listing by name
dir
The directory whose packages will be listed, o... | keyword[def] identifier[list_] ( identifier[pkg] = keyword[None] , identifier[dir] = keyword[None] , identifier[runas] = keyword[None] , identifier[env] = keyword[None] , identifier[depth] = keyword[None] ):
literal[string]
identifier[env] = identifier[env] keyword[or] {}
keyword[if] identifier[run... | def list_(pkg=None, dir=None, runas=None, env=None, depth=None):
"""
List installed NPM packages.
If no directory is specified, this will return the list of globally-
installed packages.
pkg
Limit package listing by name
dir
The directory whose packages will be listed, or None... |
def cancel(self):
"""Stops the current search and deletes the results cache.
:return: The :class:`Job`.
"""
try:
self.post("control", action="cancel")
except HTTPError as he:
if he.status == 404:
# The job has already been cancelled, so
... | def function[cancel, parameter[self]]:
constant[Stops the current search and deletes the results cache.
:return: The :class:`Job`.
]
<ast.Try object at 0x7da1b1981090>
return[name[self]] | keyword[def] identifier[cancel] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[post] ( literal[string] , identifier[action] = literal[string] )
keyword[except] identifier[HTTPError] keyword[as] identifier[he] :
keyword[if] i... | def cancel(self):
"""Stops the current search and deletes the results cache.
:return: The :class:`Job`.
"""
try:
self.post('control', action='cancel') # depends on [control=['try'], data=[]]
except HTTPError as he:
if he.status == 404:
# The job has already been... |
def do_edit(self, args: argparse.Namespace) -> None:
"""Edit a file in a text editor"""
if not self.editor:
raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.")
command = utils.quote_string_if_needed(os.path.expanduser(self.editor))
... | def function[do_edit, parameter[self, args]]:
constant[Edit a file in a text editor]
if <ast.UnaryOp object at 0x7da18fe91540> begin[:]
<ast.Raise object at 0x7da2045673d0>
variable[command] assign[=] call[name[utils].quote_string_if_needed, parameter[call[name[os].path.expanduser, param... | keyword[def] identifier[do_edit] ( identifier[self] , identifier[args] : identifier[argparse] . identifier[Namespace] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[editor] :
keyword[raise] identifier[EnvironmentError] ( literal[string] )
... | def do_edit(self, args: argparse.Namespace) -> None:
"""Edit a file in a text editor"""
if not self.editor:
raise EnvironmentError("Please use 'set editor' to specify your text editing program of choice.") # depends on [control=['if'], data=[]]
command = utils.quote_string_if_needed(os.path.expandu... |
def notify_txn_invalid(self, txn_id, message=None, extended_data=None):
"""Adds a batch id to the invalid cache along with the id of the
transaction that was rejected and any error message or extended data.
Removes that batch id from the pending set. The cache is only
temporary, and the ... | def function[notify_txn_invalid, parameter[self, txn_id, message, extended_data]]:
constant[Adds a batch id to the invalid cache along with the id of the
transaction that was rejected and any error message or extended data.
Removes that batch id from the pending set. The cache is only
te... | keyword[def] identifier[notify_txn_invalid] ( identifier[self] , identifier[txn_id] , identifier[message] = keyword[None] , identifier[extended_data] = keyword[None] ):
literal[string]
identifier[invalid_txn_info] ={ literal[string] : identifier[txn_id] }
keyword[if] identifier[message] ... | def notify_txn_invalid(self, txn_id, message=None, extended_data=None):
"""Adds a batch id to the invalid cache along with the id of the
transaction that was rejected and any error message or extended data.
Removes that batch id from the pending set. The cache is only
temporary, and the batc... |
def get_image(self, cat, img):
""" Loads an image from disk. """
filename = self.path(cat, img)
data = []
if filename.endswith('mat'):
data = loadmat(filename)['output']
else:
data = imread(filename)
if self.size is not None:
return imr... | def function[get_image, parameter[self, cat, img]]:
constant[ Loads an image from disk. ]
variable[filename] assign[=] call[name[self].path, parameter[name[cat], name[img]]]
variable[data] assign[=] list[[]]
if call[name[filename].endswith, parameter[constant[mat]]] begin[:]
... | keyword[def] identifier[get_image] ( identifier[self] , identifier[cat] , identifier[img] ):
literal[string]
identifier[filename] = identifier[self] . identifier[path] ( identifier[cat] , identifier[img] )
identifier[data] =[]
keyword[if] identifier[filename] . identifier[endswit... | def get_image(self, cat, img):
""" Loads an image from disk. """
filename = self.path(cat, img)
data = []
if filename.endswith('mat'):
data = loadmat(filename)['output'] # depends on [control=['if'], data=[]]
else:
data = imread(filename)
if self.size is not None:
return... |
def replace_parent(self, parent_simples):
"""If ``&`` (or the legacy xCSS equivalent ``self``) appears in this
selector, replace it with the given iterable of parent selectors.
Returns a tuple of simple selectors.
"""
assert parent_simples
ancestors = parent_simples[:-1... | def function[replace_parent, parameter[self, parent_simples]]:
constant[If ``&`` (or the legacy xCSS equivalent ``self``) appears in this
selector, replace it with the given iterable of parent selectors.
Returns a tuple of simple selectors.
]
assert[name[parent_simples]]
var... | keyword[def] identifier[replace_parent] ( identifier[self] , identifier[parent_simples] ):
literal[string]
keyword[assert] identifier[parent_simples]
identifier[ancestors] = identifier[parent_simples] [:- literal[int] ]
identifier[parent] = identifier[parent_simples] [- literal... | def replace_parent(self, parent_simples):
"""If ``&`` (or the legacy xCSS equivalent ``self``) appears in this
selector, replace it with the given iterable of parent selectors.
Returns a tuple of simple selectors.
"""
assert parent_simples
ancestors = parent_simples[:-1]
parent ... |
def _close_last(self):
"""Close the resultset and reset collected meta data.
"""
if self._rs:
self._rs.close()
self._rs = None
if self._prep:
self._prep.close()
self._prep = None
self._meta = None
self._description = None | def function[_close_last, parameter[self]]:
constant[Close the resultset and reset collected meta data.
]
if name[self]._rs begin[:]
call[name[self]._rs.close, parameter[]]
name[self]._rs assign[=] constant[None]
if name[self]._prep begin[:]
call[n... | keyword[def] identifier[_close_last] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_rs] :
identifier[self] . identifier[_rs] . identifier[close] ()
identifier[self] . identifier[_rs] = keyword[None]
keyword[if] identifier[self] . i... | def _close_last(self):
"""Close the resultset and reset collected meta data.
"""
if self._rs:
self._rs.close() # depends on [control=['if'], data=[]]
self._rs = None
if self._prep:
self._prep.close() # depends on [control=['if'], data=[]]
self._prep = None
self._meta = ... |
def complete_xml_element(self, xmlnode, _unused):
"""Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace,... | def function[complete_xml_element, parameter[self, xmlnode, _unused]]:
constant[Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
... | keyword[def] identifier[complete_xml_element] ( identifier[self] , identifier[xmlnode] , identifier[_unused] ):
literal[string]
identifier[tm] = identifier[self] . identifier[timestamp] . identifier[strftime] ( literal[string] )
identifier[xmlnode] . identifier[setProp] ( literal[string] ,... | def complete_xml_element(self, xmlnode, _unused):
"""Complete the XML node with `self` content.
Should be overriden in classes derived from `StanzaPayloadObject`.
:Parameters:
- `xmlnode`: XML node with the element being built. It has already
right name and namespace, but... |
def skip(self):
"""Skip this py-pdb command to avoid attaching within the same loop."""
line = self.line
self.line = ''
# 'line' is the statement line of the previous py-pdb command.
if line in self.lines:
if not self.skipping:
self.skipping = True
... | def function[skip, parameter[self]]:
constant[Skip this py-pdb command to avoid attaching within the same loop.]
variable[line] assign[=] name[self].line
name[self].line assign[=] constant[]
if compare[name[line] in name[self].lines] begin[:]
if <ast.UnaryOp object at 0x7... | keyword[def] identifier[skip] ( identifier[self] ):
literal[string]
identifier[line] = identifier[self] . identifier[line]
identifier[self] . identifier[line] = literal[string]
keyword[if] identifier[line] keyword[in] identifier[self] . identifier[lines] :
... | def skip(self):
"""Skip this py-pdb command to avoid attaching within the same loop."""
line = self.line
self.line = ''
# 'line' is the statement line of the previous py-pdb command.
if line in self.lines:
if not self.skipping:
self.skipping = True
printflush('Skippin... |
def retrieve_object(model, *args, **kwargs):
"""
Retrieves a specific object from a given model by primary-key
lookup, and stores it in a context variable.
Syntax::
{% retrieve_object [app_name].[model_name] [lookup kwargs] as [varname] %}
Example::
{% retrieve_ob... | def function[retrieve_object, parameter[model]]:
constant[
Retrieves a specific object from a given model by primary-key
lookup, and stores it in a context variable.
Syntax::
{% retrieve_object [app_name].[model_name] [lookup kwargs] as [varname] %}
Example::
... | keyword[def] identifier[retrieve_object] ( identifier[model] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
identifier[kwargs] . identifier[update] ({ literal[string] : identifier[args] [ literal[int] ]})
identi... | def retrieve_object(model, *args, **kwargs):
"""
Retrieves a specific object from a given model by primary-key
lookup, and stores it in a context variable.
Syntax::
{% retrieve_object [app_name].[model_name] [lookup kwargs] as [varname] %}
Example::
{% retrieve_ob... |
def searchNsByHref(self, doc, href):
"""Search a Ns aliasing a given URI. Recurse on the parents
until it finds the defined namespace or return None
otherwise. """
if doc is None: doc__o = None
else: doc__o = doc._o
ret = libxml2mod.xmlSearchNsByHref(doc__o, self._o,... | def function[searchNsByHref, parameter[self, doc, href]]:
constant[Search a Ns aliasing a given URI. Recurse on the parents
until it finds the defined namespace or return None
otherwise. ]
if compare[name[doc] is constant[None]] begin[:]
variable[doc__o] assign[=] co... | keyword[def] identifier[searchNsByHref] ( identifier[self] , identifier[doc] , identifier[href] ):
literal[string]
keyword[if] identifier[doc] keyword[is] keyword[None] : identifier[doc__o] = keyword[None]
keyword[else] : identifier[doc__o] = identifier[doc] . identifier[_o]
... | def searchNsByHref(self, doc, href):
"""Search a Ns aliasing a given URI. Recurse on the parents
until it finds the defined namespace or return None
otherwise. """
if doc is None:
doc__o = None # depends on [control=['if'], data=[]]
else:
doc__o = doc._o
ret = libxm... |
def blit(
self,
dest: tcod.console.Console,
fill_fore: bool = True,
fill_back: bool = True,
) -> None:
"""Use libtcod's "fill" functions to write the buffer to a console.
Args:
dest (Console): Console object to modify.
fill_fore (bool):
... | def function[blit, parameter[self, dest, fill_fore, fill_back]]:
constant[Use libtcod's "fill" functions to write the buffer to a console.
Args:
dest (Console): Console object to modify.
fill_fore (bool):
If True, fill the foreground color and characters.
... | keyword[def] identifier[blit] (
identifier[self] ,
identifier[dest] : identifier[tcod] . identifier[console] . identifier[Console] ,
identifier[fill_fore] : identifier[bool] = keyword[True] ,
identifier[fill_back] : identifier[bool] = keyword[True] ,
)-> keyword[None] :
literal[string]
keyword[... | def blit(self, dest: tcod.console.Console, fill_fore: bool=True, fill_back: bool=True) -> None:
"""Use libtcod's "fill" functions to write the buffer to a console.
Args:
dest (Console): Console object to modify.
fill_fore (bool):
If True, fill the foreground color an... |
def leave_transaction_management(self) -> None:
"""
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() must be called if changes made. If dirty, changes will be
discarded.
"""
if len(self._transactions) == 0:
raise RuntimeError("lea... | def function[leave_transaction_management, parameter[self]]:
constant[
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() must be called if changes made. If dirty, changes will be
discarded.
]
if compare[call[name[len], parameter[name[self]._tr... | keyword[def] identifier[leave_transaction_management] ( identifier[self] )-> keyword[None] :
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[_transactions] )== literal[int] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
keyword[elif... | def leave_transaction_management(self) -> None:
"""
End a transaction. Must not be dirty when doing so. ie. commit() or
rollback() must be called if changes made. If dirty, changes will be
discarded.
"""
if len(self._transactions) == 0:
raise RuntimeError('leave_transacti... |
def get_layout_view(self, request):
"""
Return the metadata about a layout
"""
template_name = request.GET['name']
# Check if template is allowed, avoid parsing random templates
templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES)
if template_name not in templa... | def function[get_layout_view, parameter[self, request]]:
constant[
Return the metadata about a layout
]
variable[template_name] assign[=] call[name[request].GET][constant[name]]
variable[templates] assign[=] call[name[dict], parameter[name[appconfig].SIMPLECMS_TEMPLATE_CHOICES]]
... | keyword[def] identifier[get_layout_view] ( identifier[self] , identifier[request] ):
literal[string]
identifier[template_name] = identifier[request] . identifier[GET] [ literal[string] ]
identifier[templates] = identifier[dict] ( identifier[appconfig] . identifier[SIMPLECMS_TEMPL... | def get_layout_view(self, request):
"""
Return the metadata about a layout
"""
template_name = request.GET['name']
# Check if template is allowed, avoid parsing random templates
templates = dict(appconfig.SIMPLECMS_TEMPLATE_CHOICES)
if template_name not in templates:
jsondata... |
def get_version():
"""Extracts the version number from the version.py file."""
VERSION_FILE = '../malcolm/version.py'
mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]',
open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1)
else:
raise RuntimeError(
... | def function[get_version, parameter[]]:
constant[Extracts the version number from the version.py file.]
variable[VERSION_FILE] assign[=] constant[../malcolm/version.py]
variable[mo] assign[=] call[name[re].search, parameter[constant[^__version__ = [\'"]([^\'"]*)[\'"]], call[call[name[open], para... | keyword[def] identifier[get_version] ():
literal[string]
identifier[VERSION_FILE] = literal[string]
identifier[mo] = identifier[re] . identifier[search] ( literal[string] ,
identifier[open] ( identifier[VERSION_FILE] , literal[string] ). identifier[read] (), identifier[re] . identifier[M] )
... | def get_version():
"""Extracts the version number from the version.py file."""
VERSION_FILE = '../malcolm/version.py'
mo = re.search('^__version__ = [\\\'"]([^\\\'"]*)[\\\'"]', open(VERSION_FILE, 'rt').read(), re.M)
if mo:
return mo.group(1) # depends on [control=['if'], data=[]]
else:
... |
def decompress(f):
"""Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed\n' string.
"""
r = meta(f.read(60))
return r, decomprest(f, r[4]) | def function[decompress, parameter[f]]:
constant[Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed
' string.
]
variable[r] assign[=] call[name[meta], parameter[call[name[f].read, parameter[constant[60]]]]]
return[tuple[[<ast.Name object at 0x7da1b0781870... | keyword[def] identifier[decompress] ( identifier[f] ):
literal[string]
identifier[r] = identifier[meta] ( identifier[f] . identifier[read] ( literal[int] ))
keyword[return] identifier[r] , identifier[decomprest] ( identifier[f] , identifier[r] [ literal[int] ]) | def decompress(f):
"""Decompress a Plan 9 image file. Assumes f is already cued past the
initial 'compressed
' string.
"""
r = meta(f.read(60))
return (r, decomprest(f, r[4])) |
def validate(schema, data, owner=None):
"""Validate input data with input schema.
:param Schema schema: schema able to validate input data.
:param data: data to validate.
:param Schema owner: input schema parent schema.
:raises: Exception if the data is not validated.
"""
schema._validate(d... | def function[validate, parameter[schema, data, owner]]:
constant[Validate input data with input schema.
:param Schema schema: schema able to validate input data.
:param data: data to validate.
:param Schema owner: input schema parent schema.
:raises: Exception if the data is not validated.
... | keyword[def] identifier[validate] ( identifier[schema] , identifier[data] , identifier[owner] = keyword[None] ):
literal[string]
identifier[schema] . identifier[_validate] ( identifier[data] = identifier[data] , identifier[owner] = identifier[owner] ) | def validate(schema, data, owner=None):
"""Validate input data with input schema.
:param Schema schema: schema able to validate input data.
:param data: data to validate.
:param Schema owner: input schema parent schema.
:raises: Exception if the data is not validated.
"""
schema._validate(d... |
def put_scheduled_update_group_action(AutoScalingGroupName=None, ScheduledActionName=None, Time=None, StartTime=None, EndTime=None, Recurrence=None, MinSize=None, MaxSize=None, DesiredCapacity=None):
"""
Creates or updates a scheduled scaling action for an Auto Scaling group. When updating a scheduled scaling a... | def function[put_scheduled_update_group_action, parameter[AutoScalingGroupName, ScheduledActionName, Time, StartTime, EndTime, Recurrence, MinSize, MaxSize, DesiredCapacity]]:
constant[
Creates or updates a scheduled scaling action for an Auto Scaling group. When updating a scheduled scaling action, if you ... | keyword[def] identifier[put_scheduled_update_group_action] ( identifier[AutoScalingGroupName] = keyword[None] , identifier[ScheduledActionName] = keyword[None] , identifier[Time] = keyword[None] , identifier[StartTime] = keyword[None] , identifier[EndTime] = keyword[None] , identifier[Recurrence] = keyword[None] , id... | def put_scheduled_update_group_action(AutoScalingGroupName=None, ScheduledActionName=None, Time=None, StartTime=None, EndTime=None, Recurrence=None, MinSize=None, MaxSize=None, DesiredCapacity=None):
"""
Creates or updates a scheduled scaling action for an Auto Scaling group. When updating a scheduled scaling a... |
def remove_pid_file(process_name):
""" removes pid file """
pid_filename = get_pid_filename(process_name)
try:
os.remove(pid_filename)
print('Removed pid file at: {0}'.format(pid_filename), file=sys.stdout)
except Exception as e:
print('Unable to remove pid file at: {0}, because ... | def function[remove_pid_file, parameter[process_name]]:
constant[ removes pid file ]
variable[pid_filename] assign[=] call[name[get_pid_filename], parameter[name[process_name]]]
<ast.Try object at 0x7da1b2440c70> | keyword[def] identifier[remove_pid_file] ( identifier[process_name] ):
literal[string]
identifier[pid_filename] = identifier[get_pid_filename] ( identifier[process_name] )
keyword[try] :
identifier[os] . identifier[remove] ( identifier[pid_filename] )
identifier[print] ( literal[stri... | def remove_pid_file(process_name):
""" removes pid file """
pid_filename = get_pid_filename(process_name)
try:
os.remove(pid_filename)
print('Removed pid file at: {0}'.format(pid_filename), file=sys.stdout) # depends on [control=['try'], data=[]]
except Exception as e:
print('Un... |
def list_ignored():
'''
List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' ... | def function[list_ignored, parameter[]]:
constant[
List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code... | keyword[def] identifier[list_ignored] ():
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] ]
identifier[out] = identifier[salt] . identifier[utils] . identifier[mac_utils] . identifier[execute_return_result] ( identifier[cmd] )
identifier... | def list_ignored():
"""
List all updates that have been ignored. Ignored updates are shown
without the '-' and version number at the end, this is how the
softwareupdate command works.
:return: The list of ignored updates
:rtype: list
CLI Example:
.. code-block:: bash
salt '*' ... |
def creep_data(data_set='creep_rupture'):
"""Brun and Yoshida's metal creep rupture data."""
if not data_available(data_set):
download_data(data_set)
path = os.path.join(data_path, data_set)
tar_file = os.path.join(path, 'creeprupt.tar')
tar = tarfile.open(tar_file)
print... | def function[creep_data, parameter[data_set]]:
constant[Brun and Yoshida's metal creep rupture data.]
if <ast.UnaryOp object at 0x7da1b1c7e860> begin[:]
call[name[download_data], parameter[name[data_set]]]
variable[path] assign[=] call[name[os].path.join, parameter[name[d... | keyword[def] identifier[creep_data] ( identifier[data_set] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[data_available] ( identifier[data_set] ):
identifier[download_data] ( identifier[data_set] )
identifier[path] = identifier[os] . identifier[path] . identif... | def creep_data(data_set='creep_rupture'):
"""Brun and Yoshida's metal creep rupture data."""
if not data_available(data_set):
download_data(data_set)
path = os.path.join(data_path, data_set)
tar_file = os.path.join(path, 'creeprupt.tar')
tar = tarfile.open(tar_file)
print... |
def write_csv_header(mol, csv_writer):
"""
Write the csv header
"""
# create line list where line elements for writing will be stored
line = []
# ID
line.append('id')
# status
line.append('status')
# query labels
queryList = mol.properties.keys()
for queryLabel in queryList... | def function[write_csv_header, parameter[mol, csv_writer]]:
constant[
Write the csv header
]
variable[line] assign[=] list[[]]
call[name[line].append, parameter[constant[id]]]
call[name[line].append, parameter[constant[status]]]
variable[queryList] assign[=] call[name[mol].prop... | keyword[def] identifier[write_csv_header] ( identifier[mol] , identifier[csv_writer] ):
literal[string]
identifier[line] =[]
identifier[line] . identifier[append] ( literal[string] )
identifier[line] . identifier[append] ( literal[string] )
identifier[queryList] = ide... | def write_csv_header(mol, csv_writer):
"""
Write the csv header
"""
# create line list where line elements for writing will be stored
line = []
# ID
line.append('id')
# status
line.append('status')
# query labels
queryList = mol.properties.keys()
for queryLabel in queryList:
... |
def from_array(array):
"""
Deserialize a new ChosenInlineResult from a given dictionary.
:return: new ChosenInlineResult instance.
:rtype: ChosenInlineResult
"""
if array is None or not array:
return None
# end if
assert_type_or_raise(array, d... | def function[from_array, parameter[array]]:
constant[
Deserialize a new ChosenInlineResult from a given dictionary.
:return: new ChosenInlineResult instance.
:rtype: ChosenInlineResult
]
if <ast.BoolOp object at 0x7da18f58d120> begin[:]
return[constant[None]]
... | keyword[def] identifier[from_array] ( identifier[array] ):
literal[string]
keyword[if] identifier[array] keyword[is] keyword[None] keyword[or] keyword[not] identifier[array] :
keyword[return] keyword[None]
identifier[assert_type_or_raise] ( identifier[arra... | def from_array(array):
"""
Deserialize a new ChosenInlineResult from a given dictionary.
:return: new ChosenInlineResult instance.
:rtype: ChosenInlineResult
"""
if array is None or not array:
return None # depends on [control=['if'], data=[]]
# end if
assert_ty... |
def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
shift_length, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0
else:
result = (value << shift_length) & constants.UINT_256_MAX
computation.sta... | def function[shl, parameter[computation]]:
constant[
Bitwise left shift
]
<ast.Tuple object at 0x7da1b175dd20> assign[=] call[name[computation].stack_pop, parameter[]]
if compare[name[shift_length] greater_or_equal[>=] constant[256]] begin[:]
variable[result] assign[=] co... | keyword[def] identifier[shl] ( identifier[computation] : identifier[BaseComputation] )-> keyword[None] :
literal[string]
identifier[shift_length] , identifier[value] = identifier[computation] . identifier[stack_pop] ( identifier[num_items] = literal[int] , identifier[type_hint] = identifier[constants] . id... | def shl(computation: BaseComputation) -> None:
"""
Bitwise left shift
"""
(shift_length, value) = computation.stack_pop(num_items=2, type_hint=constants.UINT256)
if shift_length >= 256:
result = 0 # depends on [control=['if'], data=[]]
else:
result = value << shift_length & cons... |
def create(self, fullname, shortname, category_id, **kwargs):
"""
Create a new course
:param string fullname: The course's fullname
:param string shortname: The course's shortname
:param int category_id: The course's category
:keyword string idnumber: (optional) Course ... | def function[create, parameter[self, fullname, shortname, category_id]]:
constant[
Create a new course
:param string fullname: The course's fullname
:param string shortname: The course's shortname
:param int category_id: The course's category
:keyword string idnumber: (... | keyword[def] identifier[create] ( identifier[self] , identifier[fullname] , identifier[shortname] , identifier[category_id] ,** identifier[kwargs] ):
literal[string]
identifier[allowed_options] =[ literal[string] , literal[string] ,
literal[string] , literal[string] ,
literal[str... | def create(self, fullname, shortname, category_id, **kwargs):
"""
Create a new course
:param string fullname: The course's fullname
:param string shortname: The course's shortname
:param int category_id: The course's category
:keyword string idnumber: (optional) Course ID n... |
def get_protocol(self,sweep):
"""
given a sweep, return the protocol as [Xs,Ys].
This is good for plotting/recreating the protocol trace.
There may be duplicate numbers.
"""
self.setsweep(sweep)
return list(self.protoX),list(self.protoY) | def function[get_protocol, parameter[self, sweep]]:
constant[
given a sweep, return the protocol as [Xs,Ys].
This is good for plotting/recreating the protocol trace.
There may be duplicate numbers.
]
call[name[self].setsweep, parameter[name[sweep]]]
return[tuple[[<ast... | keyword[def] identifier[get_protocol] ( identifier[self] , identifier[sweep] ):
literal[string]
identifier[self] . identifier[setsweep] ( identifier[sweep] )
keyword[return] identifier[list] ( identifier[self] . identifier[protoX] ), identifier[list] ( identifier[self] . identifier[protoY... | def get_protocol(self, sweep):
"""
given a sweep, return the protocol as [Xs,Ys].
This is good for plotting/recreating the protocol trace.
There may be duplicate numbers.
"""
self.setsweep(sweep)
return (list(self.protoX), list(self.protoY)) |
def randomize_nick(cls, base, suffix_length=3):
"""
Generates a pseudo-random nickname.
:param base: prefix to use for the generated nickname.
:type base: unicode
:param suffix_length: amount of digits to append to `base`
:type suffix_length: int
:return: generat... | def function[randomize_nick, parameter[cls, base, suffix_length]]:
constant[
Generates a pseudo-random nickname.
:param base: prefix to use for the generated nickname.
:type base: unicode
:param suffix_length: amount of digits to append to `base`
:type suffix_length: int... | keyword[def] identifier[randomize_nick] ( identifier[cls] , identifier[base] , identifier[suffix_length] = literal[int] ):
literal[string]
identifier[suffix] = literal[string] . identifier[join] ( identifier[choice] ( literal[string] ) keyword[for] identifier[_] keyword[in] identifier[range] ( i... | def randomize_nick(cls, base, suffix_length=3):
"""
Generates a pseudo-random nickname.
:param base: prefix to use for the generated nickname.
:type base: unicode
:param suffix_length: amount of digits to append to `base`
:type suffix_length: int
:return: generated n... |
def postinit(self, elt=None, generators=None):
"""Do some setup after initialisation.
:param elt: The element that forms the output of the expression.
:type elt: NodeNG or None
:param generators: The generators that are looped through.
:type generators: list(Comprehension) or N... | def function[postinit, parameter[self, elt, generators]]:
constant[Do some setup after initialisation.
:param elt: The element that forms the output of the expression.
:type elt: NodeNG or None
:param generators: The generators that are looped through.
:type generators: list(Co... | keyword[def] identifier[postinit] ( identifier[self] , identifier[elt] = keyword[None] , identifier[generators] = keyword[None] ):
literal[string]
identifier[self] . identifier[elt] = identifier[elt]
identifier[self] . identifier[generators] = identifier[generators] | def postinit(self, elt=None, generators=None):
"""Do some setup after initialisation.
:param elt: The element that forms the output of the expression.
:type elt: NodeNG or None
:param generators: The generators that are looped through.
:type generators: list(Comprehension) or None
... |
def get_region():
"""Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
"""
log = logging.getLogger(mod_logger + '.get_region')
# First get the availability zone
availability_zone = get_availability_zone()
if availability_zone is None:
msg ... | def function[get_region, parameter[]]:
constant[Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
]
variable[log] assign[=] call[name[logging].getLogger, parameter[binary_operation[name[mod_logger] + constant[.get_region]]]]
variable[availabilit... | keyword[def] identifier[get_region] ():
literal[string]
identifier[log] = identifier[logging] . identifier[getLogger] ( identifier[mod_logger] + literal[string] )
identifier[availability_zone] = identifier[get_availability_zone] ()
keyword[if] identifier[availability_zone] keyword[is] k... | def get_region():
"""Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
"""
log = logging.getLogger(mod_logger + '.get_region')
# First get the availability zone
availability_zone = get_availability_zone()
if availability_zone is None:
msg = ... |
def add_interrupt_callback(self, gpio_id, callback, edge='both',
pull_up_down=_GPIO.PUD_OFF, threaded_callback=False,
debounce_timeout_ms=None):
"""
Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='... | def function[add_interrupt_callback, parameter[self, gpio_id, callback, edge, pull_up_down, threaded_callback, debounce_timeout_ms]]:
constant[
Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_dow... | keyword[def] identifier[add_interrupt_callback] ( identifier[self] , identifier[gpio_id] , identifier[callback] , identifier[edge] = literal[string] ,
identifier[pull_up_down] = identifier[_GPIO] . identifier[PUD_OFF] , identifier[threaded_callback] = keyword[False] ,
identifier[debounce_timeout_ms] = keyword[None]... | def add_interrupt_callback(self, gpio_id, callback, edge='both', pull_up_down=_GPIO.PUD_OFF, threaded_callback=False, debounce_timeout_ms=None):
"""
Add a callback to be executed when the value on 'gpio_id' changes to
the edge specified via the 'edge' parameter (default='both').
`pull_up_do... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.