code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible com... | def function[attr_matches, parameter[self, text]]:
constant[Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are u... | keyword[def] identifier[attr_matches] ( identifier[self] , identifier[text] ):
literal[string]
keyword[import] identifier[re]
identifier[m] = identifier[re] . identifier[match] ( literal[string] , identifier[text] )
keyword[if] keyword[not] identifier[m] :
... | def attr_matches(self, text):
"""Compute matches when text contains a dot.
Assuming the text is of the form NAME.NAME....[NAME], and is
evaluatable in self.namespace or self.global_namespace, it will be
evaluated and its attributes (as revealed by dir()) are used as
possible complet... |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... | def function[_R2deriv, parameter[self, R, z, phi, t]]:
constant[
NAME:
_Rforce
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
... | keyword[def] identifier[_R2deriv] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_denom] ( identifier[R] , identifier[z] )**- literal[int] - literal[int] * identifie... | def _R2deriv(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_Rforce
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... |
def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
'''
Batch request version of get_blocks_overview
'''
for block_representation in block_representation_list:
assert is_valid_block_representation(
block_representation=block_repres... | def function[get_blocks_overview, parameter[block_representation_list, coin_symbol, txn_limit, api_key]]:
constant[
Batch request version of get_blocks_overview
]
for taget[name[block_representation]] in starred[name[block_representation_list]] begin[:]
assert[call[name[is_valid_block_re... | keyword[def] identifier[get_blocks_overview] ( identifier[block_representation_list] , identifier[coin_symbol] = literal[string] , identifier[txn_limit] = keyword[None] , identifier[api_key] = keyword[None] ):
literal[string]
keyword[for] identifier[block_representation] keyword[in] identifier[block_rep... | def get_blocks_overview(block_representation_list, coin_symbol='btc', txn_limit=None, api_key=None):
"""
Batch request version of get_blocks_overview
"""
for block_representation in block_representation_list:
assert is_valid_block_representation(block_representation=block_representation, coin_sy... |
def red_get_mount_connectors(red_data, ignore_outputs):
"""
Returns a list of mounting connectors
:param red_data: The red data to be searched
:param ignore_outputs: If outputs should be ignored
:return: A list of connectors with active mount option.
"""
keys = []
batches = red_data.g... | def function[red_get_mount_connectors, parameter[red_data, ignore_outputs]]:
constant[
Returns a list of mounting connectors
:param red_data: The red data to be searched
:param ignore_outputs: If outputs should be ignored
:return: A list of connectors with active mount option.
]
var... | keyword[def] identifier[red_get_mount_connectors] ( identifier[red_data] , identifier[ignore_outputs] ):
literal[string]
identifier[keys] =[]
identifier[batches] = identifier[red_data] . identifier[get] ( literal[string] )
identifier[inputs] = identifier[red_data] . identifier[get] ( literal[st... | def red_get_mount_connectors(red_data, ignore_outputs):
"""
Returns a list of mounting connectors
:param red_data: The red data to be searched
:param ignore_outputs: If outputs should be ignored
:return: A list of connectors with active mount option.
"""
keys = []
batches = red_data.get... |
def splitext(self):
""" p.splitext() -> Return (p.stripext(), p.ext).
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from '.' to the end of the
last path segment. This has the property that if
... | def function[splitext, parameter[self]]:
constant[ p.splitext() -> Return (p.stripext(), p.ext).
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from '.' to the end of the
last path segment. This has ... | keyword[def] identifier[splitext] ( identifier[self] ):
literal[string]
identifier[filename] , identifier[ext] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[self] )
keyword[return] identifier[self] . identifier[__class__] ( identifier[filename] ), identifier[ext]... | def splitext(self):
""" p.splitext() -> Return (p.stripext(), p.ext).
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from '.' to the end of the
last path segment. This has the property that if
(a... |
def find_element(self, by, value, view_cls=None):
# type: (By, Any, View) -> View
"""
Find one element matching condition
:param by: Type of condition
:param value: Condition value
:param view_cls: Optional custom class to wrap returned elements
:return: Matching ... | def function[find_element, parameter[self, by, value, view_cls]]:
constant[
Find one element matching condition
:param by: Type of condition
:param value: Condition value
:param view_cls: Optional custom class to wrap returned elements
:return: Matching element wrapped in... | keyword[def] identifier[find_element] ( identifier[self] , identifier[by] , identifier[value] , identifier[view_cls] = keyword[None] ):
literal[string]
keyword[if] identifier[view_cls] keyword[is] keyword[None] :
identifier[view_cls] = identifier[View]
keyword[return] i... | def find_element(self, by, value, view_cls=None):
# type: (By, Any, View) -> View
'\n Find one element matching condition\n :param by: Type of condition\n :param value: Condition value\n :param view_cls: Optional custom class to wrap returned elements\n :return: Matching eleme... |
def cycle_file(source_plaintext_filename):
"""Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt
"""
# Create a static random master key provider
key_id = os.urandom(8)
master_key_provider = StaticRandom... | def function[cycle_file, parameter[source_plaintext_filename]]:
constant[Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt
]
variable[key_id] assign[=] call[name[os].urandom, parameter[constant[8]]]
... | keyword[def] identifier[cycle_file] ( identifier[source_plaintext_filename] ):
literal[string]
identifier[key_id] = identifier[os] . identifier[urandom] ( literal[int] )
identifier[master_key_provider] = identifier[StaticRandomMasterKeyProvider] ()
identifier[master_key_provider] . identifie... | def cycle_file(source_plaintext_filename):
"""Encrypts and then decrypts a file under a custom static master key provider.
:param str source_plaintext_filename: Filename of file to encrypt
"""
# Create a static random master key provider
key_id = os.urandom(8)
master_key_provider = StaticRandom... |
def readLocationElement(self, locationElement):
""" Format 0 location reader """
loc = Location()
for dimensionElement in locationElement.findall(".dimension"):
dimName = dimensionElement.attrib.get("name")
xValue = yValue = None
try:
xValue = ... | def function[readLocationElement, parameter[self, locationElement]]:
constant[ Format 0 location reader ]
variable[loc] assign[=] call[name[Location], parameter[]]
for taget[name[dimensionElement]] in starred[call[name[locationElement].findall, parameter[constant[.dimension]]]] begin[:]
... | keyword[def] identifier[readLocationElement] ( identifier[self] , identifier[locationElement] ):
literal[string]
identifier[loc] = identifier[Location] ()
keyword[for] identifier[dimensionElement] keyword[in] identifier[locationElement] . identifier[findall] ( literal[string] ):
... | def readLocationElement(self, locationElement):
""" Format 0 location reader """
loc = Location()
for dimensionElement in locationElement.findall('.dimension'):
dimName = dimensionElement.attrib.get('name')
xValue = yValue = None
try:
xValue = dimensionElement.attrib.get(... |
def invalid_example_number(region_code):
"""Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
cou... | def function[invalid_example_number, parameter[region_code]]:
constant[Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed an... | keyword[def] identifier[invalid_example_number] ( identifier[region_code] ):
literal[string]
keyword[if] keyword[not] identifier[_is_valid_region_code] ( identifier[region_code] ):
keyword[return] keyword[None]
identifier[metadata] = identifier... | def invalid_example_number(region_code):
"""Gets an invalid number for the specified region.
This is useful for unit-testing purposes, where you want to test what
will happen with an invalid number. Note that the number that is
returned will always be able to be parsed and will have the correct
cou... |
def download_file(self, file_path, range=None):
"""
Download a file from Telegram servers
"""
headers = {"range": range} if range else None
url = "{0}/file/bot{1}/{2}".format(API_URL, self.api_token, file_path)
return self.session.get(
url, headers=headers, pr... | def function[download_file, parameter[self, file_path, range]]:
constant[
Download a file from Telegram servers
]
variable[headers] assign[=] <ast.IfExp object at 0x7da18fe92290>
variable[url] assign[=] call[constant[{0}/file/bot{1}/{2}].format, parameter[name[API_URL], name[self... | keyword[def] identifier[download_file] ( identifier[self] , identifier[file_path] , identifier[range] = keyword[None] ):
literal[string]
identifier[headers] ={ literal[string] : identifier[range] } keyword[if] identifier[range] keyword[else] keyword[None]
identifier[url] = literal[stri... | def download_file(self, file_path, range=None):
"""
Download a file from Telegram servers
"""
headers = {'range': range} if range else None
url = '{0}/file/bot{1}/{2}'.format(API_URL, self.api_token, file_path)
return self.session.get(url, headers=headers, proxy=self.proxy, proxy_auth=se... |
def replace_variable(self, variable):
"""Substitute variables with numeric values"""
if variable == 'x':
return self.value
if variable == 't':
return self.timedelta
raise ValueError("Invalid variable %s", variable) | def function[replace_variable, parameter[self, variable]]:
constant[Substitute variables with numeric values]
if compare[name[variable] equal[==] constant[x]] begin[:]
return[name[self].value]
if compare[name[variable] equal[==] constant[t]] begin[:]
return[name[self].timedelta]
... | keyword[def] identifier[replace_variable] ( identifier[self] , identifier[variable] ):
literal[string]
keyword[if] identifier[variable] == literal[string] :
keyword[return] identifier[self] . identifier[value]
keyword[if] identifier[variable] == literal[string] :
... | def replace_variable(self, variable):
"""Substitute variables with numeric values"""
if variable == 'x':
return self.value # depends on [control=['if'], data=[]]
if variable == 't':
return self.timedelta # depends on [control=['if'], data=[]]
raise ValueError('Invalid variable %s', var... |
def resolve_operator(name):
"""
Get the :namedtuple:`wily.operators.Operator` for a given name.
:param name: The name of the operator
:return: The operator type
"""
if name.lower() in ALL_OPERATORS:
return ALL_OPERATORS[name.lower()]
else:
raise ValueError(f"Operator {name} ... | def function[resolve_operator, parameter[name]]:
constant[
Get the :namedtuple:`wily.operators.Operator` for a given name.
:param name: The name of the operator
:return: The operator type
]
if compare[call[name[name].lower, parameter[]] in name[ALL_OPERATORS]] begin[:]
return[ca... | keyword[def] identifier[resolve_operator] ( identifier[name] ):
literal[string]
keyword[if] identifier[name] . identifier[lower] () keyword[in] identifier[ALL_OPERATORS] :
keyword[return] identifier[ALL_OPERATORS] [ identifier[name] . identifier[lower] ()]
keyword[else] :
keyword[... | def resolve_operator(name):
"""
Get the :namedtuple:`wily.operators.Operator` for a given name.
:param name: The name of the operator
:return: The operator type
"""
if name.lower() in ALL_OPERATORS:
return ALL_OPERATORS[name.lower()] # depends on [control=['if'], data=['ALL_OPERATORS']... |
def list_worktrees(cwd,
stale=False,
user=None,
password=None,
output_encoding=None,
**kwargs):
'''
.. versionadded:: 2015.8.0
Returns information on worktrees
.. versionchanged:: 2015.8.4
Version 2.... | def function[list_worktrees, parameter[cwd, stale, user, password, output_encoding]]:
constant[
.. versionadded:: 2015.8.0
Returns information on worktrees
.. versionchanged:: 2015.8.4
Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which
provides a lot of additio... | keyword[def] identifier[list_worktrees] ( identifier[cwd] ,
identifier[stale] = keyword[False] ,
identifier[user] = keyword[None] ,
identifier[password] = keyword[None] ,
identifier[output_encoding] = keyword[None] ,
** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[_check_... | def list_worktrees(cwd, stale=False, user=None, password=None, output_encoding=None, **kwargs):
"""
.. versionadded:: 2015.8.0
Returns information on worktrees
.. versionchanged:: 2015.8.4
Version 2.7.0 added the ``list`` subcommand to `git-worktree(1)`_ which
provides a lot of additio... |
def verify(self):
"""Checks all parameters for invalidating conditions
:returns: str -- message if error, 0 otherwise
"""
for row in range(self.nrows()):
result = self.verify_row(row)
if result != 0:
return result
return 0 | def function[verify, parameter[self]]:
constant[Checks all parameters for invalidating conditions
:returns: str -- message if error, 0 otherwise
]
for taget[name[row]] in starred[call[name[range], parameter[call[name[self].nrows, parameter[]]]]] begin[:]
variable[result]... | keyword[def] identifier[verify] ( identifier[self] ):
literal[string]
keyword[for] identifier[row] keyword[in] identifier[range] ( identifier[self] . identifier[nrows] ()):
identifier[result] = identifier[self] . identifier[verify_row] ( identifier[row] )
keyword[if] i... | def verify(self):
"""Checks all parameters for invalidating conditions
:returns: str -- message if error, 0 otherwise
"""
for row in range(self.nrows()):
result = self.verify_row(row)
if result != 0:
return result # depends on [control=['if'], data=['result']] # de... |
def vesting(ctx, account):
""" List accounts vesting balances
"""
account = Account(account, full=True)
t = [["vesting_id", "claimable"]]
for vest in account["vesting_balances"]:
vesting = Vesting(vest)
t.append([vesting["id"], str(vesting.claimable)])
print_table(t) | def function[vesting, parameter[ctx, account]]:
constant[ List accounts vesting balances
]
variable[account] assign[=] call[name[Account], parameter[name[account]]]
variable[t] assign[=] list[[<ast.List object at 0x7da20c76f6a0>]]
for taget[name[vest]] in starred[call[name[account]][... | keyword[def] identifier[vesting] ( identifier[ctx] , identifier[account] ):
literal[string]
identifier[account] = identifier[Account] ( identifier[account] , identifier[full] = keyword[True] )
identifier[t] =[[ literal[string] , literal[string] ]]
keyword[for] identifier[vest] keyword[in] iden... | def vesting(ctx, account):
""" List accounts vesting balances
"""
account = Account(account, full=True)
t = [['vesting_id', 'claimable']]
for vest in account['vesting_balances']:
vesting = Vesting(vest)
t.append([vesting['id'], str(vesting.claimable)]) # depends on [control=['for'],... |
def convert_number(string):
"""Convert a string to number
If int convert to int otherwise float
If not possible return None
"""
res = None
if isint(string):
res = int(string)
elif isfloat(string):
res = float(string)
return res | def function[convert_number, parameter[string]]:
constant[Convert a string to number
If int convert to int otherwise float
If not possible return None
]
variable[res] assign[=] constant[None]
if call[name[isint], parameter[name[string]]] begin[:]
variable[res] as... | keyword[def] identifier[convert_number] ( identifier[string] ):
literal[string]
identifier[res] = keyword[None]
keyword[if] identifier[isint] ( identifier[string] ):
identifier[res] = identifier[int] ( identifier[string] )
keyword[elif] identifier[isfloat] ( identifier[string] ):
... | def convert_number(string):
"""Convert a string to number
If int convert to int otherwise float
If not possible return None
"""
res = None
if isint(string):
res = int(string) # depends on [control=['if'], data=[]]
elif isfloat(string):
res = float(string) # depends on ... |
def _full_sub_array(data_obj, xj_path, create_dict_path):
"""Retrieves all array or dictionary elements for '*' JSON path marker.
:param dict|list data_obj: The current data object.
:param str xj_path: A json path.
:param bool create_dict_path create a dict path.
:return: tuple with two values: fir... | def function[_full_sub_array, parameter[data_obj, xj_path, create_dict_path]]:
constant[Retrieves all array or dictionary elements for '*' JSON path marker.
:param dict|list data_obj: The current data object.
:param str xj_path: A json path.
:param bool create_dict_path create a dict path.
:ret... | keyword[def] identifier[_full_sub_array] ( identifier[data_obj] , identifier[xj_path] , identifier[create_dict_path] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data_obj] , identifier[list] ):
keyword[if] identifier[xj_path] :
identifier[res] =[]
... | def _full_sub_array(data_obj, xj_path, create_dict_path):
"""Retrieves all array or dictionary elements for '*' JSON path marker.
:param dict|list data_obj: The current data object.
:param str xj_path: A json path.
:param bool create_dict_path create a dict path.
:return: tuple with two values: fir... |
def mousePressEvent(self, event):
"""Override Qt method
Select line, and starts selection
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
self._pressed = line_number
self._released = line_number
self.editor.select_lines(self._pressed,
... | def function[mousePressEvent, parameter[self, event]]:
constant[Override Qt method
Select line, and starts selection
]
variable[line_number] assign[=] call[name[self].editor.get_linenumber_from_mouse_event, parameter[name[event]]]
name[self]._pressed assign[=] name[line_number]
... | keyword[def] identifier[mousePressEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[line_number] = identifier[self] . identifier[editor] . identifier[get_linenumber_from_mouse_event] ( identifier[event] )
identifier[self] . identifier[_pressed] = identifier[line_n... | def mousePressEvent(self, event):
"""Override Qt method
Select line, and starts selection
"""
line_number = self.editor.get_linenumber_from_mouse_event(event)
self._pressed = line_number
self._released = line_number
self.editor.select_lines(self._pressed, self._released) |
def _make_tempy_tag(self, tag, attrs, void):
"""Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag."""
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknow... | def function[_make_tempy_tag, parameter[self, tag, attrs, void]]:
constant[Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag.]
variable[tempy_tag_cls] assign[=] call[name[getattr], parameter[name[self].tempy_tags, call[name[tag].ti... | keyword[def] identifier[_make_tempy_tag] ( identifier[self] , identifier[tag] , identifier[attrs] , identifier[void] ):
literal[string]
identifier[tempy_tag_cls] = identifier[getattr] ( identifier[self] . identifier[tempy_tags] , identifier[tag] . identifier[title] (), keyword[None] )
keyw... | def _make_tempy_tag(self, tag, attrs, void):
"""Searches in tempy.tags for the correct tag to use, if does not exists uses the TempyFactory to
create a custom tag."""
tempy_tag_cls = getattr(self.tempy_tags, tag.title(), None)
if not tempy_tag_cls:
unknow_maker = [self.unknown_tag_maker, sel... |
def _is_valid_endpoint(endpoint):
"""helper for interval_range to check if start/end are valid types"""
return any([is_number(endpoint),
isinstance(endpoint, Timestamp),
isinstance(endpoint, Timedelta),
endpoint is None]) | def function[_is_valid_endpoint, parameter[endpoint]]:
constant[helper for interval_range to check if start/end are valid types]
return[call[name[any], parameter[list[[<ast.Call object at 0x7da18ede6c80>, <ast.Call object at 0x7da18ede7760>, <ast.Call object at 0x7da18ede5630>, <ast.Compare object at 0x7da1... | keyword[def] identifier[_is_valid_endpoint] ( identifier[endpoint] ):
literal[string]
keyword[return] identifier[any] ([ identifier[is_number] ( identifier[endpoint] ),
identifier[isinstance] ( identifier[endpoint] , identifier[Timestamp] ),
identifier[isinstance] ( identifier[endpoint] , identi... | def _is_valid_endpoint(endpoint):
"""helper for interval_range to check if start/end are valid types"""
return any([is_number(endpoint), isinstance(endpoint, Timestamp), isinstance(endpoint, Timedelta), endpoint is None]) |
def initiate_tasks(self):
""" Loads all tasks using `TaskLoader` from respective configuration option """
self.tasks_classes = TaskLoader().load_tasks(
paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS]) | def function[initiate_tasks, parameter[self]]:
constant[ Loads all tasks using `TaskLoader` from respective configuration option ]
name[self].tasks_classes assign[=] call[call[name[TaskLoader], parameter[]].load_tasks, parameter[]] | keyword[def] identifier[initiate_tasks] ( identifier[self] ):
literal[string]
identifier[self] . identifier[tasks_classes] = identifier[TaskLoader] (). identifier[load_tasks] (
identifier[paths] = identifier[self] . identifier[configuration] [ identifier[Configuration] . identifier[ALGORIT... | def initiate_tasks(self):
""" Loads all tasks using `TaskLoader` from respective configuration option """
self.tasks_classes = TaskLoader().load_tasks(paths=self.configuration[Configuration.ALGORITHM][Configuration.TASKS][Configuration.PATHS]) |
def duration(self):
"""Duration of this series in seconds
:type: `~astropy.units.Quantity` scalar
"""
return units.Quantity(self.span[1] - self.span[0], self.xunit,
dtype=float) | def function[duration, parameter[self]]:
constant[Duration of this series in seconds
:type: `~astropy.units.Quantity` scalar
]
return[call[name[units].Quantity, parameter[binary_operation[call[name[self].span][constant[1]] - call[name[self].span][constant[0]]], name[self].xunit]]] | keyword[def] identifier[duration] ( identifier[self] ):
literal[string]
keyword[return] identifier[units] . identifier[Quantity] ( identifier[self] . identifier[span] [ literal[int] ]- identifier[self] . identifier[span] [ literal[int] ], identifier[self] . identifier[xunit] ,
identifier[... | def duration(self):
"""Duration of this series in seconds
:type: `~astropy.units.Quantity` scalar
"""
return units.Quantity(self.span[1] - self.span[0], self.xunit, dtype=float) |
def order_results_by(*fields):
"""A decorator that applies an ordering to the QuerySet returned by a
function.
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kw):
result = f(*args, **kw)
return result.order_by(*fields)
return wrapper
... | def function[order_results_by, parameter[]]:
constant[A decorator that applies an ordering to the QuerySet returned by a
function.
]
def function[decorator, parameter[f]]:
def function[wrapper, parameter[]]:
variable[result] assign[=] call[name[f], p... | keyword[def] identifier[order_results_by] (* identifier[fields] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
@ identifier[functools] . identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kw] ):
i... | def order_results_by(*fields):
"""A decorator that applies an ordering to the QuerySet returned by a
function.
"""
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kw):
result = f(*args, **kw)
return result.order_by(*fields)
return wrappe... |
def process_configs(file_lookup, app_config_format, pipeline_config):
"""Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pi... | def function[process_configs, parameter[file_lookup, app_config_format, pipeline_config]]:
constant[Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_co... | keyword[def] identifier[process_configs] ( identifier[file_lookup] , identifier[app_config_format] , identifier[pipeline_config] ):
literal[string]
identifier[app_configs] = identifier[collections] . identifier[defaultdict] ( identifier[dict] )
keyword[for] identifier[env] keyword[in] identifier[EN... | def process_configs(file_lookup, app_config_format, pipeline_config):
"""Processes the configs from lookup sources.
Args:
file_lookup (FileLookup): Source to look for file/config
app_config_format (str): The format for application config files.
pipeline_config (str): Name/path of the pi... |
def bin_hash160Bytes(bts):
"""
Get a hash of the provided message using the ripemd160 algorithm.
Args:
bts (str): message to hash.
Returns:
bytes: hash.
"""
intermed = hashlib.sha256(bts).digest()
return hashlib.new('ripemd160', intermed).digest() | def function[bin_hash160Bytes, parameter[bts]]:
constant[
Get a hash of the provided message using the ripemd160 algorithm.
Args:
bts (str): message to hash.
Returns:
bytes: hash.
]
variable[intermed] assign[=] call[call[name[hashlib].sha256, parameter[name[bts]]].diges... | keyword[def] identifier[bin_hash160Bytes] ( identifier[bts] ):
literal[string]
identifier[intermed] = identifier[hashlib] . identifier[sha256] ( identifier[bts] ). identifier[digest] ()
keyword[return] identifier[hashlib] . identifier[new] ( literal[string] , identifier[intermed] ). identifier[digest... | def bin_hash160Bytes(bts):
"""
Get a hash of the provided message using the ripemd160 algorithm.
Args:
bts (str): message to hash.
Returns:
bytes: hash.
"""
intermed = hashlib.sha256(bts).digest()
return hashlib.new('ripemd160', intermed).digest() |
def index(self, solr, collection, threads=1, send_method='stream_file', **kwargs):
'''
Will index the queue into a specified solr instance and collection. Specify multiple threads to make this faster, however keep in mind that if you specify multiple threads the items may not be in order.
Exampl... | def function[index, parameter[self, solr, collection, threads, send_method]]:
constant[
Will index the queue into a specified solr instance and collection. Specify multiple threads to make this faster, however keep in mind that if you specify multiple threads the items may not be in order.
Examp... | keyword[def] identifier[index] ( identifier[self] , identifier[solr] , identifier[collection] , identifier[threads] = literal[int] , identifier[send_method] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[method] = identifier[getattr] ( identifier... | def index(self, solr, collection, threads=1, send_method='stream_file', **kwargs):
"""
Will index the queue into a specified solr instance and collection. Specify multiple threads to make this faster, however keep in mind that if you specify multiple threads the items may not be in order.
Example::
... |
def validate_capacity(self, servers):
"""Validates if a deploy can be fulfilled.
"""
try:
return self.manager.validate_capacity(servers)
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) | def function[validate_capacity, parameter[self, servers]]:
constant[Validates if a deploy can be fulfilled.
]
<ast.Try object at 0x7da1b13abf10> | keyword[def] identifier[validate_capacity] ( identifier[self] , identifier[servers] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[manager] . identifier[validate_capacity] ( identifier[servers] )
keyword[except] identifier[packet] . identifie... | def validate_capacity(self, servers):
"""Validates if a deploy can be fulfilled.
"""
try:
return self.manager.validate_capacity(servers) # depends on [control=['try'], data=[]]
except packet.baseapi.Error as msg:
raise PacketManagerException(msg) # depends on [control=['except'], d... |
def append_child(self, name):
"""Append a child element with the specified name."""
return XMLElement(lib.lsl_append_child(self.e, str.encode(name))) | def function[append_child, parameter[self, name]]:
constant[Append a child element with the specified name.]
return[call[name[XMLElement], parameter[call[name[lib].lsl_append_child, parameter[name[self].e, call[name[str].encode, parameter[name[name]]]]]]]] | keyword[def] identifier[append_child] ( identifier[self] , identifier[name] ):
literal[string]
keyword[return] identifier[XMLElement] ( identifier[lib] . identifier[lsl_append_child] ( identifier[self] . identifier[e] , identifier[str] . identifier[encode] ( identifier[name] ))) | def append_child(self, name):
"""Append a child element with the specified name."""
return XMLElement(lib.lsl_append_child(self.e, str.encode(name))) |
def to_simple_model(self, instance, **options): # noqa
""" Convert model to simple python structure.
"""
options = self.init_options(**options)
fields, include, exclude, related = options['fields'], options['include'], options['exclude'], options['related'] # noqa
result = dict(... | def function[to_simple_model, parameter[self, instance]]:
constant[ Convert model to simple python structure.
]
variable[options] assign[=] call[name[self].init_options, parameter[]]
<ast.Tuple object at 0x7da18eb54880> assign[=] tuple[[<ast.Subscript object at 0x7da20e955ab0>, <ast.Subs... | keyword[def] identifier[to_simple_model] ( identifier[self] , identifier[instance] ,** identifier[options] ):
literal[string]
identifier[options] = identifier[self] . identifier[init_options] (** identifier[options] )
identifier[fields] , identifier[include] , identifier[exclude] , identif... | def to_simple_model(self, instance, **options): # noqa
' Convert model to simple python structure.\n '
options = self.init_options(**options)
(fields, include, exclude, related) = (options['fields'], options['include'], options['exclude'], options['related']) # noqa
result = dict(model=smart_un... |
def from_error(exc_info, json_encoder, debug_url=None):
"""Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_url: str | None
... | def function[from_error, parameter[exc_info, json_encoder, debug_url]]:
constant[Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_... | keyword[def] identifier[from_error] ( identifier[exc_info] , identifier[json_encoder] , identifier[debug_url] = keyword[None] ):
literal[string]
identifier[exc] = identifier[exc_info] [ literal[int] ]
identifier[data] = identifier[exc] . identifier[__dict__] . identifier[copy] ()
... | def from_error(exc_info, json_encoder, debug_url=None):
"""Wraps another Exception in an InternalError.
:param exc_info: The exception info for the wrapped exception
:type exc_info: (type, object, traceback)
:type json_encoder: json.JSONEncoder
:type debug_url: str | None
:r... |
def clear(self):
"""
removes all items from this manifest, and clears and removes all
sub-sections
"""
for sub in self.sub_sections.values():
sub.clear()
self.sub_sections.clear()
ManifestSection.clear(self) | def function[clear, parameter[self]]:
constant[
removes all items from this manifest, and clears and removes all
sub-sections
]
for taget[name[sub]] in starred[call[name[self].sub_sections.values, parameter[]]] begin[:]
call[name[sub].clear, parameter[]]
c... | keyword[def] identifier[clear] ( identifier[self] ):
literal[string]
keyword[for] identifier[sub] keyword[in] identifier[self] . identifier[sub_sections] . identifier[values] ():
identifier[sub] . identifier[clear] ()
identifier[self] . identifier[sub_sections] . identifie... | def clear(self):
"""
removes all items from this manifest, and clears and removes all
sub-sections
"""
for sub in self.sub_sections.values():
sub.clear() # depends on [control=['for'], data=['sub']]
self.sub_sections.clear()
ManifestSection.clear(self) |
def from_composition_and_entries(comp, entries_in_chemsys,
working_ion_symbol="Li"):
"""
Convenience constructor to make a ConversionElectrode from a
composition and all entries in a chemical system.
Args:
comp: Starting composition for C... | def function[from_composition_and_entries, parameter[comp, entries_in_chemsys, working_ion_symbol]]:
constant[
Convenience constructor to make a ConversionElectrode from a
composition and all entries in a chemical system.
Args:
comp: Starting composition for ConversionElectr... | keyword[def] identifier[from_composition_and_entries] ( identifier[comp] , identifier[entries_in_chemsys] ,
identifier[working_ion_symbol] = literal[string] ):
literal[string]
identifier[pd] = identifier[PhaseDiagram] ( identifier[entries_in_chemsys] )
keyword[return] identifier[Conversi... | def from_composition_and_entries(comp, entries_in_chemsys, working_ion_symbol='Li'):
"""
Convenience constructor to make a ConversionElectrode from a
composition and all entries in a chemical system.
Args:
comp: Starting composition for ConversionElectrode, e.g.,
... |
def authorizer(self, schemes, resource, action, request_args):
"""Construct the Authorization header for a request.
Args:
schemes (list of str): Authentication schemes supported for the
requested action.
resource (str): Object upon which an action is being performed.
... | def function[authorizer, parameter[self, schemes, resource, action, request_args]]:
constant[Construct the Authorization header for a request.
Args:
schemes (list of str): Authentication schemes supported for the
requested action.
resource (str): Object upon which an act... | keyword[def] identifier[authorizer] ( identifier[self] , identifier[schemes] , identifier[resource] , identifier[action] , identifier[request_args] ):
literal[string]
keyword[if] keyword[not] identifier[schemes] :
keyword[return] literal[string] , literal[string]
keyword[f... | def authorizer(self, schemes, resource, action, request_args):
"""Construct the Authorization header for a request.
Args:
schemes (list of str): Authentication schemes supported for the
requested action.
resource (str): Object upon which an action is being performed.
... |
def get_item_name(self, item, parent):
""" Returns the value of the first name element found inside of element """
names = self.get_name_elements(item)
if not names:
raise MissingNameElementError
name = names[0].text
prefix = self.item_name_prefix(parent)
if ... | def function[get_item_name, parameter[self, item, parent]]:
constant[ Returns the value of the first name element found inside of element ]
variable[names] assign[=] call[name[self].get_name_elements, parameter[name[item]]]
if <ast.UnaryOp object at 0x7da1b1507280> begin[:]
<ast.Raise ob... | keyword[def] identifier[get_item_name] ( identifier[self] , identifier[item] , identifier[parent] ):
literal[string]
identifier[names] = identifier[self] . identifier[get_name_elements] ( identifier[item] )
keyword[if] keyword[not] identifier[names] :
keyword[raise] identif... | def get_item_name(self, item, parent):
""" Returns the value of the first name element found inside of element """
names = self.get_name_elements(item)
if not names:
raise MissingNameElementError # depends on [control=['if'], data=[]]
name = names[0].text
prefix = self.item_name_prefix(pare... |
def install_table(self, connection, table, logger = None):
""" Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
"""
# first install all partitions of ... | def function[install_table, parameter[self, connection, table, logger]]:
constant[ Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
]
variable[queries... | keyword[def] identifier[install_table] ( identifier[self] , identifier[connection] , identifier[table] , identifier[logger] = keyword[None] ):
literal[string]
identifier[queries] =[]
identifier[query_tmpl] = literal[string]
keyword[for] identifier[partition] keyword[i... | def install_table(self, connection, table, logger=None):
""" Installs all partitons of the table and create view with union of all partitons.
Args:
connection: connection to database who stores mpr data.
table (orm.Table):
"""
# first install all partitions of the table
... |
def salsa20_8(B, x, src, s_start, dest, d_start):
"""Salsa20/8 http://en.wikipedia.org/wiki/Salsa20"""
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in xrange(4):
R(x, 4, 0,... | def function[salsa20_8, parameter[B, x, src, s_start, dest, d_start]]:
constant[Salsa20/8 http://en.wikipedia.org/wiki/Salsa20]
for taget[name[i]] in starred[call[name[xrange], parameter[constant[16]]]] begin[:]
call[name[x]][name[i]] assign[=] binary_operation[call[name[B]][name[i]] <as... | keyword[def] identifier[salsa20_8] ( identifier[B] , identifier[x] , identifier[src] , identifier[s_start] , identifier[dest] , identifier[d_start] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[xrange] ( literal[int] ):
identifier[x] [ identifier[i] ]= identifier[B]... | def salsa20_8(B, x, src, s_start, dest, d_start):
"""Salsa20/8 http://en.wikipedia.org/wiki/Salsa20"""
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i] # depends on [control=['for'], data=['i']]
# This is the actual Salsa 20/8: four identical double rounds
... |
def toDF(self, *cols):
"""Returns a new class:`DataFrame` that with new specified column names
:param cols: list of new column names (string)
>>> df.toDF('f1', 'f2').collect()
[Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]
"""
jdf = self._jdf.toDF(self._jseq(cols))
... | def function[toDF, parameter[self]]:
constant[Returns a new class:`DataFrame` that with new specified column names
:param cols: list of new column names (string)
>>> df.toDF('f1', 'f2').collect()
[Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]
]
variable[jdf] assign[=] c... | keyword[def] identifier[toDF] ( identifier[self] ,* identifier[cols] ):
literal[string]
identifier[jdf] = identifier[self] . identifier[_jdf] . identifier[toDF] ( identifier[self] . identifier[_jseq] ( identifier[cols] ))
keyword[return] identifier[DataFrame] ( identifier[jdf] , identifie... | def toDF(self, *cols):
"""Returns a new class:`DataFrame` that with new specified column names
:param cols: list of new column names (string)
>>> df.toDF('f1', 'f2').collect()
[Row(f1=2, f2=u'Alice'), Row(f1=5, f2=u'Bob')]
"""
jdf = self._jdf.toDF(self._jseq(cols))
return D... |
def get_incidents(self):
"""Get incidents."""
resp = requests.get(CRIME_URL, params=self._get_params(), headers=self.headers)
incidents = [] # type: List[Dict[str, str]]
data = resp.json()
if ATTR_CRIMES not in data:
return incidents
for incident in data.get(... | def function[get_incidents, parameter[self]]:
constant[Get incidents.]
variable[resp] assign[=] call[name[requests].get, parameter[name[CRIME_URL]]]
variable[incidents] assign[=] list[[]]
variable[data] assign[=] call[name[resp].json, parameter[]]
if compare[name[ATTR_CRIMES] <as... | keyword[def] identifier[get_incidents] ( identifier[self] ):
literal[string]
identifier[resp] = identifier[requests] . identifier[get] ( identifier[CRIME_URL] , identifier[params] = identifier[self] . identifier[_get_params] (), identifier[headers] = identifier[self] . identifier[headers] )
... | def get_incidents(self):
"""Get incidents."""
resp = requests.get(CRIME_URL, params=self._get_params(), headers=self.headers)
incidents = [] # type: List[Dict[str, str]]
data = resp.json()
if ATTR_CRIMES not in data:
return incidents # depends on [control=['if'], data=[]]
for incident ... |
def read_from_ndef_service(self, *blocks):
"""Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block numbers
to r... | def function[read_from_ndef_service, parameter[self]]:
constant[Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block nu... | keyword[def] identifier[read_from_ndef_service] ( identifier[self] ,* identifier[blocks] ):
literal[string]
keyword[if] identifier[self] . identifier[sys] == literal[int] :
identifier[sc_list] =[ identifier[ServiceCode] ( literal[int] , literal[int] )]
identifier[bc_list]... | def read_from_ndef_service(self, *blocks):
"""Read block data from an NDEF compatible tag.
This is a convinience method to read block data from a tag
that has system code 0x12FC (NDEF). For other tags this method
simply returns :const:`None`. All arguments are block numbers
to read.... |
def has_quantity(self, quantity, include_native=True):
"""
Check if *quantity* is available in this catalog
Parameters
----------
quantity : str
a quantity name to check
include_native : bool, optional
whether or not to include native quantity na... | def function[has_quantity, parameter[self, quantity, include_native]]:
constant[
Check if *quantity* is available in this catalog
Parameters
----------
quantity : str
a quantity name to check
include_native : bool, optional
whether or not to incl... | keyword[def] identifier[has_quantity] ( identifier[self] , identifier[quantity] , identifier[include_native] = keyword[True] ):
literal[string]
keyword[if] identifier[include_native] :
keyword[return] identifier[all] ( identifier[q] keyword[in] identifier[self] . identifier[_nativ... | def has_quantity(self, quantity, include_native=True):
"""
Check if *quantity* is available in this catalog
Parameters
----------
quantity : str
a quantity name to check
include_native : bool, optional
whether or not to include native quantity names ... |
def plot(self, event_names, x_axis='step'):
"""Plots a list of events. Each event (a dir+event_name) is represetented as a line
in the graph.
Args:
event_names: A list of events to plot. Each event_name may correspond to multiple events,
each in a different directory.
x_axis: whethe... | def function[plot, parameter[self, event_names, x_axis]]:
constant[Plots a list of events. Each event (a dir+event_name) is represetented as a line
in the graph.
Args:
event_names: A list of events to plot. Each event_name may correspond to multiple events,
each in a different directo... | keyword[def] identifier[plot] ( identifier[self] , identifier[event_names] , identifier[x_axis] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[event_names] , identifier[six] . identifier[string_types] ):
identifier[event_names] =[ identifier[event_names] ]
... | def plot(self, event_names, x_axis='step'):
"""Plots a list of events. Each event (a dir+event_name) is represetented as a line
in the graph.
Args:
event_names: A list of events to plot. Each event_name may correspond to multiple events,
each in a different directory.
x_axis: whethe... |
def port_profile_qos_profile_cee(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile")
name_key = ET.SubElement(port_profile, "name")
name_key.text ... | def function[port_profile_qos_profile_cee, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[port_profile] assign[=] call[name[ET].SubElement, parameter[name[config], constant[port-profile]]]
v... | keyword[def] identifier[port_profile_qos_profile_cee] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[port_profile] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal... | def port_profile_qos_profile_cee(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
port_profile = ET.SubElement(config, 'port-profile', xmlns='urn:brocade.com:mgmt:brocade-port-profile')
name_key = ET.SubElement(port_profile, 'name')
name_key.text = kwargs.pop('name')... |
def create_datastore_from_yaml_schema(self, yaml_path, delete_first=0,
path=None):
# type: (str, Optional[int], Optional[str]) -> None
"""For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file
containi... | def function[create_datastore_from_yaml_schema, parameter[self, yaml_path, delete_first, path]]:
constant[For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file
containing a list of fields and types of form {'id': 'FIELD', 'type': 'TYPE'} and optional... | keyword[def] identifier[create_datastore_from_yaml_schema] ( identifier[self] , identifier[yaml_path] , identifier[delete_first] = literal[int] ,
identifier[path] = keyword[None] ):
literal[string]
identifier[data] = identifier[load_yaml] ( identifier[yaml_path] )
identifier[self] . iden... | def create_datastore_from_yaml_schema(self, yaml_path, delete_first=0, path=None):
# type: (str, Optional[int], Optional[str]) -> None
"For tabular data, create a resource in the HDX datastore which enables data preview in HDX from a YAML file\n containing a list of fields and types of form {'id': 'FIELD... |
def _set_get_mpls_ldp_neighbor_brief(self, v, load=False):
"""
Setter method for get_mpls_ldp_neighbor_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_ldp_neighbor_brief (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mpls_ldp_neighbor_brief is cons... | def function[_set_get_mpls_ldp_neighbor_brief, parameter[self, v, load]]:
constant[
Setter method for get_mpls_ldp_neighbor_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_ldp_neighbor_brief (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mpls_l... | keyword[def] identifier[_set_get_mpls_ldp_neighbor_brief] ( 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[... | def _set_get_mpls_ldp_neighbor_brief(self, v, load=False):
"""
Setter method for get_mpls_ldp_neighbor_brief, mapped from YANG variable /brocade_mpls_rpc/get_mpls_ldp_neighbor_brief (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_mpls_ldp_neighbor_brief is cons... |
def keys(self):
"""
:returns: a list of usable keys
:rtype: list
"""
keys = list()
for attribute_name, type_instance in inspect.getmembers(self):
# ignore parameters with __ and if they are methods
if attribute_name.startswith('__') or inspect.... | def function[keys, parameter[self]]:
constant[
:returns: a list of usable keys
:rtype: list
]
variable[keys] assign[=] call[name[list], parameter[]]
for taget[tuple[[<ast.Name object at 0x7da1b0bf2740>, <ast.Name object at 0x7da1b0bf3430>]]] in starred[call[name[inspect]... | keyword[def] identifier[keys] ( identifier[self] ):
literal[string]
identifier[keys] = identifier[list] ()
keyword[for] identifier[attribute_name] , identifier[type_instance] keyword[in] identifier[inspect] . identifier[getmembers] ( identifier[self] ):
keyword[... | def keys(self):
"""
:returns: a list of usable keys
:rtype: list
"""
keys = list()
for (attribute_name, type_instance) in inspect.getmembers(self):
# ignore parameters with __ and if they are methods
if attribute_name.startswith('__') or inspect.ismethod(type_instanc... |
def get_random_voxels(dataset, n_voxels):
""" Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare
performance of a more principled feature selection method with simple
random selection.
Args:
dataset: A Dataset instance
... | def function[get_random_voxels, parameter[dataset, n_voxels]]:
constant[ Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare
performance of a more principled feature selection method with simple
random selection.
Args:
... | keyword[def] identifier[get_random_voxels] ( identifier[dataset] , identifier[n_voxels] ):
literal[string]
identifier[voxels] = identifier[np] . identifier[arange] ( identifier[dataset] . identifier[masker] . identifier[n_vox_in_vol] )
identifier[np] . identifier[random] . identifier[shuffle] ( identi... | def get_random_voxels(dataset, n_voxels):
""" Returns mappable data for a random subset of voxels.
May be useful as a baseline in predictive analyses--e.g., to compare
performance of a more principled feature selection method with simple
random selection.
Args:
dataset: A Dataset instance
... |
def kill_process(process):
"""Kill the process group associated with the given process. (posix)"""
logger = logging.getLogger('xenon')
logger.info('Terminating Xenon-GRPC server.')
os.kill(process.pid, signal.SIGINT)
process.wait() | def function[kill_process, parameter[process]]:
constant[Kill the process group associated with the given process. (posix)]
variable[logger] assign[=] call[name[logging].getLogger, parameter[constant[xenon]]]
call[name[logger].info, parameter[constant[Terminating Xenon-GRPC server.]]]
ca... | keyword[def] identifier[kill_process] ( identifier[process] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[os] . identifier[kill] ( identifier[process] . identifier[pid] ,... | def kill_process(process):
"""Kill the process group associated with the given process. (posix)"""
logger = logging.getLogger('xenon')
logger.info('Terminating Xenon-GRPC server.')
os.kill(process.pid, signal.SIGINT)
process.wait() |
def delete(self, list_id, segment_id):
"""
removes an existing list segment from the list. This cannot be undone.
"""
return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id)) | def function[delete, parameter[self, list_id, segment_id]]:
constant[
removes an existing list segment from the list. This cannot be undone.
]
return[call[name[self]._mc_client._delete, parameter[]]] | keyword[def] identifier[delete] ( identifier[self] , identifier[list_id] , identifier[segment_id] ):
literal[string]
keyword[return] identifier[self] . identifier[_mc_client] . identifier[_delete] ( identifier[url] = identifier[self] . identifier[_build_path] ( identifier[list_id] , literal[string... | def delete(self, list_id, segment_id):
"""
removes an existing list segment from the list. This cannot be undone.
"""
return self._mc_client._delete(url=self._build_path(list_id, 'segments', segment_id)) |
def namespace_match(pattern: str, namespace: str):
"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == '*' and namespace.endswith(patt... | def function[namespace_match, parameter[pattern, namespace]]:
constant[
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
]
if <ast.BoolOp object at ... | keyword[def] identifier[namespace_match] ( identifier[pattern] : identifier[str] , identifier[namespace] : identifier[str] ):
literal[string]
keyword[if] identifier[pattern] [ literal[int] ]== literal[string] keyword[and] identifier[namespace] . identifier[endswith] ( identifier[pattern] [ literal[int] ... | def namespace_match(pattern: str, namespace: str):
"""
Matches a namespace pattern against a namespace string. For example, ``*tags`` matches
``passage_tags`` and ``question_tags`` and ``tokens`` matches ``tokens`` but not
``stemmed_tokens``.
"""
if pattern[0] == '*' and namespace.endswith(patt... |
def data(self, c):
"""Send byte of data to display."""
if self._spi is not None:
# SPI write.
self._gpio.set_high(self._dc)
self._spi.write([c])
else:
# I2C write.
control = 0x40 # Co = 0, DC = 0
self._i2c.write8(control, ... | def function[data, parameter[self, c]]:
constant[Send byte of data to display.]
if compare[name[self]._spi is_not constant[None]] begin[:]
call[name[self]._gpio.set_high, parameter[name[self]._dc]]
call[name[self]._spi.write, parameter[list[[<ast.Name object at 0x7da1b1d3... | keyword[def] identifier[data] ( identifier[self] , identifier[c] ):
literal[string]
keyword[if] identifier[self] . identifier[_spi] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[_gpio] . identifier[set_high] ( identifier[self] . identifier[_dc] )
... | def data(self, c):
"""Send byte of data to display."""
if self._spi is not None:
# SPI write.
self._gpio.set_high(self._dc)
self._spi.write([c]) # depends on [control=['if'], data=[]]
else:
# I2C write.
control = 64 # Co = 0, DC = 0
self._i2c.write8(control,... |
def _extract_variable_parts(variable_key, variable):
"""Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: Name of the variable up to the pa... | def function[_extract_variable_parts, parameter[variable_key, variable]]:
constant[Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: ... | keyword[def] identifier[_extract_variable_parts] ( identifier[variable_key] , identifier[variable] ):
literal[string]
identifier[name] , identifier[offset] , identifier[partitioned] = keyword[None] , keyword[None] , keyword[False]
keyword[if] identifier[variable] . identifier[_save_slice_info] :
i... | def _extract_variable_parts(variable_key, variable):
"""Matches a variable to individual parts.
Args:
variable_key: String identifier of the variable in the module scope.
variable: Variable tensor.
Returns:
partitioned: Whether the variable is partitioned.
name: Name of the variable up to the ... |
def agg(self, aggregations):
"""Multiple aggregations optimized.
Parameters
----------
aggregations : list of str
Which aggregations to perform.
Returns
-------
Series
Series with resulting aggregations.
"""
check_type(ag... | def function[agg, parameter[self, aggregations]]:
constant[Multiple aggregations optimized.
Parameters
----------
aggregations : list of str
Which aggregations to perform.
Returns
-------
Series
Series with resulting aggregations.
... | keyword[def] identifier[agg] ( identifier[self] , identifier[aggregations] ):
literal[string]
identifier[check_type] ( identifier[aggregations] , identifier[list] )
identifier[new_index] = identifier[Index] ( identifier[np] . identifier[array] ( identifier[aggregations] , identifier[dtype... | def agg(self, aggregations):
"""Multiple aggregations optimized.
Parameters
----------
aggregations : list of str
Which aggregations to perform.
Returns
-------
Series
Series with resulting aggregations.
"""
check_type(aggregatio... |
def _is_nanpa_number_with_national_prefix(self):
"""Returns true if the current country is a NANPA country and the
national number begins with the national prefix.
"""
# For NANPA numbers beginning with 1[2-9], treat the 1 as the national
# prefix. The reason is that national sig... | def function[_is_nanpa_number_with_national_prefix, parameter[self]]:
constant[Returns true if the current country is a NANPA country and the
national number begins with the national prefix.
]
return[<ast.BoolOp object at 0x7da1b18bdbd0>] | keyword[def] identifier[_is_nanpa_number_with_national_prefix] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[self] . identifier[_current_metadata] . identifier[country_code] == literal[int] keyword[and] identifier[self] . identifie... | def _is_nanpa_number_with_national_prefix(self):
"""Returns true if the current country is a NANPA country and the
national number begins with the national prefix.
"""
# For NANPA numbers beginning with 1[2-9], treat the 1 as the national
# prefix. The reason is that national significant num... |
def expand_range(range, mul=0, add=0, zero_width=1):
"""
Expand a range with a multiplicative or additive constant
Parameters
----------
range : tuple
Range of data. Size 2.
mul : int | float
Multiplicative constant
add : int | float | timedelta
Additive constant
... | def function[expand_range, parameter[range, mul, add, zero_width]]:
constant[
Expand a range with a multiplicative or additive constant
Parameters
----------
range : tuple
Range of data. Size 2.
mul : int | float
Multiplicative constant
add : int | float | timedelta
... | keyword[def] identifier[expand_range] ( identifier[range] , identifier[mul] = literal[int] , identifier[add] = literal[int] , identifier[zero_width] = literal[int] ):
literal[string]
identifier[x] = identifier[range]
keyword[try] :
identifier[x] [ literal[int] ]
keyword[except] i... | def expand_range(range, mul=0, add=0, zero_width=1):
"""
Expand a range with a multiplicative or additive constant
Parameters
----------
range : tuple
Range of data. Size 2.
mul : int | float
Multiplicative constant
add : int | float | timedelta
Additive constant
... |
def post_internal_command(self, int_cmd, thread_id):
""" if thread_id is *, post to the '*' queue"""
queue = self.get_internal_queue(thread_id)
queue.put(int_cmd) | def function[post_internal_command, parameter[self, int_cmd, thread_id]]:
constant[ if thread_id is *, post to the '*' queue]
variable[queue] assign[=] call[name[self].get_internal_queue, parameter[name[thread_id]]]
call[name[queue].put, parameter[name[int_cmd]]] | keyword[def] identifier[post_internal_command] ( identifier[self] , identifier[int_cmd] , identifier[thread_id] ):
literal[string]
identifier[queue] = identifier[self] . identifier[get_internal_queue] ( identifier[thread_id] )
identifier[queue] . identifier[put] ( identifier[int_cmd] ) | def post_internal_command(self, int_cmd, thread_id):
""" if thread_id is *, post to the '*' queue"""
queue = self.get_internal_queue(thread_id)
queue.put(int_cmd) |
def album(self):
"""
album as :class:`Album` object
"""
if not self._album:
self._album = Album(self._album_id, self._album_name,
self._artist_id, self._artist_name,
self._cover_url, self._connection)
ret... | def function[album, parameter[self]]:
constant[
album as :class:`Album` object
]
if <ast.UnaryOp object at 0x7da20c76fa30> begin[:]
name[self]._album assign[=] call[name[Album], parameter[name[self]._album_id, name[self]._album_name, name[self]._artist_id, name[self]._art... | keyword[def] identifier[album] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_album] :
identifier[self] . identifier[_album] = identifier[Album] ( identifier[self] . identifier[_album_id] , identifier[self] . identifier[_album_name] ,
... | def album(self):
"""
album as :class:`Album` object
"""
if not self._album:
self._album = Album(self._album_id, self._album_name, self._artist_id, self._artist_name, self._cover_url, self._connection) # depends on [control=['if'], data=[]]
return self._album |
def getWindowByPID(self, pid, order=0):
""" Returns a handle for the first window that matches the provided PID """
for w in self._get_window_list():
if "kCGWindowOwnerPID" in w and w["kCGWindowOwnerPID"] == pid:
# Matches - make sure we get it in the correct order
... | def function[getWindowByPID, parameter[self, pid, order]]:
constant[ Returns a handle for the first window that matches the provided PID ]
for taget[name[w]] in starred[call[name[self]._get_window_list, parameter[]]] begin[:]
if <ast.BoolOp object at 0x7da18dc9ab30> begin[:]
... | keyword[def] identifier[getWindowByPID] ( identifier[self] , identifier[pid] , identifier[order] = literal[int] ):
literal[string]
keyword[for] identifier[w] keyword[in] identifier[self] . identifier[_get_window_list] ():
keyword[if] literal[string] keyword[in] identifier[w] key... | def getWindowByPID(self, pid, order=0):
""" Returns a handle for the first window that matches the provided PID """
for w in self._get_window_list():
if 'kCGWindowOwnerPID' in w and w['kCGWindowOwnerPID'] == pid:
# Matches - make sure we get it in the correct order
if order == 0:... |
def infoObject(object, cat, format, *args):
"""
Log an informational message in the given category.
"""
doLog(INFO, object, cat, format, args) | def function[infoObject, parameter[object, cat, format]]:
constant[
Log an informational message in the given category.
]
call[name[doLog], parameter[name[INFO], name[object], name[cat], name[format], name[args]]] | keyword[def] identifier[infoObject] ( identifier[object] , identifier[cat] , identifier[format] ,* identifier[args] ):
literal[string]
identifier[doLog] ( identifier[INFO] , identifier[object] , identifier[cat] , identifier[format] , identifier[args] ) | def infoObject(object, cat, format, *args):
"""
Log an informational message in the given category.
"""
doLog(INFO, object, cat, format, args) |
def dmp(self, thing):
"""Dump the content of an object in a dict for wdb.js"""
def safe_getattr(key):
"""Avoid crash on getattr"""
try:
return getattr(thing, key)
except Exception as e:
return 'Error getting attr "%s" from "%s" (%s: %s... | def function[dmp, parameter[self, thing]]:
constant[Dump the content of an object in a dict for wdb.js]
def function[safe_getattr, parameter[key]]:
constant[Avoid crash on getattr]
<ast.Try object at 0x7da204344a00>
return[call[name[dict], parameter[<ast.GeneratorExp object a... | keyword[def] identifier[dmp] ( identifier[self] , identifier[thing] ):
literal[string]
keyword[def] identifier[safe_getattr] ( identifier[key] ):
literal[string]
keyword[try] :
keyword[return] identifier[getattr] ( identifier[thing] , identifier[key] )... | def dmp(self, thing):
"""Dump the content of an object in a dict for wdb.js"""
def safe_getattr(key):
"""Avoid crash on getattr"""
try:
return getattr(thing, key) # depends on [control=['try'], data=[]]
except Exception as e:
return 'Error getting attr "%s" from... |
def _rotate_to_arbitrary_vector(v,a,inv=False,_dontcutsmall=False):
""" Return a rotation matrix that rotates v to align with unit vector a
i.e. R . v = |v|\hat{a} """
normv= v/numpy.tile(numpy.sqrt(numpy.sum(v**2.,axis=1)),(3,1)).T
rotaxis= numpy.cross(normv,a)
rotaxis/= numpy.tile(numpy.sqrt(n... | def function[_rotate_to_arbitrary_vector, parameter[v, a, inv, _dontcutsmall]]:
constant[ Return a rotation matrix that rotates v to align with unit vector a
i.e. R . v = |v|\hat{a} ]
variable[normv] assign[=] binary_operation[name[v] / call[name[numpy].tile, parameter[call[name[numpy].sqrt, par... | keyword[def] identifier[_rotate_to_arbitrary_vector] ( identifier[v] , identifier[a] , identifier[inv] = keyword[False] , identifier[_dontcutsmall] = keyword[False] ):
literal[string]
identifier[normv] = identifier[v] / identifier[numpy] . identifier[tile] ( identifier[numpy] . identifier[sqrt] ( identifie... | def _rotate_to_arbitrary_vector(v, a, inv=False, _dontcutsmall=False):
""" Return a rotation matrix that rotates v to align with unit vector a
i.e. R . v = |v|\\hat{a} """
normv = v / numpy.tile(numpy.sqrt(numpy.sum(v ** 2.0, axis=1)), (3, 1)).T
rotaxis = numpy.cross(normv, a)
rotaxis /= numpy.t... |
def inject_basic_program(self, ascii_listing):
"""
save the given ASCII BASIC program listing into the emulator RAM.
"""
program_start = self.cpu.memory.read_word(
self.machine_api.PROGRAM_START_ADDR
)
tokens = self.machine_api.ascii_listing2program_dump(ascii... | def function[inject_basic_program, parameter[self, ascii_listing]]:
constant[
save the given ASCII BASIC program listing into the emulator RAM.
]
variable[program_start] assign[=] call[name[self].cpu.memory.read_word, parameter[name[self].machine_api.PROGRAM_START_ADDR]]
variable... | keyword[def] identifier[inject_basic_program] ( identifier[self] , identifier[ascii_listing] ):
literal[string]
identifier[program_start] = identifier[self] . identifier[cpu] . identifier[memory] . identifier[read_word] (
identifier[self] . identifier[machine_api] . identifier[PROGRAM_STAR... | def inject_basic_program(self, ascii_listing):
"""
save the given ASCII BASIC program listing into the emulator RAM.
"""
program_start = self.cpu.memory.read_word(self.machine_api.PROGRAM_START_ADDR)
tokens = self.machine_api.ascii_listing2program_dump(ascii_listing)
self.cpu.memory.load... |
def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name):
"""
Check and return a list of SSH key IDs or fingerprints according
to DigitalOcean's API. This method is used to check and create a
droplet with the correct SSH keys.
"""
ssh_keys_id = list()
... | def function[__get_ssh_keys_id_or_fingerprint, parameter[ssh_keys, token, name]]:
constant[
Check and return a list of SSH key IDs or fingerprints according
to DigitalOcean's API. This method is used to check and create a
droplet with the correct SSH keys.
]
v... | keyword[def] identifier[__get_ssh_keys_id_or_fingerprint] ( identifier[ssh_keys] , identifier[token] , identifier[name] ):
literal[string]
identifier[ssh_keys_id] = identifier[list] ()
keyword[for] identifier[ssh_key] keyword[in] identifier[ssh_keys] :
keyword[if] identifi... | def __get_ssh_keys_id_or_fingerprint(ssh_keys, token, name):
"""
Check and return a list of SSH key IDs or fingerprints according
to DigitalOcean's API. This method is used to check and create a
droplet with the correct SSH keys.
"""
ssh_keys_id = list()
for ssh_k... |
def _exists(fs, path):
"""
Check that the given path exists on the filesystem.
Note that unlike `os.path.exists`, we *do* propagate file system errors
other than a non-existent path or non-existent directory component.
E.g., should EPERM or ELOOP be raised, an exception will bubble up.
"""
... | def function[_exists, parameter[fs, path]]:
constant[
Check that the given path exists on the filesystem.
Note that unlike `os.path.exists`, we *do* propagate file system errors
other than a non-existent path or non-existent directory component.
E.g., should EPERM or ELOOP be raised, an except... | keyword[def] identifier[_exists] ( identifier[fs] , identifier[path] ):
literal[string]
keyword[try] :
identifier[fs] . identifier[stat] ( identifier[path] )
keyword[except] ( identifier[exceptions] . identifier[FileNotFound] , identifier[exceptions] . identifier[NotADirectory] ):
ke... | def _exists(fs, path):
"""
Check that the given path exists on the filesystem.
Note that unlike `os.path.exists`, we *do* propagate file system errors
other than a non-existent path or non-existent directory component.
E.g., should EPERM or ELOOP be raised, an exception will bubble up.
"""
... |
def register_entity(self, entity_value, entity_type, alias_of=None, domain=0):
"""
Register an entity to be tagged in potential parse results.
Args:
entity_value(str): the value/proper name of an entity instance
(Ex: "The Big Bang Theory")
entity_type(str... | def function[register_entity, parameter[self, entity_value, entity_type, alias_of, domain]]:
constant[
Register an entity to be tagged in potential parse results.
Args:
entity_value(str): the value/proper name of an entity instance
(Ex: "The Big Bang Theory")
... | keyword[def] identifier[register_entity] ( identifier[self] , identifier[entity_value] , identifier[entity_type] , identifier[alias_of] = keyword[None] , identifier[domain] = literal[int] ):
literal[string]
keyword[if] identifier[domain] keyword[not] keyword[in] identifier[self] . identifier[do... | def register_entity(self, entity_value, entity_type, alias_of=None, domain=0):
"""
Register an entity to be tagged in potential parse results.
Args:
entity_value(str): the value/proper name of an entity instance
(Ex: "The Big Bang Theory")
entity_type(str): t... |
def direct_deployment_mode(command, parser, cluster, cl_args):
'''
check the direct deployment mode for the given cluster
if it is valid return the valid set of args
:param command:
:param parser:
:param cluster:
:param cl_args:
:return:
'''
cluster = cl_args['cluster']
try:
config_path = cl_... | def function[direct_deployment_mode, parameter[command, parser, cluster, cl_args]]:
constant[
check the direct deployment mode for the given cluster
if it is valid return the valid set of args
:param command:
:param parser:
:param cluster:
:param cl_args:
:return:
]
variable[cluster] ass... | keyword[def] identifier[direct_deployment_mode] ( identifier[command] , identifier[parser] , identifier[cluster] , identifier[cl_args] ):
literal[string]
identifier[cluster] = identifier[cl_args] [ literal[string] ]
keyword[try] :
identifier[config_path] = identifier[cl_args] [ literal[string] ]
... | def direct_deployment_mode(command, parser, cluster, cl_args):
"""
check the direct deployment mode for the given cluster
if it is valid return the valid set of args
:param command:
:param parser:
:param cluster:
:param cl_args:
:return:
"""
cluster = cl_args['cluster']
try:
config_p... |
def color(self, values, ids=(), key_on='feature.id', palette='YlOrBr', **kwargs):
"""Color map features by binning values.
values -- a sequence of values or a table of keys and values
ids -- an ID for each value; if none are provided, indices are used
key_on -- attribute of each feature... | def function[color, parameter[self, values, ids, key_on, palette]]:
constant[Color map features by binning values.
values -- a sequence of values or a table of keys and values
ids -- an ID for each value; if none are provided, indices are used
key_on -- attribute of each feature to matc... | keyword[def] identifier[color] ( identifier[self] , identifier[values] , identifier[ids] =(), identifier[key_on] = literal[string] , identifier[palette] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[id_name] , identifier[value_name] = literal[string] , literal[stri... | def color(self, values, ids=(), key_on='feature.id', palette='YlOrBr', **kwargs):
"""Color map features by binning values.
values -- a sequence of values or a table of keys and values
ids -- an ID for each value; if none are provided, indices are used
key_on -- attribute of each feature to ... |
def render_update(self, value, system, common_kw):
""" Render response for view `update` method (item PATCH) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPOk('Updated', **kw) | def function[render_update, parameter[self, value, system, common_kw]]:
constant[ Render response for view `update` method (item PATCH) ]
variable[kw] assign[=] call[name[self]._get_create_update_kwargs, parameter[name[value], name[common_kw]]]
return[call[name[JHTTPOk], parameter[constant[Updated]]... | keyword[def] identifier[render_update] ( identifier[self] , identifier[value] , identifier[system] , identifier[common_kw] ):
literal[string]
identifier[kw] = identifier[self] . identifier[_get_create_update_kwargs] ( identifier[value] , identifier[common_kw] )
keyword[return] identifier[... | def render_update(self, value, system, common_kw):
""" Render response for view `update` method (item PATCH) """
kw = self._get_create_update_kwargs(value, common_kw)
return JHTTPOk('Updated', **kw) |
def _write_angle_information(gsd_file, structure):
"""Write the angles in the system.
Parameters
----------
gsd_file :
The file object of the GSD file being written
structure : parmed.Structure
Parmed structure object holding system information
"""
gsd_file.angles.N = len(... | def function[_write_angle_information, parameter[gsd_file, structure]]:
constant[Write the angles in the system.
Parameters
----------
gsd_file :
The file object of the GSD file being written
structure : parmed.Structure
Parmed structure object holding system information
]
... | keyword[def] identifier[_write_angle_information] ( identifier[gsd_file] , identifier[structure] ):
literal[string]
identifier[gsd_file] . identifier[angles] . identifier[N] = identifier[len] ( identifier[structure] . identifier[angles] )
identifier[unique_angle_types] = identifier[set] ()
keyw... | def _write_angle_information(gsd_file, structure):
"""Write the angles in the system.
Parameters
----------
gsd_file :
The file object of the GSD file being written
structure : parmed.Structure
Parmed structure object holding system information
"""
gsd_file.angles.N = len(s... |
def getXML(self):
"""Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
"""
s = ''
for element in self._svgElements:
s += element.getXML()
return s | def function[getXML, parameter[self]]:
constant[Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
]
variable[s] assign[=] constant[]
for taget[name[element]] in starred[name[self]._svgElements] begin[:]
<ast.AugAssign ... | keyword[def] identifier[getXML] ( identifier[self] ):
literal[string]
identifier[s] = literal[string]
keyword[for] identifier[element] keyword[in] identifier[self] . identifier[_svgElements] :
identifier[s] += identifier[element] . identifier[getXML] ()
keyword[re... | def getXML(self):
"""Retrieves the pysvg elements that make up the turtles path and returns them as String in an xml representation.
"""
s = ''
for element in self._svgElements:
s += element.getXML() # depends on [control=['for'], data=['element']]
return s |
def calc_neg_log_likelihood_and_neg_gradient(self, params):
"""
Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize.
"""
neg_log_likelihood = -1 * self.conve... | def function[calc_neg_log_likelihood_and_neg_gradient, parameter[self, params]]:
constant[
Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize.
]
variable[ne... | keyword[def] identifier[calc_neg_log_likelihood_and_neg_gradient] ( identifier[self] , identifier[params] ):
literal[string]
identifier[neg_log_likelihood] =- literal[int] * identifier[self] . identifier[convenience_calc_log_likelihood] ( identifier[params] )
identifier[neg_gradient] =- li... | def calc_neg_log_likelihood_and_neg_gradient(self, params):
"""
Calculates and returns the negative of the log-likelihood and the
negative of the gradient. This function is used as the objective
function in scipy.optimize.minimize.
"""
neg_log_likelihood = -1 * self.convenience_c... |
def add_edge(self, u, v, **kwargs):
"""
Add an edge between variable_node and factor_node.
Parameters
----------
u, v: nodes
Nodes can be any hashable Python object.
Examples
--------
>>> from pgmpy.models import FactorGraph
>>> G = F... | def function[add_edge, parameter[self, u, v]]:
constant[
Add an edge between variable_node and factor_node.
Parameters
----------
u, v: nodes
Nodes can be any hashable Python object.
Examples
--------
>>> from pgmpy.models import FactorGraph
... | keyword[def] identifier[add_edge] ( identifier[self] , identifier[u] , identifier[v] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[u] != identifier[v] :
identifier[super] ( identifier[FactorGraph] , identifier[self] ). identifier[add_edge] ( identifier[u] , identifi... | def add_edge(self, u, v, **kwargs):
"""
Add an edge between variable_node and factor_node.
Parameters
----------
u, v: nodes
Nodes can be any hashable Python object.
Examples
--------
>>> from pgmpy.models import FactorGraph
>>> G = Facto... |
def name(self, name: str):
""" Name Setter
Set name with passed in variable.
@param name: New name string.
@type name: String
"""
self.pathName = os.path.join(self.path, name) | def function[name, parameter[self, name]]:
constant[ Name Setter
Set name with passed in variable.
@param name: New name string.
@type name: String
]
name[self].pathName assign[=] call[name[os].path.join, parameter[name[self].path, name[name]]] | keyword[def] identifier[name] ( identifier[self] , identifier[name] : identifier[str] ):
literal[string]
identifier[self] . identifier[pathName] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[path] , identifier[name] ) | def name(self, name: str):
""" Name Setter
Set name with passed in variable.
@param name: New name string.
@type name: String
"""
self.pathName = os.path.join(self.path, name) |
def appendhdf5(table, source, where=None, name=None):
"""
As :func:`petl.io.hdf5.tohdf5` but don't truncate the target table before
loading.
"""
with _get_hdf5_table(source, where, name, mode='a') as h5table:
# load the data
_insert(table, h5table) | def function[appendhdf5, parameter[table, source, where, name]]:
constant[
As :func:`petl.io.hdf5.tohdf5` but don't truncate the target table before
loading.
]
with call[name[_get_hdf5_table], parameter[name[source], name[where], name[name]]] begin[:]
call[name[_insert], par... | keyword[def] identifier[appendhdf5] ( identifier[table] , identifier[source] , identifier[where] = keyword[None] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[_get_hdf5_table] ( identifier[source] , identifier[where] , identifier[name] , identifier[mode] = literal[string]... | def appendhdf5(table, source, where=None, name=None):
"""
As :func:`petl.io.hdf5.tohdf5` but don't truncate the target table before
loading.
"""
with _get_hdf5_table(source, where, name, mode='a') as h5table:
# load the data
_insert(table, h5table) # depends on [control=['with'], d... |
def pformat(arg, width=79, height=24, compact=True):
"""Return pretty formatted representation of object as string.
Whitespace might be altered.
"""
if height is None or height < 1:
height = 1024
if width is None or width < 1:
width = 256
npopt = numpy.get_printoptions()
n... | def function[pformat, parameter[arg, width, height, compact]]:
constant[Return pretty formatted representation of object as string.
Whitespace might be altered.
]
if <ast.BoolOp object at 0x7da20e9b06d0> begin[:]
variable[height] assign[=] constant[1024]
if <ast.BoolOp ... | keyword[def] identifier[pformat] ( identifier[arg] , identifier[width] = literal[int] , identifier[height] = literal[int] , identifier[compact] = keyword[True] ):
literal[string]
keyword[if] identifier[height] keyword[is] keyword[None] keyword[or] identifier[height] < literal[int] :
identifie... | def pformat(arg, width=79, height=24, compact=True):
"""Return pretty formatted representation of object as string.
Whitespace might be altered.
"""
if height is None or height < 1:
height = 1024 # depends on [control=['if'], data=[]]
if width is None or width < 1:
width = 256 # ... |
def get_after(self, timestamp, s=None):
"""
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
strings list. For list, al... | def function[get_after, parameter[self, timestamp, s]]:
constant[
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
stri... | keyword[def] identifier[get_after] ( identifier[self] , identifier[timestamp] , identifier[s] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[timestamp] , identifier[time] ):
keyword[raise] identifier[TypeError] (
literal[... | def get_after(self, timestamp, s=None):
"""
Find all the (available) logs that are after the given time stamp.
If `s` is not supplied, then all lines are used. Otherwise, only the
lines contain the `s` are used. `s` can be either a single string or a
strings list. For list, all ke... |
def plot_line_loading_diff(networkA, networkB, timestep=0):
"""
Plot difference in line loading between two networks
(with and without switches) as color on lines
Positive values mean that line loading with switches is bigger than without
Plot switches as small dots
Parameters
--------... | def function[plot_line_loading_diff, parameter[networkA, networkB, timestep]]:
constant[
Plot difference in line loading between two networks
(with and without switches) as color on lines
Positive values mean that line loading with switches is bigger than without
Plot switches as small dots
... | keyword[def] identifier[plot_line_loading_diff] ( identifier[networkA] , identifier[networkB] , identifier[timestep] = literal[int] ):
literal[string]
keyword[def] identifier[shiftedColorMap] (
identifier[cmap] ,
identifier[start] = literal[int] ,
identifier[midpoint] = literal[int] ,... | def plot_line_loading_diff(networkA, networkB, timestep=0):
"""
Plot difference in line loading between two networks
(with and without switches) as color on lines
Positive values mean that line loading with switches is bigger than without
Plot switches as small dots
Parameters
--------... |
def configure_installed_apps_logger(level, verbose=False,
additional_packages=None, filename=None):
"""Builds and enables a logger with a logger list of the top-level list of
installed app modules (based on package name) plus any additional
application packages passed in ... | def function[configure_installed_apps_logger, parameter[level, verbose, additional_packages, filename]]:
constant[Builds and enables a logger with a logger list of the top-level list of
installed app modules (based on package name) plus any additional
application packages passed in - for example, a user... | keyword[def] identifier[configure_installed_apps_logger] ( identifier[level] , identifier[verbose] = keyword[False] ,
identifier[additional_packages] = keyword[None] , identifier[filename] = keyword[None] ):
literal[string]
keyword[if] identifier[settings] . identifier[LOGGING_CONFIG] :
keyword[... | def configure_installed_apps_logger(level, verbose=False, additional_packages=None, filename=None):
"""Builds and enables a logger with a logger list of the top-level list of
installed app modules (based on package name) plus any additional
application packages passed in - for example, a user may want to lo... |
def unlock(self, time=3):
"""
unlock the door\n
thanks to https://github.com/SoftwareHouseMerida/pyzk/
:param time: define delay in seconds
:return: bool
"""
command = const.CMD_UNLOCK
command_string = pack("I",int(time)*10)
cmd_response = self.__... | def function[unlock, parameter[self, time]]:
constant[
unlock the door
thanks to https://github.com/SoftwareHouseMerida/pyzk/
:param time: define delay in seconds
:return: bool
]
variable[command] assign[=] name[const].CMD_UNLOCK
variable[command_string]... | keyword[def] identifier[unlock] ( identifier[self] , identifier[time] = literal[int] ):
literal[string]
identifier[command] = identifier[const] . identifier[CMD_UNLOCK]
identifier[command_string] = identifier[pack] ( literal[string] , identifier[int] ( identifier[time] )* literal[int] )
... | def unlock(self, time=3):
"""
unlock the door
thanks to https://github.com/SoftwareHouseMerida/pyzk/
:param time: define delay in seconds
:return: bool
"""
command = const.CMD_UNLOCK
command_string = pack('I', int(time) * 10)
cmd_response = self.__send_command(c... |
def move_left(self):
"""Make the drone move left."""
self.at(ardrone.at.pcmd, True, -self.speed, 0, 0, 0) | def function[move_left, parameter[self]]:
constant[Make the drone move left.]
call[name[self].at, parameter[name[ardrone].at.pcmd, constant[True], <ast.UnaryOp object at 0x7da1b1042740>, constant[0], constant[0], constant[0]]] | keyword[def] identifier[move_left] ( identifier[self] ):
literal[string]
identifier[self] . identifier[at] ( identifier[ardrone] . identifier[at] . identifier[pcmd] , keyword[True] ,- identifier[self] . identifier[speed] , literal[int] , literal[int] , literal[int] ) | def move_left(self):
"""Make the drone move left."""
self.at(ardrone.at.pcmd, True, -self.speed, 0, 0, 0) |
def log_likelihood(z, x, P, H, R):
"""
Returns log-likelihood of the measurement z given the Gaussian
posterior (x, P) using measurement function H and measurement
covariance error R
"""
S = np.dot(H, np.dot(P, H.T)) + R
return logpdf(z, np.dot(H, x), S) | def function[log_likelihood, parameter[z, x, P, H, R]]:
constant[
Returns log-likelihood of the measurement z given the Gaussian
posterior (x, P) using measurement function H and measurement
covariance error R
]
variable[S] assign[=] binary_operation[call[name[np].dot, parameter[name[H],... | keyword[def] identifier[log_likelihood] ( identifier[z] , identifier[x] , identifier[P] , identifier[H] , identifier[R] ):
literal[string]
identifier[S] = identifier[np] . identifier[dot] ( identifier[H] , identifier[np] . identifier[dot] ( identifier[P] , identifier[H] . identifier[T] ))+ identifier[R]
... | def log_likelihood(z, x, P, H, R):
"""
Returns log-likelihood of the measurement z given the Gaussian
posterior (x, P) using measurement function H and measurement
covariance error R
"""
S = np.dot(H, np.dot(P, H.T)) + R
return logpdf(z, np.dot(H, x), S) |
def create_spooled_temporary_file(filepath=None, fileobj=None):
"""
Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
defined its content will be copied into temporary file.
:param filepath: Path of input file
:type filepath: str
:param fileobj: Input file object
:type fil... | def function[create_spooled_temporary_file, parameter[filepath, fileobj]]:
constant[
Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
defined its content will be copied into temporary file.
:param filepath: Path of input file
:type filepath: str
:param fileobj: Input file... | keyword[def] identifier[create_spooled_temporary_file] ( identifier[filepath] = keyword[None] , identifier[fileobj] = keyword[None] ):
literal[string]
identifier[spooled_file] = identifier[tempfile] . identifier[SpooledTemporaryFile] (
identifier[max_size] = identifier[settings] . identifier[TMP_FILE_... | def create_spooled_temporary_file(filepath=None, fileobj=None):
"""
Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
defined its content will be copied into temporary file.
:param filepath: Path of input file
:type filepath: str
:param fileobj: Input file object
:type fil... |
def _zforce(self, R, z, phi=0., t=0.):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | def function[_zforce, parameter[self, R, z, phi, t]]:
constant[
NAME:
_zforce
PURPOSE:
evaluate the vertical force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
... | keyword[def] identifier[_zforce] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[isNonAxi] keyword[and] identifier[phi] keyword[is] keyword[None] :
... | def _zforce(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force at (R,z, phi)
INPUT:
R - Cylindrical Galactocentric radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
v... |
def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests)
wire_removal_set = block.wirevector_set.difference(valid_wires)
for removed_wire in wire... | def function[_remove_unused_wires, parameter[block, keep_inputs]]:
constant[ Removes all unconnected wires from a block]
variable[valid_wires] assign[=] call[name[set], parameter[]]
for taget[name[logic_net]] in starred[name[block].logic] begin[:]
call[name[valid_wires].update, p... | keyword[def] identifier[_remove_unused_wires] ( identifier[block] , identifier[keep_inputs] = keyword[True] ):
literal[string]
identifier[valid_wires] = identifier[set] ()
keyword[for] identifier[logic_net] keyword[in] identifier[block] . identifier[logic] :
identifier[valid_wires] . ident... | def _remove_unused_wires(block, keep_inputs=True):
""" Removes all unconnected wires from a block"""
valid_wires = set()
for logic_net in block.logic:
valid_wires.update(logic_net.args, logic_net.dests) # depends on [control=['for'], data=['logic_net']]
wire_removal_set = block.wirevector_set.d... |
def sites_at_edges( self ):
"""
Finds the six sites with the maximum and minimum coordinates along x, y, and z.
Args:
None
Returns:
(List(List)): In the order [ +x, -x, +y, -y, +z, -z ]
"""
min_x = min( [ s.r[0] for s in self.sites ] )
m... | def function[sites_at_edges, parameter[self]]:
constant[
Finds the six sites with the maximum and minimum coordinates along x, y, and z.
Args:
None
Returns:
(List(List)): In the order [ +x, -x, +y, -y, +z, -z ]
]
variable[min_x] assign[=] call[n... | keyword[def] identifier[sites_at_edges] ( identifier[self] ):
literal[string]
identifier[min_x] = identifier[min] ([ identifier[s] . identifier[r] [ literal[int] ] keyword[for] identifier[s] keyword[in] identifier[self] . identifier[sites] ])
identifier[max_x] = identifier[max] ([ ident... | def sites_at_edges(self):
"""
Finds the six sites with the maximum and minimum coordinates along x, y, and z.
Args:
None
Returns:
(List(List)): In the order [ +x, -x, +y, -y, +z, -z ]
"""
min_x = min([s.r[0] for s in self.sites])
max_x = max([s.r[0]... |
def stop(self, timeout=None, callback=None):
"""Stop ioloop (if managed) and call callback in ioloop before close.
Parameters
----------
timeout : float or None
Seconds to wait for ioloop to have *started*.
Returns
-------
stopped : thread-safe Futur... | def function[stop, parameter[self, timeout, callback]]:
constant[Stop ioloop (if managed) and call callback in ioloop before close.
Parameters
----------
timeout : float or None
Seconds to wait for ioloop to have *started*.
Returns
-------
stopped : ... | keyword[def] identifier[stop] ( identifier[self] , identifier[timeout] = keyword[None] , identifier[callback] = keyword[None] ):
literal[string]
keyword[if] identifier[timeout] :
identifier[self] . identifier[_running] . identifier[wait] ( identifier[timeout] )
identifier[st... | def stop(self, timeout=None, callback=None):
"""Stop ioloop (if managed) and call callback in ioloop before close.
Parameters
----------
timeout : float or None
Seconds to wait for ioloop to have *started*.
Returns
-------
stopped : thread-safe Future
... |
def add_tag(self, tag):
""" add a tag to the tag list """
if tag not in self._tags:
self._tags[tag] = dict() | def function[add_tag, parameter[self, tag]]:
constant[ add a tag to the tag list ]
if compare[name[tag] <ast.NotIn object at 0x7da2590d7190> name[self]._tags] begin[:]
call[name[self]._tags][name[tag]] assign[=] call[name[dict], parameter[]] | keyword[def] identifier[add_tag] ( identifier[self] , identifier[tag] ):
literal[string]
keyword[if] identifier[tag] keyword[not] keyword[in] identifier[self] . identifier[_tags] :
identifier[self] . identifier[_tags] [ identifier[tag] ]= identifier[dict] () | def add_tag(self, tag):
""" add a tag to the tag list """
if tag not in self._tags:
self._tags[tag] = dict() # depends on [control=['if'], data=['tag']] |
async def _cancel(log, **tasks):
"""
Helper to cancel one or more tasks gracefully, logging exceptions.
"""
for name, task in tasks.items():
if not task:
continue
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
... | <ast.AsyncFunctionDef object at 0x7da1b21d7670> | keyword[async] keyword[def] identifier[_cancel] ( identifier[log] ,** identifier[tasks] ):
literal[string]
keyword[for] identifier[name] , identifier[task] keyword[in] identifier[tasks] . identifier[items] ():
keyword[if] keyword[not] identifier[task] :
keyword[continue]
... | async def _cancel(log, **tasks):
"""
Helper to cancel one or more tasks gracefully, logging exceptions.
"""
for (name, task) in tasks.items():
if not task:
continue # depends on [control=['if'], data=[]]
task.cancel()
try:
await task # depends on [contro... |
def simxGetDistanceHandle(clientID, distanceObjectName, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
handle = ct.c_int()
if (sys.version_info[0] == 3) and (type(distanceObjectName) is str):
distanceObjectName=distanceObjectNam... | def function[simxGetDistanceHandle, parameter[clientID, distanceObjectName, operationMode]]:
constant[
Please have a look at the function description/documentation in the V-REP user manual
]
variable[handle] assign[=] call[name[ct].c_int, parameter[]]
if <ast.BoolOp object at 0x7da1b138d... | keyword[def] identifier[simxGetDistanceHandle] ( identifier[clientID] , identifier[distanceObjectName] , identifier[operationMode] ):
literal[string]
identifier[handle] = identifier[ct] . identifier[c_int] ()
keyword[if] ( identifier[sys] . identifier[version_info] [ literal[int] ]== literal[int] ) k... | def simxGetDistanceHandle(clientID, distanceObjectName, operationMode):
"""
Please have a look at the function description/documentation in the V-REP user manual
"""
handle = ct.c_int()
if sys.version_info[0] == 3 and type(distanceObjectName) is str:
distanceObjectName = distanceObjectName.e... |
def trim_floating_solid(im):
r"""
Removes all solid that that is not attached to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected solid removed... | def function[trim_floating_solid, parameter[im]]:
constant[
Removes all solid that that is not attached to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all ... | keyword[def] identifier[trim_floating_solid] ( identifier[im] ):
literal[string]
identifier[im] = identifier[sp] . identifier[copy] ( identifier[im] )
identifier[holes] = identifier[find_disconnected_voxels] (~ identifier[im] )
identifier[im] [ identifier[holes] ]= keyword[True]
keyword[ret... | def trim_floating_solid(im):
"""
Removes all solid that that is not attached to the edges of the image.
Parameters
----------
im : ND-array
The image of the porous material
Returns
-------
image : ND-array
A version of ``im`` but with all the disconnected solid removed.... |
def get_library(path=None, root=None, db=None):
import ambry.library as _l
"""Return the default library for this installation."""
rc = config(path=path, root=root, db=db )
return _l.new_library(rc) | def function[get_library, parameter[path, root, db]]:
import module[ambry.library] as alias[_l]
constant[Return the default library for this installation.]
variable[rc] assign[=] call[name[config], parameter[]]
return[call[name[_l].new_library, parameter[name[rc]]]] | keyword[def] identifier[get_library] ( identifier[path] = keyword[None] , identifier[root] = keyword[None] , identifier[db] = keyword[None] ):
keyword[import] identifier[ambry] . identifier[library] keyword[as] identifier[_l]
literal[string]
identifier[rc] = identifier[config] ( identifier[path] ... | def get_library(path=None, root=None, db=None):
import ambry.library as _l
'Return the default library for this installation.'
rc = config(path=path, root=root, db=db)
return _l.new_library(rc) |
def percentile(a, q):
"""
Compute the qth percentile of the data along the specified axis.
Simpler version than the numpy version that always flattens input arrays.
Examples
--------
>>> a = [[10, 7, 4], [3, 2, 1]]
>>> percentile(a, 20)
2.0
>>> percentile(a, 50)
3.5
>>> perc... | def function[percentile, parameter[a, q]]:
constant[
Compute the qth percentile of the data along the specified axis.
Simpler version than the numpy version that always flattens input arrays.
Examples
--------
>>> a = [[10, 7, 4], [3, 2, 1]]
>>> percentile(a, 20)
2.0
>>> percent... | keyword[def] identifier[percentile] ( identifier[a] , identifier[q] ):
literal[string]
keyword[if] keyword[not] identifier[a] :
keyword[return] keyword[None]
keyword[if] identifier[isinstance] ( identifier[q] ,( identifier[float] , identifier[int] )):
identifier[qq] =[ identifi... | def percentile(a, q):
"""
Compute the qth percentile of the data along the specified axis.
Simpler version than the numpy version that always flattens input arrays.
Examples
--------
>>> a = [[10, 7, 4], [3, 2, 1]]
>>> percentile(a, 20)
2.0
>>> percentile(a, 50)
3.5
>>> perc... |
def sign_with_privkey(
digest: bytes,
privkey: Ed25519PrivateKey,
global_pubkey: Ed25519PublicPoint,
nonce: int,
global_commit: Ed25519PublicPoint,
) -> Ed25519Signature:
"""Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key a... | def function[sign_with_privkey, parameter[digest, privkey, global_pubkey, nonce, global_commit]]:
constant[Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment.
]
variable[h] assign[=] call[name[_ed25519].H, pa... | keyword[def] identifier[sign_with_privkey] (
identifier[digest] : identifier[bytes] ,
identifier[privkey] : identifier[Ed25519PrivateKey] ,
identifier[global_pubkey] : identifier[Ed25519PublicPoint] ,
identifier[nonce] : identifier[int] ,
identifier[global_commit] : identifier[Ed25519PublicPoint] ,
)-> identifie... | def sign_with_privkey(digest: bytes, privkey: Ed25519PrivateKey, global_pubkey: Ed25519PublicPoint, nonce: int, global_commit: Ed25519PublicPoint) -> Ed25519Signature:
"""Create a CoSi signature of `digest` with the supplied private key.
This function needs to know the global public key and global commitment.
... |
def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissio... | def function[is_done, parameter[self, submissionid_or_submission, user_check]]:
constant[ Tells if a submission is done and its result is available ]
if call[name[isinstance], parameter[name[submissionid_or_submission], name[dict]]] begin[:]
variable[submission] assign[=] name[submission... | keyword[def] identifier[is_done] ( identifier[self] , identifier[submissionid_or_submission] , identifier[user_check] = keyword[True] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[submissionid_or_submission] , identifier[dict] ):
identifier[submission] = ... | def is_done(self, submissionid_or_submission, user_check=True):
""" Tells if a submission is done and its result is available """
# TODO: not a very nice way to avoid too many database call. Should be refactored.
if isinstance(submissionid_or_submission, dict):
submission = submissionid_or_submissio... |
def _M2_const(Xvar, mask_X, xvarsum, xconst, Yvar, mask_Y, yvarsum, yconst, weights=None):
r""" Computes the unnormalized covariance matrix between X and Y, exploiting constant input columns
Computes the unnormalized covariance matrix :math:`C = X^\top Y`
(for symmetric=False) or :math:`C = \frac{1}{2} (X^... | def function[_M2_const, parameter[Xvar, mask_X, xvarsum, xconst, Yvar, mask_Y, yvarsum, yconst, weights]]:
constant[ Computes the unnormalized covariance matrix between X and Y, exploiting constant input columns
Computes the unnormalized covariance matrix :math:`C = X^\top Y`
(for symmetric=False) or :... | keyword[def] identifier[_M2_const] ( identifier[Xvar] , identifier[mask_X] , identifier[xvarsum] , identifier[xconst] , identifier[Yvar] , identifier[mask_Y] , identifier[yvarsum] , identifier[yconst] , identifier[weights] = keyword[None] ):
literal[string]
identifier[C] = identifier[np] . identifier[zeros... | def _M2_const(Xvar, mask_X, xvarsum, xconst, Yvar, mask_Y, yvarsum, yconst, weights=None):
""" Computes the unnormalized covariance matrix between X and Y, exploiting constant input columns
Computes the unnormalized covariance matrix :math:`C = X^\\top Y`
(for symmetric=False) or :math:`C = \\frac{1}{2} (X... |
def createKeyPair(type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
"""
pkey = crypto.PKey()
pkey.generate_key(typ... | def function[createKeyPair, parameter[type, bits]]:
constant[
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
]
variable[pkey... | keyword[def] identifier[createKeyPair] ( identifier[type] , identifier[bits] ):
literal[string]
identifier[pkey] = identifier[crypto] . identifier[PKey] ()
identifier[pkey] . identifier[generate_key] ( identifier[type] , identifier[bits] )
keyword[return] identifier[pkey] | def createKeyPair(type, bits):
"""
Create a public/private key pair.
Arguments: type - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
"""
pkey = crypto.PKey()
pkey.generate_key(typ... |
def translate_noetic(s):
"""M:.O:.-O:.O:.-B:.T:.n.-' => s.M:O:.O:O:.-"""
subst, attr, mode = s
return m(script('s.'),
m(subst.children[0].children[0], subst.children[1].children[0]),
m(attr.children[0].children[0], attr.children[1].children[0])) | def function[translate_noetic, parameter[s]]:
constant[M:.O:.-O:.O:.-B:.T:.n.-' => s.M:O:.O:O:.-]
<ast.Tuple object at 0x7da1b032c610> assign[=] name[s]
return[call[name[m], parameter[call[name[script], parameter[constant[s.]]], call[name[m], parameter[call[call[name[subst].children][constant[0]].ch... | keyword[def] identifier[translate_noetic] ( identifier[s] ):
literal[string]
identifier[subst] , identifier[attr] , identifier[mode] = identifier[s]
keyword[return] identifier[m] ( identifier[script] ( literal[string] ),
identifier[m] ( identifier[subst] . identifier[children] [ literal[int] ].... | def translate_noetic(s):
"""M:.O:.-O:.O:.-B:.T:.n.-' => s.M:O:.O:O:.-"""
(subst, attr, mode) = s
return m(script('s.'), m(subst.children[0].children[0], subst.children[1].children[0]), m(attr.children[0].children[0], attr.children[1].children[0])) |
def _retrieve_archive():
"""
Returns a tuple with archive content: the first element is a TodoListBase
and the second element is a TodoFile.
"""
archive_file = TodoFile.TodoFile(config().archive())
archive = TodoListBase.TodoListBase(archive_file.read())
return (archive, archive_file) | def function[_retrieve_archive, parameter[]]:
constant[
Returns a tuple with archive content: the first element is a TodoListBase
and the second element is a TodoFile.
]
variable[archive_file] assign[=] call[name[TodoFile].TodoFile, parameter[call[call[name[config], parameter[]].archive, par... | keyword[def] identifier[_retrieve_archive] ():
literal[string]
identifier[archive_file] = identifier[TodoFile] . identifier[TodoFile] ( identifier[config] (). identifier[archive] ())
identifier[archive] = identifier[TodoListBase] . identifier[TodoListBase] ( identifier[archive_file] . identifier[read]... | def _retrieve_archive():
"""
Returns a tuple with archive content: the first element is a TodoListBase
and the second element is a TodoFile.
"""
archive_file = TodoFile.TodoFile(config().archive())
archive = TodoListBase.TodoListBase(archive_file.read())
return (archive, archive_file) |
def userlogin(self, event):
"""Checks if an alert is ongoing and alerts the newly connected
client, if so."""
client_uuid = event.clientuuid
self.log(event.user, pretty=True, lvl=verbose)
self.log('Adding client')
self.clients[event.clientuuid] = event.user
fo... | def function[userlogin, parameter[self, event]]:
constant[Checks if an alert is ongoing and alerts the newly connected
client, if so.]
variable[client_uuid] assign[=] name[event].clientuuid
call[name[self].log, parameter[name[event].user]]
call[name[self].log, parameter[constant[... | keyword[def] identifier[userlogin] ( identifier[self] , identifier[event] ):
literal[string]
identifier[client_uuid] = identifier[event] . identifier[clientuuid]
identifier[self] . identifier[log] ( identifier[event] . identifier[user] , identifier[pretty] = keyword[True] , identifier[l... | def userlogin(self, event):
"""Checks if an alert is ongoing and alerts the newly connected
client, if so."""
client_uuid = event.clientuuid
self.log(event.user, pretty=True, lvl=verbose)
self.log('Adding client')
self.clients[event.clientuuid] = event.user
for (topic, alert) in self.ale... |
def range(self, start, end=None, step=1, numSlices=None):
"""
Create a new RDD of int containing elements from `start` to `end`
(exclusive), increased by `step` every element. Can be called the same
way as python's built-in range() function. If called with a single argument,
the ... | def function[range, parameter[self, start, end, step, numSlices]]:
constant[
Create a new RDD of int containing elements from `start` to `end`
(exclusive), increased by `step` every element. Can be called the same
way as python's built-in range() function. If called with a single argumen... | keyword[def] identifier[range] ( identifier[self] , identifier[start] , identifier[end] = keyword[None] , identifier[step] = literal[int] , identifier[numSlices] = keyword[None] ):
literal[string]
keyword[if] identifier[end] keyword[is] keyword[None] :
identifier[end] = identifier[s... | def range(self, start, end=None, step=1, numSlices=None):
"""
Create a new RDD of int containing elements from `start` to `end`
(exclusive), increased by `step` every element. Can be called the same
way as python's built-in range() function. If called with a single argument,
the argu... |
def DbPutDeviceAlias(self, argin):
""" Define alias for a given device name
:param argin: Str[0] = device name
Str[1] = alias name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbPutDeviceAlias()")
if len(argin) <... | def function[DbPutDeviceAlias, parameter[self, argin]]:
constant[ Define alias for a given device name
:param argin: Str[0] = device name
Str[1] = alias name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid ]
call[name[self]._log.debug, parameter[co... | keyword[def] identifier[DbPutDeviceAlias] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
keyword[if] identifier[len] ( identifier[argin] )< literal[int] :
identifier[self] . identifier[war... | def DbPutDeviceAlias(self, argin):
""" Define alias for a given device name
:param argin: Str[0] = device name
Str[1] = alias name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug('In DbPutDeviceAlias()')
if len(argin) < 2:
s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.