code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request(
"{0}_{1}".format(request_id, user_id), method="DELETE"
) | def function[delete_request, parameter[self, user_id, request_id]]:
constant[Deletes the Request with the given ID for the given user.]
return[call[name[self].request, parameter[call[constant[{0}_{1}].format, parameter[name[request_id], name[user_id]]]]]] | keyword[def] identifier[delete_request] ( identifier[self] , identifier[user_id] , identifier[request_id] ):
literal[string]
keyword[return] identifier[self] . identifier[request] (
literal[string] . identifier[format] ( identifier[request_id] , identifier[user_id] ), identifier[method] =... | def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
return self.request('{0}_{1}'.format(request_id, user_id), method='DELETE') |
def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_... | def function[_arith_method_SERIES, parameter[cls, op, special]]:
constant[
Wrapper function for Series arithmetic operations, to avoid
code duplication.
]
variable[str_rep] assign[=] call[name[_get_opstr], parameter[name[op], name[cls]]]
variable[op_name] assign[=] call[name[_get_op_... | keyword[def] identifier[_arith_method_SERIES] ( identifier[cls] , identifier[op] , identifier[special] ):
literal[string]
identifier[str_rep] = identifier[_get_opstr] ( identifier[op] , identifier[cls] )
identifier[op_name] = identifier[_get_op_name] ( identifier[op] , identifier[special] )
ident... | def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_... |
def to_networkx_graph(self, node_attribute_name='bias', edge_attribute_name='bias'):
"""Convert a binary quadratic model to NetworkX graph format.
Args:
node_attribute_name (hashable, optional, default='bias'):
Attribute name for linear biases.
edge_attribute_na... | def function[to_networkx_graph, parameter[self, node_attribute_name, edge_attribute_name]]:
constant[Convert a binary quadratic model to NetworkX graph format.
Args:
node_attribute_name (hashable, optional, default='bias'):
Attribute name for linear biases.
edge... | keyword[def] identifier[to_networkx_graph] ( identifier[self] , identifier[node_attribute_name] = literal[string] , identifier[edge_attribute_name] = literal[string] ):
literal[string]
keyword[import] identifier[networkx] keyword[as] identifier[nx]
identifier[BQM] = identifier[nx] . i... | def to_networkx_graph(self, node_attribute_name='bias', edge_attribute_name='bias'):
"""Convert a binary quadratic model to NetworkX graph format.
Args:
node_attribute_name (hashable, optional, default='bias'):
Attribute name for linear biases.
edge_attribute_name (... |
def append_records(self, dataset_key, stream_id, body):
"""Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:param body: Object body
... | def function[append_records, parameter[self, dataset_key, stream_id, body]]:
constant[Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:para... | keyword[def] identifier[append_records] ( identifier[self] , identifier[dataset_key] , identifier[stream_id] , identifier[body] ):
literal[string]
identifier[owner_id] , identifier[dataset_id] = identifier[parse_dataset_key] ( identifier[dataset_key] )
keyword[try] :
keyword[r... | def append_records(self, dataset_key, stream_id, body):
"""Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:param body: Object body
:ty... |
def serial_number(self, serial_number):
"""
Sets the serial_number of this DeviceDataPostRequest.
The serial number of the device.
:param serial_number: The serial_number of this DeviceDataPostRequest.
:type: str
"""
if serial_number is not None and len(serial_nu... | def function[serial_number, parameter[self, serial_number]]:
constant[
Sets the serial_number of this DeviceDataPostRequest.
The serial number of the device.
:param serial_number: The serial_number of this DeviceDataPostRequest.
:type: str
]
if <ast.BoolOp object... | keyword[def] identifier[serial_number] ( identifier[self] , identifier[serial_number] ):
literal[string]
keyword[if] identifier[serial_number] keyword[is] keyword[not] keyword[None] keyword[and] identifier[len] ( identifier[serial_number] )> literal[int] :
keyword[raise] identif... | def serial_number(self, serial_number):
"""
Sets the serial_number of this DeviceDataPostRequest.
The serial number of the device.
:param serial_number: The serial_number of this DeviceDataPostRequest.
:type: str
"""
if serial_number is not None and len(serial_number) > ... |
def _wait(self):
"""Block until an upload finishes
Raise an exception if that tar volume failed with an error.
"""
val = self.wait_change.get()
if isinstance(val, Exception):
# Don't other uncharging, because execution is going to stop
raise val
... | def function[_wait, parameter[self]]:
constant[Block until an upload finishes
Raise an exception if that tar volume failed with an error.
]
variable[val] assign[=] call[name[self].wait_change.get, parameter[]]
if call[name[isinstance], parameter[name[val], name[Exception]]] begi... | keyword[def] identifier[_wait] ( identifier[self] ):
literal[string]
identifier[val] = identifier[self] . identifier[wait_change] . identifier[get] ()
keyword[if] identifier[isinstance] ( identifier[val] , identifier[Exception] ):
keyword[raise] identifier[val]
... | def _wait(self):
"""Block until an upload finishes
Raise an exception if that tar volume failed with an error.
"""
val = self.wait_change.get()
if isinstance(val, Exception):
# Don't other uncharging, because execution is going to stop
raise val # depends on [control=['if']... |
def create_datapipeline(self):
"""Creates data pipeline and adds definition"""
utils.banner("Creating Data Pipeline")
dpobj = datapipeline.AWSDataPipeline(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
dpobj.create_datapipeline()
dpobj.set_pipeline_defi... | def function[create_datapipeline, parameter[self]]:
constant[Creates data pipeline and adds definition]
call[name[utils].banner, parameter[constant[Creating Data Pipeline]]]
variable[dpobj] assign[=] call[name[datapipeline].AWSDataPipeline, parameter[]]
call[name[dpobj].create_datapipeli... | keyword[def] identifier[create_datapipeline] ( identifier[self] ):
literal[string]
identifier[utils] . identifier[banner] ( literal[string] )
identifier[dpobj] = identifier[datapipeline] . identifier[AWSDataPipeline] ( identifier[app] = identifier[self] . identifier[app] , identifier[env] ... | def create_datapipeline(self):
"""Creates data pipeline and adds definition"""
utils.banner('Creating Data Pipeline')
dpobj = datapipeline.AWSDataPipeline(app=self.app, env=self.env, region=self.region, prop_path=self.json_path)
dpobj.create_datapipeline()
dpobj.set_pipeline_definition()
if self... |
def plot_eqarea_mean(self, meanpars, fig):
"""
Given a dictionary of parameters from pmag.dofisher, pmag.dolnp, or
pmag.dobingham (meanpars) plots parameters to fig
"""
mpars_to_plot = []
if meanpars == {}:
return
if meanpars['calculation_type'] == 'Fi... | def function[plot_eqarea_mean, parameter[self, meanpars, fig]]:
constant[
Given a dictionary of parameters from pmag.dofisher, pmag.dolnp, or
pmag.dobingham (meanpars) plots parameters to fig
]
variable[mpars_to_plot] assign[=] list[[]]
if compare[name[meanpars] equal[==]... | keyword[def] identifier[plot_eqarea_mean] ( identifier[self] , identifier[meanpars] , identifier[fig] ):
literal[string]
identifier[mpars_to_plot] =[]
keyword[if] identifier[meanpars] =={}:
keyword[return]
keyword[if] identifier[meanpars] [ literal[string] ]== lite... | def plot_eqarea_mean(self, meanpars, fig):
"""
Given a dictionary of parameters from pmag.dofisher, pmag.dolnp, or
pmag.dobingham (meanpars) plots parameters to fig
"""
mpars_to_plot = []
if meanpars == {}:
return # depends on [control=['if'], data=[]]
if meanpars['calcu... |
def _check_reply_pending(self, option):
"""Test the status of requested Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption()
return self.telnet_opt_dict[option].reply_pending | def function[_check_reply_pending, parameter[self, option]]:
constant[Test the status of requested Telnet options.]
if <ast.UnaryOp object at 0x7da18fe90820> begin[:]
call[name[self].telnet_opt_dict][name[option]] assign[=] call[name[TelnetOption], parameter[]]
return[call[name[self]... | keyword[def] identifier[_check_reply_pending] ( identifier[self] , identifier[option] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[telnet_opt_dict] . identifier[has_key] ( identifier[option] ):
identifier[self] . identifier[telnet_opt_dict] [ identifier[o... | def _check_reply_pending(self, option):
"""Test the status of requested Telnet options."""
if not self.telnet_opt_dict.has_key(option):
self.telnet_opt_dict[option] = TelnetOption() # depends on [control=['if'], data=[]]
return self.telnet_opt_dict[option].reply_pending |
def set_decimal(self, pos, decimal):
"""Turn decimal point on or off at provided position. Position should be
a value 0 to 3 with 0 being the left most digit on the display. Decimal
should be True to turn on the decimal point and False to turn it off.
"""
if pos < 0 or pos > 3:... | def function[set_decimal, parameter[self, pos, decimal]]:
constant[Turn decimal point on or off at provided position. Position should be
a value 0 to 3 with 0 being the left most digit on the display. Decimal
should be True to turn on the decimal point and False to turn it off.
]
... | keyword[def] identifier[set_decimal] ( identifier[self] , identifier[pos] , identifier[decimal] ):
literal[string]
keyword[if] identifier[pos] < literal[int] keyword[or] identifier[pos] > literal[int] :
keyword[return]
identifier[offset] = literal[int... | def set_decimal(self, pos, decimal):
"""Turn decimal point on or off at provided position. Position should be
a value 0 to 3 with 0 being the left most digit on the display. Decimal
should be True to turn on the decimal point and False to turn it off.
"""
if pos < 0 or pos > 3:
... |
def parse_device_list(device_list_str, key):
"""Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a ... | def function[parse_device_list, parameter[device_list_str, key]]:
constant[Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
k... | keyword[def] identifier[parse_device_list] ( identifier[device_list_str] , identifier[key] ):
literal[string]
identifier[clean_lines] = identifier[new_str] ( identifier[device_list_str] , literal[string] ). identifier[strip] (). identifier[split] ( literal[string] )
identifier[results] =[]
keywor... | def parse_device_list(device_list_str, key):
"""Parses a byte string representing a list of devices.
The string is generated by calling either adb or fastboot. The tokens in
each string is tab-separated.
Args:
device_list_str: Output of adb or fastboot.
key: The token that signifies a ... |
def update(self, auth, resource, desc={}, defer=False):
""" Updates the description of the resource.
Args:
auth: <cik> for authentication
resource: Resource to be updated
desc: A Dictionary containing the update for the resource.
"""
return self._call... | def function[update, parameter[self, auth, resource, desc, defer]]:
constant[ Updates the description of the resource.
Args:
auth: <cik> for authentication
resource: Resource to be updated
desc: A Dictionary containing the update for the resource.
]
retur... | keyword[def] identifier[update] ( identifier[self] , identifier[auth] , identifier[resource] , identifier[desc] ={}, identifier[defer] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_call] ( literal[string] , identifier[auth] ,[ identifier[resource] , identifier[... | def update(self, auth, resource, desc={}, defer=False):
""" Updates the description of the resource.
Args:
auth: <cik> for authentication
resource: Resource to be updated
desc: A Dictionary containing the update for the resource.
"""
return self._call('update... |
def get_admin_url(self, query_params=None, use_path=False):
"""Returns the URL for viewing a FileNode in the admin."""
if not query_params:
query_params = {}
url = ''
if self.is_top_node():
url = reverse('admin:media_tree_filenode_changelist');
elif use_... | def function[get_admin_url, parameter[self, query_params, use_path]]:
constant[Returns the URL for viewing a FileNode in the admin.]
if <ast.UnaryOp object at 0x7da18c4ce860> begin[:]
variable[query_params] assign[=] dictionary[[], []]
variable[url] assign[=] constant[]
i... | keyword[def] identifier[get_admin_url] ( identifier[self] , identifier[query_params] = keyword[None] , identifier[use_path] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[query_params] :
identifier[query_params] ={}
identifier[url] = literal[string... | def get_admin_url(self, query_params=None, use_path=False):
"""Returns the URL for viewing a FileNode in the admin."""
if not query_params:
query_params = {} # depends on [control=['if'], data=[]]
url = ''
if self.is_top_node():
url = reverse('admin:media_tree_filenode_changelist') # d... |
def get_fields(self):
"""
get property instance according self.columns
"""
columns = self.columns
model = self.model
fields = []
for col in columns:
if isinstance(col, (str, unicode)):
v = col.split('.')
if len(v) > 1:
... | def function[get_fields, parameter[self]]:
constant[
get property instance according self.columns
]
variable[columns] assign[=] name[self].columns
variable[model] assign[=] name[self].model
variable[fields] assign[=] list[[]]
for taget[name[col]] in starred[name[c... | keyword[def] identifier[get_fields] ( identifier[self] ):
literal[string]
identifier[columns] = identifier[self] . identifier[columns]
identifier[model] = identifier[self] . identifier[model]
identifier[fields] =[]
keyword[for] identifier[col] keyword[in] identifier[... | def get_fields(self):
"""
get property instance according self.columns
"""
columns = self.columns
model = self.model
fields = []
for col in columns:
if isinstance(col, (str, unicode)):
v = col.split('.')
if len(v) > 1:
field = get_model... |
def get_value_from_cfg(cfg_file):
''' initial the configuration with file that you specify
Sample usage:
config = get_value_from_cfg()
return:
return a dict -->config[section][option] such as config["twsm"]["dut_ip"] ... | def function[get_value_from_cfg, parameter[cfg_file]]:
constant[ initial the configuration with file that you specify
Sample usage:
config = get_value_from_cfg()
return:
return a dict -->config[section][option] such as conf... | keyword[def] identifier[get_value_from_cfg] ( identifier[cfg_file] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[cfg_file] ):
keyword[return]
identifier[cfg] ={}
identifier[config] = identif... | def get_value_from_cfg(cfg_file):
""" initial the configuration with file that you specify
Sample usage:
config = get_value_from_cfg()
return:
return a dict -->config[section][option] such as config["twsm"]["dut_ip"] ... |
def setparents(self):
"""Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy`"""
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() | def function[setparents, parameter[self]]:
constant[Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy`]
for taget[name[c]] in starred[name[self]] begin[:]
if call[name[isinstance], parameter[name[c]... | keyword[def] identifier[setparents] ( identifier[self] ):
literal[string]
keyword[for] identifier[c] keyword[in] identifier[self] :
keyword[if] identifier[isinstance] ( identifier[c] , identifier[AbstractElement] ):
identifier[c] . identifier[parent] = identifier[s... | def setparents(self):
"""Correct all parent relations for elements within the scop. There is sually no need to call this directly, invoked implicitly by :meth:`copy`"""
for c in self:
if isinstance(c, AbstractElement):
c.parent = self
c.setparents() # depends on [control=['if'],... |
def _set_index_map(self, atom_mapping):
"""T(r_i) in Eq.(3) is given as permutation of atom indices.
_index_set : ndarray
For each translation (shift), atomic indices of the positions
(_ideal_positions - shift) are searched and stored. The indices
are used to select ... | def function[_set_index_map, parameter[self, atom_mapping]]:
constant[T(r_i) in Eq.(3) is given as permutation of atom indices.
_index_set : ndarray
For each translation (shift), atomic indices of the positions
(_ideal_positions - shift) are searched and stored. The indices
... | keyword[def] identifier[_set_index_map] ( identifier[self] , identifier[atom_mapping] ):
literal[string]
identifier[lattice] = identifier[self] . identifier[_phonon] . identifier[supercell] . identifier[get_cell] ()
identifier[natom] = identifier[len] ( identifier[self] . identifier[_idea... | def _set_index_map(self, atom_mapping):
"""T(r_i) in Eq.(3) is given as permutation of atom indices.
_index_set : ndarray
For each translation (shift), atomic indices of the positions
(_ideal_positions - shift) are searched and stored. The indices
are used to select eige... |
def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
if not super(AdminSiteOTPRequiredMixin, self).has_permission(request):
return False
return request.user.is_verified() | def function[has_permission, parameter[self, request]]:
constant[
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
]
if <ast.UnaryOp object at 0x7da1b1e7d300> begin[:]
return[constant[False]]
return[call[name[request]... | keyword[def] identifier[has_permission] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] keyword[not] identifier[super] ( identifier[AdminSiteOTPRequiredMixin] , identifier[self] ). identifier[has_permission] ( identifier[request] ):
keyword[return] keyword[Fa... | def has_permission(self, request):
"""
Returns True if the given HttpRequest has permission to view
*at least one* page in the admin site.
"""
if not super(AdminSiteOTPRequiredMixin, self).has_permission(request):
return False # depends on [control=['if'], data=[]]
return re... |
def _textOutput(self, gaObjects):
"""
Prints out the specified Variant objects in a VCF-like form.
"""
for variant in gaObjects:
print(
variant.id, variant.variant_set_id, variant.names,
variant.reference_name, variant.start, variant.end,
... | def function[_textOutput, parameter[self, gaObjects]]:
constant[
Prints out the specified Variant objects in a VCF-like form.
]
for taget[name[variant]] in starred[name[gaObjects]] begin[:]
call[name[print], parameter[name[variant].id, name[variant].variant_set_id, name[v... | keyword[def] identifier[_textOutput] ( identifier[self] , identifier[gaObjects] ):
literal[string]
keyword[for] identifier[variant] keyword[in] identifier[gaObjects] :
identifier[print] (
identifier[variant] . identifier[id] , identifier[variant] . identifier[variant_se... | def _textOutput(self, gaObjects):
"""
Prints out the specified Variant objects in a VCF-like form.
"""
for variant in gaObjects:
print(variant.id, variant.variant_set_id, variant.names, variant.reference_name, variant.start, variant.end, variant.reference_bases, variant.alternate_bases, ... |
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any],
deleted_value: Any = None) -> Dict[Any, Any]:
"""
Returns a representation of the changes that need to be made to ``d1`` to
create ``d2``.
Args:
d1: a dictionary
d2: another dictionary
deleted_value: value to us... | def function[dict_diff, parameter[d1, d2, deleted_value]]:
constant[
Returns a representation of the changes that need to be made to ``d1`` to
create ``d2``.
Args:
d1: a dictionary
d2: another dictionary
deleted_value: value to use for deleted keys; see below
Returns:
... | keyword[def] identifier[dict_diff] ( identifier[d1] : identifier[Dict] [ identifier[Any] , identifier[Any] ], identifier[d2] : identifier[Dict] [ identifier[Any] , identifier[Any] ],
identifier[deleted_value] : identifier[Any] = keyword[None] )-> identifier[Dict] [ identifier[Any] , identifier[Any] ]:
literal[s... | def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any=None) -> Dict[Any, Any]:
"""
Returns a representation of the changes that need to be made to ``d1`` to
create ``d2``.
Args:
d1: a dictionary
d2: another dictionary
deleted_value: value to use for deleted ke... |
def count_variants(graph):
"""Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter
"""
return Counter(
variant_data[KIND]
for data in graph
if has_variant(graph, data)
for variant_data in data[VARIANTS]
) | def function[count_variants, parameter[graph]]:
constant[Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter
]
return[call[name[Counter], parameter[<ast.GeneratorExp object at 0x7da1b0cb7d90>]]] | keyword[def] identifier[count_variants] ( identifier[graph] ):
literal[string]
keyword[return] identifier[Counter] (
identifier[variant_data] [ identifier[KIND] ]
keyword[for] identifier[data] keyword[in] identifier[graph]
keyword[if] identifier[has_variant] ( identifier[graph] , ident... | def count_variants(graph):
"""Count how many of each type of variant a graph has.
:param pybel.BELGraph graph: A BEL graph
:rtype: Counter
"""
return Counter((variant_data[KIND] for data in graph if has_variant(graph, data) for variant_data in data[VARIANTS])) |
def dir():
"""Return the list of patched function names. Used for patching
functions imported from the module.
"""
dir = [
'access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync',
'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs',
'mkdi... | def function[dir, parameter[]]:
constant[Return the list of patched function names. Used for patching
functions imported from the module.
]
variable[dir] assign[=] list[[<ast.Constant object at 0x7da20c794430>, <ast.Constant object at 0x7da20c795570>, <ast.Constant object at 0x7da20c794e... | keyword[def] identifier[dir] ():
literal[string]
identifier[dir] =[
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] , literal[string] , literal[string]... | def dir():
"""Return the list of patched function names. Used for patching
functions imported from the module.
"""
dir = ['access', 'chdir', 'chmod', 'chown', 'close', 'fstat', 'fsync', 'getcwd', 'lchmod', 'link', 'listdir', 'lstat', 'makedirs', 'mkdir', 'mknod', 'open', 'read', 'readlink', 'rem... |
def do_loop_turn(self): # pylint: disable=too-many-branches
"""Satellite main loop::
* Check and delete zombies actions / modules
* Get returns from queues
* Adjust worker number
* Get new actions
:return: None
"""
# Try to see if one of my module is de... | def function[do_loop_turn, parameter[self]]:
constant[Satellite main loop::
* Check and delete zombies actions / modules
* Get returns from queues
* Adjust worker number
* Get new actions
:return: None
]
call[name[self].check_and_del_zombie_modules, para... | keyword[def] identifier[do_loop_turn] ( identifier[self] ):
literal[string]
identifier[self] . identifier[check_and_del_zombie_modules] ()
identifier[self] . identifier[check_and_del_zombie_workers] ()
identifier[self] . identifier[hook_point] ( litera... | def do_loop_turn(self): # pylint: disable=too-many-branches
'Satellite main loop::\n\n * Check and delete zombies actions / modules\n * Get returns from queues\n * Adjust worker number\n * Get new actions\n\n :return: None\n '
# Try to see if one of my module is dead, ... |
def make_definition(name, base, schema):
"""
Create a new definition.
"""
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls | def function[make_definition, parameter[name, base, schema]]:
constant[
Create a new definition.
]
variable[class_name] assign[=] call[name[make_class_name], parameter[name[name]]]
variable[cls] assign[=] call[name[register], parameter[call[name[make], parameter[name[class_name], name[b... | keyword[def] identifier[make_definition] ( identifier[name] , identifier[base] , identifier[schema] ):
literal[string]
identifier[class_name] = identifier[make_class_name] ( identifier[name] )
identifier[cls] = identifier[register] ( identifier[make] ( identifier[class_name] , identifier[base] , ident... | def make_definition(name, base, schema):
"""
Create a new definition.
"""
class_name = make_class_name(name)
cls = register(make(class_name, base, schema))
globals()[class_name] = cls |
def footprint(self,nside):
"""
Download the survey footprint for HEALpix pixels.
"""
import healpy
import ugali.utils.projector
if nside > 2**9: raise Exception("Overflow error: nside must be <=2**9")
pix = np.arange(healpy.nside2npix(nside),dtype='int')
f... | def function[footprint, parameter[self, nside]]:
constant[
Download the survey footprint for HEALpix pixels.
]
import module[healpy]
import module[ugali.utils.projector]
if compare[name[nside] greater[>] binary_operation[constant[2] ** constant[9]]] begin[:]
<ast.Raise ob... | keyword[def] identifier[footprint] ( identifier[self] , identifier[nside] ):
literal[string]
keyword[import] identifier[healpy]
keyword[import] identifier[ugali] . identifier[utils] . identifier[projector]
keyword[if] identifier[nside] > literal[int] ** literal[int] : keyword... | def footprint(self, nside):
"""
Download the survey footprint for HEALpix pixels.
"""
import healpy
import ugali.utils.projector
if nside > 2 ** 9:
raise Exception('Overflow error: nside must be <=2**9') # depends on [control=['if'], data=[]]
pix = np.arange(healpy.nside2npi... |
def clear_reply_handlers_by_message_id(self, message_id):
"""
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
"""
self.reply_handlers[message_id] ... | def function[clear_reply_handlers_by_message_id, parameter[self, message_id]]:
constant[
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
]
call[na... | keyword[def] identifier[clear_reply_handlers_by_message_id] ( identifier[self] , identifier[message_id] ):
literal[string]
identifier[self] . identifier[reply_handlers] [ identifier[message_id] ]=[]
keyword[if] identifier[self] . identifier[reply_saver] keyword[is] keyword[not] keywor... | def clear_reply_handlers_by_message_id(self, message_id):
"""
Clears all callback functions registered by register_for_reply() and register_for_reply_by_message_id().
:param message_id: The message id for which we want to clear reply handlers
"""
self.reply_handlers[message_id] = []
... |
def align(args):
"""
%prog align database.fasta read1.fq [read2.fq]
Wrapper for `bowtie2` single-end or paired-end, depending on the number of args.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.set_firstN(firstN=0)
p.add_option("--full", default=Fals... | def function[align, parameter[args]]:
constant[
%prog align database.fasta read1.fq [read2.fq]
Wrapper for `bowtie2` single-end or paired-end, depending on the number of args.
]
from relative_module[jcvi.formats.fastq] import module[guessoffset]
variable[p] assign[=] call[name[OptionPar... | keyword[def] identifier[align] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[fastq] keyword[import] identifier[guessoffset]
identifier[p] = identifier[OptionParser] ( identifier[align] . identifier[__doc__] )
identifier[p] . identifie... | def align(args):
"""
%prog align database.fasta read1.fq [read2.fq]
Wrapper for `bowtie2` single-end or paired-end, depending on the number of args.
"""
from jcvi.formats.fastq import guessoffset
p = OptionParser(align.__doc__)
p.set_firstN(firstN=0)
p.add_option('--full', default=False... |
def _outside_contraction_fn(objective_function,
simplex,
objective_values,
face_centroid,
best_index,
worst_index,
reflected,
... | def function[_outside_contraction_fn, parameter[objective_function, simplex, objective_values, face_centroid, best_index, worst_index, reflected, objective_at_reflected, contraction, shrinkage, batch_evaluate_objective]]:
constant[Creates the condition function pair for an outside contraction.]
def func... | keyword[def] identifier[_outside_contraction_fn] ( identifier[objective_function] ,
identifier[simplex] ,
identifier[objective_values] ,
identifier[face_centroid] ,
identifier[best_index] ,
identifier[worst_index] ,
identifier[reflected] ,
identifier[objective_at_reflected] ,
identifier[contraction] ,
identi... | def _outside_contraction_fn(objective_function, simplex, objective_values, face_centroid, best_index, worst_index, reflected, objective_at_reflected, contraction, shrinkage, batch_evaluate_objective):
"""Creates the condition function pair for an outside contraction."""
def _contraction():
"""Performs ... |
def radio_status_send(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed, force_mavlink1=False):
'''
Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi ... | def function[radio_status_send, parameter[self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed, force_mavlink1]]:
constant[
Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi ... | keyword[def] identifier[radio_status_send] ( identifier[self] , identifier[rssi] , identifier[remrssi] , identifier[txbuf] , identifier[noise] , identifier[remnoise] , identifier[rxerrors] , identifier[fixed] , identifier[force_mavlink1] = keyword[False] ):
literal[string]
keyword[r... | def radio_status_send(self, rssi, remrssi, txbuf, noise, remnoise, rxerrors, fixed, force_mavlink1=False):
"""
Status generated by radio and injected into MAVLink stream.
rssi : Local signal strength (uint8_t)
remrssi : Remote s... |
def transaction(self):
"""
Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only.
"""
# The idea here is to fake the nesting of transactions. Only when
# we've gotten back to the topmost transaction contex... | def function[transaction, parameter[self]]:
constant[
Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only.
]
with name[self].mdr begin[:]
<ast.Try object at 0x7da18fe92d70>
if compare[nam... | keyword[def] identifier[transaction] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[mdr] :
keyword[try] :
identifier[self] . identifier[_depth] += literal[int]
keyword[yield] identifier[s... | def transaction(self):
"""
Sets up a context where all the statements within it are ran within
a single database transaction. For internal use only.
"""
# The idea here is to fake the nesting of transactions. Only when
# we've gotten back to the topmost transaction context do we actu... |
def rename_page(self, old_slug, new_title):
'''Load the page corresponding to the slug, and rename it.'''
#load page
p = s2page.Page(self, old_slug, isslug=True)
p.rename(new_title) | def function[rename_page, parameter[self, old_slug, new_title]]:
constant[Load the page corresponding to the slug, and rename it.]
variable[p] assign[=] call[name[s2page].Page, parameter[name[self], name[old_slug]]]
call[name[p].rename, parameter[name[new_title]]] | keyword[def] identifier[rename_page] ( identifier[self] , identifier[old_slug] , identifier[new_title] ):
literal[string]
identifier[p] = identifier[s2page] . identifier[Page] ( identifier[self] , identifier[old_slug] , identifier[isslug] = keyword[True] )
identifier[p] . identifi... | def rename_page(self, old_slug, new_title):
"""Load the page corresponding to the slug, and rename it."""
#load page
p = s2page.Page(self, old_slug, isslug=True)
p.rename(new_title) |
def lognet_vxlan_walker(prepush = True):
"""
Return a walker function to retrieve necessary information from ObjectDB
"""
def _walk_lognet(key, value, walk, save):
save(key)
if value is None:
return
try:
phynet = walk(value.physicalnetwork.getkey())
... | def function[lognet_vxlan_walker, parameter[prepush]]:
constant[
Return a walker function to retrieve necessary information from ObjectDB
]
def function[_walk_lognet, parameter[key, value, walk, save]]:
call[name[save], parameter[name[key]]]
if compare[name[value]... | keyword[def] identifier[lognet_vxlan_walker] ( identifier[prepush] = keyword[True] ):
literal[string]
keyword[def] identifier[_walk_lognet] ( identifier[key] , identifier[value] , identifier[walk] , identifier[save] ):
identifier[save] ( identifier[key] )
keyword[if] identifier[value] ... | def lognet_vxlan_walker(prepush=True):
"""
Return a walker function to retrieve necessary information from ObjectDB
"""
def _walk_lognet(key, value, walk, save):
save(key)
if value is None:
return # depends on [control=['if'], data=[]]
try:
phynet = walk... |
def _transfer_str(self, conn, tmp, name, data):
''' transfer string to remote file '''
if type(data) == dict:
data = utils.jsonify(data)
afd, afile = tempfile.mkstemp()
afo = os.fdopen(afd, 'w')
try:
afo.write(data.encode('utf8'))
except:
... | def function[_transfer_str, parameter[self, conn, tmp, name, data]]:
constant[ transfer string to remote file ]
if compare[call[name[type], parameter[name[data]]] equal[==] name[dict]] begin[:]
variable[data] assign[=] call[name[utils].jsonify, parameter[name[data]]]
<ast.Tuple o... | keyword[def] identifier[_transfer_str] ( identifier[self] , identifier[conn] , identifier[tmp] , identifier[name] , identifier[data] ):
literal[string]
keyword[if] identifier[type] ( identifier[data] )== identifier[dict] :
identifier[data] = identifier[utils] . identifier[jsonify] ( ... | def _transfer_str(self, conn, tmp, name, data):
""" transfer string to remote file """
if type(data) == dict:
data = utils.jsonify(data) # depends on [control=['if'], data=[]]
(afd, afile) = tempfile.mkstemp()
afo = os.fdopen(afd, 'w')
try:
afo.write(data.encode('utf8')) # depends ... |
def generate_hosts(config, app):
'''
app: {
"container id": continer details
...
}
'''
# hosts = {app[container]["NetworkSettings"]["IPAddress"]:app[container]["Name"].replace('/','') for container in app}
hosts = {}
for container in app:
hosts[app[container]["NetworkS... | def function[generate_hosts, parameter[config, app]]:
constant[
app: {
"container id": continer details
...
}
]
variable[hosts] assign[=] dictionary[[], []]
for taget[name[container]] in starred[name[app]] begin[:]
call[name[hosts]][call[call[call[name... | keyword[def] identifier[generate_hosts] ( identifier[config] , identifier[app] ):
literal[string]
identifier[hosts] ={}
keyword[for] identifier[container] keyword[in] identifier[app] :
identifier[hosts] [ identifier[app] [ identifier[container] ][ literal[string] ][ literal[string] ]]... | def generate_hosts(config, app):
"""
app: {
"container id": continer details
...
}
"""
# hosts = {app[container]["NetworkSettings"]["IPAddress"]:app[container]["Name"].replace('/','') for container in app}
hosts = {}
for container in app:
hosts[app[container]['Netw... |
def parse_keyvalue(self, tup_tree):
"""
Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to create the corresponding CIM
... | def function[parse_keyvalue, parameter[self, tup_tree]]:
constant[
Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to cre... | keyword[def] identifier[parse_keyvalue] ( identifier[self] , identifier[tup_tree] ):
literal[string]
identifier[self] . identifier[check_node] ( identifier[tup_tree] , literal[string] ,(),( literal[string] , literal[string] ),(),
identifier[allow_pcdata] = keyword[True] )
identi... | def parse_keyvalue(self, tup_tree):
"""
Parse a KEYVALUE element and return the keybinding value as a CIM data
type object, based upon the type information in its VALUETYPE and TYPE
attributes, if present.
If TYPE is specified, its value is used to create the corresponding CIM
... |
def _bin_exp(self, n_bin, scale=1.0):
""" Calculate the bin locations to approximate exponential distribution.
It breaks the cumulative probability of exponential distribution
into n_bin equal bins, each covering 1 / n_bin probability. Then it
calculates the center of mass in... | def function[_bin_exp, parameter[self, n_bin, scale]]:
constant[ Calculate the bin locations to approximate exponential distribution.
It breaks the cumulative probability of exponential distribution
into n_bin equal bins, each covering 1 / n_bin probability. Then it
calculate... | keyword[def] identifier[_bin_exp] ( identifier[self] , identifier[n_bin] , identifier[scale] = literal[int] ):
literal[string]
identifier[boundaries] = identifier[np] . identifier[flip] ( identifier[scipy] . identifier[stats] . identifier[expon] . identifier[isf] (
identifier[np] . identif... | def _bin_exp(self, n_bin, scale=1.0):
""" Calculate the bin locations to approximate exponential distribution.
It breaks the cumulative probability of exponential distribution
into n_bin equal bins, each covering 1 / n_bin probability. Then it
calculates the center of mass in eac... |
def open_channel(self):
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
"""
_logger.info('Creating a new channel')
self._connection.channel(... | def function[open_channel, parameter[self]]:
constant[Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
]
call[name[_logger].info, parameter[constant[Cre... | keyword[def] identifier[open_channel] ( identifier[self] ):
literal[string]
identifier[_logger] . identifier[info] ( literal[string] )
identifier[self] . identifier[_connection] . identifier[channel] ( identifier[on_open_callback] = identifier[self] . identifier[on_channel_open] ) | def open_channel(self):
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika.
"""
_logger.info('Creating a new channel')
self._connection.channel(on_open_call... |
def _get_securitygroupname_id(securitygroupname_list):
'''
Returns the SecurityGroupId of a SecurityGroupName to use
'''
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list]
params = {'Action': 'DescribeSecurityGro... | def function[_get_securitygroupname_id, parameter[securitygroupname_list]]:
constant[
Returns the SecurityGroupId of a SecurityGroupName to use
]
variable[securitygroupid_set] assign[=] call[name[set], parameter[]]
if <ast.UnaryOp object at 0x7da1b1c66f20> begin[:]
variab... | keyword[def] identifier[_get_securitygroupname_id] ( identifier[securitygroupname_list] ):
literal[string]
identifier[securitygroupid_set] = identifier[set] ()
keyword[if] keyword[not] identifier[isinstance] ( identifier[securitygroupname_list] , identifier[list] ):
identifier[securitygroup... | def _get_securitygroupname_id(securitygroupname_list):
"""
Returns the SecurityGroupId of a SecurityGroupName to use
"""
securitygroupid_set = set()
if not isinstance(securitygroupname_list, list):
securitygroupname_list = [securitygroupname_list] # depends on [control=['if'], data=[]]
... |
def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic... | def function[binary_gas_search, parameter[state, transaction, tolerance]]:
constant[
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic_gas, state... | keyword[def] identifier[binary_gas_search] ( identifier[state] : identifier[BaseState] , identifier[transaction] : identifier[BaseTransaction] , identifier[tolerance] : identifier[int] = literal[int] )-> identifier[int] :
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[transacti... | def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int:
"""
Run the transaction with various gas limits, progressively
approaching the minimum needed to succeed without an OutOfGas exception.
The starting range of possible estimates is:
[transaction.intrinsic... |
def compcor_variance_plot(metadata_files, metadata_sources=None,
output_file=None, varexp_thresh=(0.5, 0.7, 0.9),
fig=None):
"""
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
... | def function[compcor_variance_plot, parameter[metadata_files, metadata_sources, output_file, varexp_thresh, fig]]:
constant[
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anato... | keyword[def] identifier[compcor_variance_plot] ( identifier[metadata_files] , identifier[metadata_sources] = keyword[None] ,
identifier[output_file] = keyword[None] , identifier[varexp_thresh] =( literal[int] , literal[int] , literal[int] ),
identifier[fig] = keyword[None] ):
literal[string]
identifier[m... | def compcor_variance_plot(metadata_files, metadata_sources=None, output_file=None, varexp_thresh=(0.5, 0.7, 0.9), fig=None):
"""
Parameters
----------
metadata_files: list
List of paths to files containing component metadata. If more than one
decomposition has been performed (e.g., anato... |
def lru_cache(maxsize=128, typed=False, state=None, unhashable='error'):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and
the cache can grow without bound.
If *typed* is True, arguments of different types will be cached
separately. For example,... | def function[lru_cache, parameter[maxsize, typed, state, unhashable]]:
constant[Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and
the cache can grow without bound.
If *typed* is True, arguments of different types will be cached
separately. For ... | keyword[def] identifier[lru_cache] ( identifier[maxsize] = literal[int] , identifier[typed] = keyword[False] , identifier[state] = keyword[None] , identifier[unhashable] = literal[string] ):
literal[string]
keyword[def] identifier[func_wrapper] ( identifier[func] ):
identifier[_cached_func] = ide... | def lru_cache(maxsize=128, typed=False, state=None, unhashable='error'):
"""Least-recently-used cache decorator.
If *maxsize* is set to None, the LRU features are disabled and
the cache can grow without bound.
If *typed* is True, arguments of different types will be cached
separately. For example,... |
def add_final_training_ops(self,
embeddings,
all_labels_count,
bottleneck_tensor_size,
hidden_layer_size=BOTTLENECK_TENSOR_SIZE / 4,
dropout_keep_prob=None):
"""Adds a new... | def function[add_final_training_ops, parameter[self, embeddings, all_labels_count, bottleneck_tensor_size, hidden_layer_size, dropout_keep_prob]]:
constant[Adds a new softmax and fully-connected layer for training.
The set up for the softmax and fully-connected layers is based on:
https://tensorflow.... | keyword[def] identifier[add_final_training_ops] ( identifier[self] ,
identifier[embeddings] ,
identifier[all_labels_count] ,
identifier[bottleneck_tensor_size] ,
identifier[hidden_layer_size] = identifier[BOTTLENECK_TENSOR_SIZE] / literal[int] ,
identifier[dropout_keep_prob] = keyword[None] ):
literal[strin... | def add_final_training_ops(self, embeddings, all_labels_count, bottleneck_tensor_size, hidden_layer_size=BOTTLENECK_TENSOR_SIZE / 4, dropout_keep_prob=None):
"""Adds a new softmax and fully-connected layer for training.
The set up for the softmax and fully-connected layers is based on:
https://tensorflow... |
def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None
elif isinstance(val, six.string_types):
return import_from_string(val, setting_name)
elif isinstance(val,... | def function[perform_import, parameter[val, setting_name]]:
constant[
If the given setting is a string import notation,
then perform the necessary import or imports.
]
if compare[name[val] is constant[None]] begin[:]
return[constant[None]]
return[name[val]] | keyword[def] identifier[perform_import] ( identifier[val] , identifier[setting_name] ):
literal[string]
keyword[if] identifier[val] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] identifier[isinstance] ( identifier[val] , identifier[six] . identifier[string_type... | def perform_import(val, setting_name):
"""
If the given setting is a string import notation,
then perform the necessary import or imports.
"""
if val is None:
return None # depends on [control=['if'], data=[]]
elif isinstance(val, six.string_types):
return import_from_string(val... |
def on_open(self, websocket):
'''When a new websocket connection is established it creates a
new :class:`ChatClient` and adds it to the set of clients of the
:attr:`pubsub` handler.'''
self.pubsub.add_client(ChatClient(websocket, self.channel)) | def function[on_open, parameter[self, websocket]]:
constant[When a new websocket connection is established it creates a
new :class:`ChatClient` and adds it to the set of clients of the
:attr:`pubsub` handler.]
call[name[self].pubsub.add_client, parameter[call[name[ChatClient], parameter[... | keyword[def] identifier[on_open] ( identifier[self] , identifier[websocket] ):
literal[string]
identifier[self] . identifier[pubsub] . identifier[add_client] ( identifier[ChatClient] ( identifier[websocket] , identifier[self] . identifier[channel] )) | def on_open(self, websocket):
"""When a new websocket connection is established it creates a
new :class:`ChatClient` and adds it to the set of clients of the
:attr:`pubsub` handler."""
self.pubsub.add_client(ChatClient(websocket, self.channel)) |
def metadata(access_token, text): # (Legacy)
'''
Name: metadata_only
Parameters: access_token, text (string)
Return: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + str(access_token)
}
payload = {'text': text}
request = requests.post(met... | def function[metadata, parameter[access_token, text]]:
constant[
Name: metadata_only
Parameters: access_token, text (string)
Return: dictionary
]
variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c76a0>, <ast.Constant object at 0x7da20c6c5cc0>], [<ast.Constant object at 0x7da2... | keyword[def] identifier[metadata] ( identifier[access_token] , identifier[text] ):
literal[string]
identifier[headers] ={
literal[string] : literal[string] ,
literal[string] : literal[string] + identifier[str] ( identifier[access_token] )
}
identifier[payload] ={ literal[string] : iden... | def metadata(access_token, text): # (Legacy)
'\n\tName: metadata_only\n\tParameters: access_token, text (string)\n\tReturn: dictionary\n\t'
headers = {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + str(access_token)}
payload = {'text': text}
request = requests.post(metadata_url, json=... |
def format_general_name(name):
"""Format a single general name.
>>> import ipaddress
>>> format_general_name(x509.DNSName('example.com'))
'DNS:example.com'
>>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1')))
'IP:127.0.0.1'
"""
if isinstance(name, x509.DirectoryN... | def function[format_general_name, parameter[name]]:
constant[Format a single general name.
>>> import ipaddress
>>> format_general_name(x509.DNSName('example.com'))
'DNS:example.com'
>>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1')))
'IP:127.0.0.1'
]
if ... | keyword[def] identifier[format_general_name] ( identifier[name] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[name] , identifier[x509] . identifier[DirectoryName] ):
identifier[value] = identifier[format_name] ( identifier[name] . identifier[value] )
keyword[else] :
... | def format_general_name(name):
"""Format a single general name.
>>> import ipaddress
>>> format_general_name(x509.DNSName('example.com'))
'DNS:example.com'
>>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1')))
'IP:127.0.0.1'
"""
if isinstance(name, x509.DirectoryNa... |
def load_tile(self, tile):
'''load a tile from cache or tile server'''
# see if its in the tile cache
key = tile.key()
if key in self._tile_cache:
img = self._tile_cache[key]
if np.array_equal(img, self._unavailable):
img = self.load_tile_lowres(t... | def function[load_tile, parameter[self, tile]]:
constant[load a tile from cache or tile server]
variable[key] assign[=] call[name[tile].key, parameter[]]
if compare[name[key] in name[self]._tile_cache] begin[:]
variable[img] assign[=] call[name[self]._tile_cache][name[key]]
... | keyword[def] identifier[load_tile] ( identifier[self] , identifier[tile] ):
literal[string]
identifier[key] = identifier[tile] . identifier[key] ()
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_tile_cache] :
identifier[img] = identifier[se... | def load_tile(self, tile):
"""load a tile from cache or tile server"""
# see if its in the tile cache
key = tile.key()
if key in self._tile_cache:
img = self._tile_cache[key]
if np.array_equal(img, self._unavailable):
img = self.load_tile_lowres(tile)
if img is No... |
def setDefault(self, key, value):
"""
Sets the default for a given key to the value.
:param key | <str>
value | <str> || <XResourceManager>
"""
if value is None:
self._defaults.pop(key, None)
else:
self._... | def function[setDefault, parameter[self, key, value]]:
constant[
Sets the default for a given key to the value.
:param key | <str>
value | <str> || <XResourceManager>
]
if compare[name[value] is constant[None]] begin[:]
call[name[... | keyword[def] identifier[setDefault] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[None] :
identifier[self] . identifier[_defaults] . identifier[pop] ( identifier[key] , keyword[None] )
keywo... | def setDefault(self, key, value):
"""
Sets the default for a given key to the value.
:param key | <str>
value | <str> || <XResourceManager>
"""
if value is None:
self._defaults.pop(key, None) # depends on [control=['if'], data=[]]
else:
... |
def createNoiseExperimentArgs():
"""Run the probability of false negatives with noise experiment."""
experimentArguments = []
n = 6000
for a in [128]:
noisePct = 0.75
while noisePct <= 0.85:
noise = int(round(noisePct*a,0))
# Some parameter combinations are just not worth running!
expe... | def function[createNoiseExperimentArgs, parameter[]]:
constant[Run the probability of false negatives with noise experiment.]
variable[experimentArguments] assign[=] list[[]]
variable[n] assign[=] constant[6000]
for taget[name[a]] in starred[list[[<ast.Constant object at 0x7da1b0847f10>]... | keyword[def] identifier[createNoiseExperimentArgs] ():
literal[string]
identifier[experimentArguments] =[]
identifier[n] = literal[int]
keyword[for] identifier[a] keyword[in] [ literal[int] ]:
identifier[noisePct] = literal[int]
keyword[while] identifier[noisePct] <= literal[int] :
... | def createNoiseExperimentArgs():
"""Run the probability of false negatives with noise experiment."""
experimentArguments = []
n = 6000
for a in [128]:
noisePct = 0.75
while noisePct <= 0.85:
noise = int(round(noisePct * a, 0))
# Some parameter combinations are jus... |
def is_key(cls, result):
"""Return ``True`` if result is a key object."""
from boto.s3.key import Key
return isinstance(result, Key) | def function[is_key, parameter[cls, result]]:
constant[Return ``True`` if result is a key object.]
from relative_module[boto.s3.key] import module[Key]
return[call[name[isinstance], parameter[name[result], name[Key]]]] | keyword[def] identifier[is_key] ( identifier[cls] , identifier[result] ):
literal[string]
keyword[from] identifier[boto] . identifier[s3] . identifier[key] keyword[import] identifier[Key]
keyword[return] identifier[isinstance] ( identifier[result] , identifier[Key] ) | def is_key(cls, result):
"""Return ``True`` if result is a key object."""
from boto.s3.key import Key
return isinstance(result, Key) |
def do_eos(self, _: argparse.Namespace) -> None:
"""Handle cleanup when a script has finished executing"""
if self._script_dir:
self._script_dir.pop() | def function[do_eos, parameter[self, _]]:
constant[Handle cleanup when a script has finished executing]
if name[self]._script_dir begin[:]
call[name[self]._script_dir.pop, parameter[]] | keyword[def] identifier[do_eos] ( identifier[self] , identifier[_] : identifier[argparse] . identifier[Namespace] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[_script_dir] :
identifier[self] . identifier[_script_dir] . identifier[pop] () | def do_eos(self, _: argparse.Namespace) -> None:
"""Handle cleanup when a script has finished executing"""
if self._script_dir:
self._script_dir.pop() # depends on [control=['if'], data=[]] |
def GetJson(self):
"""Returns JSON version of ClientData compatible with FIDO spec."""
# The U2F Raw Messages specification specifies that the challenge is encoded
# with URL safe Base64 without padding encoding specified in RFC 4648.
# Python does not natively support a paddingless encoding, so we sim... | def function[GetJson, parameter[self]]:
constant[Returns JSON version of ClientData compatible with FIDO spec.]
variable[server_challenge_b64] assign[=] call[call[name[base64].urlsafe_b64encode, parameter[name[self].raw_server_challenge]].decode, parameter[]]
variable[server_challenge_b64] assig... | keyword[def] identifier[GetJson] ( identifier[self] ):
literal[string]
identifier[server_challenge_b64] = identifier[base64] . identifier[urlsafe_b64encode] (
identifier[self] . identifier[raw_server_challenge] ). identifier[decode] ()
identifier[server_challenge_b64] = ident... | def GetJson(self):
"""Returns JSON version of ClientData compatible with FIDO spec."""
# The U2F Raw Messages specification specifies that the challenge is encoded
# with URL safe Base64 without padding encoding specified in RFC 4648.
# Python does not natively support a paddingless encoding, so we simp... |
def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
"""
self._baseLogger.debug(self, self.getExtendedM... | def function[debug, parameter[self, msg]]:
constant[
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
]
call[name[self]._baseLogger.de... | keyword[def] identifier[debug] ( identifier[self] , identifier[msg] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[_baseLogger] . identifier[debug] ( identifier[self] , identifier[self] . identifier[getExtendedMsg] ( identifier[msg] ),* identifier[args] ,** iden... | def debug(self, msg, *args, **kwargs):
"""
Log 'msg % args' with severity 'DEBUG'.
To pass exception information, use the keyword argument exc_info with
a true value, e.g.
logger.debug("Houston, we have a %s", "thorny problem", exc_info=1)
"""
self._baseLogger.debug(self, self.getExtendedM... |
def connect(self):
"""Returns an open connection (socket) to the Splunk instance.
This method is used for writing bulk events to an index or similar tasks
where the overhead of opening a connection multiple times would be
prohibitive.
:returns: A socket.
**Example**::
... | def function[connect, parameter[self]]:
constant[Returns an open connection (socket) to the Splunk instance.
This method is used for writing bulk events to an index or similar tasks
where the overhead of opening a connection multiple times would be
prohibitive.
:returns: A sock... | keyword[def] identifier[connect] ( identifier[self] ):
literal[string]
identifier[sock] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] )
keyword[if] identifier[self] . identifier[scheme] == literal[string... | def connect(self):
"""Returns an open connection (socket) to the Splunk instance.
This method is used for writing bulk events to an index or similar tasks
where the overhead of opening a connection multiple times would be
prohibitive.
:returns: A socket.
**Example**::
... |
def plus_dora(tile, dora_indicators):
"""
:param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora
"""
tile_index = tile // 4
dora_count = 0
for dora in dora_indicators:
dora //= 4
# sou, pin, man
if tile_ind... | def function[plus_dora, parameter[tile, dora_indicators]]:
constant[
:param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora
]
variable[tile_index] assign[=] binary_operation[name[tile] <ast.FloorDiv object at 0x7da2590d6bc0> constan... | keyword[def] identifier[plus_dora] ( identifier[tile] , identifier[dora_indicators] ):
literal[string]
identifier[tile_index] = identifier[tile] // literal[int]
identifier[dora_count] = literal[int]
keyword[for] identifier[dora] keyword[in] identifier[dora_indicators] :
identifier[... | def plus_dora(tile, dora_indicators):
"""
:param tile: int 136 tiles format
:param dora_indicators: array of 136 tiles format
:return: int count of dora
"""
tile_index = tile // 4
dora_count = 0
for dora in dora_indicators:
dora //= 4
# sou, pin, man
if tile_index... |
def _parse_request(self, url=None, handle=None):
'''Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test()
'''
# To accomdate self.redirect, we need to be able to parse a... | def function[_parse_request, parameter[self, url, handle]]:
constant[Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test()
]
if compare[name[url] is constant[None]] begi... | keyword[def] identifier[_parse_request] ( identifier[self] , identifier[url] = keyword[None] , identifier[handle] = keyword[None] ):
literal[string]
keyword[if] identifier[url] keyword[is] keyword[None] :
identifier[url] = identifier[sys] . identifier[argv] [ liter... | def _parse_request(self, url=None, handle=None):
"""Handles setup of the plugin state, including request
arguments, handle, mode.
This method never needs to be called directly. For testing, see
plugin.test()
"""
# To accomdate self.redirect, we need to be able to parse a full ur... |
def spkez(targ, et, ref, abcorr, obs):
"""
Return the state (position and velocity) of a target body
relative to an observing body, optionally corrected for light
time (planetary aberration) and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html
:param tar... | def function[spkez, parameter[targ, et, ref, abcorr, obs]]:
constant[
Return the state (position and velocity) of a target body
relative to an observing body, optionally corrected for light
time (planetary aberration) and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspi... | keyword[def] identifier[spkez] ( identifier[targ] , identifier[et] , identifier[ref] , identifier[abcorr] , identifier[obs] ):
literal[string]
identifier[targ] = identifier[ctypes] . identifier[c_int] ( identifier[targ] )
identifier[et] = identifier[ctypes] . identifier[c_double] ( identifier[et] )
... | def spkez(targ, et, ref, abcorr, obs):
"""
Return the state (position and velocity) of a target body
relative to an observing body, optionally corrected for light
time (planetary aberration) and stellar aberration.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkez_c.html
:param tar... |
def zoning_defined_configuration_alias_member_entry_alias_entry_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
zoning = ET.SubElement(config, "zoning", xmlns="urn:brocade.com:mgmt:brocade-zone")
defined_configuration = ET.SubElement(zoning, "define... | def function[zoning_defined_configuration_alias_member_entry_alias_entry_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[zoning] assign[=] call[name[ET].SubElement, parameter[name[config], cons... | keyword[def] identifier[zoning_defined_configuration_alias_member_entry_alias_entry_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[zoning] = identifier[ET] . identifier[SubElement] ... | def zoning_defined_configuration_alias_member_entry_alias_entry_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
zoning = ET.SubElement(config, 'zoning', xmlns='urn:brocade.com:mgmt:brocade-zone')
defined_configuration = ET.SubElement(zoning, 'defined-configuration'... |
def protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises
an error if that does not exist."""
return self.query(Protocol).filter(Protocol.name==name).one() | def function[protocol, parameter[self, name]]:
constant[Returns the protocol object in the database given a certain name. Raises
an error if that does not exist.]
return[call[call[call[name[self].query, parameter[name[Protocol]]].filter, parameter[compare[name[Protocol].name equal[==] name[name]]]].one,... | keyword[def] identifier[protocol] ( identifier[self] , identifier[name] ):
literal[string]
keyword[return] identifier[self] . identifier[query] ( identifier[Protocol] ). identifier[filter] ( identifier[Protocol] . identifier[name] == identifier[name] ). identifier[one] () | def protocol(self, name):
"""Returns the protocol object in the database given a certain name. Raises
an error if that does not exist."""
return self.query(Protocol).filter(Protocol.name == name).one() |
def get_artists(self, limit=50, cacheable=True):
"""
Returns a sequence of Album objects
if limit==None it will return all (may take a while)
"""
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + ".getArtists", cacheable
):
... | def function[get_artists, parameter[self, limit, cacheable]]:
constant[
Returns a sequence of Album objects
if limit==None it will return all (may take a while)
]
variable[seq] assign[=] list[[]]
for taget[name[node]] in starred[call[name[_collect_nodes], parameter[name[l... | keyword[def] identifier[get_artists] ( identifier[self] , identifier[limit] = literal[int] , identifier[cacheable] = keyword[True] ):
literal[string]
identifier[seq] =[]
keyword[for] identifier[node] keyword[in] identifier[_collect_nodes] (
identifier[limit] , identifier[self]... | def get_artists(self, limit=50, cacheable=True):
"""
Returns a sequence of Album objects
if limit==None it will return all (may take a while)
"""
seq = []
for node in _collect_nodes(limit, self, self.ws_prefix + '.getArtists', cacheable):
name = _extract(node, 'name')
... |
def from_EmailMessage(cls, message):
"""Create a Mail object from an instance of
email.message.EmailMessage.
:type message: email.message.EmailMessage
:rtype: Mail
"""
mail = cls(
from_email=Email(message.get('From')),
subject=message.get('Subject... | def function[from_EmailMessage, parameter[cls, message]]:
constant[Create a Mail object from an instance of
email.message.EmailMessage.
:type message: email.message.EmailMessage
:rtype: Mail
]
variable[mail] assign[=] call[name[cls], parameter[]]
<ast.Try object at 0... | keyword[def] identifier[from_EmailMessage] ( identifier[cls] , identifier[message] ):
literal[string]
identifier[mail] = identifier[cls] (
identifier[from_email] = identifier[Email] ( identifier[message] . identifier[get] ( literal[string] )),
identifier[subject] = identifier[mess... | def from_EmailMessage(cls, message):
"""Create a Mail object from an instance of
email.message.EmailMessage.
:type message: email.message.EmailMessage
:rtype: Mail
"""
mail = cls(from_email=Email(message.get('From')), subject=message.get('Subject'), to_emails=Email(message.get('... |
def set(self, value):
'''set a setting'''
if value == 'None' and self.default is None:
value = None
if value is not None:
if self.type == bool:
if str(value).lower() in ['1', 'true', 'yes']:
value = True
elif str(value).... | def function[set, parameter[self, value]]:
constant[set a setting]
if <ast.BoolOp object at 0x7da20c76fbe0> begin[:]
variable[value] assign[=] constant[None]
if compare[name[value] is_not constant[None]] begin[:]
if compare[name[self].type equal[==] name[bool]] be... | keyword[def] identifier[set] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] == literal[string] keyword[and] identifier[self] . identifier[default] keyword[is] keyword[None] :
identifier[value] = keyword[None]
keyword[if] identifi... | def set(self, value):
"""set a setting"""
if value == 'None' and self.default is None:
value = None # depends on [control=['if'], data=[]]
if value is not None:
if self.type == bool:
if str(value).lower() in ['1', 'true', 'yes']:
value = True # depends on [contr... |
def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram minimum cu... | def function[metadata, parameter[sceneid, pmin, pmax]]:
constant[
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Hist... | keyword[def] identifier[metadata] ( identifier[sceneid] , identifier[pmin] = literal[int] , identifier[pmax] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[scene_params] = identifier[_landsat_parse_scene_id] ( identifier[sceneid] )
identifier[meta_data] = identifier[_landsat_get_m... | def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram minimum cu... |
def get_checkerboard_matrix(kernel_width):
"""
example matrix for width = 2
-1 -1 1 1
-1 -1 1 1
1 1 -1 -1
1 1 -1 -1
:param kernel_width:
:return:
"""
return np.vstack((
np.hstack((
-1 * np.ones((kernel_width, kernel_width)), np.ones... | def function[get_checkerboard_matrix, parameter[kernel_width]]:
constant[
example matrix for width = 2
-1 -1 1 1
-1 -1 1 1
1 1 -1 -1
1 1 -1 -1
:param kernel_width:
:return:
]
return[call[name[np].vstack, parameter[tuple[[<ast.Call object at 0x7da1b13... | keyword[def] identifier[get_checkerboard_matrix] ( identifier[kernel_width] ):
literal[string]
keyword[return] identifier[np] . identifier[vstack] ((
identifier[np] . identifier[hstack] ((
- literal[int] * identifier[np] . identifier[ones] (( identifier[kernel_width] , identifier[kernel_width] ... | def get_checkerboard_matrix(kernel_width):
"""
example matrix for width = 2
-1 -1 1 1
-1 -1 1 1
1 1 -1 -1
1 1 -1 -1
:param kernel_width:
:return:
"""
return np.vstack((np.hstack((-1 * np.ones((kernel_width, kernel_width)), np.ones((kernel_width, kernel_w... |
def _install_one(
repo_url, branch, destination, commit='', patches=None,
exclude_modules=None, include_modules=None, base=False, work_directory=''
):
""" Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to c... | def function[_install_one, parameter[repo_url, branch, destination, commit, patches, exclude_modules, include_modules, base, work_directory]]:
constant[ Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to checkou... | keyword[def] identifier[_install_one] (
identifier[repo_url] , identifier[branch] , identifier[destination] , identifier[commit] = literal[string] , identifier[patches] = keyword[None] ,
identifier[exclude_modules] = keyword[None] , identifier[include_modules] = keyword[None] , identifier[base] = keyword[False] , i... | def _install_one(repo_url, branch, destination, commit='', patches=None, exclude_modules=None, include_modules=None, base=False, work_directory=''):
""" Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to checkout.
... |
async def open(self):
"""Register with the publisher."""
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self.publish(message) | <ast.AsyncFunctionDef object at 0x7da1b244add0> | keyword[async] keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[self] . identifier[store] . identifier[register] ( identifier[self] )
keyword[while] keyword[not] identifier[self] . identifier[finished] :
identifier[message] = keyword[await]... | async def open(self):
"""Register with the publisher."""
self.store.register(self)
while not self.finished:
message = await self.messages.get()
await self.publish(message) # depends on [control=['while'], data=[]] |
def flush_commit(self, commits, repos=tuple()):
"""
Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of the jobs that are t... | def function[flush_commit, parameter[self, commits, repos]]:
constant[
Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of ... | keyword[def] identifier[flush_commit] ( identifier[self] , identifier[commits] , identifier[repos] = identifier[tuple] ()):
literal[string]
identifier[req] = identifier[proto] . identifier[FlushCommitRequest] ( identifier[commit] =[ identifier[commit_from] ( identifier[c] ) keyword[for] identifier... | def flush_commit(self, commits, repos=tuple()):
"""
Blocks until all of the commits which have a set of commits as
provenance have finished. For commits to be considered they must have
all of the specified commits as provenance. This in effect waits for
all of the jobs that are trigg... |
def connect(self, callback, ref=False, position='first',
before=None, after=None):
"""Connect this emitter to a new callback.
Parameters
----------
callback : function | tuple
*callback* may be either a callable object or a tuple
(object, attr_nam... | def function[connect, parameter[self, callback, ref, position, before, after]]:
constant[Connect this emitter to a new callback.
Parameters
----------
callback : function | tuple
*callback* may be either a callable object or a tuple
(object, attr_name) where obje... | keyword[def] identifier[connect] ( identifier[self] , identifier[callback] , identifier[ref] = keyword[False] , identifier[position] = literal[string] ,
identifier[before] = keyword[None] , identifier[after] = keyword[None] ):
literal[string]
identifier[callbacks] = identifier[self] . identifier[c... | def connect(self, callback, ref=False, position='first', before=None, after=None):
"""Connect this emitter to a new callback.
Parameters
----------
callback : function | tuple
*callback* may be either a callable object or a tuple
(object, attr_name) where object.attr... |
def url(value):
"""Validate a URL.
:param string value: The URL to validate
:returns: The URL if valid.
:raises: ValueError
"""
if not url_regex.search(value):
message = u"{0} is not a valid URL".format(value)
if url_regex.search('http://' + value):
message += u". Di... | def function[url, parameter[value]]:
constant[Validate a URL.
:param string value: The URL to validate
:returns: The URL if valid.
:raises: ValueError
]
if <ast.UnaryOp object at 0x7da20c76f100> begin[:]
variable[message] assign[=] call[constant[{0} is not a valid URL].f... | keyword[def] identifier[url] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[url_regex] . identifier[search] ( identifier[value] ):
identifier[message] = literal[string] . identifier[format] ( identifier[value] )
keyword[if] identifier[url_regex] . identifier... | def url(value):
"""Validate a URL.
:param string value: The URL to validate
:returns: The URL if valid.
:raises: ValueError
"""
if not url_regex.search(value):
message = u'{0} is not a valid URL'.format(value)
if url_regex.search('http://' + value):
message += u'. Di... |
def fetch_public_key(repo):
"""Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read())
if 'key' not in data:
errms... | def function[fetch_public_key, parameter[repo]]:
constant[Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
]
variable[keyurl] assign[=] call[constant[https://api.travis-ci.org/repos/{0}/key].format, parameter[name[repo]]]
... | keyword[def] identifier[fetch_public_key] ( identifier[repo] ):
literal[string]
identifier[keyurl] = literal[string] . identifier[format] ( identifier[repo] )
identifier[data] = identifier[json] . identifier[loads] ( identifier[urlopen] ( identifier[keyurl] ). identifier[read] ())
keyword[if] li... | def fetch_public_key(repo):
"""Download RSA public key Travis will use for this repo.
Travis API docs: http://docs.travis-ci.com/api/#repository-keys
"""
keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo)
data = json.loads(urlopen(keyurl).read())
if 'key' not in data:
errms... |
def get_semantic_data(self, path_as_list):
""" Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
"""
target_dict = self.semantic_data
for path_element in path_as_list:
if path_eleme... | def function[get_semantic_data, parameter[self, path_as_list]]:
constant[ Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
]
variable[target_dict] assign[=] name[self].semantic_data
for taget[... | keyword[def] identifier[get_semantic_data] ( identifier[self] , identifier[path_as_list] ):
literal[string]
identifier[target_dict] = identifier[self] . identifier[semantic_data]
keyword[for] identifier[path_element] keyword[in] identifier[path_as_list] :
keyword[if] iden... | def get_semantic_data(self, path_as_list):
""" Retrieves an entry of the semantic data.
:param list path_as_list: The path in the vividict to retrieve the value from
:return:
"""
target_dict = self.semantic_data
for path_element in path_as_list:
if path_element in target_dic... |
def start(self):
"""Start the scheduler threads."""
# TODO(BMo) having this check is probably a good idea but I've \
# disabled it for now while the PBC is in flux.
# assert sip_pbc.release.__version__ == '1.2.3'
scheduler_threads = [
Thread(target=self._monitor_even... | def function[start, parameter[self]]:
constant[Start the scheduler threads.]
variable[scheduler_threads] assign[=] list[[<ast.Call object at 0x7da1b0536f20>, <ast.Call object at 0x7da1b05342b0>, <ast.Call object at 0x7da20c9909d0>, <ast.Call object at 0x7da20c9914e0>]]
for taget[name[thread]] in... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[scheduler_threads] =[
identifier[Thread] ( identifier[target] = identifier[self] . identifier[_monitor_events] , identifier[daemon] = keyword[True] ),
identifier[Thread] ( i... | def start(self):
"""Start the scheduler threads."""
# TODO(BMo) having this check is probably a good idea but I've \
# disabled it for now while the PBC is in flux.
# assert sip_pbc.release.__version__ == '1.2.3'
scheduler_threads = [Thread(target=self._monitor_events, daemon=True), Thread(target=se... |
def local(self, fun, tgt, **kwargs):
'''
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
'''
self.client_cache['local'].cmd_async(tgt, fun, **kwargs) | def function[local, parameter[self, fun, tgt]]:
constant[
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
]
call[call[name[self].client_cache][constant[local]].cmd_async, parameter[name[tgt], name[fun]]] | keyword[def] identifier[local] ( identifier[self] , identifier[fun] , identifier[tgt] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[client_cache] [ literal[string] ]. identifier[cmd_async] ( identifier[tgt] , identifier[fun] ,** identifier[kwargs] ) | def local(self, fun, tgt, **kwargs):
"""
Wrap LocalClient for running :ref:`execution modules <all-salt.modules>`
"""
self.client_cache['local'].cmd_async(tgt, fun, **kwargs) |
def import_i2c_addr(bus, opt="sensors"):
""" import_i2c_addresses will return a list of the
currently connected I2C devices.
This can be used a means to automatically detect
the number of connected sensor modules.
Modules are between int(112) and int(119)
By... | def function[import_i2c_addr, parameter[bus, opt]]:
constant[ import_i2c_addresses will return a list of the
currently connected I2C devices.
This can be used a means to automatically detect
the number of connected sensor modules.
Modules are between int(112) and int(119... | keyword[def] identifier[import_i2c_addr] ( identifier[bus] , identifier[opt] = literal[string] ):
literal[string]
identifier[i2c_list] =[]
keyword[for] identifier[device] keyword[in] identifier[range] ( literal[int] ):
keyword[try] :
identifier[bus] . identifier[read_by... | def import_i2c_addr(bus, opt='sensors'):
""" import_i2c_addresses will return a list of the
currently connected I2C devices.
This can be used a means to automatically detect
the number of connected sensor modules.
Modules are between int(112) and int(119)
By default... |
def create_remote_subnet(self, account_id, identifier, cidr):
"""Creates a remote subnet on the given account.
:param string account_id: The account identifier.
:param string identifier: The network identifier of the remote subnet.
:param string cidr: The CIDR value of the remote subnet... | def function[create_remote_subnet, parameter[self, account_id, identifier, cidr]]:
constant[Creates a remote subnet on the given account.
:param string account_id: The account identifier.
:param string identifier: The network identifier of the remote subnet.
:param string cidr: The CIDR... | keyword[def] identifier[create_remote_subnet] ( identifier[self] , identifier[account_id] , identifier[identifier] , identifier[cidr] ):
literal[string]
keyword[return] identifier[self] . identifier[remote_subnet] . identifier[createObject] ({
literal[string] : identifier[account_id] ,
... | def create_remote_subnet(self, account_id, identifier, cidr):
"""Creates a remote subnet on the given account.
:param string account_id: The account identifier.
:param string identifier: The network identifier of the remote subnet.
:param string cidr: The CIDR value of the remote subnet.
... |
def run(self, target, args=()):
""" Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function.
"""
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args ... | def function[run, parameter[self, target, args]]:
constant[ Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function.
]
variable[run_event] assign[=] call[name[threading].Event, parameter[]]
call[name[ru... | keyword[def] identifier[run] ( identifier[self] , identifier[target] , identifier[args] =()):
literal[string]
identifier[run_event] = identifier[threading] . identifier[Event] ()
identifier[run_event] . identifier[set] ()
identifier[thread] = identifier[threading] . identifier[Thr... | def run(self, target, args=()):
""" Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function.
"""
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args + (run_event,))
... |
def describe_target_health(target_group_arn, targets=None, client=None):
"""
Permission: elasticloadbalancing:DescribeTargetHealth
"""
kwargs = dict(TargetGroupArn=target_group_arn)
if targets:
kwargs.update(Targets=targets)
return client.describe_target_health(**kwargs)['TargetHealthDes... | def function[describe_target_health, parameter[target_group_arn, targets, client]]:
constant[
Permission: elasticloadbalancing:DescribeTargetHealth
]
variable[kwargs] assign[=] call[name[dict], parameter[]]
if name[targets] begin[:]
call[name[kwargs].update, parameter[]]
... | keyword[def] identifier[describe_target_health] ( identifier[target_group_arn] , identifier[targets] = keyword[None] , identifier[client] = keyword[None] ):
literal[string]
identifier[kwargs] = identifier[dict] ( identifier[TargetGroupArn] = identifier[target_group_arn] )
keyword[if] identifier[targe... | def describe_target_health(target_group_arn, targets=None, client=None):
"""
Permission: elasticloadbalancing:DescribeTargetHealth
"""
kwargs = dict(TargetGroupArn=target_group_arn)
if targets:
kwargs.update(Targets=targets) # depends on [control=['if'], data=[]]
return client.describe_... |
def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.topological_op_nodes():
name = node.name
if name not in op_dict:
op_dict[name] ... | def function[count_ops, parameter[self]]:
constant[Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
]
variable[op_dict] assign[=] dictionary[[], []]
for taget[name[node]] in starred[call[name[self].topological_op_nodes, parame... | keyword[def] identifier[count_ops] ( identifier[self] ):
literal[string]
identifier[op_dict] ={}
keyword[for] identifier[node] keyword[in] identifier[self] . identifier[topological_op_nodes] ():
identifier[name] = identifier[node] . identifier[name]
keyword[if... | def count_ops(self):
"""Count the occurrences of operation names.
Returns a dictionary of counts keyed on the operation name.
"""
op_dict = {}
for node in self.topological_op_nodes():
name = node.name
if name not in op_dict:
op_dict[name] = 1 # depends on [contr... |
def style_layout(style_less,
theme='grade3',
cursorwidth=2,
cursorcolor='default',
cellwidth='980',
lineheight=170,
margins='auto',
vimext=False,
toolbar=False,
nbname... | def function[style_layout, parameter[style_less, theme, cursorwidth, cursorcolor, cellwidth, lineheight, margins, vimext, toolbar, nbname, kernellogo, altprompt, altmd, altout, hideprompt]]:
constant[Set general layout and style properties of text and code cells]
with call[name[fileOpen], parameter[name... | keyword[def] identifier[style_layout] ( identifier[style_less] ,
identifier[theme] = literal[string] ,
identifier[cursorwidth] = literal[int] ,
identifier[cursorcolor] = literal[string] ,
identifier[cellwidth] = literal[string] ,
identifier[lineheight] = literal[int] ,
identifier[margins] = literal[string] ,
i... | def style_layout(style_less, theme='grade3', cursorwidth=2, cursorcolor='default', cellwidth='980', lineheight=170, margins='auto', vimext=False, toolbar=False, nbname=False, kernellogo=False, altprompt=False, altmd=False, altout=False, hideprompt=False):
"""Set general layout and style properties of text and code ... |
def resolve(self, pointer):
"""Resolve from documents.
:param pointer: foo
:type pointer: DocumentPointer
"""
dp = DocumentPointer(pointer)
obj, fetcher = self.prototype(dp)
for token in dp.pointer:
obj = token.extract(obj, bypass_ref=True)
... | def function[resolve, parameter[self, pointer]]:
constant[Resolve from documents.
:param pointer: foo
:type pointer: DocumentPointer
]
variable[dp] assign[=] call[name[DocumentPointer], parameter[name[pointer]]]
<ast.Tuple object at 0x7da2054a4490> assign[=] call[name[se... | keyword[def] identifier[resolve] ( identifier[self] , identifier[pointer] ):
literal[string]
identifier[dp] = identifier[DocumentPointer] ( identifier[pointer] )
identifier[obj] , identifier[fetcher] = identifier[self] . identifier[prototype] ( identifier[dp] )
keyword[for] ide... | def resolve(self, pointer):
"""Resolve from documents.
:param pointer: foo
:type pointer: DocumentPointer
"""
dp = DocumentPointer(pointer)
(obj, fetcher) = self.prototype(dp)
for token in dp.pointer:
obj = token.extract(obj, bypass_ref=True)
reference = ref(obj)... |
def hash_distance(left_hash, right_hash):
"""Compute the hamming distance between two hashes"""
if len(left_hash) != len(right_hash):
raise ValueError('Hamming distance requires two strings of equal length')
return sum(map(lambda x: 0 if x[0] == x[1] else 1, zip(left_hash, right_hash))) | def function[hash_distance, parameter[left_hash, right_hash]]:
constant[Compute the hamming distance between two hashes]
if compare[call[name[len], parameter[name[left_hash]]] not_equal[!=] call[name[len], parameter[name[right_hash]]]] begin[:]
<ast.Raise object at 0x7da1b03fab00>
return[cal... | keyword[def] identifier[hash_distance] ( identifier[left_hash] , identifier[right_hash] ):
literal[string]
keyword[if] identifier[len] ( identifier[left_hash] )!= identifier[len] ( identifier[right_hash] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifi... | def hash_distance(left_hash, right_hash):
"""Compute the hamming distance between two hashes"""
if len(left_hash) != len(right_hash):
raise ValueError('Hamming distance requires two strings of equal length') # depends on [control=['if'], data=[]]
return sum(map(lambda x: 0 if x[0] == x[1] else 1, z... |
def matching_number_line_and_regex(source_lines, generated_regexes, max_line_count=15):
"""
The first line and its number (starting with 0) in the source code that
indicated that the source code is generated.
:param source_lines: lines of text to scan
:param generated_regexes: regular expressions a ... | def function[matching_number_line_and_regex, parameter[source_lines, generated_regexes, max_line_count]]:
constant[
The first line and its number (starting with 0) in the source code that
indicated that the source code is generated.
:param source_lines: lines of text to scan
:param generated_reg... | keyword[def] identifier[matching_number_line_and_regex] ( identifier[source_lines] , identifier[generated_regexes] , identifier[max_line_count] = literal[int] ):
literal[string]
identifier[initial_numbers_and_lines] = identifier[enumerate] ( identifier[itertools] . identifier[islice] ( identifier[source_li... | def matching_number_line_and_regex(source_lines, generated_regexes, max_line_count=15):
"""
The first line and its number (starting with 0) in the source code that
indicated that the source code is generated.
:param source_lines: lines of text to scan
:param generated_regexes: regular expressions a ... |
def shutdown(cls):
"""Close all connections on in all pools"""
for pid in list(cls._pools.keys()):
cls._pools[pid].shutdown()
LOGGER.info('Shutdown complete, all pooled connections closed') | def function[shutdown, parameter[cls]]:
constant[Close all connections on in all pools]
for taget[name[pid]] in starred[call[name[list], parameter[call[name[cls]._pools.keys, parameter[]]]]] begin[:]
call[call[name[cls]._pools][name[pid]].shutdown, parameter[]]
call[name[LOGGER].... | keyword[def] identifier[shutdown] ( identifier[cls] ):
literal[string]
keyword[for] identifier[pid] keyword[in] identifier[list] ( identifier[cls] . identifier[_pools] . identifier[keys] ()):
identifier[cls] . identifier[_pools] [ identifier[pid] ]. identifier[shutdown] ()
... | def shutdown(cls):
"""Close all connections on in all pools"""
for pid in list(cls._pools.keys()):
cls._pools[pid].shutdown() # depends on [control=['for'], data=['pid']]
LOGGER.info('Shutdown complete, all pooled connections closed') |
def get_data_files_dir():
"""
Find directory with data_files (sys.prefix or local PmagPy/data_files)
and return the path.
"""
if 'data_files' in os.listdir(sys.prefix):
return os.path.join(sys.prefix, 'data_files')
else:
return os.path.join(get_pmag_dir(), 'data_files') | def function[get_data_files_dir, parameter[]]:
constant[
Find directory with data_files (sys.prefix or local PmagPy/data_files)
and return the path.
]
if compare[constant[data_files] in call[name[os].listdir, parameter[name[sys].prefix]]] begin[:]
return[call[name[os].path.join, para... | keyword[def] identifier[get_data_files_dir] ():
literal[string]
keyword[if] literal[string] keyword[in] identifier[os] . identifier[listdir] ( identifier[sys] . identifier[prefix] ):
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[sys] . identifier[prefix] , l... | def get_data_files_dir():
"""
Find directory with data_files (sys.prefix or local PmagPy/data_files)
and return the path.
"""
if 'data_files' in os.listdir(sys.prefix):
return os.path.join(sys.prefix, 'data_files') # depends on [control=['if'], data=[]]
else:
return os.path.join... |
def write(self, output_filepath):
"""
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
"""
with open(output_filepath, 'w') as out_fil... | def function[write, parameter[self, output_filepath]]:
constant[
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
]
with call[name[op... | keyword[def] identifier[write] ( identifier[self] , identifier[output_filepath] ):
literal[string]
keyword[with] identifier[open] ( identifier[output_filepath] , literal[string] ) keyword[as] identifier[out_file] :
identifier[out_file] . identifier[write] ( identifier[self] . identif... | def write(self, output_filepath):
"""
serialize the ExmaraldaFile instance and write it to a file.
Parameters
----------
output_filepath : str
relative or absolute path to the Exmaralda file to be created
"""
with open(output_filepath, 'w') as out_file:
... |
def double_typos(self):
"""letter combinations two typos away from word"""
return {e2 for e1 in self.typos()
for e2 in Word(e1).typos()} | def function[double_typos, parameter[self]]:
constant[letter combinations two typos away from word]
return[<ast.SetComp object at 0x7da20c992260>] | keyword[def] identifier[double_typos] ( identifier[self] ):
literal[string]
keyword[return] { identifier[e2] keyword[for] identifier[e1] keyword[in] identifier[self] . identifier[typos] ()
keyword[for] identifier[e2] keyword[in] identifier[Word] ( identifier[e1] ). identifier[typos]... | def double_typos(self):
"""letter combinations two typos away from word"""
return {e2 for e1 in self.typos() for e2 in Word(e1).typos()} |
def average_convergence_of_1_radius_in_units(self, unit_length='arcsec', kpc_per_arcsec=None):
"""The radius a critical curve forms for this mass profile, e.g. where the mean convergence is equal to 1.0.
In case of ellipitical mass profiles, the 'average' critical curve is used, whereby the convergenc... | def function[average_convergence_of_1_radius_in_units, parameter[self, unit_length, kpc_per_arcsec]]:
constant[The radius a critical curve forms for this mass profile, e.g. where the mean convergence is equal to 1.0.
In case of ellipitical mass profiles, the 'average' critical curve is used, whereby t... | keyword[def] identifier[average_convergence_of_1_radius_in_units] ( identifier[self] , identifier[unit_length] = literal[string] , identifier[kpc_per_arcsec] = keyword[None] ):
literal[string]
keyword[def] identifier[func] ( identifier[radius] ):
identifier[radius] = identifier[dim] ... | def average_convergence_of_1_radius_in_units(self, unit_length='arcsec', kpc_per_arcsec=None):
"""The radius a critical curve forms for this mass profile, e.g. where the mean convergence is equal to 1.0.
In case of ellipitical mass profiles, the 'average' critical curve is used, whereby the convergence is... |
def call(self, *values, **named_values):
"""
Call an expression to evaluate it at the given point.
Future improvements: I would like if func and signature could be buffered after the
first call so they don't have to be recalculated for every call. However, nothing
can be stored on self as sympy use... | def function[call, parameter[self]]:
constant[
Call an expression to evaluate it at the given point.
Future improvements: I would like if func and signature could be buffered after the
first call so they don't have to be recalculated for every call. However, nothing
can be stored on self as sym... | keyword[def] identifier[call] ( identifier[self] ,* identifier[values] ,** identifier[named_values] ):
literal[string]
identifier[independent_vars] , identifier[params] = identifier[seperate_symbols] ( identifier[self] )
identifier[func] = identifier[sympy_to_py] ( identifier[self] , identifier[i... | def call(self, *values, **named_values):
"""
Call an expression to evaluate it at the given point.
Future improvements: I would like if func and signature could be buffered after the
first call so they don't have to be recalculated for every call. However, nothing
can be stored on self as sympy use... |
def service(self):
""" Returns a Splunk service object for this command invocation or None.
The service object is created from the Splunkd URI and authentication
token passed to the command invocation in the search results info file.
This data is not passed to a command invocation by de... | def function[service, parameter[self]]:
constant[ Returns a Splunk service object for this command invocation or None.
The service object is created from the Splunkd URI and authentication
token passed to the command invocation in the search results info file.
This data is not passed to... | keyword[def] identifier[service] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_service] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_service]
identifier[info] = identifier[self] . identifier[s... | def service(self):
""" Returns a Splunk service object for this command invocation or None.
The service object is created from the Splunkd URI and authentication
token passed to the command invocation in the search results info file.
This data is not passed to a command invocation by defaul... |
def error(message, code='ERROR'):
"""Display Error.
Method prints the error message, message being given
as an input.
Arguments:
message {string} -- The message to be displayed.
"""
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
output = now + ' [' + torn.plugins.colors.FAIL + ... | def function[error, parameter[message, code]]:
constant[Display Error.
Method prints the error message, message being given
as an input.
Arguments:
message {string} -- The message to be displayed.
]
variable[now] assign[=] call[call[name[datetime].now, parameter[]].strftime, pa... | keyword[def] identifier[error] ( identifier[message] , identifier[code] = literal[string] ):
literal[string]
identifier[now] = identifier[datetime] . identifier[now] (). identifier[strftime] ( literal[string] )
identifier[output] = identifier[now] + literal[string] + identifier[torn] . identifier[plug... | def error(message, code='ERROR'):
"""Display Error.
Method prints the error message, message being given
as an input.
Arguments:
message {string} -- The message to be displayed.
"""
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
output = now + ' [' + torn.plugins.colors.FAIL + ... |
def make_slice_key(cls, start_string, size_string):
"""
Converts the given start and size query parts to a slice key.
:return: slice key
:rtype: slice
"""
try:
start = int(start_string)
except ValueError:
raise ValueError('Query parameter ... | def function[make_slice_key, parameter[cls, start_string, size_string]]:
constant[
Converts the given start and size query parts to a slice key.
:return: slice key
:rtype: slice
]
<ast.Try object at 0x7da2041daad0>
if compare[name[start] less[<] constant[0]] begin[:]... | keyword[def] identifier[make_slice_key] ( identifier[cls] , identifier[start_string] , identifier[size_string] ):
literal[string]
keyword[try] :
identifier[start] = identifier[int] ( identifier[start_string] )
keyword[except] identifier[ValueError] :
keyword[rais... | def make_slice_key(cls, start_string, size_string):
"""
Converts the given start and size query parts to a slice key.
:return: slice key
:rtype: slice
"""
try:
start = int(start_string) # depends on [control=['try'], data=[]]
except ValueError:
raise ValueEr... |
def mtf_slice(x, begin, size, slice_dim_name, name=None):
"""Slice operation.
Call externally as mtf.slice()
Args:
x: a list of Tensors
begin: integer, where to begin slicing from along the axis
size: integer, size to slice from axis.
slice_dim_name: string, dimension name of slicing axis.
n... | def function[mtf_slice, parameter[x, begin, size, slice_dim_name, name]]:
constant[Slice operation.
Call externally as mtf.slice()
Args:
x: a list of Tensors
begin: integer, where to begin slicing from along the axis
size: integer, size to slice from axis.
slice_dim_name: string, dimension... | keyword[def] identifier[mtf_slice] ( identifier[x] , identifier[begin] , identifier[size] , identifier[slice_dim_name] , identifier[name] = keyword[None] ):
literal[string]
keyword[return] identifier[SliceOperation] (
identifier[x] , identifier[begin] , identifier[size] , identifier[slice_dim_name] , ident... | def mtf_slice(x, begin, size, slice_dim_name, name=None):
"""Slice operation.
Call externally as mtf.slice()
Args:
x: a list of Tensors
begin: integer, where to begin slicing from along the axis
size: integer, size to slice from axis.
slice_dim_name: string, dimension name of slicing axis.
... |
def editors(self):
"""Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead."""
result = set()
for role in self._EDITOR_ROLES:
for member in self._bindings.get(role, ()):
result.add(member)
return frozenset(result) | def function[editors, parameter[self]]:
constant[Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead.]
variable[result] assign[=] call[name[set], parameter[]]
for taget[name[role]] in starred[name[self]._EDITOR_ROLES] begin[:]
for taget[nam... | keyword[def] identifier[editors] ( identifier[self] ):
literal[string]
identifier[result] = identifier[set] ()
keyword[for] identifier[role] keyword[in] identifier[self] . identifier[_EDITOR_ROLES] :
keyword[for] identifier[member] keyword[in] identifier[self] . identifi... | def editors(self):
"""Legacy access to editor role.
DEPRECATED: use ``policy["roles/editors"]`` instead."""
result = set()
for role in self._EDITOR_ROLES:
for member in self._bindings.get(role, ()):
result.add(member) # depends on [control=['for'], data=['member']] # depends ... |
def OnRightClickListctrl(self, event):
"""
Edits the logger and the Zeq_GUI parent object so that the selected interpretation is now marked as bad
@param: event -> wx.ListCtrlEvent that triggered this function
"""
i = event.GetIndex()
fit,spec = self.fit_list[i][0],self.f... | def function[OnRightClickListctrl, parameter[self, event]]:
constant[
Edits the logger and the Zeq_GUI parent object so that the selected interpretation is now marked as bad
@param: event -> wx.ListCtrlEvent that triggered this function
]
variable[i] assign[=] call[name[event].Ge... | keyword[def] identifier[OnRightClickListctrl] ( identifier[self] , identifier[event] ):
literal[string]
identifier[i] = identifier[event] . identifier[GetIndex] ()
identifier[fit] , identifier[spec] = identifier[self] . identifier[fit_list] [ identifier[i] ][ literal[int] ], identifier[sel... | def OnRightClickListctrl(self, event):
"""
Edits the logger and the Zeq_GUI parent object so that the selected interpretation is now marked as bad
@param: event -> wx.ListCtrlEvent that triggered this function
"""
i = event.GetIndex()
(fit, spec) = (self.fit_list[i][0], self.fit_list... |
def record_manifest(self):
"""
Called after a deployment to record any data necessary to detect changes
for a future deployment.
"""
manifest = super(TarballSatchel, self).record_manifest()
manifest['timestamp'] = self.timestamp
return manifest | def function[record_manifest, parameter[self]]:
constant[
Called after a deployment to record any data necessary to detect changes
for a future deployment.
]
variable[manifest] assign[=] call[call[name[super], parameter[name[TarballSatchel], name[self]]].record_manifest, paramete... | keyword[def] identifier[record_manifest] ( identifier[self] ):
literal[string]
identifier[manifest] = identifier[super] ( identifier[TarballSatchel] , identifier[self] ). identifier[record_manifest] ()
identifier[manifest] [ literal[string] ]= identifier[self] . identifier[timestamp]
... | def record_manifest(self):
"""
Called after a deployment to record any data necessary to detect changes
for a future deployment.
"""
manifest = super(TarballSatchel, self).record_manifest()
manifest['timestamp'] = self.timestamp
return manifest |
def density_matrix(self):
"""Returns the density matrix at this step in the simulation.
The density matrix that is stored in this result is returned in the
computational basis with these basis states defined by the qubit_map.
In particular the value in the qubit_map is the index of the ... | def function[density_matrix, parameter[self]]:
constant[Returns the density matrix at this step in the simulation.
The density matrix that is stored in this result is returned in the
computational basis with these basis states defined by the qubit_map.
In particular the value in the qub... | keyword[def] identifier[density_matrix] ( identifier[self] ):
literal[string]
identifier[size] = literal[int] ** identifier[len] ( identifier[self] . identifier[_qubit_map] )
keyword[return] identifier[np] . identifier[reshape] ( identifier[self] . identifier[_density_matrix] ,( identifie... | def density_matrix(self):
"""Returns the density matrix at this step in the simulation.
The density matrix that is stored in this result is returned in the
computational basis with these basis states defined by the qubit_map.
In particular the value in the qubit_map is the index of the qubi... |
def override (overrider_id, overridee_id):
"""Make generator 'overrider-id' be preferred to
'overridee-id'. If, when searching for generators
that could produce a target of certain type,
both those generators are amoung viable generators,
the overridden generator is immediately discarded.
The o... | def function[override, parameter[overrider_id, overridee_id]]:
constant[Make generator 'overrider-id' be preferred to
'overridee-id'. If, when searching for generators
that could produce a target of certain type,
both those generators are amoung viable generators,
the overridden generator is imm... | keyword[def] identifier[override] ( identifier[overrider_id] , identifier[overridee_id] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[overrider_id] , identifier[basestring] )
keyword[assert] identifier[isinstance] ( identifier[overridee_id] , identifier[basestring] )
i... | def override(overrider_id, overridee_id):
"""Make generator 'overrider-id' be preferred to
'overridee-id'. If, when searching for generators
that could produce a target of certain type,
both those generators are amoung viable generators,
the overridden generator is immediately discarded.
The ov... |
def check_garden_requirements(self):
'''Ensure required garden packages are available to be included.
'''
garden_requirements = self.config.getlist('app',
'garden_requirements', '')
# have we installed the garden packages?
if exists(self.gardenlibs_dir) and \
... | def function[check_garden_requirements, parameter[self]]:
constant[Ensure required garden packages are available to be included.
]
variable[garden_requirements] assign[=] call[name[self].config.getlist, parameter[constant[app], constant[garden_requirements], constant[]]]
if <ast.BoolOp o... | keyword[def] identifier[check_garden_requirements] ( identifier[self] ):
literal[string]
identifier[garden_requirements] = identifier[self] . identifier[config] . identifier[getlist] ( literal[string] ,
literal[string] , literal[string] )
keyword[if] identifier[exists] ... | def check_garden_requirements(self):
"""Ensure required garden packages are available to be included.
"""
garden_requirements = self.config.getlist('app', 'garden_requirements', '')
# have we installed the garden packages?
if exists(self.gardenlibs_dir) and self.state.get('cache.gardenlibs', '')... |
def _call(self, x):
"""Return wavelet transform of ``x``."""
if self.impl == 'pywt':
coeffs = pywt.wavedecn(
x, wavelet=self.pywt_wavelet, level=self.nlevels,
mode=self.pywt_pad_mode, axes=self.axes)
return pywt.ravel_coeffs(coeffs, axes=self.axes)... | def function[_call, parameter[self, x]]:
constant[Return wavelet transform of ``x``.]
if compare[name[self].impl equal[==] constant[pywt]] begin[:]
variable[coeffs] assign[=] call[name[pywt].wavedecn, parameter[name[x]]]
return[call[call[name[pywt].ravel_coeffs, parameter[name[co... | keyword[def] identifier[_call] ( identifier[self] , identifier[x] ):
literal[string]
keyword[if] identifier[self] . identifier[impl] == literal[string] :
identifier[coeffs] = identifier[pywt] . identifier[wavedecn] (
identifier[x] , identifier[wavelet] = identifier[self] ... | def _call(self, x):
"""Return wavelet transform of ``x``."""
if self.impl == 'pywt':
coeffs = pywt.wavedecn(x, wavelet=self.pywt_wavelet, level=self.nlevels, mode=self.pywt_pad_mode, axes=self.axes)
return pywt.ravel_coeffs(coeffs, axes=self.axes)[0] # depends on [control=['if'], data=[]]
e... |
def from_web(network_id: int, host: Optional[str] = None) -> BELGraph:
"""Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Com... | def function[from_web, parameter[network_id, host]]:
constant[Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Commons ser... | keyword[def] identifier[from_web] ( identifier[network_id] : identifier[int] , identifier[host] : identifier[Optional] [ identifier[str] ]= keyword[None] )-> identifier[BELGraph] :
literal[string]
keyword[if] identifier[host] keyword[is] keyword[None] :
identifier[host] = identifier[_get_host] ... | def from_web(network_id: int, host: Optional[str]=None) -> BELGraph:
"""Retrieve a public network from BEL Commons.
In the future, this function may be extended to support authentication.
:param int network_id: The BEL Commons network identifier
:param Optional[str] host: The location of the BEL Commo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.