code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def delete_channel(self, chname):
"""Delete a given channel from viewer."""
name = chname.lower()
if len(self.channel_names) < 1:
self.logger.error('Delete channel={0} failed. '
'No channels left.'.format(chname))
return
with self.l... | def function[delete_channel, parameter[self, chname]]:
constant[Delete a given channel from viewer.]
variable[name] assign[=] call[name[chname].lower, parameter[]]
if compare[call[name[len], parameter[name[self].channel_names]] less[<] constant[1]] begin[:]
call[name[self].logger... | keyword[def] identifier[delete_channel] ( identifier[self] , identifier[chname] ):
literal[string]
identifier[name] = identifier[chname] . identifier[lower] ()
keyword[if] identifier[len] ( identifier[self] . identifier[channel_names] )< literal[int] :
identifier[self] . ide... | def delete_channel(self, chname):
"""Delete a given channel from viewer."""
name = chname.lower()
if len(self.channel_names) < 1:
self.logger.error('Delete channel={0} failed. No channels left.'.format(chname))
return # depends on [control=['if'], data=[]]
with self.lock:
channe... |
def get_gid(path, follow_symlinks=True):
'''
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd... | def function[get_gid, parameter[path, follow_symlinks]]:
constant[
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*... | keyword[def] identifier[get_gid] ( identifier[path] , identifier[follow_symlinks] = keyword[True] ):
literal[string]
keyword[return] identifier[stats] ( identifier[os] . identifier[path] . identifier[expanduser] ( identifier[path] ), identifier[follow_symlinks] = identifier[follow_symlinks] ). identifier[... | def get_gid(path, follow_symlinks=True):
"""
Return the id of the group that owns a given file
path
file or directory of which to get the gid
follow_symlinks
indicated if symlinks should be followed
CLI Example:
.. code-block:: bash
salt '*' file.get_gid /etc/passwd... |
def list_databases(self):
"""
Runs the ``\\list`` command and returns a list of column values with
information about all databases.
"""
lines = output_lines(self.exec_psql('\\list'))
return [line.split('|') for line in lines] | def function[list_databases, parameter[self]]:
constant[
Runs the ``\list`` command and returns a list of column values with
information about all databases.
]
variable[lines] assign[=] call[name[output_lines], parameter[call[name[self].exec_psql, parameter[constant[\list]]]]]
... | keyword[def] identifier[list_databases] ( identifier[self] ):
literal[string]
identifier[lines] = identifier[output_lines] ( identifier[self] . identifier[exec_psql] ( literal[string] ))
keyword[return] [ identifier[line] . identifier[split] ( literal[string] ) keyword[for] identifier[lin... | def list_databases(self):
"""
Runs the ``\\list`` command and returns a list of column values with
information about all databases.
"""
lines = output_lines(self.exec_psql('\\list'))
return [line.split('|') for line in lines] |
def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Linear.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras... | def function[convert_gemm, parameter[params, w_name, scope_name, inputs, layers, weights, names]]:
constant[
Convert Linear.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
... | keyword[def] identifier[convert_gemm] ( identifier[params] , identifier[w_name] , identifier[scope_name] , identifier[inputs] , identifier[layers] , identifier[weights] , identifier[names] ):
literal[string]
identifier[print] ( literal[string] )
keyword[if] identifier[names] == literal[string] :
... | def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Linear.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras... |
def prepare_request(self, kwargs):
""" If session is in use, prepares the request headers and
checks if the session is expired.
"""
if self.session_id is not None:
actual = dt.datetime.now()
if (self.last_activity + self.inactivity_limit) < actual:
... | def function[prepare_request, parameter[self, kwargs]]:
constant[ If session is in use, prepares the request headers and
checks if the session is expired.
]
if compare[name[self].session_id is_not constant[None]] begin[:]
variable[actual] assign[=] call[name[dt].datetime... | keyword[def] identifier[prepare_request] ( identifier[self] , identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[session_id] keyword[is] keyword[not] keyword[None] :
identifier[actual] = identifier[dt] . identifier[datetime] . identifier[now] ()
... | def prepare_request(self, kwargs):
""" If session is in use, prepares the request headers and
checks if the session is expired.
"""
if self.session_id is not None:
actual = dt.datetime.now()
if self.last_activity + self.inactivity_limit < actual:
# session expired
... |
def p_localparamdecl_signed_width(self, p):
'localparamdecl : LOCALPARAM SIGNED width param_substitution_list SEMICOLON'
paramlist = [Localparam(rname, rvalue, p[3], signed=True, lineno=p.lineno(3))
for rname, rvalue in p[4]]
p[0] = Decl(tuple(paramlist), lineno=p.lineno(1))... | def function[p_localparamdecl_signed_width, parameter[self, p]]:
constant[localparamdecl : LOCALPARAM SIGNED width param_substitution_list SEMICOLON]
variable[paramlist] assign[=] <ast.ListComp object at 0x7da1b1603910>
call[name[p]][constant[0]] assign[=] call[name[Decl], parameter[call[name[tu... | keyword[def] identifier[p_localparamdecl_signed_width] ( identifier[self] , identifier[p] ):
literal[string]
identifier[paramlist] =[ identifier[Localparam] ( identifier[rname] , identifier[rvalue] , identifier[p] [ literal[int] ], identifier[signed] = keyword[True] , identifier[lineno] = identifie... | def p_localparamdecl_signed_width(self, p):
"""localparamdecl : LOCALPARAM SIGNED width param_substitution_list SEMICOLON"""
paramlist = [Localparam(rname, rvalue, p[3], signed=True, lineno=p.lineno(3)) for (rname, rvalue) in p[4]]
p[0] = Decl(tuple(paramlist), lineno=p.lineno(1))
p.set_lineno(0, p.line... |
def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202
"""Add a ``summarize`` command to main :mod:`click` function."""
@main.command()
@click.pass_obj
def summarize(manager: AbstractManager):
"""Summarize the contents of the database."""
if not manager.is_populated():
... | def function[add_cli_summarize, parameter[main]]:
constant[Add a ``summarize`` command to main :mod:`click` function.]
def function[summarize, parameter[manager]]:
constant[Summarize the contents of the database.]
if <ast.UnaryOp object at 0x7da1b00fbc70> begin[:]
... | keyword[def] identifier[add_cli_summarize] ( identifier[main] : identifier[click] . identifier[Group] )-> identifier[click] . identifier[Group] :
literal[string]
@ identifier[main] . identifier[command] ()
@ identifier[click] . identifier[pass_obj]
keyword[def] identifier[summarize] ( identifier... | def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202
'Add a ``summarize`` command to main :mod:`click` function.'
@main.command()
@click.pass_obj
def summarize(manager: AbstractManager):
"""Summarize the contents of the database."""
if not manager.is_populated():
... |
def add(self, *items):
"""
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
"""
for item in items:
self.unsorted.append(item)
key = item[0]
self.i... | def function[add, parameter[self]]:
constant[
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
]
for taget[name[item]] in starred[name[items]] begin[:]
call[name[self... | keyword[def] identifier[add] ( identifier[self] ,* identifier[items] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[items] :
identifier[self] . identifier[unsorted] . identifier[append] ( identifier[item] )
identifier[key] = identifier[item] [ l... | def add(self, *items):
"""
Add items to be sorted.
@param items: One or more items to be added.
@type items: I{item}
@return: self
@rtype: L{DepList}
"""
for item in items:
self.unsorted.append(item)
key = item[0]
self.index[key] = item # ... |
def triangular_membership(bin_center, bin_width, smoothness = 0.5):
r"""
Create a triangular membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width : number
The wid... | def function[triangular_membership, parameter[bin_center, bin_width, smoothness]]:
constant[
Create a triangular membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width ... | keyword[def] identifier[triangular_membership] ( identifier[bin_center] , identifier[bin_width] , identifier[smoothness] = literal[int] ):
literal[string]
keyword[if] identifier[smoothness] > literal[int] : keyword[raise] identifier[AttributeError] ( literal[string] )
keyword[if] identifier[smoothn... | def triangular_membership(bin_center, bin_width, smoothness=0.5):
"""
Create a triangular membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width : number
The width ... |
def post(self, request, bot_id, id, format=None):
"""
Add a new kik recipient to a handler
---
serializer: KikRecipientSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
... | def function[post, parameter[self, request, bot_id, id, format]]:
constant[
Add a new kik recipient to a handler
---
serializer: KikRecipientSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message... | keyword[def] identifier[post] ( identifier[self] , identifier[request] , identifier[bot_id] , identifier[id] , identifier[format] = keyword[None] ):
literal[string]
keyword[return] identifier[super] ( identifier[KikRecipientList] , identifier[self] ). identifier[post] ( identifier[request] , ident... | def post(self, request, bot_id, id, format=None):
"""
Add a new kik recipient to a handler
---
serializer: KikRecipientSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
... |
def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
PluginBase.get_arguments(self)
if self.args.organizationName is not None:
self.organizationName = self.args.organizationName
if self.args.repositoryName is not None:
self.... | def function[get_arguments, parameter[self]]:
constant[
Extracts the specific arguments of this CLI
]
call[name[PluginBase].get_arguments, parameter[name[self]]]
if compare[name[self].args.organizationName is_not constant[None]] begin[:]
name[self].organizationNam... | keyword[def] identifier[get_arguments] ( identifier[self] ):
literal[string]
identifier[PluginBase] . identifier[get_arguments] ( identifier[self] )
keyword[if] identifier[self] . identifier[args] . identifier[organizationName] keyword[is] keyword[not] keyword[None] :
iden... | def get_arguments(self):
"""
Extracts the specific arguments of this CLI
"""
PluginBase.get_arguments(self)
if self.args.organizationName is not None:
self.organizationName = self.args.organizationName # depends on [control=['if'], data=[]]
if self.args.repositoryName is not Non... |
def simplify_list(maybe_list):
"""Turn a length one list loaded by cwltool into a scalar.
Anything else is passed as-is, by reference."""
if isinstance(maybe_list, MutableSequence):
is_list = aslist(maybe_list)
if len(is_list) == 1:
return is_list[0]
return maybe_list | def function[simplify_list, parameter[maybe_list]]:
constant[Turn a length one list loaded by cwltool into a scalar.
Anything else is passed as-is, by reference.]
if call[name[isinstance], parameter[name[maybe_list], name[MutableSequence]]] begin[:]
variable[is_list] assign[=] call[n... | keyword[def] identifier[simplify_list] ( identifier[maybe_list] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[maybe_list] , identifier[MutableSequence] ):
identifier[is_list] = identifier[aslist] ( identifier[maybe_list] )
keyword[if] identifier[len] ( identifier[is... | def simplify_list(maybe_list):
"""Turn a length one list loaded by cwltool into a scalar.
Anything else is passed as-is, by reference."""
if isinstance(maybe_list, MutableSequence):
is_list = aslist(maybe_list)
if len(is_list) == 1:
return is_list[0] # depends on [control=['if']... |
def iter_prefixes(path):
"""
Iterate through all (non-empty) prefixes of a dotted path.
Example:
>>> list(iter_prefixes('foo.bar.baz'))
['foo', 'foo.bar', 'foo.bar.baz']
"""
split_path = path.split('.')
for i in range(1, len(split_path) + 1):
yield join_paths(*split_path[:i]) | def function[iter_prefixes, parameter[path]]:
constant[
Iterate through all (non-empty) prefixes of a dotted path.
Example:
>>> list(iter_prefixes('foo.bar.baz'))
['foo', 'foo.bar', 'foo.bar.baz']
]
variable[split_path] assign[=] call[name[path].split, parameter[constant[.]]]
... | keyword[def] identifier[iter_prefixes] ( identifier[path] ):
literal[string]
identifier[split_path] = identifier[path] . identifier[split] ( literal[string] )
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , identifier[len] ( identifier[split_path] )+ literal[int] ):
... | def iter_prefixes(path):
"""
Iterate through all (non-empty) prefixes of a dotted path.
Example:
>>> list(iter_prefixes('foo.bar.baz'))
['foo', 'foo.bar', 'foo.bar.baz']
"""
split_path = path.split('.')
for i in range(1, len(split_path) + 1):
yield join_paths(*split_path[:i]) #... |
def _set_redist_connected(self, v, load=False):
"""
Setter method for redist_connected, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_connected (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redist_connected is consider... | def function[_set_redist_connected, parameter[self, v, load]]:
constant[
Setter method for redist_connected, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_connected (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_red... | keyword[def] identifier[_set_redist_connected] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_redist_connected(self, v, load=False):
"""
Setter method for redist_connected, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_connected (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redist_connected is consider... |
def img2img_transformer2d_base():
"""Base params for img2img 2d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = "n"
hparams.layer_postprocess_sequence = "da"
# This version seems to benefit from a higher learning rate.
hparams.learning_rate =... | def function[img2img_transformer2d_base, parameter[]]:
constant[Base params for img2img 2d attention.]
variable[hparams] assign[=] call[name[image_transformer2d_base], parameter[]]
name[hparams].layer_preprocess_sequence assign[=] constant[n]
name[hparams].layer_postprocess_sequence assi... | keyword[def] identifier[img2img_transformer2d_base] ():
literal[string]
identifier[hparams] = identifier[image_transformer2d_base] ()
identifier[hparams] . identifier[layer_preprocess_sequence] = literal[string]
identifier[hparams] . identifier[layer_postprocess_sequence] = literal[string]
ide... | def img2img_transformer2d_base():
"""Base params for img2img 2d attention."""
hparams = image_transformer2d_base()
# learning related flags
hparams.layer_preprocess_sequence = 'n'
hparams.layer_postprocess_sequence = 'da'
# This version seems to benefit from a higher learning rate.
hparams.l... |
def p_importPart(self, p):
"""importPart : imports
| empty"""
# libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1!
if p[1]:
importDict = {}
for imp in p[1]: # don't do just dict() because moduleNames may be repeated
fromModule, symbol... | def function[p_importPart, parameter[self, p]]:
constant[importPart : imports
| empty]
if call[name[p]][constant[1]] begin[:]
variable[importDict] assign[=] dictionary[[], []]
for taget[name[imp]] in starred[call[name[p]][constant[1]]] begin[:]
... | keyword[def] identifier[p_importPart] ( identifier[self] , identifier[p] ):
literal[string]
keyword[if] identifier[p] [ literal[int] ]:
identifier[importDict] ={}
keyword[for] identifier[imp] keyword[in] identifier[p] [ literal[int] ]:
identif... | def p_importPart(self, p):
"""importPart : imports
| empty"""
# libsmi: TODO: ``IMPORTS ;'' allowed? refer ASN.1!
if p[1]:
importDict = {}
for imp in p[1]: # don't do just dict() because moduleNames may be repeated
(fromModule, symbols) = imp
if... |
def _decompose_tree(ttree, orient='right', use_edge_lengths=True):
""" decomposes tree into component parts for plotting """
## set attributes
ttree._orient = orient
ttree._use_edge_lengths = use_edge_lengths
ult = use_edge_lengths == False
## map numeric values to internal nodes from root to... | def function[_decompose_tree, parameter[ttree, orient, use_edge_lengths]]:
constant[ decomposes tree into component parts for plotting ]
name[ttree]._orient assign[=] name[orient]
name[ttree]._use_edge_lengths assign[=] name[use_edge_lengths]
variable[ult] assign[=] compare[name[use_edge... | keyword[def] identifier[_decompose_tree] ( identifier[ttree] , identifier[orient] = literal[string] , identifier[use_edge_lengths] = keyword[True] ):
literal[string]
identifier[ttree] . identifier[_orient] = identifier[orient]
identifier[ttree] . identifier[_use_edge_lengths] = identifier[use_e... | def _decompose_tree(ttree, orient='right', use_edge_lengths=True):
""" decomposes tree into component parts for plotting """
## set attributes
ttree._orient = orient
ttree._use_edge_lengths = use_edge_lengths
ult = use_edge_lengths == False
## map numeric values to internal nodes from root to ti... |
def handle_func(self, multiprocessing_enabled, func, data):
'''
Execute this method in a multiprocess or thread
'''
if salt.utils.platform.is_windows() \
or self.opts.get('transport') == 'zeromq':
# Since function references can't be pickled and pickling
... | def function[handle_func, parameter[self, multiprocessing_enabled, func, data]]:
constant[
Execute this method in a multiprocess or thread
]
if <ast.BoolOp object at 0x7da1b1f8f1f0> begin[:]
if compare[call[name[self].opts][constant[__role]] equal[==] constant[master]] be... | keyword[def] identifier[handle_func] ( identifier[self] , identifier[multiprocessing_enabled] , identifier[func] , identifier[data] ):
literal[string]
keyword[if] identifier[salt] . identifier[utils] . identifier[platform] . identifier[is_windows] () keyword[or] identifier[self] . identifier[opts... | def handle_func(self, multiprocessing_enabled, func, data):
"""
Execute this method in a multiprocess or thread
"""
if salt.utils.platform.is_windows() or self.opts.get('transport') == 'zeromq':
# Since function references can't be pickled and pickling
# is required when spawning... |
def visit_field_class(self, item, descriptor=None, fields=None):
"""Visit a class node containing a list of field definitions."""
discovered_fields = collections.OrderedDict()
field_groups = {}
for node in item.body:
if isinstance(node, ast.ClassDef):
field_gr... | def function[visit_field_class, parameter[self, item, descriptor, fields]]:
constant[Visit a class node containing a list of field definitions.]
variable[discovered_fields] assign[=] call[name[collections].OrderedDict, parameter[]]
variable[field_groups] assign[=] dictionary[[], []]
for ... | keyword[def] identifier[visit_field_class] ( identifier[self] , identifier[item] , identifier[descriptor] = keyword[None] , identifier[fields] = keyword[None] ):
literal[string]
identifier[discovered_fields] = identifier[collections] . identifier[OrderedDict] ()
identifier[field_groups] ={... | def visit_field_class(self, item, descriptor=None, fields=None):
"""Visit a class node containing a list of field definitions."""
discovered_fields = collections.OrderedDict()
field_groups = {}
for node in item.body:
if isinstance(node, ast.ClassDef):
field_groups[node.name] = self.v... |
def guess_archive_type(name):
'''
Guess an archive type (tar, zip, or rar) by its file extension
'''
name = name.lower()
for ending in ('tar', 'tar.gz', 'tgz',
'tar.bz2', 'tbz2', 'tbz',
'tar.xz', 'txz',
'tar.lzma', 'tlz'):
if name.ends... | def function[guess_archive_type, parameter[name]]:
constant[
Guess an archive type (tar, zip, or rar) by its file extension
]
variable[name] assign[=] call[name[name].lower, parameter[]]
for taget[name[ending]] in starred[tuple[[<ast.Constant object at 0x7da1b1c36380>, <ast.Constant obje... | keyword[def] identifier[guess_archive_type] ( identifier[name] ):
literal[string]
identifier[name] = identifier[name] . identifier[lower] ()
keyword[for] identifier[ending] keyword[in] ( literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] ,
... | def guess_archive_type(name):
"""
Guess an archive type (tar, zip, or rar) by its file extension
"""
name = name.lower()
for ending in ('tar', 'tar.gz', 'tgz', 'tar.bz2', 'tbz2', 'tbz', 'tar.xz', 'txz', 'tar.lzma', 'tlz'):
if name.endswith('.' + ending):
return 'tar' # depends o... |
def overflow(self, overflow):
"""
Update the overflow algorithm of successive INCRBY operations
:param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
Redis docs for descriptions of these algorithmsself.
:returns: a :py:class:`BitFieldOperation` instance.
... | def function[overflow, parameter[self, overflow]]:
constant[
Update the overflow algorithm of successive INCRBY operations
:param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
Redis docs for descriptions of these algorithmsself.
:returns: a :py:class:`BitField... | keyword[def] identifier[overflow] ( identifier[self] , identifier[overflow] ):
literal[string]
identifier[overflow] = identifier[overflow] . identifier[upper] ()
keyword[if] identifier[overflow] != identifier[self] . identifier[_last_overflow] :
identifier[self] . identifier[... | def overflow(self, overflow):
"""
Update the overflow algorithm of successive INCRBY operations
:param overflow: Overflow algorithm, one of WRAP, SAT, FAIL. See the
Redis docs for descriptions of these algorithmsself.
:returns: a :py:class:`BitFieldOperation` instance.
""... |
def calibrate_plunger(
self,
top=None,
bottom=None,
blow_out=None,
drop_tip=None):
"""Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
... | def function[calibrate_plunger, parameter[self, top, bottom, blow_out, drop_tip]]:
constant[Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
... | keyword[def] identifier[calibrate_plunger] (
identifier[self] ,
identifier[top] = keyword[None] ,
identifier[bottom] = keyword[None] ,
identifier[blow_out] = keyword[None] ,
identifier[drop_tip] = keyword[None] ):
literal[string]
keyword[if] identifier[top] keyword[is] keyword[not] keyword... | def calibrate_plunger(self, top=None, bottom=None, blow_out=None, drop_tip=None):
"""Set calibration values for the pipette plunger.
This can be called multiple times as the user sets each value,
or you can set them all at once.
Parameters
----------
top : int
T... |
def run_script(self, script_name, script_args=None, node_paths=None):
"""Returns a command to execute a package.json script.
:param script_name: Name of the script to name. Note that script name 'test'
can be used to run node tests.
:param script_args: Args to be passed to package.json script.
:... | def function[run_script, parameter[self, script_name, script_args, node_paths]]:
constant[Returns a command to execute a package.json script.
:param script_name: Name of the script to name. Note that script name 'test'
can be used to run node tests.
:param script_args: Args to be passed to packa... | keyword[def] identifier[run_script] ( identifier[self] , identifier[script_name] , identifier[script_args] = keyword[None] , identifier[node_paths] = keyword[None] ):
literal[string]
identifier[package_manager_args] = identifier[self] . identifier[_get_run_script_args] ()
identifier[package_manag... | def run_script(self, script_name, script_args=None, node_paths=None):
"""Returns a command to execute a package.json script.
:param script_name: Name of the script to name. Note that script name 'test'
can be used to run node tests.
:param script_args: Args to be passed to package.json script.
:... |
def current_line(self):
'''Get the text of the current source line as a string, with a trailing
newline character'''
if self.is_optimized_out():
return '(frame information optimized out)'
with open(self.filename(), 'r') as f:
all_lines = f.readlines()
... | def function[current_line, parameter[self]]:
constant[Get the text of the current source line as a string, with a trailing
newline character]
if call[name[self].is_optimized_out, parameter[]] begin[:]
return[constant[(frame information optimized out)]]
with call[name[open], param... | keyword[def] identifier[current_line] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_optimized_out] ():
keyword[return] literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[filename] (), literal[string] ) keywor... | def current_line(self):
"""Get the text of the current source line as a string, with a trailing
newline character"""
if self.is_optimized_out():
return '(frame information optimized out)' # depends on [control=['if'], data=[]]
with open(self.filename(), 'r') as f:
all_lines = f.read... |
def _send_scp(self, cabinet, frame, board, *args, **kwargs):
"""Determine the best connection to use to send an SCP packet and use
it to transmit.
See the arguments for
:py:meth:`~rig.machine_control.scp_connection.SCPConnection` for
details.
"""
# Find the conne... | def function[_send_scp, parameter[self, cabinet, frame, board]]:
constant[Determine the best connection to use to send an SCP packet and use
it to transmit.
See the arguments for
:py:meth:`~rig.machine_control.scp_connection.SCPConnection` for
details.
]
variable... | keyword[def] identifier[_send_scp] ( identifier[self] , identifier[cabinet] , identifier[frame] , identifier[board] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[connection] = identifier[self] . identifier[connections] . identifier[get] (( identifier[cab... | def _send_scp(self, cabinet, frame, board, *args, **kwargs):
"""Determine the best connection to use to send an SCP packet and use
it to transmit.
See the arguments for
:py:meth:`~rig.machine_control.scp_connection.SCPConnection` for
details.
"""
# Find the connection wh... |
def print_row_failures(failing_items, verbose=False, outfile_name=None):
"""
Take output from get_row_failures (DataFrame), and output it to
stdout, an outfile, or both.
"""
if outfile_name:
outfile = open(outfile_name, "w")
outfile.write("\t".join(["name", "row_number", "problem_typ... | def function[print_row_failures, parameter[failing_items, verbose, outfile_name]]:
constant[
Take output from get_row_failures (DataFrame), and output it to
stdout, an outfile, or both.
]
if name[outfile_name] begin[:]
variable[outfile] assign[=] call[name[open], parameter[na... | keyword[def] identifier[print_row_failures] ( identifier[failing_items] , identifier[verbose] = keyword[False] , identifier[outfile_name] = keyword[None] ):
literal[string]
keyword[if] identifier[outfile_name] :
identifier[outfile] = identifier[open] ( identifier[outfile_name] , literal[string] )... | def print_row_failures(failing_items, verbose=False, outfile_name=None):
"""
Take output from get_row_failures (DataFrame), and output it to
stdout, an outfile, or both.
"""
if outfile_name:
outfile = open(outfile_name, 'w')
outfile.write('\t'.join(['name', 'row_number', 'problem_typ... |
def _is_twave(self, peak_num):
"""
Check whether a segment is a t-wave. Compare the maximum gradient of
the filtered signal segment with that of the previous qrs segment.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is ... | def function[_is_twave, parameter[self, peak_num]]:
constant[
Check whether a segment is a t-wave. Compare the maximum gradient of
the filtered signal segment with that of the previous qrs segment.
Parameters
----------
peak_num : int
The peak number of the m... | keyword[def] identifier[_is_twave] ( identifier[self] , identifier[peak_num] ):
literal[string]
identifier[i] = identifier[self] . identifier[peak_inds_i] [ identifier[peak_num] ]
keyword[if] identifier[self] . identifier[last_qrs_ind] - identifier[self] . identifier[qr... | def _is_twave(self, peak_num):
"""
Check whether a segment is a t-wave. Compare the maximum gradient of
the filtered signal segment with that of the previous qrs segment.
Parameters
----------
peak_num : int
The peak number of the mwi signal where the qrs is dete... |
def generate_project_name():
"""Generates a random project name."""
adjectives = [
'aged', 'ancient', 'autumn', 'billowing', 'bitter', 'black', 'blue', 'bold',
'broad', 'broken', 'calm', 'cold', 'cool', 'crimson', 'curly', 'damp',
'dark', 'dawn', 'delicate', 'divine', 'dry', 'empty', 'f... | def function[generate_project_name, parameter[]]:
constant[Generates a random project name.]
variable[adjectives] assign[=] list[[<ast.Constant object at 0x7da20c6aa440>, <ast.Constant object at 0x7da20c6abe80>, <ast.Constant object at 0x7da20c6abb20>, <ast.Constant object at 0x7da20c6aa410>, <ast.Const... | keyword[def] identifier[generate_project_name] ():
literal[string]
identifier[adjectives] =[
literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] , liter... | def generate_project_name():
"""Generates a random project name."""
adjectives = ['aged', 'ancient', 'autumn', 'billowing', 'bitter', 'black', 'blue', 'bold', 'broad', 'broken', 'calm', 'cold', 'cool', 'crimson', 'curly', 'damp', 'dark', 'dawn', 'delicate', 'divine', 'dry', 'empty', 'falling', 'fancy', 'flat', ... |
def plot_graph_folium(G, graph_map=None, popup_attribute=None,
tiles='cartodbpositron', zoom=1, fit_bounds=True,
edge_color='#333333', edge_width=5, edge_opacity=1):
"""
Plot a graph on an interactive folium web map.
Note that anything larger than a small city ca... | def function[plot_graph_folium, parameter[G, graph_map, popup_attribute, tiles, zoom, fit_bounds, edge_color, edge_width, edge_opacity]]:
constant[
Plot a graph on an interactive folium web map.
Note that anything larger than a small city can take a long time to plot and
create a large web map file... | keyword[def] identifier[plot_graph_folium] ( identifier[G] , identifier[graph_map] = keyword[None] , identifier[popup_attribute] = keyword[None] ,
identifier[tiles] = literal[string] , identifier[zoom] = literal[int] , identifier[fit_bounds] = keyword[True] ,
identifier[edge_color] = literal[string] , identifier[ed... | def plot_graph_folium(G, graph_map=None, popup_attribute=None, tiles='cartodbpositron', zoom=1, fit_bounds=True, edge_color='#333333', edge_width=5, edge_opacity=1):
"""
Plot a graph on an interactive folium web map.
Note that anything larger than a small city can take a long time to plot and
create a ... |
def solubility_parameter(self):
r'''Solubility parameter of the chemical at its
current temperature and pressure, in units of [Pa^0.5].
.. math::
\delta = \sqrt{\frac{\Delta H_{vap} - RT}{V_m}}
Calculated based on enthalpy of vaporization and molar volume.
Normally ... | def function[solubility_parameter, parameter[self]]:
constant[Solubility parameter of the chemical at its
current temperature and pressure, in units of [Pa^0.5].
.. math::
\delta = \sqrt{\frac{\Delta H_{vap} - RT}{V_m}}
Calculated based on enthalpy of vaporization and molar... | keyword[def] identifier[solubility_parameter] ( identifier[self] ):
literal[string]
keyword[return] identifier[solubility_parameter] ( identifier[T] = identifier[self] . identifier[T] , identifier[Hvapm] = identifier[self] . identifier[Hvapm] , identifier[Vml] = identifier[self] . identifier[Vml] ... | def solubility_parameter(self):
"""Solubility parameter of the chemical at its
current temperature and pressure, in units of [Pa^0.5].
.. math::
\\delta = \\sqrt{\\frac{\\Delta H_{vap} - RT}{V_m}}
Calculated based on enthalpy of vaporization and molar volume.
Normally c... |
def CheckTemplates(self, base_dir, version):
"""Verify we have at least one template that matches maj.minor version."""
major_minor = ".".join(version.split(".")[0:2])
templates = glob.glob(
os.path.join(base_dir, "templates/*%s*.zip" % major_minor))
required_templates = set(
[x.replace(... | def function[CheckTemplates, parameter[self, base_dir, version]]:
constant[Verify we have at least one template that matches maj.minor version.]
variable[major_minor] assign[=] call[constant[.].join, parameter[call[call[name[version].split, parameter[constant[.]]]][<ast.Slice object at 0x7da1b1c0ec20>]]... | keyword[def] identifier[CheckTemplates] ( identifier[self] , identifier[base_dir] , identifier[version] ):
literal[string]
identifier[major_minor] = literal[string] . identifier[join] ( identifier[version] . identifier[split] ( literal[string] )[ literal[int] : literal[int] ])
identifier[templates] = ... | def CheckTemplates(self, base_dir, version):
"""Verify we have at least one template that matches maj.minor version."""
major_minor = '.'.join(version.split('.')[0:2])
templates = glob.glob(os.path.join(base_dir, 'templates/*%s*.zip' % major_minor))
required_templates = set([x.replace('maj.minor', major... |
def init_subclass_by_name(baseclass, short_name, params):
"""
Find the subclass, `kls` of baseclass with class attribute `short_name`
that matches the supplied `short_name`, and then instantiate and return
that class with:
return kls(**params)
This function also tries its best to catch any... | def function[init_subclass_by_name, parameter[baseclass, short_name, params]]:
constant[
Find the subclass, `kls` of baseclass with class attribute `short_name`
that matches the supplied `short_name`, and then instantiate and return
that class with:
return kls(**params)
This function a... | keyword[def] identifier[init_subclass_by_name] ( identifier[baseclass] , identifier[short_name] , identifier[params] ):
literal[string]
identifier[sc] = identifier[baseclass] . identifier[__subclasses__] ()
keyword[for] identifier[kls] keyword[in] identifier[sc] :
keyword[if] identifier[k... | def init_subclass_by_name(baseclass, short_name, params):
"""
Find the subclass, `kls` of baseclass with class attribute `short_name`
that matches the supplied `short_name`, and then instantiate and return
that class with:
return kls(**params)
This function also tries its best to catch any... |
def calc_2d_ellipse_properties(cov,nstd=2):
"""Calculate the properties for 2d ellipse given the covariance matrix."""
def eigsorted(cov):
vals, vecs = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return vals[order], vecs[:,order]
vals, vecs = eigsorted(cov)
width, height = ... | def function[calc_2d_ellipse_properties, parameter[cov, nstd]]:
constant[Calculate the properties for 2d ellipse given the covariance matrix.]
def function[eigsorted, parameter[cov]]:
<ast.Tuple object at 0x7da1b13934c0> assign[=] call[name[np].linalg.eigh, parameter[name[cov]]]
... | keyword[def] identifier[calc_2d_ellipse_properties] ( identifier[cov] , identifier[nstd] = literal[int] ):
literal[string]
keyword[def] identifier[eigsorted] ( identifier[cov] ):
identifier[vals] , identifier[vecs] = identifier[np] . identifier[linalg] . identifier[eigh] ( identifier[cov] )
... | def calc_2d_ellipse_properties(cov, nstd=2):
"""Calculate the properties for 2d ellipse given the covariance matrix."""
def eigsorted(cov):
(vals, vecs) = np.linalg.eigh(cov)
order = vals.argsort()[::-1]
return (vals[order], vecs[:, order])
(vals, vecs) = eigsorted(cov)
(width, ... |
def run_synthetic_SGLD():
"""Run synthetic SGLD"""
theta1 = 0
theta2 = 1
sigma1 = numpy.sqrt(10)
sigma2 = 1
sigmax = numpy.sqrt(2)
X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100)
minibatch_size = 1
total_iter_num = 1000000
lr_scheduler = SGLDScheduler(beg... | def function[run_synthetic_SGLD, parameter[]]:
constant[Run synthetic SGLD]
variable[theta1] assign[=] constant[0]
variable[theta2] assign[=] constant[1]
variable[sigma1] assign[=] call[name[numpy].sqrt, parameter[constant[10]]]
variable[sigma2] assign[=] constant[1]
vari... | keyword[def] identifier[run_synthetic_SGLD] ():
literal[string]
identifier[theta1] = literal[int]
identifier[theta2] = literal[int]
identifier[sigma1] = identifier[numpy] . identifier[sqrt] ( literal[int] )
identifier[sigma2] = literal[int]
identifier[sigmax] = identifier[numpy] . id... | def run_synthetic_SGLD():
"""Run synthetic SGLD"""
theta1 = 0
theta2 = 1
sigma1 = numpy.sqrt(10)
sigma2 = 1
sigmax = numpy.sqrt(2)
X = load_synthetic(theta1=theta1, theta2=theta2, sigmax=sigmax, num=100)
minibatch_size = 1
total_iter_num = 1000000
lr_scheduler = SGLDScheduler(beg... |
def _refresh_mine_cache(wrapped):
'''
Decorator to trigger a refresh of salt mine data.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
refresh salt mine on exit.
'''
returned = wrapped(*args, **__utils__['args.clean_kwargs'](**kwargs))
if _che... | def function[_refresh_mine_cache, parameter[wrapped]]:
constant[
Decorator to trigger a refresh of salt mine data.
]
def function[wrapper, parameter[]]:
constant[
refresh salt mine on exit.
]
variable[returned] assign[=] call[name[wrapped], paramet... | keyword[def] identifier[_refresh_mine_cache] ( identifier[wrapped] ):
literal[string]
@ identifier[functools] . identifier[wraps] ( identifier[wrapped] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[returned] = identifier[... | def _refresh_mine_cache(wrapped):
"""
Decorator to trigger a refresh of salt mine data.
"""
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
"""
refresh salt mine on exit.
"""
returned = wrapped(*args, **__utils__['args.clean_kwargs'](**kwargs))
if _ch... |
def unlink_parameter(self, param):
"""
:param param: param object to remove from being a parameter of this parameterized object.
"""
if not param in self.parameters:
try:
raise HierarchyError("{} does not belong to this object {}, remove parameters directly fr... | def function[unlink_parameter, parameter[self, param]]:
constant[
:param param: param object to remove from being a parameter of this parameterized object.
]
if <ast.UnaryOp object at 0x7da1b0f58730> begin[:]
<ast.Try object at 0x7da1b0f5b1f0>
variable[start] assign[=] ca... | keyword[def] identifier[unlink_parameter] ( identifier[self] , identifier[param] ):
literal[string]
keyword[if] keyword[not] identifier[param] keyword[in] identifier[self] . identifier[parameters] :
keyword[try] :
keyword[raise] identifier[HierarchyError] ( litera... | def unlink_parameter(self, param):
"""
:param param: param object to remove from being a parameter of this parameterized object.
"""
if not param in self.parameters:
try:
raise HierarchyError('{} does not belong to this object {}, remove parameters directly from their respect... |
def p_typeDeclarationRHS(self, p):
"""typeDeclarationRHS : Syntax
| TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax
| choiceClause"""
if p[1]:
if p[1] == 'TEXTUAL-CONVENTION':
p[... | def function[p_typeDeclarationRHS, parameter[self, p]]:
constant[typeDeclarationRHS : Syntax
| TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax
| choiceClause]
if call[name[p]][constant[1]] begin[:]
... | keyword[def] identifier[p_typeDeclarationRHS] ( identifier[self] , identifier[p] ):
literal[string]
keyword[if] identifier[p] [ literal[int] ]:
keyword[if] identifier[p] [ literal[int] ]== literal[string] :
identifier[p] [ literal[int] ]=( literal[string] , identifie... | def p_typeDeclarationRHS(self, p):
"""typeDeclarationRHS : Syntax
| TEXTUAL_CONVENTION DisplayPart STATUS Status DESCRIPTION Text ReferPart SYNTAX Syntax
| choiceClause"""
if p[1]:
if p[1] == 'TEXTUAL-CONVENTION': # display
# statu... |
def receiver(self, func=None, json=False):
"""
Registers a receiver function
"""
self.receivers.append((func, json)) | def function[receiver, parameter[self, func, json]]:
constant[
Registers a receiver function
]
call[name[self].receivers.append, parameter[tuple[[<ast.Name object at 0x7da2044c2080>, <ast.Name object at 0x7da2044c3cd0>]]]] | keyword[def] identifier[receiver] ( identifier[self] , identifier[func] = keyword[None] , identifier[json] = keyword[False] ):
literal[string]
identifier[self] . identifier[receivers] . identifier[append] (( identifier[func] , identifier[json] )) | def receiver(self, func=None, json=False):
"""
Registers a receiver function
"""
self.receivers.append((func, json)) |
def check_valid(self, values, flag=None):
"""Check if the data contains any non-valid status information
Parameters
----------
values: pycbc.types.Array
Array of status information
flag: str, optional
Override the default valid mask with a user defined ma... | def function[check_valid, parameter[self, values, flag]]:
constant[Check if the data contains any non-valid status information
Parameters
----------
values: pycbc.types.Array
Array of status information
flag: str, optional
Override the default valid mask ... | keyword[def] identifier[check_valid] ( identifier[self] , identifier[values] , identifier[flag] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[valid_on_zero] :
identifier[valid] = identifier[values] . identifier[numpy] ()== literal[int]
keyword[... | def check_valid(self, values, flag=None):
"""Check if the data contains any non-valid status information
Parameters
----------
values: pycbc.types.Array
Array of status information
flag: str, optional
Override the default valid mask with a user defined mask.
... |
def set_color(self, rgb):
"""Set dimmer color.
"""
target = ','.join([str(c) for c in rgb])
self.set_service_value(
self.color_service,
'ColorRGB',
'newColorRGBTarget',
target)
rgbi = self.get_color_index(['R', 'G', 'B'])
... | def function[set_color, parameter[self, rgb]]:
constant[Set dimmer color.
]
variable[target] assign[=] call[constant[,].join, parameter[<ast.ListComp object at 0x7da18fe91750>]]
call[name[self].set_service_value, parameter[name[self].color_service, constant[ColorRGB], constant[newColorRG... | keyword[def] identifier[set_color] ( identifier[self] , identifier[rgb] ):
literal[string]
identifier[target] = literal[string] . identifier[join] ([ identifier[str] ( identifier[c] ) keyword[for] identifier[c] keyword[in] identifier[rgb] ])
identifier[self] . identifier[set_service_va... | def set_color(self, rgb):
"""Set dimmer color.
"""
target = ','.join([str(c) for c in rgb])
self.set_service_value(self.color_service, 'ColorRGB', 'newColorRGBTarget', target)
rgbi = self.get_color_index(['R', 'G', 'B'])
if rgbi is None:
return # depends on [control=['if'], data=[]]... |
def remove_challenge_for_url(url):
""" Removes the cached challenge for the specified URL.
:param url: the URL for which to remove the cached challenge """
if not url:
raise ValueError('URL cannot be empty')
url = parse.urlparse(url)
_lock.acquire()
del _cache[url.netloc]
_lock.r... | def function[remove_challenge_for_url, parameter[url]]:
constant[ Removes the cached challenge for the specified URL.
:param url: the URL for which to remove the cached challenge ]
if <ast.UnaryOp object at 0x7da1b2346590> begin[:]
<ast.Raise object at 0x7da1b2344a60>
variable[url] a... | keyword[def] identifier[remove_challenge_for_url] ( identifier[url] ):
literal[string]
keyword[if] keyword[not] identifier[url] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[url] = identifier[parse] . identifier[urlparse] ( identifier[url] )
identifier[_lock... | def remove_challenge_for_url(url):
""" Removes the cached challenge for the specified URL.
:param url: the URL for which to remove the cached challenge """
if not url:
raise ValueError('URL cannot be empty') # depends on [control=['if'], data=[]]
url = parse.urlparse(url)
_lock.acquire()
... |
def _get_post_data(cls, args):
'''Return the post data.'''
if args.post_data:
return args.post_data
elif args.post_file:
return args.post_file.read() | def function[_get_post_data, parameter[cls, args]]:
constant[Return the post data.]
if name[args].post_data begin[:]
return[name[args].post_data] | keyword[def] identifier[_get_post_data] ( identifier[cls] , identifier[args] ):
literal[string]
keyword[if] identifier[args] . identifier[post_data] :
keyword[return] identifier[args] . identifier[post_data]
keyword[elif] identifier[args] . identifier[post_file] :
... | def _get_post_data(cls, args):
"""Return the post data."""
if args.post_data:
return args.post_data # depends on [control=['if'], data=[]]
elif args.post_file:
return args.post_file.read() # depends on [control=['if'], data=[]] |
def has_source_contents(self, src_id):
"""Checks if some sources exist."""
return bool(rustcall(_lib.lsm_view_has_source_contents,
self._get_ptr(), src_id)) | def function[has_source_contents, parameter[self, src_id]]:
constant[Checks if some sources exist.]
return[call[name[bool], parameter[call[name[rustcall], parameter[name[_lib].lsm_view_has_source_contents, call[name[self]._get_ptr, parameter[]], name[src_id]]]]]] | keyword[def] identifier[has_source_contents] ( identifier[self] , identifier[src_id] ):
literal[string]
keyword[return] identifier[bool] ( identifier[rustcall] ( identifier[_lib] . identifier[lsm_view_has_source_contents] ,
identifier[self] . identifier[_get_ptr] (), identifier[src_id] )) | def has_source_contents(self, src_id):
"""Checks if some sources exist."""
return bool(rustcall(_lib.lsm_view_has_source_contents, self._get_ptr(), src_id)) |
def _get_blockade_id_from_cwd(self, cwd=None):
'''Generate a new blockade ID based on the CWD'''
if not cwd:
cwd = os.getcwd()
# this follows a similar pattern as docker-compose uses
parent_dir = os.path.abspath(cwd)
basename = os.path.basename(parent_dir).lower()
... | def function[_get_blockade_id_from_cwd, parameter[self, cwd]]:
constant[Generate a new blockade ID based on the CWD]
if <ast.UnaryOp object at 0x7da1b0192ec0> begin[:]
variable[cwd] assign[=] call[name[os].getcwd, parameter[]]
variable[parent_dir] assign[=] call[name[os].path.abs... | keyword[def] identifier[_get_blockade_id_from_cwd] ( identifier[self] , identifier[cwd] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[cwd] :
identifier[cwd] = identifier[os] . identifier[getcwd] ()
identifier[parent_dir] = identifier[os]... | def _get_blockade_id_from_cwd(self, cwd=None):
"""Generate a new blockade ID based on the CWD"""
if not cwd:
cwd = os.getcwd() # depends on [control=['if'], data=[]]
# this follows a similar pattern as docker-compose uses
parent_dir = os.path.abspath(cwd)
basename = os.path.basename(parent_... |
def authenticate_through_netrc(path=None):
"""
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
"""
errors = []
netrc_machine = 'coursera-dl'
paths = [path] if path else get_config_paths("netrc")
for path in path... | def function[authenticate_through_netrc, parameter[path]]:
constant[
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
]
variable[errors] assign[=] list[[]]
variable[netrc_machine] assign[=] constant[coursera-... | keyword[def] identifier[authenticate_through_netrc] ( identifier[path] = keyword[None] ):
literal[string]
identifier[errors] =[]
identifier[netrc_machine] = literal[string]
identifier[paths] =[ identifier[path] ] keyword[if] identifier[path] keyword[else] identifier[get_config_paths] ( litera... | def authenticate_through_netrc(path=None):
"""
Return the tuple user / password given a path for the .netrc file.
Raises CredentialsError if no valid netrc file is found.
"""
errors = []
netrc_machine = 'coursera-dl'
paths = [path] if path else get_config_paths('netrc')
for path in path... |
def basescript(line):
'''
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba... | def function[basescript, parameter[line]]:
constant[
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local... | keyword[def] identifier[basescript] ( identifier[line] ):
literal[string]
identifier[log] = identifier[json] . identifier[loads] ( identifier[line] )
keyword[return] identifier[dict] (
identifier[timestamp] = identifier[log] [ literal[string] ],
identifier[data] = identifier[log] ,
i... | def basescript(line):
"""
>>> import pprint
>>> input_line = '{"level": "warning", "timestamp": "2018-02-07T06:37:00.297610Z", "event": "exited via keyboard interrupt", "type": "log", "id": "20180207T063700_4d03fe800bd111e89ecb96000007bc65", "_": {"ln": 58, "file": "/usr/local/lib/python2.7/dist-packages/ba... |
def prettify(unicode_text):
"""Return a pretty-printed version of a unicode XML string.
Useful for debugging.
Args:
unicode_text (str): A text representation of XML (unicode,
*not* utf-8).
Returns:
str: A pretty-printed version of the input.
"""
import xml.dom.min... | def function[prettify, parameter[unicode_text]]:
constant[Return a pretty-printed version of a unicode XML string.
Useful for debugging.
Args:
unicode_text (str): A text representation of XML (unicode,
*not* utf-8).
Returns:
str: A pretty-printed version of the input.
... | keyword[def] identifier[prettify] ( identifier[unicode_text] ):
literal[string]
keyword[import] identifier[xml] . identifier[dom] . identifier[minidom]
identifier[reparsed] = identifier[xml] . identifier[dom] . identifier[minidom] . identifier[parseString] ( identifier[unicode_text] . identifier[enc... | def prettify(unicode_text):
"""Return a pretty-printed version of a unicode XML string.
Useful for debugging.
Args:
unicode_text (str): A text representation of XML (unicode,
*not* utf-8).
Returns:
str: A pretty-printed version of the input.
"""
import xml.dom.min... |
def create_instance(self, **kwargs):
"""Creates a new virtual server instance.
.. warning::
This will add charges to your account
Example::
new_vsi = {
'domain': u'test01.labs.sftlyr.ws',
'hostname': u'minion05',
'datace... | def function[create_instance, parameter[self]]:
constant[Creates a new virtual server instance.
.. warning::
This will add charges to your account
Example::
new_vsi = {
'domain': u'test01.labs.sftlyr.ws',
'hostname': u'minion05',
... | keyword[def] identifier[create_instance] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[tags] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
identifier[inst] = identifier[self] . identifier[guest] . identifier[createObject] ( identifier[... | def create_instance(self, **kwargs):
"""Creates a new virtual server instance.
.. warning::
This will add charges to your account
Example::
new_vsi = {
'domain': u'test01.labs.sftlyr.ws',
'hostname': u'minion05',
'datacenter... |
def parse_modes(modes, targets=None, noargs=''):
"""Parse channel modes:
.. code-block:: python
>>> parse_modes('+c-n', noargs='cn')
[('+', 'c', None), ('-', 'n', None)]
>>> parse_modes('+c-v', ['gawel'], noargs='c')
[('+', 'c', None), ('-', 'v', 'gawel')]
"""
if not ta... | def function[parse_modes, parameter[modes, targets, noargs]]:
constant[Parse channel modes:
.. code-block:: python
>>> parse_modes('+c-n', noargs='cn')
[('+', 'c', None), ('-', 'n', None)]
>>> parse_modes('+c-v', ['gawel'], noargs='c')
[('+', 'c', None), ('-', 'v', 'gawel')... | keyword[def] identifier[parse_modes] ( identifier[modes] , identifier[targets] = keyword[None] , identifier[noargs] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[targets] :
identifier[targets] =[]
identifier[cleaned] =[]
keyword[for] identifier[mode] keywor... | def parse_modes(modes, targets=None, noargs=''):
"""Parse channel modes:
.. code-block:: python
>>> parse_modes('+c-n', noargs='cn')
[('+', 'c', None), ('-', 'n', None)]
>>> parse_modes('+c-v', ['gawel'], noargs='c')
[('+', 'c', None), ('-', 'v', 'gawel')]
"""
if not ta... |
def mean_by_window(self, indices, window):
"""
Average series across multiple windows specified by their centers.
Parameters
----------
indices : array-like
List of times specifying window centers
window : int
Window size
"""
mask... | def function[mean_by_window, parameter[self, indices, window]]:
constant[
Average series across multiple windows specified by their centers.
Parameters
----------
indices : array-like
List of times specifying window centers
window : int
Window si... | keyword[def] identifier[mean_by_window] ( identifier[self] , identifier[indices] , identifier[window] ):
literal[string]
identifier[masks] = identifier[self] . identifier[_makewindows] ( identifier[indices] , identifier[window] )
identifier[newindex] = identifier[arange] ( literal[int] , i... | def mean_by_window(self, indices, window):
"""
Average series across multiple windows specified by their centers.
Parameters
----------
indices : array-like
List of times specifying window centers
window : int
Window size
"""
masks = self... |
def newline(self, copy_margin=True):
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line)
else:
self.insert_text('\n') | def function[newline, parameter[self, copy_margin]]:
constant[
Insert a line ending at the current position.
]
if name[copy_margin] begin[:]
call[name[self].insert_text, parameter[binary_operation[constant[
] + name[self].document.leading_whitespace_in_current_line]]] | keyword[def] identifier[newline] ( identifier[self] , identifier[copy_margin] = keyword[True] ):
literal[string]
keyword[if] identifier[copy_margin] :
identifier[self] . identifier[insert_text] ( literal[string] + identifier[self] . identifier[document] . identifier[leading_whitespace... | def newline(self, copy_margin=True):
"""
Insert a line ending at the current position.
"""
if copy_margin:
self.insert_text('\n' + self.document.leading_whitespace_in_current_line) # depends on [control=['if'], data=[]]
else:
self.insert_text('\n') |
def assign_unassigned_members(self, group_category_id, sync=None):
"""
Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups.
"""
path = {}
data = {}
params = {}
# REQUIRED - P... | def function[assign_unassigned_members, parameter[self, group_category_id, sync]]:
constant[
Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups.
]
variable[path] assign[=] dictionary[[], []]
variable[d... | keyword[def] identifier[assign_unassigned_members] ( identifier[self] , identifier[group_category_id] , identifier[sync] = keyword[None] ):
literal[string]
identifier[path] ={}
identifier[data] ={}
identifier[params] ={}
literal[string]
identif... | def assign_unassigned_members(self, group_category_id, sync=None):
"""
Assign unassigned members.
Assign all unassigned members as evenly as possible among the existing
student groups.
"""
path = {}
data = {}
params = {} # REQUIRED - PATH - group_category_id
'ID'
... |
def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or rep... | def function[_subs, parameter[self, substitutions, default, simplify]]:
constant[
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
]
variable[new_argumen... | keyword[def] identifier[_subs] ( identifier[self] , identifier[substitutions] , identifier[default] , identifier[simplify] ):
literal[string]
identifier[new_arguments] =[]
identifier[changed_something] = keyword[False]
keyword[if] identifier[self] ke... | def _subs(self, substitutions, default, simplify):
"""
Return an expression where all subterms equal to a key expression are
substituted by the corresponding value expression using a mapping of:
{expr->expr to substitute.}
"""
# track the new list of unchanged args or replaced ar... |
def init(cwd,
bare=False,
template=None,
separate_git_dir=None,
shared=None,
opts='',
git_opts='',
user=None,
password=None,
ignore_retcode=False,
output_encoding=None):
'''
Interface to `git-init(1)`_
cwd
The... | def function[init, parameter[cwd, bare, template, separate_git_dir, shared, opts, git_opts, user, password, ignore_retcode, output_encoding]]:
constant[
Interface to `git-init(1)`_
cwd
The path to the directory to be initialized
bare : False
If ``True``, init a bare repository
... | keyword[def] identifier[init] ( identifier[cwd] ,
identifier[bare] = keyword[False] ,
identifier[template] = keyword[None] ,
identifier[separate_git_dir] = keyword[None] ,
identifier[shared] = keyword[None] ,
identifier[opts] = literal[string] ,
identifier[git_opts] = literal[string] ,
identifier[user] = keywo... | def init(cwd, bare=False, template=None, separate_git_dir=None, shared=None, opts='', git_opts='', user=None, password=None, ignore_retcode=False, output_encoding=None):
"""
Interface to `git-init(1)`_
cwd
The path to the directory to be initialized
bare : False
If ``True``, init a bar... |
def assure_entity(fnc):
"""
Converts an entityID passed as the entity to a CloudMonitorEntity object.
"""
@wraps(fnc)
def _wrapped(self, entity, *args, **kwargs):
if not isinstance(entity, CloudMonitorEntity):
# Must be the ID
entity = self._entity_manager.get(entity)... | def function[assure_entity, parameter[fnc]]:
constant[
Converts an entityID passed as the entity to a CloudMonitorEntity object.
]
def function[_wrapped, parameter[self, entity]]:
if <ast.UnaryOp object at 0x7da1b056c2e0> begin[:]
variable[entity] assign[=... | keyword[def] identifier[assure_entity] ( identifier[fnc] ):
literal[string]
@ identifier[wraps] ( identifier[fnc] )
keyword[def] identifier[_wrapped] ( identifier[self] , identifier[entity] ,* identifier[args] ,** identifier[kwargs] ):
keyword[if] keyword[not] identifier[isinstance] ( ident... | def assure_entity(fnc):
"""
Converts an entityID passed as the entity to a CloudMonitorEntity object.
"""
@wraps(fnc)
def _wrapped(self, entity, *args, **kwargs):
if not isinstance(entity, CloudMonitorEntity):
# Must be the ID
entity = self._entity_manager.get(entity... |
def set_symbol(self, symbol):
"""(symbol, bondorder) -> set the bondsymbol
of the molecule"""
raise "Deprecated"
self.symbol, self.bondtype, bondorder, self.equiv_class = \
BONDLOOKUP[symbol]
if self.bondtype == 4:
self.aromatic = 1
else:
... | def function[set_symbol, parameter[self, symbol]]:
constant[(symbol, bondorder) -> set the bondsymbol
of the molecule]
<ast.Raise object at 0x7da18ede5cf0>
<ast.Tuple object at 0x7da18ede72e0> assign[=] call[name[BONDLOOKUP]][name[symbol]]
if compare[name[self].bondtype equal[==] con... | keyword[def] identifier[set_symbol] ( identifier[self] , identifier[symbol] ):
literal[string]
keyword[raise] literal[string]
identifier[self] . identifier[symbol] , identifier[self] . identifier[bondtype] , identifier[bondorder] , identifier[self] . identifier[equiv_class] = identifier[... | def set_symbol(self, symbol):
"""(symbol, bondorder) -> set the bondsymbol
of the molecule"""
raise 'Deprecated'
(self.symbol, self.bondtype, bondorder, self.equiv_class) = BONDLOOKUP[symbol]
if self.bondtype == 4:
self.aromatic = 1 # depends on [control=['if'], data=[]]
else:
... |
def set_monthly(self, interval, *, day_of_month=None, days_of_week=None,
index=None, **kwargs):
""" Set to repeat every month on specified days for every x no. of days
:param int interval: no. of days to repeat at
:param int day_of_month: repeat day of a month
:param... | def function[set_monthly, parameter[self, interval]]:
constant[ Set to repeat every month on specified days for every x no. of days
:param int interval: no. of days to repeat at
:param int day_of_month: repeat day of a month
:param list[str] days_of_week: list of days of the week to rep... | keyword[def] identifier[set_monthly] ( identifier[self] , identifier[interval] ,*, identifier[day_of_month] = keyword[None] , identifier[days_of_week] = keyword[None] ,
identifier[index] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[day_of_month] ... | def set_monthly(self, interval, *, day_of_month=None, days_of_week=None, index=None, **kwargs):
""" Set to repeat every month on specified days for every x no. of days
:param int interval: no. of days to repeat at
:param int day_of_month: repeat day of a month
:param list[str] days_of_week:... |
def table_extract(self, table_name, destination, format='CSV', compress=True,
field_delimiter=',', print_header=True):
"""Exports the table to GCS.
Args:
table_name: the name of the table as a tuple of components.
destination: the destination URI(s). Can be a single URI or a lis... | def function[table_extract, parameter[self, table_name, destination, format, compress, field_delimiter, print_header]]:
constant[Exports the table to GCS.
Args:
table_name: the name of the table as a tuple of components.
destination: the destination URI(s). Can be a single URI or a list.
... | keyword[def] identifier[table_extract] ( identifier[self] , identifier[table_name] , identifier[destination] , identifier[format] = literal[string] , identifier[compress] = keyword[True] ,
identifier[field_delimiter] = literal[string] , identifier[print_header] = keyword[True] ):
literal[string]
identifie... | def table_extract(self, table_name, destination, format='CSV', compress=True, field_delimiter=',', print_header=True):
"""Exports the table to GCS.
Args:
table_name: the name of the table as a tuple of components.
destination: the destination URI(s). Can be a single URI or a list.
format: the... |
def restore_row(self, row, schema):
"""Restore row from BigQuery
"""
for index, field in enumerate(schema.fields):
if field.type == 'datetime':
row[index] = parse(row[index])
if field.type == 'date':
row[index] = parse(row[index]).date()
... | def function[restore_row, parameter[self, row, schema]]:
constant[Restore row from BigQuery
]
for taget[tuple[[<ast.Name object at 0x7da1b262a8c0>, <ast.Name object at 0x7da1b262ac80>]]] in starred[call[name[enumerate], parameter[name[schema].fields]]] begin[:]
if compare[name[fi... | keyword[def] identifier[restore_row] ( identifier[self] , identifier[row] , identifier[schema] ):
literal[string]
keyword[for] identifier[index] , identifier[field] keyword[in] identifier[enumerate] ( identifier[schema] . identifier[fields] ):
keyword[if] identifier[field] . identi... | def restore_row(self, row, schema):
"""Restore row from BigQuery
"""
for (index, field) in enumerate(schema.fields):
if field.type == 'datetime':
row[index] = parse(row[index]) # depends on [control=['if'], data=[]]
if field.type == 'date':
row[index] = parse(row... |
def get_language_details(self, language):
"""Get user's status about a language."""
for lang in self.user_data.languages:
if language == lang['language_string']:
return lang
return {} | def function[get_language_details, parameter[self, language]]:
constant[Get user's status about a language.]
for taget[name[lang]] in starred[name[self].user_data.languages] begin[:]
if compare[name[language] equal[==] call[name[lang]][constant[language_string]]] begin[:]
ret... | keyword[def] identifier[get_language_details] ( identifier[self] , identifier[language] ):
literal[string]
keyword[for] identifier[lang] keyword[in] identifier[self] . identifier[user_data] . identifier[languages] :
keyword[if] identifier[language] == identifier[lang] [ literal[str... | def get_language_details(self, language):
"""Get user's status about a language."""
for lang in self.user_data.languages:
if language == lang['language_string']:
return lang # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['lang']]
return {} |
def make_union(*transformers, **kwargs):
"""Construct a FeatureUnion from the given transformers.
This is a shorthand for the FeatureUnion constructor; it does not require,
and does not permit, naming the transformers. Instead, they will be given
names automatically based on their types. It also does n... | def function[make_union, parameter[]]:
constant[Construct a FeatureUnion from the given transformers.
This is a shorthand for the FeatureUnion constructor; it does not require,
and does not permit, naming the transformers. Instead, they will be given
names automatically based on their types. It als... | keyword[def] identifier[make_union] (* identifier[transformers] ,** identifier[kwargs] ):
literal[string]
identifier[n_jobs] = identifier[kwargs] . identifier[pop] ( literal[string] , literal[int] )
identifier[concatenate] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[True] )
... | def make_union(*transformers, **kwargs):
"""Construct a FeatureUnion from the given transformers.
This is a shorthand for the FeatureUnion constructor; it does not require,
and does not permit, naming the transformers. Instead, they will be given
names automatically based on their types. It also does n... |
def delete_admin(self, account_id, user_id, role):
"""
Remove an account admin role from a user.
https://canvas.instructure.com/doc/api/admins.html#method.admins.destroy
"""
url = ADMINS_API.format(account_id) + "/{}?role={}".format(
user_id, quote(role))
re... | def function[delete_admin, parameter[self, account_id, user_id, role]]:
constant[
Remove an account admin role from a user.
https://canvas.instructure.com/doc/api/admins.html#method.admins.destroy
]
variable[url] assign[=] binary_operation[call[name[ADMINS_API].format, parameter... | keyword[def] identifier[delete_admin] ( identifier[self] , identifier[account_id] , identifier[user_id] , identifier[role] ):
literal[string]
identifier[url] = identifier[ADMINS_API] . identifier[format] ( identifier[account_id] )+ literal[string] . identifier[format] (
identifier[user_id]... | def delete_admin(self, account_id, user_id, role):
"""
Remove an account admin role from a user.
https://canvas.instructure.com/doc/api/admins.html#method.admins.destroy
"""
url = ADMINS_API.format(account_id) + '/{}?role={}'.format(user_id, quote(role))
response = self._delete_reso... |
def stat(self, path):
""" safely gets the Znode's Stat """
try:
stat = self.exists(str(path))
except (NoNodeError, NoAuthError):
stat = None
return stat | def function[stat, parameter[self, path]]:
constant[ safely gets the Znode's Stat ]
<ast.Try object at 0x7da18f00ecb0>
return[name[stat]] | keyword[def] identifier[stat] ( identifier[self] , identifier[path] ):
literal[string]
keyword[try] :
identifier[stat] = identifier[self] . identifier[exists] ( identifier[str] ( identifier[path] ))
keyword[except] ( identifier[NoNodeError] , identifier[NoAuthError] ):
... | def stat(self, path):
""" safely gets the Znode's Stat """
try:
stat = self.exists(str(path)) # depends on [control=['try'], data=[]]
except (NoNodeError, NoAuthError):
stat = None # depends on [control=['except'], data=[]]
return stat |
def sqs_create_queue(queue_name, options=None, client=None):
"""
This creates an SQS queue.
Parameters
----------
queue_name : str
The name of the queue to create.
options : dict or None
A dict of options indicate extra attributes the queue should have.
See the SQS doc... | def function[sqs_create_queue, parameter[queue_name, options, client]]:
constant[
This creates an SQS queue.
Parameters
----------
queue_name : str
The name of the queue to create.
options : dict or None
A dict of options indicate extra attributes the queue should have.
... | keyword[def] identifier[sqs_create_queue] ( identifier[queue_name] , identifier[options] = keyword[None] , identifier[client] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[client] :
identifier[client] = identifier[boto3] . identifier[client] ( literal[string] )
ke... | def sqs_create_queue(queue_name, options=None, client=None):
"""
This creates an SQS queue.
Parameters
----------
queue_name : str
The name of the queue to create.
options : dict or None
A dict of options indicate extra attributes the queue should have.
See the SQS doc... |
def _update(self):
'''
Calculate heading and distance from dx and dy
'''
try:
theta_radians = math.atan(float(self.dy)/self.dx)
except ZeroDivisionError:
if self.dy > 0: theta_radians = 0.5*math.pi
elif self.dy < 0: theta_radians = 1.5*math.pi
... | def function[_update, parameter[self]]:
constant[
Calculate heading and distance from dx and dy
]
<ast.Try object at 0x7da18f09df90>
variable[theta] assign[=] call[name[math].degrees, parameter[name[theta_radians]]]
name[self].heading assign[=] call[name[self]._angle_or_headi... | keyword[def] identifier[_update] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[theta_radians] = identifier[math] . identifier[atan] ( identifier[float] ( identifier[self] . identifier[dy] )/ identifier[self] . identifier[dx] )
keyword[except] identifier[Zero... | def _update(self):
"""
Calculate heading and distance from dx and dy
"""
try:
theta_radians = math.atan(float(self.dy) / self.dx) # depends on [control=['try'], data=[]]
except ZeroDivisionError:
if self.dy > 0:
theta_radians = 0.5 * math.pi # depends on [contro... |
def overlapped_convolution(bin_template, bin_image,
tollerance=0.5, splits=(4, 2)):
"""
As each of these images are hold only binary values, and RFFT2 works on
float64 greyscale values, we can make the convolution more efficient by
breaking the image up into :splits: sect... | def function[overlapped_convolution, parameter[bin_template, bin_image, tollerance, splits]]:
constant[
As each of these images are hold only binary values, and RFFT2 works on
float64 greyscale values, we can make the convolution more efficient by
breaking the image up into :splits: sectons. Each on... | keyword[def] identifier[overlapped_convolution] ( identifier[bin_template] , identifier[bin_image] ,
identifier[tollerance] = literal[int] , identifier[splits] =( literal[int] , literal[int] )):
literal[string]
identifier[th] , identifier[tw] = identifier[bin_template] . identifier[shape]
identi... | def overlapped_convolution(bin_template, bin_image, tollerance=0.5, splits=(4, 2)):
"""
As each of these images are hold only binary values, and RFFT2 works on
float64 greyscale values, we can make the convolution more efficient by
breaking the image up into :splits: sectons. Each one of these sections
... |
def debug(message, *args, **kwargs):
"""
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
"""
if 'end' in kwargs:
end = kwargs['end']
else:
end = '\n'
if DEBUG: ... | def function[debug, parameter[message]]:
constant[
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
]
if compare[constant[end] in name[kwargs]] begin[:]
variable[... | keyword[def] identifier[debug] ( identifier[message] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[end] = identifier[kwargs] [ literal[string] ]
keyword[else] :
identifier[end] = literal[string... | def debug(message, *args, **kwargs):
"""
debug output goes to stderr so you can still redirect the stdout to a file
or another program. Controlled by the JUT_DEBUG environment variable being
present
"""
if 'end' in kwargs:
end = kwargs['end'] # depends on [control=['if'], data=['kwargs... |
def process_new_post(self, bulk_mode, api_post, posts, author, post_categories, post_tags, post_media_attachments):
"""
Instantiate a new Post object using data from the WP API.
Related fields -- author, categories, tags, and attachments should be processed in advance
:param bulk_mode: ... | def function[process_new_post, parameter[self, bulk_mode, api_post, posts, author, post_categories, post_tags, post_media_attachments]]:
constant[
Instantiate a new Post object using data from the WP API.
Related fields -- author, categories, tags, and attachments should be processed in advance
... | keyword[def] identifier[process_new_post] ( identifier[self] , identifier[bulk_mode] , identifier[api_post] , identifier[posts] , identifier[author] , identifier[post_categories] , identifier[post_tags] , identifier[post_media_attachments] ):
literal[string]
identifier[post] = identifier[Post] ( id... | def process_new_post(self, bulk_mode, api_post, posts, author, post_categories, post_tags, post_media_attachments):
"""
Instantiate a new Post object using data from the WP API.
Related fields -- author, categories, tags, and attachments should be processed in advance
:param bulk_mode: If T... |
def iter_stack_frames(frames=None):
"""
Given an optional list of frames (defaults to current stack),
iterates over all frames that do not contain the ``__traceback_hide__``
local variable.
"""
if not frames:
frames = inspect.stack()[1:]
for frame, lineno in ((f[0], f[2]) for f in r... | def function[iter_stack_frames, parameter[frames]]:
constant[
Given an optional list of frames (defaults to current stack),
iterates over all frames that do not contain the ``__traceback_hide__``
local variable.
]
if <ast.UnaryOp object at 0x7da1b1726e90> begin[:]
variabl... | keyword[def] identifier[iter_stack_frames] ( identifier[frames] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[frames] :
identifier[frames] = identifier[inspect] . identifier[stack] ()[ literal[int] :]
keyword[for] identifier[frame] , identifier[lineno] keyword[in... | def iter_stack_frames(frames=None):
"""
Given an optional list of frames (defaults to current stack),
iterates over all frames that do not contain the ``__traceback_hide__``
local variable.
"""
if not frames:
frames = inspect.stack()[1:] # depends on [control=['if'], data=[]]
for (f... |
def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yie... | def function[list, parameter[self, ignore_patterns]]:
constant[
List all files in all app storages.
]
for taget[name[storage]] in starred[call[name[six].itervalues, parameter[name[self].storages]]] begin[:]
if call[name[storage].exists, parameter[constant[]]] begin[:]
... | keyword[def] identifier[list] ( identifier[self] , identifier[ignore_patterns] ):
literal[string]
keyword[for] identifier[storage] keyword[in] identifier[six] . identifier[itervalues] ( identifier[self] . identifier[storages] ):
keyword[if] identifier[storage] . identifier[exists] ... | def list(self, ignore_patterns):
"""
List all files in all app storages.
"""
for storage in six.itervalues(self.storages):
if storage.exists(''): # check if storage location exists
for path in utils.get_files(storage, ignore_patterns):
yield (path, storage) ... |
def register_data(self, typename, value):
"""Registers a data product, raising if a product was already registered.
:API: public
:param typename: The type of product to register a value for.
:param value: The data product to register under `typename`.
:returns: The registered `value`.
:raises:... | def function[register_data, parameter[self, typename, value]]:
constant[Registers a data product, raising if a product was already registered.
:API: public
:param typename: The type of product to register a value for.
:param value: The data product to register under `typename`.
:returns: The r... | keyword[def] identifier[register_data] ( identifier[self] , identifier[typename] , identifier[value] ):
literal[string]
keyword[if] identifier[typename] keyword[in] identifier[self] . identifier[data_products] :
keyword[raise] identifier[ProductError] ( literal[string]
. identifier[format... | def register_data(self, typename, value):
"""Registers a data product, raising if a product was already registered.
:API: public
:param typename: The type of product to register a value for.
:param value: The data product to register under `typename`.
:returns: The registered `value`.
:raises:... |
def login(request):
"""View to check the persona assertion and remember the user"""
email = verify_login(request)
request.response.headers.extend(remember(request, email))
return {'redirect': request.POST.get('came_from', '/'), 'success': True} | def function[login, parameter[request]]:
constant[View to check the persona assertion and remember the user]
variable[email] assign[=] call[name[verify_login], parameter[name[request]]]
call[name[request].response.headers.extend, parameter[call[name[remember], parameter[name[request], name[email... | keyword[def] identifier[login] ( identifier[request] ):
literal[string]
identifier[email] = identifier[verify_login] ( identifier[request] )
identifier[request] . identifier[response] . identifier[headers] . identifier[extend] ( identifier[remember] ( identifier[request] , identifier[email] ))
ke... | def login(request):
"""View to check the persona assertion and remember the user"""
email = verify_login(request)
request.response.headers.extend(remember(request, email))
return {'redirect': request.POST.get('came_from', '/'), 'success': True} |
def write_graph(self, filename):
"""
Write raw graph data which can be post-processed using graphviz.
"""
f = open(filename, 'w')
f.write(self._get_graphviz_data())
f.close() | def function[write_graph, parameter[self, filename]]:
constant[
Write raw graph data which can be post-processed using graphviz.
]
variable[f] assign[=] call[name[open], parameter[name[filename], constant[w]]]
call[name[f].write, parameter[call[name[self]._get_graphviz_data, para... | keyword[def] identifier[write_graph] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[f] = identifier[open] ( identifier[filename] , literal[string] )
identifier[f] . identifier[write] ( identifier[self] . identifier[_get_graphviz_data] ())
identifier[f] . i... | def write_graph(self, filename):
"""
Write raw graph data which can be post-processed using graphviz.
"""
f = open(filename, 'w')
f.write(self._get_graphviz_data())
f.close() |
def from_dict(input_dict):
"""
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _build_from_input_dict of the de... | def function[from_dict, parameter[input_dict]]:
constant[
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _buil... | keyword[def] identifier[from_dict] ( identifier[input_dict] ):
literal[string]
keyword[import] identifier[copy]
identifier[input_dict] = identifier[copy] . identifier[deepcopy] ( identifier[input_dict] )
identifier[normalizer_class] = identifier[input_dict] . identifier[pop] ( ... | def from_dict(input_dict):
"""
Instantiate an object of a derived class using the information
in input_dict (built by the to_dict method of the derived class).
More specifically, after reading the derived class from input_dict,
it calls the method _build_from_input_dict of the derive... |
def _get_redis_cache_opts():
'''
Return the Redis server connection details from the __opts__.
'''
return {
'host': __opts__.get('cache.redis.host', 'localhost'),
'port': __opts__.get('cache.redis.port', 6379),
'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None... | def function[_get_redis_cache_opts, parameter[]]:
constant[
Return the Redis server connection details from the __opts__.
]
return[dictionary[[<ast.Constant object at 0x7da1b2036da0>, <ast.Constant object at 0x7da1b2034d30>, <ast.Constant object at 0x7da1b2034880>, <ast.Constant object at 0x7da1b203... | keyword[def] identifier[_get_redis_cache_opts] ():
literal[string]
keyword[return] {
literal[string] : identifier[__opts__] . identifier[get] ( literal[string] , literal[string] ),
literal[string] : identifier[__opts__] . identifier[get] ( literal[string] , literal[int] ),
literal[string] : ... | def _get_redis_cache_opts():
"""
Return the Redis server connection details from the __opts__.
"""
return {'host': __opts__.get('cache.redis.host', 'localhost'), 'port': __opts__.get('cache.redis.port', 6379), 'unix_socket_path': __opts__.get('cache.redis.unix_socket_path', None), 'db': __opts__.get('ca... |
def write_json(filename, data):
""" Write data to JSON file
:param filename: name of JSON file to write data to
:type filename: str
:param data: data to write to JSON file
:type data: list, tuple
"""
with open(filename, 'w') as file:
json.dump(data, file, indent=4, sort_keys=True) | def function[write_json, parameter[filename, data]]:
constant[ Write data to JSON file
:param filename: name of JSON file to write data to
:type filename: str
:param data: data to write to JSON file
:type data: list, tuple
]
with call[name[open], parameter[name[filename], constant[w... | keyword[def] identifier[write_json] ( identifier[filename] , identifier[data] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[file] :
identifier[json] . identifier[dump] ( identifier[data] , identifier[file] , identifier[indent]... | def write_json(filename, data):
""" Write data to JSON file
:param filename: name of JSON file to write data to
:type filename: str
:param data: data to write to JSON file
:type data: list, tuple
"""
with open(filename, 'w') as file:
json.dump(data, file, indent=4, sort_keys=True) ... |
def _seed(self, seed=-1):
"""
Initialize the random seed
"""
if seed != -1:
self._random = NupicRandom(seed)
else:
self._random = NupicRandom() | def function[_seed, parameter[self, seed]]:
constant[
Initialize the random seed
]
if compare[name[seed] not_equal[!=] <ast.UnaryOp object at 0x7da18f720c10>] begin[:]
name[self]._random assign[=] call[name[NupicRandom], parameter[name[seed]]] | keyword[def] identifier[_seed] ( identifier[self] , identifier[seed] =- literal[int] ):
literal[string]
keyword[if] identifier[seed] !=- literal[int] :
identifier[self] . identifier[_random] = identifier[NupicRandom] ( identifier[seed] )
keyword[else] :
identifier[self] . identifier[_ra... | def _seed(self, seed=-1):
"""
Initialize the random seed
"""
if seed != -1:
self._random = NupicRandom(seed) # depends on [control=['if'], data=['seed']]
else:
self._random = NupicRandom() |
def escapeUnderscores(self):
"""
Escape underscores so that the markdown is correct
"""
new_metrics = []
for m in self.metrics:
m['name'] = m['name'].replace("_", "\_")
new_metrics.append(m)
self.metrics = new_metrics | def function[escapeUnderscores, parameter[self]]:
constant[
Escape underscores so that the markdown is correct
]
variable[new_metrics] assign[=] list[[]]
for taget[name[m]] in starred[name[self].metrics] begin[:]
call[name[m]][constant[name]] assign[=] call[call[n... | keyword[def] identifier[escapeUnderscores] ( identifier[self] ):
literal[string]
identifier[new_metrics] =[]
keyword[for] identifier[m] keyword[in] identifier[self] . identifier[metrics] :
identifier[m] [ literal[string] ]= identifier[m] [ literal[string] ]. identifier[repl... | def escapeUnderscores(self):
"""
Escape underscores so that the markdown is correct
"""
new_metrics = []
for m in self.metrics:
m['name'] = m['name'].replace('_', '\\_')
new_metrics.append(m) # depends on [control=['for'], data=['m']]
self.metrics = new_metrics |
def get_behaviors(brain_or_object):
"""Iterate over all behaviors that are assigned to the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Behaviors
:rtype: list
"""
obj = get_object(bra... | def function[get_behaviors, parameter[brain_or_object]]:
constant[Iterate over all behaviors that are assigned to the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Behaviors
:rtype: list
... | keyword[def] identifier[get_behaviors] ( identifier[brain_or_object] ):
literal[string]
identifier[obj] = identifier[get_object] ( identifier[brain_or_object] )
keyword[if] keyword[not] identifier[is_dexterity_content] ( identifier[obj] ):
identifier[fail] ( literal[int] , literal[string] )... | def get_behaviors(brain_or_object):
"""Iterate over all behaviors that are assigned to the object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Behaviors
:rtype: list
"""
obj = get_object(bra... |
def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int
) -> Iterable[ops.Operation]:
"""
Each layer index corresponds to a shift/transpose of this CZ pattern:
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ●───● . . .
●───● ● ● ●... | def function[_make_cz_layer, parameter[qubits, layer_index]]:
constant[
Each layer index corresponds to a shift/transpose of this CZ pattern:
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ●───● . . .
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ... | keyword[def] identifier[_make_cz_layer] ( identifier[qubits] : identifier[Iterable] [ identifier[devices] . identifier[GridQubit] ], identifier[layer_index] : identifier[int]
)-> identifier[Iterable] [ identifier[ops] . identifier[Operation] ]:
literal[string]
identifier[layer_index_map] =[ literal[... | def _make_cz_layer(qubits: Iterable[devices.GridQubit], layer_index: int) -> Iterable[ops.Operation]:
"""
Each layer index corresponds to a shift/transpose of this CZ pattern:
●───● ● ● ●───● ● ● . . .
● ● ●───● ● ● ●───● . . .
●───● ● ● ●───● ● ● . . .
... |
def delete(self, task, params={}, **options):
"""A specific, existing task can be deleted by making a DELETE request on the
URL for that task. Deleted tasks go into the "trash" of the user making
the delete request. Tasks can be recovered from the trash within a period
of 30 days; after... | def function[delete, parameter[self, task, params]]:
constant[A specific, existing task can be deleted by making a DELETE request on the
URL for that task. Deleted tasks go into the "trash" of the user making
the delete request. Tasks can be recovered from the trash within a period
of 30... | keyword[def] identifier[delete] ( identifier[self] , identifier[task] , identifier[params] ={},** identifier[options] ):
literal[string]
identifier[path] = literal[string] %( identifier[task] )
keyword[return] identifier[self] . identifier[client] . identifier[delete] ( identifier[path] ,... | def delete(self, task, params={}, **options):
"""A specific, existing task can be deleted by making a DELETE request on the
URL for that task. Deleted tasks go into the "trash" of the user making
the delete request. Tasks can be recovered from the trash within a period
of 30 days; afterward ... |
def handle_signature(self, sig, signode):
"""Parse the signature *sig* into individual nodes and append them to the
*signode*. If ValueError is raises, parsing is aborted and the whole
*sig* string is put into a single desc_name node.
The return value is the value that identifies the ob... | def function[handle_signature, parameter[self, sig, signode]]:
constant[Parse the signature *sig* into individual nodes and append them to the
*signode*. If ValueError is raises, parsing is aborted and the whole
*sig* string is put into a single desc_name node.
The return value is the v... | keyword[def] identifier[handle_signature] ( identifier[self] , identifier[sig] , identifier[signode] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_attr_like] ():
identifier[sig_match] = identifier[chpl_attr_sig_pattern] . identifier[match] ( identifier[sig] )
... | def handle_signature(self, sig, signode):
"""Parse the signature *sig* into individual nodes and append them to the
*signode*. If ValueError is raises, parsing is aborted and the whole
*sig* string is put into a single desc_name node.
The return value is the value that identifies the object... |
def setTime(self, yy, mm, dd, hh, minutes, ss, password="00000000"):
""" Serial set time with day of week calculation.
Args:
yy (int): Last two digits of year.
mm (int): Month 1-12.
dd (int): Day 1-31
hh (int): Hour 0 to 23.
minutes (int): Min... | def function[setTime, parameter[self, yy, mm, dd, hh, minutes, ss, password]]:
constant[ Serial set time with day of week calculation.
Args:
yy (int): Last two digits of year.
mm (int): Month 1-12.
dd (int): Day 1-31
hh (int): Hour 0 to 23.
mi... | keyword[def] identifier[setTime] ( identifier[self] , identifier[yy] , identifier[mm] , identifier[dd] , identifier[hh] , identifier[minutes] , identifier[ss] , identifier[password] = literal[string] ):
literal[string]
identifier[result] = keyword[False]
identifier[self] . identifier[setC... | def setTime(self, yy, mm, dd, hh, minutes, ss, password='00000000'):
""" Serial set time with day of week calculation.
Args:
yy (int): Last two digits of year.
mm (int): Month 1-12.
dd (int): Day 1-31
hh (int): Hour 0 to 23.
minutes (int): Minutes... |
def localmax(x, axis=0):
"""Find local maxima in an array `x`.
An element `x[i]` is considered a local maximum if the following
conditions are met:
- `x[i] > x[i-1]`
- `x[i] >= x[i+1]`
Note that the first condition is strict, and that the first element
`x[0]` will never be considered as a... | def function[localmax, parameter[x, axis]]:
constant[Find local maxima in an array `x`.
An element `x[i]` is considered a local maximum if the following
conditions are met:
- `x[i] > x[i-1]`
- `x[i] >= x[i+1]`
Note that the first condition is strict, and that the first element
`x[0]` ... | keyword[def] identifier[localmax] ( identifier[x] , identifier[axis] = literal[int] ):
literal[string]
identifier[paddings] =[( literal[int] , literal[int] )]* identifier[x] . identifier[ndim]
identifier[paddings] [ identifier[axis] ]=( literal[int] , literal[int] )
identifier[x_pad] = identif... | def localmax(x, axis=0):
"""Find local maxima in an array `x`.
An element `x[i]` is considered a local maximum if the following
conditions are met:
- `x[i] > x[i-1]`
- `x[i] >= x[i+1]`
Note that the first condition is strict, and that the first element
`x[0]` will never be considered as a... |
def write(self,
container: Container,
filepath: str,
contents: str
) -> str:
"""
Reads the contents of a given file belonging to a container.
"""
logger.debug("writing to file [%s] inside container [%s]",
filepa... | def function[write, parameter[self, container, filepath, contents]]:
constant[
Reads the contents of a given file belonging to a container.
]
call[name[logger].debug, parameter[constant[writing to file [%s] inside container [%s]], name[filepath], name[container].id]]
variable[fil... | keyword[def] identifier[write] ( identifier[self] ,
identifier[container] : identifier[Container] ,
identifier[filepath] : identifier[str] ,
identifier[contents] : identifier[str]
)-> identifier[str] :
literal[string]
identifier[logger] . identifier[debug] ( literal[string] ,
identifie... | def write(self, container: Container, filepath: str, contents: str) -> str:
"""
Reads the contents of a given file belonging to a container.
"""
logger.debug('writing to file [%s] inside container [%s]', filepath, container.id)
filepath = self._resolve_path(container, filepath)
# write t... |
def _remove_old_stderr_files(self):
"""
Remove stderr files left by previous Spyder instances.
This is only required on Windows because we can't
clean up stderr files while Spyder is running on it.
"""
if os.name == 'nt':
tmpdir = get_temp_dir()
... | def function[_remove_old_stderr_files, parameter[self]]:
constant[
Remove stderr files left by previous Spyder instances.
This is only required on Windows because we can't
clean up stderr files while Spyder is running on it.
]
if compare[name[os].name equal[==] constant[... | keyword[def] identifier[_remove_old_stderr_files] ( identifier[self] ):
literal[string]
keyword[if] identifier[os] . identifier[name] == literal[string] :
identifier[tmpdir] = identifier[get_temp_dir] ()
keyword[for] identifier[fname] keyword[in] identifier[os] . i... | def _remove_old_stderr_files(self):
"""
Remove stderr files left by previous Spyder instances.
This is only required on Windows because we can't
clean up stderr files while Spyder is running on it.
"""
if os.name == 'nt':
tmpdir = get_temp_dir()
for fname in os.l... |
def stop_recording_skipped(cls):
"""
Stop collecting OptionErrors recorded with the
record_skipped_option method and return them
"""
if cls._errors_recorded is None:
raise Exception('Cannot stop recording before it is started')
recorded = cls._errors_recorded[... | def function[stop_recording_skipped, parameter[cls]]:
constant[
Stop collecting OptionErrors recorded with the
record_skipped_option method and return them
]
if compare[name[cls]._errors_recorded is constant[None]] begin[:]
<ast.Raise object at 0x7da1b2347400>
var... | keyword[def] identifier[stop_recording_skipped] ( identifier[cls] ):
literal[string]
keyword[if] identifier[cls] . identifier[_errors_recorded] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
identifier[recorded] = identifier[cls] . ide... | def stop_recording_skipped(cls):
"""
Stop collecting OptionErrors recorded with the
record_skipped_option method and return them
"""
if cls._errors_recorded is None:
raise Exception('Cannot stop recording before it is started') # depends on [control=['if'], data=[]]
recorded... |
def tupled_argmax(a):
"""
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-di... | def function[tupled_argmax, parameter[a]]:
constant[
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple ... | keyword[def] identifier[tupled_argmax] ( identifier[a] ):
literal[string]
keyword[return] identifier[np] . identifier[unravel_index] ( identifier[np] . identifier[argmax] ( identifier[a] ), identifier[np] . identifier[shape] ( identifier[a] )) | def tupled_argmax(a):
"""
Argmax that returns an index tuple. Note that `numpy.argmax` will return a
scalar index as if you had flattened the array.
Parameters
----------
a : array_like
Input array.
Returns
-------
index : tuple
Tuple of index, even if `a` is one-di... |
def summarize_methdods_and_functions(api_modules, out_dir,
printlog=False, clean=True,
str_above_header=''):
"""Generates subpacke-level summary files.
Description
-----------
A function to generate subpacke-level summary markdow... | def function[summarize_methdods_and_functions, parameter[api_modules, out_dir, printlog, clean, str_above_header]]:
constant[Generates subpacke-level summary files.
Description
-----------
A function to generate subpacke-level summary markdown API files from
a module-level API documentation pre... | keyword[def] identifier[summarize_methdods_and_functions] ( identifier[api_modules] , identifier[out_dir] ,
identifier[printlog] = keyword[False] , identifier[clean] = keyword[True] ,
identifier[str_above_header] = literal[string] ):
literal[string]
keyword[if] identifier[printlog] :
identifier... | def summarize_methdods_and_functions(api_modules, out_dir, printlog=False, clean=True, str_above_header=''):
"""Generates subpacke-level summary files.
Description
-----------
A function to generate subpacke-level summary markdown API files from
a module-level API documentation previously created v... |
def list_teams(profile="github", ignore_cache=False):
'''
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mymini... | def function[list_teams, parameter[profile, ignore_cache]]:
constant[
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
... | keyword[def] identifier[list_teams] ( identifier[profile] = literal[string] , identifier[ignore_cache] = keyword[False] ):
literal[string]
identifier[key] = literal[string] . identifier[format] (
identifier[_get_config_value] ( identifier[profile] , literal[string] )
)
keyword[if] identifie... | def list_teams(profile='github', ignore_cache=False):
"""
Lists all teams with the organization.
profile
The name of the profile configuration to use. Defaults to ``github``.
ignore_cache
Bypasses the use of cached teams.
CLI Example:
.. code-block:: bash
salt mymini... |
def format_index(prefix, timestamp, sep='-'):
"""
:type prefix str
:type timestamp int
:type sep str
:rtype: str
"""
tz_info = tz.tzutc()
# ex. logstash-other-2017.05.09
return "{prefix}{sep}{date}".format(
prefix=prefix, sep=sep, date... | def function[format_index, parameter[prefix, timestamp, sep]]:
constant[
:type prefix str
:type timestamp int
:type sep str
:rtype: str
]
variable[tz_info] assign[=] call[name[tz].tzutc, parameter[]]
return[call[constant[{prefix}{sep}{date}].format, parameter[... | keyword[def] identifier[format_index] ( identifier[prefix] , identifier[timestamp] , identifier[sep] = literal[string] ):
literal[string]
identifier[tz_info] = identifier[tz] . identifier[tzutc] ()
keyword[return] literal[string] . identifier[format] (
identifier[prefix... | def format_index(prefix, timestamp, sep='-'):
"""
:type prefix str
:type timestamp int
:type sep str
:rtype: str
"""
tz_info = tz.tzutc()
# ex. logstash-other-2017.05.09
return '{prefix}{sep}{date}'.format(prefix=prefix, sep=sep, date=datetime.fromtimestamp(timest... |
def time_segments_average(X, interval, time_column):
"""Compute average of values over fixed length time segments."""
warnings.warn(_TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING, DeprecationWarning)
if isinstance(X, np.ndarray):
X = pd.DataFrame(X)
X = X.sort_values(time_column).set_index(time_co... | def function[time_segments_average, parameter[X, interval, time_column]]:
constant[Compute average of values over fixed length time segments.]
call[name[warnings].warn, parameter[name[_TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING], name[DeprecationWarning]]]
if call[name[isinstance], parameter[name... | keyword[def] identifier[time_segments_average] ( identifier[X] , identifier[interval] , identifier[time_column] ):
literal[string]
identifier[warnings] . identifier[warn] ( identifier[_TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING] , identifier[DeprecationWarning] )
keyword[if] identifier[isinstance] ( ... | def time_segments_average(X, interval, time_column):
"""Compute average of values over fixed length time segments."""
warnings.warn(_TIME_SEGMENTS_AVERAGE_DEPRECATION_WARNING, DeprecationWarning)
if isinstance(X, np.ndarray):
X = pd.DataFrame(X) # depends on [control=['if'], data=[]]
X = X.sort... |
def read_mm_uic3(fd, byte_order, dtype, count):
"""Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order+'I', 2*count)
return {'wavelengths': t[0::2] // t[1::2]} | def function[read_mm_uic3, parameter[fd, byte_order, dtype, count]]:
constant[Read MM_UIC3 tag from file and return as dictionary.]
variable[t] assign[=] call[name[numpy].fromfile, parameter[name[fd], binary_operation[name[byte_order] + constant[I]], binary_operation[constant[2] * name[count]]]]
ret... | keyword[def] identifier[read_mm_uic3] ( identifier[fd] , identifier[byte_order] , identifier[dtype] , identifier[count] ):
literal[string]
identifier[t] = identifier[numpy] . identifier[fromfile] ( identifier[fd] , identifier[byte_order] + literal[string] , literal[int] * identifier[count] )
keyword[r... | def read_mm_uic3(fd, byte_order, dtype, count):
"""Read MM_UIC3 tag from file and return as dictionary."""
t = numpy.fromfile(fd, byte_order + 'I', 2 * count)
return {'wavelengths': t[0::2] // t[1::2]} |
def get_acquisition_options(self, item_id, installation_target, test_commerce=None, is_free_or_trial_install=None):
"""GetAcquisitionOptions.
[Preview API]
:param str item_id:
:param str installation_target:
:param bool test_commerce:
:param bool is_free_or_trial_install:... | def function[get_acquisition_options, parameter[self, item_id, installation_target, test_commerce, is_free_or_trial_install]]:
constant[GetAcquisitionOptions.
[Preview API]
:param str item_id:
:param str installation_target:
:param bool test_commerce:
:param bool is_free_... | keyword[def] identifier[get_acquisition_options] ( identifier[self] , identifier[item_id] , identifier[installation_target] , identifier[test_commerce] = keyword[None] , identifier[is_free_or_trial_install] = keyword[None] ):
literal[string]
identifier[route_values] ={}
keyword[if] identi... | def get_acquisition_options(self, item_id, installation_target, test_commerce=None, is_free_or_trial_install=None):
"""GetAcquisitionOptions.
[Preview API]
:param str item_id:
:param str installation_target:
:param bool test_commerce:
:param bool is_free_or_trial_install:
... |
def parse_public(data):
"""
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certificate.
:param data:
A... | def function[parse_public, parameter[data]]:
constant[
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certifica... | keyword[def] identifier[parse_public] ( identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[data] , identifier[byte_cls] ):
keyword[raise] identifier[TypeError] ( identifier[pretty_message] (
literal[string] ,
identifier[type_name]... | def parse_public(data):
"""
Loads a public key from a DER or PEM-formatted file. Supports RSA, DSA and
EC public keys. For RSA keys, both the old RSAPublicKey and
SubjectPublicKeyInfo structures are supported. Also allows extracting a
public key from an X.509 certificate.
:param data:
A... |
def get_name(self):
"""Get the host name.
Try several attributes before returning UNNAMED*
:return: The name of the host
:rtype: str
"""
if not self.is_tpl():
try:
return self.host_name
except AttributeError: # outch, no hostname
... | def function[get_name, parameter[self]]:
constant[Get the host name.
Try several attributes before returning UNNAMED*
:return: The name of the host
:rtype: str
]
if <ast.UnaryOp object at 0x7da20c7c9960> begin[:]
<ast.Try object at 0x7da20c7cbac0> | keyword[def] identifier[get_name] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_tpl] ():
keyword[try] :
keyword[return] identifier[self] . identifier[host_name]
keyword[except] identifier[AttributeErro... | def get_name(self):
"""Get the host name.
Try several attributes before returning UNNAMED*
:return: The name of the host
:rtype: str
"""
if not self.is_tpl():
try:
return self.host_name # depends on [control=['try'], data=[]]
except AttributeError: ... |
def connect(self, sinks):
"""! @brief Connect one or more downstream trace sinks.
@param self
@param sinks If this parameter is a single object, it will be added to the list of
downstream trace event sinks. If it is an iterable (list, tuple, etc.), then it will
compl... | def function[connect, parameter[self, sinks]]:
constant[! @brief Connect one or more downstream trace sinks.
@param self
@param sinks If this parameter is a single object, it will be added to the list of
downstream trace event sinks. If it is an iterable (list, tuple, etc.), t... | keyword[def] identifier[connect] ( identifier[self] , identifier[sinks] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[sinks] , identifier[collections] . identifier[Iterable] ):
identifier[self] . identifier[_sinks] = identifier[sinks]
keyword[elif] iden... | def connect(self, sinks):
"""! @brief Connect one or more downstream trace sinks.
@param self
@param sinks If this parameter is a single object, it will be added to the list of
downstream trace event sinks. If it is an iterable (list, tuple, etc.), then it will
completel... |
def extra_downloader_converter(value):
"""Parses extra_{downloader,converter} arguments.
Parameters
----------
value : iterable or str
If the value is a string, it is split into a list using spaces
as delimiters. Otherwise, it is returned as is.
"""
if isinstance(value, six.str... | def function[extra_downloader_converter, parameter[value]]:
constant[Parses extra_{downloader,converter} arguments.
Parameters
----------
value : iterable or str
If the value is a string, it is split into a list using spaces
as delimiters. Otherwise, it is returned as is.
]
... | keyword[def] identifier[extra_downloader_converter] ( identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[six] . identifier[string_types] ):
identifier[value] = identifier[value] . identifier[split] ( literal[string] )
keyword[return] ide... | def extra_downloader_converter(value):
"""Parses extra_{downloader,converter} arguments.
Parameters
----------
value : iterable or str
If the value is a string, it is split into a list using spaces
as delimiters. Otherwise, it is returned as is.
"""
if isinstance(value, six.str... |
def copy_abs(self):
""" Return a copy of self with the sign bit unset.
Unlike abs(self), this does not make use of the context: the result
has the same precision as the original.
"""
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
... | def function[copy_abs, parameter[self]]:
constant[ Return a copy of self with the sign bit unset.
Unlike abs(self), this does not make use of the context: the result
has the same precision as the original.
]
variable[result] assign[=] call[name[mpfr].Mpfr_t.__new__, parameter[n... | keyword[def] identifier[copy_abs] ( identifier[self] ):
literal[string]
identifier[result] = identifier[mpfr] . identifier[Mpfr_t] . identifier[__new__] ( identifier[BigFloat] )
identifier[mpfr] . identifier[mpfr_init2] ( identifier[result] , identifier[self] . identifier[precision] )
... | def copy_abs(self):
""" Return a copy of self with the sign bit unset.
Unlike abs(self), this does not make use of the context: the result
has the same precision as the original.
"""
result = mpfr.Mpfr_t.__new__(BigFloat)
mpfr.mpfr_init2(result, self.precision)
mpfr.mpfr_setsig... |
def best_match(self, req, working_set, installer=None):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitabl... | def function[best_match, parameter[self, req, working_set, installer]]:
constant[Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConf... | keyword[def] identifier[best_match] ( identifier[self] , identifier[req] , identifier[working_set] , identifier[installer] = keyword[None] ):
literal[string]
identifier[dist] = identifier[working_set] . identifier[find] ( identifier[req] )
keyword[if] identifier[dist] keyword[is] keywor... | def best_match(self, req, working_set, installer=None):
"""Find distribution best matching `req` and usable on `working_set`
This calls the ``find(req)`` method of the `working_set` to see if a
suitable distribution is already active. (This may raise
``VersionConflict`` if an unsuitable ve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.