code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def save_dict_to_hdf5(dic, filename):
"""
....
"""
with h5py.File(filename, 'w') as h5file:
rf = recursively_save_dict_contents_to_group(h5file, '/', dic)
h5_rf = h5file.create_group("_reconstruction_flags")
# h5_rf = h5file.create_group("_reconstruction_key_flags")
for k... | def function[save_dict_to_hdf5, parameter[dic, filename]]:
constant[
....
]
with call[name[h5py].File, parameter[name[filename], constant[w]]] begin[:]
variable[rf] assign[=] call[name[recursively_save_dict_contents_to_group], parameter[name[h5file], constant[/], name[dic]]]
... | keyword[def] identifier[save_dict_to_hdf5] ( identifier[dic] , identifier[filename] ):
literal[string]
keyword[with] identifier[h5py] . identifier[File] ( identifier[filename] , literal[string] ) keyword[as] identifier[h5file] :
identifier[rf] = identifier[recursively_save_dict_contents_to_group... | def save_dict_to_hdf5(dic, filename):
"""
....
"""
with h5py.File(filename, 'w') as h5file:
rf = recursively_save_dict_contents_to_group(h5file, '/', dic)
h5_rf = h5file.create_group('_reconstruction_flags')
# h5_rf = h5file.create_group("_reconstruction_key_flags")
for (... |
def load(self, env=None):
""" Load a section values of given environment.
If nothing to specified, use environmental variable.
If unknown environment was specified, warn it on logger.
:param env: environment key to load in a coercive manner
:type env: string
:rtype: dict... | def function[load, parameter[self, env]]:
constant[ Load a section values of given environment.
If nothing to specified, use environmental variable.
If unknown environment was specified, warn it on logger.
:param env: environment key to load in a coercive manner
:type env: strin... | keyword[def] identifier[load] ( identifier[self] , identifier[env] = keyword[None] ):
literal[string]
identifier[self] . identifier[_load] ()
identifier[e] = identifier[env] keyword[or] identifier[os] . identifier[environ] . identifier[get] ( identifier[RUNNING_MODE_ENVKEY] , identifier[... | def load(self, env=None):
""" Load a section values of given environment.
If nothing to specified, use environmental variable.
If unknown environment was specified, warn it on logger.
:param env: environment key to load in a coercive manner
:type env: string
:rtype: dict
... |
def set_show_all(self, state):
"""Toggle 'show all files' state"""
if state:
self.fsmodel.setNameFilters([])
else:
self.fsmodel.setNameFilters(self.name_filters) | def function[set_show_all, parameter[self, state]]:
constant[Toggle 'show all files' state]
if name[state] begin[:]
call[name[self].fsmodel.setNameFilters, parameter[list[[]]]] | keyword[def] identifier[set_show_all] ( identifier[self] , identifier[state] ):
literal[string]
keyword[if] identifier[state] :
identifier[self] . identifier[fsmodel] . identifier[setNameFilters] ([])
keyword[else] :
identifier[self] . identifier[fsmodel] . ... | def set_show_all(self, state):
"""Toggle 'show all files' state"""
if state:
self.fsmodel.setNameFilters([]) # depends on [control=['if'], data=[]]
else:
self.fsmodel.setNameFilters(self.name_filters) |
def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged ... | def function[critical, parameter[cls, name, message]]:
constant[
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments ... | keyword[def] identifier[critical] ( identifier[cls] , identifier[name] , identifier[message] ,* identifier[args] ):
literal[string]
identifier[cls] . identifier[getLogger] ( identifier[name] ). identifier[critical] ( identifier[message] ,* identifier[args] ) | def critical(cls, name, message, *args):
"""
Convenience function to log a message at the CRITICAL level.
:param name: The name of the logger instance in the VSG namespace (VSG.<name>)
:param message: A message format string.
:param args: The arguments that are are merged into... |
def find_matching_endpoints(self, discovery_ns):
"""
Compute current matching endpoints.
Evaluated as a property to defer evaluation.
"""
def match_func(operation, ns, rule):
return operation in self.matching_operations
return list(iter_endpoints(self.graph... | def function[find_matching_endpoints, parameter[self, discovery_ns]]:
constant[
Compute current matching endpoints.
Evaluated as a property to defer evaluation.
]
def function[match_func, parameter[operation, ns, rule]]:
return[compare[name[operation] in name[self].matc... | keyword[def] identifier[find_matching_endpoints] ( identifier[self] , identifier[discovery_ns] ):
literal[string]
keyword[def] identifier[match_func] ( identifier[operation] , identifier[ns] , identifier[rule] ):
keyword[return] identifier[operation] keyword[in] identifier[self] . ... | def find_matching_endpoints(self, discovery_ns):
"""
Compute current matching endpoints.
Evaluated as a property to defer evaluation.
"""
def match_func(operation, ns, rule):
return operation in self.matching_operations
return list(iter_endpoints(self.graph, match_func)) |
def splits(cls, text_field, label_field, parse_field=None,
extra_fields={}, root='.data', train='train.jsonl',
validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
A... | def function[splits, parameter[cls, text_field, label_field, parse_field, extra_fields, root, train, validation, test]]:
constant[Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
Arguments:
text_field: The field that will be u... | keyword[def] identifier[splits] ( identifier[cls] , identifier[text_field] , identifier[label_field] , identifier[parse_field] = keyword[None] ,
identifier[extra_fields] ={}, identifier[root] = literal[string] , identifier[train] = literal[string] ,
identifier[validation] = literal[string] , identifier[test] = lite... | def splits(cls, text_field, label_field, parse_field=None, extra_fields={}, root='.data', train='train.jsonl', validation='val.jsonl', test='test.jsonl'):
"""Create dataset objects for splits of the SNLI dataset.
This is the most flexible way to use the dataset.
Arguments:
text_field: ... |
def _add_orfs(self, which, symbol, ind, val, dt_log=None, user=None, comment=None):
"""
Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
See add_override and add_fail_safe.
Parameters
... | def function[_add_orfs, parameter[self, which, symbol, ind, val, dt_log, user, comment]]:
constant[
Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
See add_override and add_fail_safe.
Parame... | keyword[def] identifier[_add_orfs] ( identifier[self] , identifier[which] , identifier[symbol] , identifier[ind] , identifier[val] , identifier[dt_log] = keyword[None] , identifier[user] = keyword[None] , identifier[comment] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier... | def _add_orfs(self, which, symbol, ind, val, dt_log=None, user=None, comment=None):
"""
Appends a single indexed-value pair, to a symbol object, to be
used during the final steps of the aggregation of the datatable.
See add_override and add_fail_safe.
Parameters
---... |
async def reply(self, *args, **kwargs):
"""
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
"""
kwargs['reply_to'] = self.id
return await self._client.send... | <ast.AsyncFunctionDef object at 0x7da18ede7be0> | keyword[async] keyword[def] identifier[reply] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[self] . identifier[id]
keyword[return] keyword[await] identifier[self] . identifier[_client] . identifier[se... | async def reply(self, *args, **kwargs):
"""
Replies to the message (as a reply). Shorthand for
`telethon.client.messages.MessageMethods.send_message`
with both ``entity`` and ``reply_to`` already set.
"""
kwargs['reply_to'] = self.id
return await self._client.send_message(awa... |
def _get_controller_help(self, controller):
"""Return the value of the HELP attribute for a controller that should
describe the functionality of the controller.
:rtype: str|None
"""
if hasattr(self._controllers[controller], 'HELP'):
return self._controllers[controll... | def function[_get_controller_help, parameter[self, controller]]:
constant[Return the value of the HELP attribute for a controller that should
describe the functionality of the controller.
:rtype: str|None
]
if call[name[hasattr], parameter[call[name[self]._controllers][name[con... | keyword[def] identifier[_get_controller_help] ( identifier[self] , identifier[controller] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] . identifier[_controllers] [ identifier[controller] ], literal[string] ):
keyword[return] identifier[self] . identifier[_con... | def _get_controller_help(self, controller):
"""Return the value of the HELP attribute for a controller that should
describe the functionality of the controller.
:rtype: str|None
"""
if hasattr(self._controllers[controller], 'HELP'):
return self._controllers[controller].HELP # ... |
def execute_python_script(self, script):
"""
Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution
"""
# Create the local file to copy to remote
file_handle,... | def function[execute_python_script, parameter[self, script]]:
constant[
Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution
]
<ast.Tuple object at 0x7da1b12aab60> ... | keyword[def] identifier[execute_python_script] ( identifier[self] , identifier[script] ):
literal[string]
identifier[file_handle] , identifier[filename] = identifier[tempfile] . identifier[mkstemp] ()
identifier[temp_file] = identifier[os] . identifier[fdopen] ( identifier[file_ha... | def execute_python_script(self, script):
"""
Execute a python script of the remote server
:param script: Inline script to convert to a file and execute remotely
:return: The output of the script execution
"""
# Create the local file to copy to remote
(file_handle, filename) ... |
def set(self, key, value):
""" Set a key's value regardless of whether a change is seen."""
return self.__setitem__(key, value, force=True) | def function[set, parameter[self, key, value]]:
constant[ Set a key's value regardless of whether a change is seen.]
return[call[name[self].__setitem__, parameter[name[key], name[value]]]] | keyword[def] identifier[set] ( identifier[self] , identifier[key] , identifier[value] ):
literal[string]
keyword[return] identifier[self] . identifier[__setitem__] ( identifier[key] , identifier[value] , identifier[force] = keyword[True] ) | def set(self, key, value):
""" Set a key's value regardless of whether a change is seen."""
return self.__setitem__(key, value, force=True) |
def similar(self, threshold, **criterias):
'''Find text-based field matches with similarity (1-levenshtein/length)
higher than specified threshold (0 to 1, 1 being an exact match)'''
# XXX: use F from https://docs.djangoproject.com/en/1.8/ref/models/expressions/
meta = self.model._meta
funcs, params = list()... | def function[similar, parameter[self, threshold]]:
constant[Find text-based field matches with similarity (1-levenshtein/length)
higher than specified threshold (0 to 1, 1 being an exact match)]
variable[meta] assign[=] name[self].model._meta
<ast.Tuple object at 0x7da18fe92740> assign[=] tup... | keyword[def] identifier[similar] ( identifier[self] , identifier[threshold] ,** identifier[criterias] ):
literal[string]
identifier[meta] = identifier[self] . identifier[model] . identifier[_meta]
identifier[funcs] , identifier[params] = identifier[list] (), identifier[list] ()
keyword[for] identifi... | def similar(self, threshold, **criterias):
"""Find text-based field matches with similarity (1-levenshtein/length)
higher than specified threshold (0 to 1, 1 being an exact match)""" # XXX: use F from https://docs.djangoproject.com/en/1.8/ref/models/expressions/
meta = self.model._meta
(funcs, params) =... |
def _build_url(self, endpoint):
"""
Builds the absolute URL using the target and desired endpoint.
"""
try:
path = self.endpoints[endpoint]
except KeyError:
msg = 'Unknown endpoint `{0}`'
raise ValueError(msg.format(endpoint))
absolute_... | def function[_build_url, parameter[self, endpoint]]:
constant[
Builds the absolute URL using the target and desired endpoint.
]
<ast.Try object at 0x7da1b063cf70>
variable[absolute_url] assign[=] call[name[urljoin], parameter[name[self].target, name[path]]]
return[name[absolute_u... | keyword[def] identifier[_build_url] ( identifier[self] , identifier[endpoint] ):
literal[string]
keyword[try] :
identifier[path] = identifier[self] . identifier[endpoints] [ identifier[endpoint] ]
keyword[except] identifier[KeyError] :
identifier[msg] = literal[s... | def _build_url(self, endpoint):
"""
Builds the absolute URL using the target and desired endpoint.
"""
try:
path = self.endpoints[endpoint] # depends on [control=['try'], data=[]]
except KeyError:
msg = 'Unknown endpoint `{0}`'
raise ValueError(msg.format(endpoint)) ... |
def _winreg_getShellFolder( name ):
"""Get a shell folder by string name from the registry"""
k = _winreg.OpenKey(
_winreg.HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
)
try:
# should check that it's valid? How?
return _winreg.Que... | def function[_winreg_getShellFolder, parameter[name]]:
constant[Get a shell folder by string name from the registry]
variable[k] assign[=] call[name[_winreg].OpenKey, parameter[name[_winreg].HKEY_CURRENT_USER, constant[Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders]]]
<ast.Try obje... | keyword[def] identifier[_winreg_getShellFolder] ( identifier[name] ):
literal[string]
identifier[k] = identifier[_winreg] . identifier[OpenKey] (
identifier[_winreg] . identifier[HKEY_CURRENT_USER] ,
literal[string]
)
keyword[try] :
keyword[return] identifier[_winreg] . i... | def _winreg_getShellFolder(name):
"""Get a shell folder by string name from the registry"""
k = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders')
try:
# should check that it's valid? How?
return _winreg.QueryValueEx(k, name)[0... |
def login_with_api_key(self, email, api_key, application='Default'):
"""
Login and get a token. If you do not specify a specific application,
'Default' will be used.
:param email: Email address of the user
:type email: string
:param api_key: API key assigned to the user
... | def function[login_with_api_key, parameter[self, email, api_key, application]]:
constant[
Login and get a token. If you do not specify a specific application,
'Default' will be used.
:param email: Email address of the user
:type email: string
:param api_key: API key assi... | keyword[def] identifier[login_with_api_key] ( identifier[self] , identifier[email] , identifier[api_key] , identifier[application] = literal[string] ):
literal[string]
identifier[parameters] = identifier[dict] ()
identifier[parameters] [ literal[string] ]= identifier[BaseDriver] . identifi... | def login_with_api_key(self, email, api_key, application='Default'):
"""
Login and get a token. If you do not specify a specific application,
'Default' will be used.
:param email: Email address of the user
:type email: string
:param api_key: API key assigned to the user
... |
def list_documents(self, limit=None):
""" Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
"""
limit_str = ''
if limit:
... | def function[list_documents, parameter[self, limit]]:
constant[ Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
]
variable[limit_str] assig... | keyword[def] identifier[list_documents] ( identifier[self] , identifier[limit] = keyword[None] ):
literal[string]
identifier[limit_str] = literal[string]
keyword[if] identifier[limit] :
keyword[try] :
identifier[limit_str] = literal[string] . identifier[form... | def list_documents(self, limit=None):
""" Generates vids of all indexed identifiers.
Args:
limit (int, optional): If not empty, the maximum number of results to return
Generates:
str: vid of the document.
"""
limit_str = ''
if limit:
try:
... |
def event(tagmatch='*',
count=-1,
quiet=False,
sock_dir=None,
pretty=False,
node='minion'):
r'''
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be eith... | def function[event, parameter[tagmatch, count, quiet, sock_dir, pretty, node]]:
constant[
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is useful ... | keyword[def] identifier[event] ( identifier[tagmatch] = literal[string] ,
identifier[count] =- literal[int] ,
identifier[quiet] = keyword[False] ,
identifier[sock_dir] = keyword[None] ,
identifier[pretty] = keyword[False] ,
identifier[node] = literal[string] ):
literal[string]
identifier[sevent] = ide... | def event(tagmatch='*', count=-1, quiet=False, sock_dir=None, pretty=False, node='minion'):
"""
Watch Salt's event bus and block until the given tag is matched
.. versionadded:: 2016.3.0
.. versionchanged:: 2019.2.0
``tagmatch`` can now be either a glob or regular expression.
This is usefu... |
def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# C-NMF params
niter = self.con... | def function[processFlat, parameter[self]]:
constant[Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
]
variable[niter... | keyword[def] identifier[processFlat] ( identifier[self] ):
literal[string]
identifier[niter] = identifier[self] . identifier[config] [ literal[string] ]
identifier[F] = identifier[self] . identifier[_preprocess] ()
identifier[F] = identifier[U] . ident... | def processFlat(self):
"""Main process.
Returns
-------
est_idxs : np.array(N)
Estimated indeces for the segment boundaries in frames.
est_labels : np.array(N-1)
Estimated labels for the segments.
"""
# C-NMF params
niter = self.config['niters'... |
def stop(self):
"""
Stop this process.
Once closed, it should not, and cannot be used again.
:return: :py:attr:`~exitcode`.
"""
self.child.terminate()
self._cleanup()
return self.child.exitcode | def function[stop, parameter[self]]:
constant[
Stop this process.
Once closed, it should not, and cannot be used again.
:return: :py:attr:`~exitcode`.
]
call[name[self].child.terminate, parameter[]]
call[name[self]._cleanup, parameter[]]
return[name[self].ch... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
identifier[self] . identifier[child] . identifier[terminate] ()
identifier[self] . identifier[_cleanup] ()
keyword[return] identifier[self] . identifier[child] . identifier[exitcode] | def stop(self):
"""
Stop this process.
Once closed, it should not, and cannot be used again.
:return: :py:attr:`~exitcode`.
"""
self.child.terminate()
self._cleanup()
return self.child.exitcode |
def right(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press right key n times.
**中文文档**
按右方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.right_key, n, interval)
self.delay(post_dl) | def function[right, parameter[self, n, interval, pre_dl, post_dl]]:
constant[Press right key n times.
**中文文档**
按右方向键 n 次。
]
call[name[self].delay, parameter[name[pre_dl]]]
call[name[self].k.tap_key, parameter[name[self].k.right_key, name[n], name[interval]]]
cal... | keyword[def] identifier[right] ( identifier[self] , identifier[n] = literal[int] , identifier[interval] = literal[int] , identifier[pre_dl] = keyword[None] , identifier[post_dl] = keyword[None] ):
literal[string]
identifier[self] . identifier[delay] ( identifier[pre_dl] )
identifier[self] ... | def right(self, n=1, interval=0, pre_dl=None, post_dl=None):
"""Press right key n times.
**中文文档**
按右方向键 n 次。
"""
self.delay(pre_dl)
self.k.tap_key(self.k.right_key, n, interval)
self.delay(post_dl) |
def check_schema_transforms_match(schema, inverted_features):
"""Checks that the transform and schema do not conflict.
Args:
schema: schema list
inverted_features: inverted_features dict
Raises:
ValueError if transform cannot be applied given schema type.
"""
num_target_transforms = 0
for col... | def function[check_schema_transforms_match, parameter[schema, inverted_features]]:
constant[Checks that the transform and schema do not conflict.
Args:
schema: schema list
inverted_features: inverted_features dict
Raises:
ValueError if transform cannot be applied given schema type.
]
... | keyword[def] identifier[check_schema_transforms_match] ( identifier[schema] , identifier[inverted_features] ):
literal[string]
identifier[num_target_transforms] = literal[int]
keyword[for] identifier[col_schema] keyword[in] identifier[schema] :
identifier[col_name] = identifier[col_schema] [ liter... | def check_schema_transforms_match(schema, inverted_features):
"""Checks that the transform and schema do not conflict.
Args:
schema: schema list
inverted_features: inverted_features dict
Raises:
ValueError if transform cannot be applied given schema type.
"""
num_target_transforms = 0
fo... |
def _resolve_template(value, model_instance=None, context=None):
"""Resolves any template references in the given value."""
if isinstance(value, string_types) and "{" in value:
if context is None:
context = Context()
if model_instance is not None:
... | def function[_resolve_template, parameter[value, model_instance, context]]:
constant[Resolves any template references in the given value.]
if <ast.BoolOp object at 0x7da207f01c60> begin[:]
if compare[name[context] is constant[None]] begin[:]
variable[context] assi... | keyword[def] identifier[_resolve_template] ( identifier[value] , identifier[model_instance] = keyword[None] , identifier[context] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[string_types] ) keyword[and] literal[string] keyword[in] ident... | def _resolve_template(value, model_instance=None, context=None):
"""Resolves any template references in the given value."""
if isinstance(value, string_types) and '{' in value:
if context is None:
context = Context() # depends on [control=['if'], data=['context']]
if model_instance ... |
def query_pmid():
"""
Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
... | def function[query_pmid, parameter[]]:
constant[
Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697... | keyword[def] identifier[query_pmid] ():
literal[string]
identifier[args] = identifier[get_args] (
identifier[request_args] = identifier[request] . identifier[args] ,
identifier[allowed_str_args] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[s... | def query_pmid():
"""
Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
... |
def parent(self):
"""Parent directory that holds this directory"""
if self._parent is None:
if self.pid is not None:
self._parent = self.api._load_directory(self.pid)
return self._parent | def function[parent, parameter[self]]:
constant[Parent directory that holds this directory]
if compare[name[self]._parent is constant[None]] begin[:]
if compare[name[self].pid is_not constant[None]] begin[:]
name[self]._parent assign[=] call[name[self].api._load_d... | keyword[def] identifier[parent] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_parent] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[pid] keyword[is] keyword[not] keyword[None] :
identifier[self] . identi... | def parent(self):
"""Parent directory that holds this directory"""
if self._parent is None:
if self.pid is not None:
self._parent = self.api._load_directory(self.pid) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return self._parent |
def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None,
weights_column=None, validation_frame=None, max_runtime_secs=None, ignored_columns=None,
model_id=None, verbose=False):
"""
Train the H2O model.
:param x: A list of column name... | def function[train, parameter[self, x, y, training_frame, offset_column, fold_column, weights_column, validation_frame, max_runtime_secs, ignored_columns, model_id, verbose]]:
constant[
Train the H2O model.
:param x: A list of column names or indices indicating the predictor columns.
:p... | keyword[def] identifier[train] ( identifier[self] , identifier[x] = keyword[None] , identifier[y] = keyword[None] , identifier[training_frame] = keyword[None] , identifier[offset_column] = keyword[None] , identifier[fold_column] = keyword[None] ,
identifier[weights_column] = keyword[None] , identifier[validation_fra... | def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None, weights_column=None, validation_frame=None, max_runtime_secs=None, ignored_columns=None, model_id=None, verbose=False):
"""
Train the H2O model.
:param x: A list of column names or indices indicating the pred... |
def main(reactor):
"""
Close all open streams and circuits in the Tor we connect to
"""
control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control')
tor = yield txtorcon.connect(reactor, control_ep)
state = yield tor.create_state()
print("Closing all circuits:")
for circuit in list(s... | def function[main, parameter[reactor]]:
constant[
Close all open streams and circuits in the Tor we connect to
]
variable[control_ep] assign[=] call[name[UNIXClientEndpoint], parameter[name[reactor], constant[/var/run/tor/control]]]
variable[tor] assign[=] <ast.Yield object at 0x7da20c6a... | keyword[def] identifier[main] ( identifier[reactor] ):
literal[string]
identifier[control_ep] = identifier[UNIXClientEndpoint] ( identifier[reactor] , literal[string] )
identifier[tor] = keyword[yield] identifier[txtorcon] . identifier[connect] ( identifier[reactor] , identifier[control_ep] )
id... | def main(reactor):
"""
Close all open streams and circuits in the Tor we connect to
"""
control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control')
tor = (yield txtorcon.connect(reactor, control_ep))
state = (yield tor.create_state())
print('Closing all circuits:')
for circuit in li... |
def get_go2nt_all(self, rcntobj):
"""For each GO id, put all printable fields in one namedtuple."""
if 'go2nt' in self.kws:
go2nt = self.kws['go2nt']
return {go:go2nt[go] for go in self.go2obj}
else:
return self._get_go2nt_all(rcntobj) | def function[get_go2nt_all, parameter[self, rcntobj]]:
constant[For each GO id, put all printable fields in one namedtuple.]
if compare[constant[go2nt] in name[self].kws] begin[:]
variable[go2nt] assign[=] call[name[self].kws][constant[go2nt]]
return[<ast.DictComp object at 0x7da... | keyword[def] identifier[get_go2nt_all] ( identifier[self] , identifier[rcntobj] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[kws] :
identifier[go2nt] = identifier[self] . identifier[kws] [ literal[string] ]
keyword[return] { i... | def get_go2nt_all(self, rcntobj):
"""For each GO id, put all printable fields in one namedtuple."""
if 'go2nt' in self.kws:
go2nt = self.kws['go2nt']
return {go: go2nt[go] for go in self.go2obj} # depends on [control=['if'], data=[]]
else:
return self._get_go2nt_all(rcntobj) |
def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest() | def function[candidate_foundation, parameter[candidate_type, candidate_transport, base_address]]:
constant[
See RFC 5245 - 4.1.1.3. Computing Foundations
]
variable[key] assign[=] binary_operation[constant[%s|%s|%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18f00ee30>, <... | keyword[def] identifier[candidate_foundation] ( identifier[candidate_type] , identifier[candidate_transport] , identifier[base_address] ):
literal[string]
identifier[key] = literal[string] %( identifier[candidate_type] , identifier[candidate_transport] , identifier[base_address] )
keyword[return] ide... | def candidate_foundation(candidate_type, candidate_transport, base_address):
"""
See RFC 5245 - 4.1.1.3. Computing Foundations
"""
key = '%s|%s|%s' % (candidate_type, candidate_transport, base_address)
return hashlib.md5(key.encode('ascii')).hexdigest() |
def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def ... | def function[_get_namedrange, parameter[book, rangename, sheetname]]:
constant[Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
... | keyword[def] identifier[_get_namedrange] ( identifier[book] , identifier[rangename] , identifier[sheetname] = keyword[None] ):
literal[string]
keyword[def] identifier[cond] ( identifier[namedef] ):
keyword[if] identifier[namedef] . identifier[type] . identifier[upper] ()== literal[string] :
... | def _get_namedrange(book, rangename, sheetname=None):
"""Get range from a workbook.
A workbook can contain multiple definitions for a single name,
as a name can be defined for the entire book or for
a particular sheet.
If sheet is None, the book-wide def is searched,
otherwise sheet-local def ... |
def set_active_state(self, name, value):
"""Set active state."""
if name not in self.__active_states.keys():
raise ValueError("Can not set unknown state '" + name + "'")
if (isinstance(self.__active_states[name], int) and
isinstance(value, str)):
# we get... | def function[set_active_state, parameter[self, name, value]]:
constant[Set active state.]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> call[name[self].__active_states.keys, parameter[]]] begin[:]
<ast.Raise object at 0x7da1b0d57ca0>
if <ast.BoolOp object at 0x7da1b0d56ce0> ... | keyword[def] identifier[set_active_state] ( identifier[self] , identifier[name] , identifier[value] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[__active_states] . identifier[keys] ():
keyword[raise] identifier[ValueError] ... | def set_active_state(self, name, value):
"""Set active state."""
if name not in self.__active_states.keys():
raise ValueError("Can not set unknown state '" + name + "'") # depends on [control=['if'], data=['name']]
if isinstance(self.__active_states[name], int) and isinstance(value, str):
#... |
def S_isothermal_pipe_to_isothermal_pipe(D1, D2, W, L=1.):
r'''Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D1` which is `w` distance from another infinite
pipe of outer diameter`D2`. Length `L` must be provided, but can be set to
1 to obtain a dimensionles... | def function[S_isothermal_pipe_to_isothermal_pipe, parameter[D1, D2, W, L]]:
constant[Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D1` which is `w` distance from another infinite
pipe of outer diameter`D2`. Length `L` must be provided, but can be set to
... | keyword[def] identifier[S_isothermal_pipe_to_isothermal_pipe] ( identifier[D1] , identifier[D2] , identifier[W] , identifier[L] = literal[int] ):
literal[string]
keyword[return] literal[int] * identifier[pi] * identifier[L] / identifier[acosh] (( literal[int] * identifier[W] ** literal[int] - identifier[D... | def S_isothermal_pipe_to_isothermal_pipe(D1, D2, W, L=1.0):
"""Returns the Shape factor `S` of a pipe of constant outer temperature
and of outer diameter `D1` which is `w` distance from another infinite
pipe of outer diameter`D2`. Length `L` must be provided, but can be set to
1 to obtain a dimensionles... |
def __get_dbms_version(self, make_connection=True):
"""
Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True.
"""
if not self.connection and make_connection:
... | def function[__get_dbms_version, parameter[self, make_connection]]:
constant[
Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True.
]
if <ast.BoolOp object at 0... | keyword[def] identifier[__get_dbms_version] ( identifier[self] , identifier[make_connection] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[connection] keyword[and] identifier[make_connection] :
identifier[self] . identifier[connect] ()
... | def __get_dbms_version(self, make_connection=True):
"""
Returns the 'DBMS Version' string, or ''. If a connection to the
database has not already been established, a connection will be made
when `make_connection` is True.
"""
if not self.connection and make_connection:
se... |
def _output_format(cls, func, override=None):
""" Decorator in charge of giving the output its right format, either
json or pandas
Keyword Arguments:
func: The function to be decorated
override: Override the internal format of the call, default None
"""
... | def function[_output_format, parameter[cls, func, override]]:
constant[ Decorator in charge of giving the output its right format, either
json or pandas
Keyword Arguments:
func: The function to be decorated
override: Override the internal format of the call, default No... | keyword[def] identifier[_output_format] ( identifier[cls] , identifier[func] , identifier[override] = keyword[None] ):
literal[string]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[_format_wrapper] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
... | def _output_format(cls, func, override=None):
""" Decorator in charge of giving the output its right format, either
json or pandas
Keyword Arguments:
func: The function to be decorated
override: Override the internal format of the call, default None
"""
@wraps... |
def instructions(self):
"""
Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction.
"""
if not self.is_block:
raise ValueError('expected block value, got %s' % (self._kind,))
it = ffi.lib.LLVMPY_BlockInstruct... | def function[instructions, parameter[self]]:
constant[
Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction.
]
if <ast.UnaryOp object at 0x7da1b18a17b0> begin[:]
<ast.Raise object at 0x7da1b18a28c0>
variable[it... | keyword[def] identifier[instructions] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_block] :
keyword[raise] identifier[ValueError] ( literal[string] %( identifier[self] . identifier[_kind] ,))
identifier[it] = identifier[ffi... | def instructions(self):
"""
Return an iterator over this block's instructions.
The iterator will yield a ValueRef for each instruction.
"""
if not self.is_block:
raise ValueError('expected block value, got %s' % (self._kind,)) # depends on [control=['if'], data=[]]
it = ffi.... |
def sampler(dataframe, modulo, column="client_id", sample_id=42):
""" Collect a sample of clients given an input column
Filter dataframe based on the modulus of the CRC32 of a given string
column matching a given sample_id. if dataframe has already been filtered
by sample_id, then modulo should be a mu... | def function[sampler, parameter[dataframe, modulo, column, sample_id]]:
constant[ Collect a sample of clients given an input column
Filter dataframe based on the modulus of the CRC32 of a given string
column matching a given sample_id. if dataframe has already been filtered
by sample_id, then modul... | keyword[def] identifier[sampler] ( identifier[dataframe] , identifier[modulo] , identifier[column] = literal[string] , identifier[sample_id] = literal[int] ):
literal[string]
keyword[return] identifier[dataframe] . identifier[withColumn] (
literal[string] ,
identifier[udf] ( keyword[lambda] ide... | def sampler(dataframe, modulo, column='client_id', sample_id=42):
""" Collect a sample of clients given an input column
Filter dataframe based on the modulus of the CRC32 of a given string
column matching a given sample_id. if dataframe has already been filtered
by sample_id, then modulo should be a mu... |
def changeGroupImageRemote(self, image_url, thread_id=None):
"""
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
... | def function[changeGroupImageRemote, parameter[self, image_url, thread_id]]:
constant[
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if r... | keyword[def] identifier[changeGroupImageRemote] ( identifier[self] , identifier[image_url] , identifier[thread_id] = keyword[None] ):
literal[string]
( identifier[image_id] , identifier[mimetype] ),= identifier[self] . identifier[_upload] ( identifier[get_files_from_urls] ([ identifier[image_url] ])... | def changeGroupImageRemote(self, image_url, thread_id=None):
"""
Changes a thread image from a URL
:param image_url: URL of an image to upload and change
:param thread_id: User/Group ID to change image. See :ref:`intro_threads`
:raises: FBchatException if request failed
"""
... |
def _write_zip(self, func_src, fpath):
"""
Write the function source to a zip file, suitable for upload to
Lambda.
Note there's a bit of undocumented magic going on here; Lambda needs
the execute bit set on the module with the handler in it (i.e. 0755
or 0555 permissions... | def function[_write_zip, parameter[self, func_src, fpath]]:
constant[
Write the function source to a zip file, suitable for upload to
Lambda.
Note there's a bit of undocumented magic going on here; Lambda needs
the execute bit set on the module with the handler in it (i.e. 0755
... | keyword[def] identifier[_write_zip] ( identifier[self] , identifier[func_src] , identifier[fpath] ):
literal[string]
identifier[now] = identifier[datetime] . identifier[now] ()
identifier[zi_tup] =( identifier[now] . identifier[year] , identifier[now] . identifier[month] , identif... | def _write_zip(self, func_src, fpath):
"""
Write the function source to a zip file, suitable for upload to
Lambda.
Note there's a bit of undocumented magic going on here; Lambda needs
the execute bit set on the module with the handler in it (i.e. 0755
or 0555 permissions). T... |
def wait_next_block_factory(app, timeout=None):
"""Creates a `wait_next_block` function, that
will wait `timeout` seconds (`None` = indefinitely)
for a new block to appear.
:param app: the app-instance the function should work for
:param timeout: timeout in seconds
"""
chain = app.services... | def function[wait_next_block_factory, parameter[app, timeout]]:
constant[Creates a `wait_next_block` function, that
will wait `timeout` seconds (`None` = indefinitely)
for a new block to appear.
:param app: the app-instance the function should work for
:param timeout: timeout in seconds
]
... | keyword[def] identifier[wait_next_block_factory] ( identifier[app] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[chain] = identifier[app] . identifier[services] . identifier[chain]
identifier[new_block_evt] = identifier[gevent] . identifier[event] . identifier[Event] ()
... | def wait_next_block_factory(app, timeout=None):
"""Creates a `wait_next_block` function, that
will wait `timeout` seconds (`None` = indefinitely)
for a new block to appear.
:param app: the app-instance the function should work for
:param timeout: timeout in seconds
"""
chain = app.services.... |
def Back(self, n = 1, dl = 0):
"""退格键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.backspace_key, n) | def function[Back, parameter[self, n, dl]]:
constant[退格键n次
]
call[name[self].Delay, parameter[name[dl]]]
call[name[self].keyboard.tap_key, parameter[name[self].keyboard.backspace_key, name[n]]] | keyword[def] identifier[Back] ( identifier[self] , identifier[n] = literal[int] , identifier[dl] = literal[int] ):
literal[string]
identifier[self] . identifier[Delay] ( identifier[dl] )
identifier[self] . identifier[keyboard] . identifier[tap_key] ( identifier[self] . identifier[keyboard]... | def Back(self, n=1, dl=0):
"""退格键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.backspace_key, n) |
def syslog_generate(str_processName, str_pid):
'''
Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id.
'''
localtime = time.asct... | def function[syslog_generate, parameter[str_processName, str_pid]]:
constant[
Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id.
]
... | keyword[def] identifier[syslog_generate] ( identifier[str_processName] , identifier[str_pid] ):
literal[string]
identifier[localtime] = identifier[time] . identifier[asctime] ( identifier[time] . identifier[localtime] ( identifier[time] . identifier[time] ()))
identifier[hostname] = identifier[o... | def syslog_generate(str_processName, str_pid):
"""
Returns a string similar to:
Tue Oct 9 10:49:53 2012 pretoria message.py[26873]:
where 'pretoria' is the hostname, 'message.py' is the current process
name and 26873 is the current process id.
"""
localtime = time.asctime(... |
def sector(self, start_ray, end_ray, start_distance=None, end_distance=None, units='b'):
"""Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
slicin... | def function[sector, parameter[self, start_ray, end_ray, start_distance, end_distance, units]]:
constant[Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
... | keyword[def] identifier[sector] ( identifier[self] , identifier[start_ray] , identifier[end_ray] , identifier[start_distance] = keyword[None] , identifier[end_distance] = keyword[None] , identifier[units] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[dataset] keyw... | def sector(self, start_ray, end_ray, start_distance=None, end_distance=None, units='b'):
"""Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
slicing co... |
def AddServiceDescriptor(self, service_desc):
"""Adds a ServiceDescriptor to the pool.
Args:
service_desc: A ServiceDescriptor.
"""
if not isinstance(service_desc, descriptor.ServiceDescriptor):
raise TypeError('Expected instance of descriptor.ServiceDescriptor.')
self._service_descri... | def function[AddServiceDescriptor, parameter[self, service_desc]]:
constant[Adds a ServiceDescriptor to the pool.
Args:
service_desc: A ServiceDescriptor.
]
if <ast.UnaryOp object at 0x7da1b208c040> begin[:]
<ast.Raise object at 0x7da1b1f77b80>
call[name[self]._service_des... | keyword[def] identifier[AddServiceDescriptor] ( identifier[self] , identifier[service_desc] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[service_desc] , identifier[descriptor] . identifier[ServiceDescriptor] ):
keyword[raise] identifier[TypeError] ( literal[str... | def AddServiceDescriptor(self, service_desc):
"""Adds a ServiceDescriptor to the pool.
Args:
service_desc: A ServiceDescriptor.
"""
if not isinstance(service_desc, descriptor.ServiceDescriptor):
raise TypeError('Expected instance of descriptor.ServiceDescriptor.') # depends on [control=[... |
def get_params(self, deep=False):
"""Get parameters."""
params = super(XGBModel, self).get_params(deep=deep)
if isinstance(self.kwargs, dict): # if kwargs is a dict, update params accordingly
params.update(self.kwargs)
if params['missing'] is np.nan:
params['miss... | def function[get_params, parameter[self, deep]]:
constant[Get parameters.]
variable[params] assign[=] call[call[name[super], parameter[name[XGBModel], name[self]]].get_params, parameter[]]
if call[name[isinstance], parameter[name[self].kwargs, name[dict]]] begin[:]
call[name[para... | keyword[def] identifier[get_params] ( identifier[self] , identifier[deep] = keyword[False] ):
literal[string]
identifier[params] = identifier[super] ( identifier[XGBModel] , identifier[self] ). identifier[get_params] ( identifier[deep] = identifier[deep] )
keyword[if] identifier[isinstanc... | def get_params(self, deep=False):
"""Get parameters."""
params = super(XGBModel, self).get_params(deep=deep)
if isinstance(self.kwargs, dict): # if kwargs is a dict, update params accordingly
params.update(self.kwargs) # depends on [control=['if'], data=[]]
if params['missing'] is np.nan:
... |
def set_random_state(state):
"""Force-set the state of factory.fuzzy's random generator."""
randgen.state_set = True
randgen.setstate(state)
faker.generator.random.setstate(state) | def function[set_random_state, parameter[state]]:
constant[Force-set the state of factory.fuzzy's random generator.]
name[randgen].state_set assign[=] constant[True]
call[name[randgen].setstate, parameter[name[state]]]
call[name[faker].generator.random.setstate, parameter[name[state]]] | keyword[def] identifier[set_random_state] ( identifier[state] ):
literal[string]
identifier[randgen] . identifier[state_set] = keyword[True]
identifier[randgen] . identifier[setstate] ( identifier[state] )
identifier[faker] . identifier[generator] . identifier[random] . identifier[setstate] ( i... | def set_random_state(state):
"""Force-set the state of factory.fuzzy's random generator."""
randgen.state_set = True
randgen.setstate(state)
faker.generator.random.setstate(state) |
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
return False
# Chec... | def function[is_positive_semidefinite_matrix, parameter[mat, rtol, atol]]:
constant[Test if a matrix is positive semidefinite]
if compare[name[atol] is constant[None]] begin[:]
variable[atol] assign[=] name[ATOL_DEFAULT]
if compare[name[rtol] is constant[None]] begin[:]
... | keyword[def] identifier[is_positive_semidefinite_matrix] ( identifier[mat] , identifier[rtol] = identifier[RTOL_DEFAULT] , identifier[atol] = identifier[ATOL_DEFAULT] ):
literal[string]
keyword[if] identifier[atol] keyword[is] keyword[None] :
identifier[atol] = identifier[ATOL_DEFAULT]
ke... | def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT # depends on [control=['if'], data=['atol']]
if rtol is None:
rtol = RTOL_DEFAULT # depends on [control=['if'], data=['rtol']... |
def is_operation(term: Any) -> bool:
"""Return True iff the given term is a subclass of :class:`.Operation`."""
return isinstance(term, type) and issubclass(term, Operation) | def function[is_operation, parameter[term]]:
constant[Return True iff the given term is a subclass of :class:`.Operation`.]
return[<ast.BoolOp object at 0x7da1b06cee00>] | keyword[def] identifier[is_operation] ( identifier[term] : identifier[Any] )-> identifier[bool] :
literal[string]
keyword[return] identifier[isinstance] ( identifier[term] , identifier[type] ) keyword[and] identifier[issubclass] ( identifier[term] , identifier[Operation] ) | def is_operation(term: Any) -> bool:
"""Return True iff the given term is a subclass of :class:`.Operation`."""
return isinstance(term, type) and issubclass(term, Operation) |
def rosh_hashana_dow(self):
"""Return the Hebrew day of week for Rosh Hashana."""
jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Tishrei, 1))
return (jdn + 1) % 7 + 1 | def function[rosh_hashana_dow, parameter[self]]:
constant[Return the Hebrew day of week for Rosh Hashana.]
variable[jdn] assign[=] call[name[conv].hdate_to_jdn, parameter[call[name[HebrewDate], parameter[name[self].hdate.year, name[Months].Tishrei, constant[1]]]]]
return[binary_operation[binary_oper... | keyword[def] identifier[rosh_hashana_dow] ( identifier[self] ):
literal[string]
identifier[jdn] = identifier[conv] . identifier[hdate_to_jdn] ( identifier[HebrewDate] ( identifier[self] . identifier[hdate] . identifier[year] , identifier[Months] . identifier[Tishrei] , literal[int] ))
keyw... | def rosh_hashana_dow(self):
"""Return the Hebrew day of week for Rosh Hashana."""
jdn = conv.hdate_to_jdn(HebrewDate(self.hdate.year, Months.Tishrei, 1))
return (jdn + 1) % 7 + 1 |
def _findRow(subNo, model):
"""Finds a row in a given model which has a column with a given
number."""
items = model.findItems(str(subNo))
if len(items) == 0:
return None
if len(items) > 1:
raise IndexError("Too many items with sub number %s" % subNo)
return items[0].row() | def function[_findRow, parameter[subNo, model]]:
constant[Finds a row in a given model which has a column with a given
number.]
variable[items] assign[=] call[name[model].findItems, parameter[call[name[str], parameter[name[subNo]]]]]
if compare[call[name[len], parameter[name[items]]] equal[=... | keyword[def] identifier[_findRow] ( identifier[subNo] , identifier[model] ):
literal[string]
identifier[items] = identifier[model] . identifier[findItems] ( identifier[str] ( identifier[subNo] ))
keyword[if] identifier[len] ( identifier[items] )== literal[int] :
keyword[return] keyword[None... | def _findRow(subNo, model):
"""Finds a row in a given model which has a column with a given
number."""
items = model.findItems(str(subNo))
if len(items) == 0:
return None # depends on [control=['if'], data=[]]
if len(items) > 1:
raise IndexError('Too many items with sub number %s' %... |
def d2logpdf_df2(self, f, y, Y_metadata=None):
"""
Evaluates the link function link(f) then computes the second derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\\frac{d^{2}\\log p(y|\\lambda(f))}{df^{2}} = \\frac{d^{2}\\log ... | def function[d2logpdf_df2, parameter[self, f, y, Y_metadata]]:
constant[
Evaluates the link function link(f) then computes the second derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\frac{d^{2}\log p(y|\lambda(f))}{df^{2}} =... | keyword[def] identifier[d2logpdf_df2] ( identifier[self] , identifier[f] , identifier[y] , identifier[Y_metadata] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[gp_link] , identifier[link_functions] . identifier[Identity] ):
ident... | def d2logpdf_df2(self, f, y, Y_metadata=None):
"""
Evaluates the link function link(f) then computes the second derivative of log likelihood using it
Uses the Faa di Bruno's formula for the chain rule
.. math::
\\frac{d^{2}\\log p(y|\\lambda(f))}{df^{2}} = \\frac{d^{2}\\log p(y|... |
def free_parameters(self):
"""
Returns a dictionary of free parameters for this source.
We use the parameter path as the key because it's
guaranteed to be unique, unlike the parameter name.
:return:
"""
free_parameters = collections.OrderedDict()
for co... | def function[free_parameters, parameter[self]]:
constant[
Returns a dictionary of free parameters for this source.
We use the parameter path as the key because it's
guaranteed to be unique, unlike the parameter name.
:return:
]
variable[free_parameters] assign[=... | keyword[def] identifier[free_parameters] ( identifier[self] ):
literal[string]
identifier[free_parameters] = identifier[collections] . identifier[OrderedDict] ()
keyword[for] identifier[component] keyword[in] identifier[self] . identifier[_components] . identifier[values] ():
... | def free_parameters(self):
"""
Returns a dictionary of free parameters for this source.
We use the parameter path as the key because it's
guaranteed to be unique, unlike the parameter name.
:return:
"""
free_parameters = collections.OrderedDict()
for component in se... |
def save(self,
filename="phonopy_params.yaml",
settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
I... | def function[save, parameter[self, filename, settings]]:
constant[Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which param... | keyword[def] identifier[save] ( identifier[self] ,
identifier[filename] = literal[string] ,
identifier[settings] = keyword[None] ):
literal[string]
identifier[phpy_yaml] = identifier[PhonopyYaml] ( identifier[calculator] = identifier[self] . identifier[_calculator] ,
identifier[settings]... | def save(self, filename='phonopy_params.yaml', settings=None):
"""Save parameters in Phonopy instants into file.
Parameters
----------
filename: str, optional
File name. Default is "phonopy_params.yaml"
settings: dict, optional
It is described which parameter... |
def unsigned_input(outpoint, redeem_script=None, sequence=None):
'''
Outpoint, byte-like, int -> TxIn
'''
if redeem_script is not None and sequence is None:
sequence = guess_sequence(redeem_script)
if sequence is None:
sequence = 0xFFFFFFFE
return tb.make_legacy_input(
ou... | def function[unsigned_input, parameter[outpoint, redeem_script, sequence]]:
constant[
Outpoint, byte-like, int -> TxIn
]
if <ast.BoolOp object at 0x7da1b06775e0> begin[:]
variable[sequence] assign[=] call[name[guess_sequence], parameter[name[redeem_script]]]
if compare[na... | keyword[def] identifier[unsigned_input] ( identifier[outpoint] , identifier[redeem_script] = keyword[None] , identifier[sequence] = keyword[None] ):
literal[string]
keyword[if] identifier[redeem_script] keyword[is] keyword[not] keyword[None] keyword[and] identifier[sequence] keyword[is] keyword[Non... | def unsigned_input(outpoint, redeem_script=None, sequence=None):
"""
Outpoint, byte-like, int -> TxIn
"""
if redeem_script is not None and sequence is None:
sequence = guess_sequence(redeem_script) # depends on [control=['if'], data=[]]
if sequence is None:
sequence = 4294967294 # ... |
def add_external_tracker(self, bug_ids, ext_bz_bug_id, ext_type_id=None,
ext_type_description=None, ext_type_url=None,
ext_status=None, ext_description=None,
ext_priority=None):
"""
Wrapper method to allow adding of e... | def function[add_external_tracker, parameter[self, bug_ids, ext_bz_bug_id, ext_type_id, ext_type_description, ext_type_url, ext_status, ext_description, ext_priority]]:
constant[
Wrapper method to allow adding of external tracking bugs using the
ExternalBugs::WebService::add_external_bug method.... | keyword[def] identifier[add_external_tracker] ( identifier[self] , identifier[bug_ids] , identifier[ext_bz_bug_id] , identifier[ext_type_id] = keyword[None] ,
identifier[ext_type_description] = keyword[None] , identifier[ext_type_url] = keyword[None] ,
identifier[ext_status] = keyword[None] , identifier[ext_descrip... | def add_external_tracker(self, bug_ids, ext_bz_bug_id, ext_type_id=None, ext_type_description=None, ext_type_url=None, ext_status=None, ext_description=None, ext_priority=None):
"""
Wrapper method to allow adding of external tracking bugs using the
ExternalBugs::WebService::add_external_bug method.
... |
def sink_update(
self, project, sink_name, filter_, destination, unique_writer_identity=False
):
"""API call: update a sink resource.
:type project: str
:param project: ID of the project containing the sink.
:type sink_name: str
:param sink_name: the name of the si... | def function[sink_update, parameter[self, project, sink_name, filter_, destination, unique_writer_identity]]:
constant[API call: update a sink resource.
:type project: str
:param project: ID of the project containing the sink.
:type sink_name: str
:param sink_name: the name of... | keyword[def] identifier[sink_update] (
identifier[self] , identifier[project] , identifier[sink_name] , identifier[filter_] , identifier[destination] , identifier[unique_writer_identity] = keyword[False]
):
literal[string]
identifier[path] = literal[string] %( identifier[project] , identifier[sin... | def sink_update(self, project, sink_name, filter_, destination, unique_writer_identity=False):
"""API call: update a sink resource.
:type project: str
:param project: ID of the project containing the sink.
:type sink_name: str
:param sink_name: the name of the sink
:type ... |
def get_allposts(self):
''' Return all posts in blog sorted by date
'''
result = self.client.posts(self.blog, offset = 0, limit = 1)
try:
total_posts = result['total_posts']
except:
raise phasetumblr_errors.TumblrBlogException(result['meta']['msg'])
delta = (total_posts / 10) + 1
all_posts = []
... | def function[get_allposts, parameter[self]]:
constant[ Return all posts in blog sorted by date
]
variable[result] assign[=] call[name[self].client.posts, parameter[name[self].blog]]
<ast.Try object at 0x7da1b15f7040>
variable[delta] assign[=] binary_operation[binary_operation[name[total_po... | keyword[def] identifier[get_allposts] ( identifier[self] ):
literal[string]
identifier[result] = identifier[self] . identifier[client] . identifier[posts] ( identifier[self] . identifier[blog] , identifier[offset] = literal[int] , identifier[limit] = literal[int] )
keyword[try] :
identifier[total_posts]... | def get_allposts(self):
""" Return all posts in blog sorted by date
"""
result = self.client.posts(self.blog, offset=0, limit=1)
try:
total_posts = result['total_posts'] # depends on [control=['try'], data=[]]
except:
raise phasetumblr_errors.TumblrBlogException(result['meta']['msg'])... |
def make_json_response(rv):
""" Make JsonResponse
:param rv: Response: the object to encode, or tuple (response, status, headers)
:type rv: tuple|*
:rtype: JsonResponse
"""
# Tuple of (response, status, headers)
rv, status, headers = normalize_response_value(rv)
# JsonResponse
if is... | def function[make_json_response, parameter[rv]]:
constant[ Make JsonResponse
:param rv: Response: the object to encode, or tuple (response, status, headers)
:type rv: tuple|*
:rtype: JsonResponse
]
<ast.Tuple object at 0x7da18eb55690> assign[=] call[name[normalize_response_value], parame... | keyword[def] identifier[make_json_response] ( identifier[rv] ):
literal[string]
identifier[rv] , identifier[status] , identifier[headers] = identifier[normalize_response_value] ( identifier[rv] )
keyword[if] identifier[isinstance] ( identifier[rv] , identifier[JsonResponse] ):
key... | def make_json_response(rv):
""" Make JsonResponse
:param rv: Response: the object to encode, or tuple (response, status, headers)
:type rv: tuple|*
:rtype: JsonResponse
"""
# Tuple of (response, status, headers)
(rv, status, headers) = normalize_response_value(rv)
# JsonResponse
if i... |
def handle(self, connection_id, message_content):
"""
The simplest authorization type will be Trust. If Trust authorization
is enabled, the validator will trust the connection and approve any
roles requested that are available on that endpoint. If the requester
wishes to gain acc... | def function[handle, parameter[self, connection_id, message_content]]:
constant[
The simplest authorization type will be Trust. If Trust authorization
is enabled, the validator will trust the connection and approve any
roles requested that are available on that endpoint. If the requester... | keyword[def] identifier[handle] ( identifier[self] , identifier[connection_id] , identifier[message_content] ):
literal[string]
keyword[if] identifier[self] . identifier[_network] . identifier[get_connection_status] ( identifier[connection_id] )!= identifier[ConnectionStatus] . identifier[CONNECTI... | def handle(self, connection_id, message_content):
"""
The simplest authorization type will be Trust. If Trust authorization
is enabled, the validator will trust the connection and approve any
roles requested that are available on that endpoint. If the requester
wishes to gain access ... |
def _execActions(self, type, msg):
""" Execute Registered Actions """
for action in self.ACTIONS:
action(type, msg) | def function[_execActions, parameter[self, type, msg]]:
constant[ Execute Registered Actions ]
for taget[name[action]] in starred[name[self].ACTIONS] begin[:]
call[name[action], parameter[name[type], name[msg]]] | keyword[def] identifier[_execActions] ( identifier[self] , identifier[type] , identifier[msg] ):
literal[string]
keyword[for] identifier[action] keyword[in] identifier[self] . identifier[ACTIONS] :
identifier[action] ( identifier[type] , identifier[msg] ) | def _execActions(self, type, msg):
""" Execute Registered Actions """
for action in self.ACTIONS:
action(type, msg) # depends on [control=['for'], data=['action']] |
def RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False):
"""Apply RANSAC.
This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated u... | def function[RANSAC, parameter[model_func, eval_func, data, num_points, num_iter, threshold, recalculate]]:
constant[Apply RANSAC.
This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then ... | keyword[def] identifier[RANSAC] ( identifier[model_func] , identifier[eval_func] , identifier[data] , identifier[num_points] , identifier[num_iter] , identifier[threshold] , identifier[recalculate] = keyword[False] ):
literal[string]
identifier[M] = keyword[None]
identifier[max_consensus] = literal[i... | def RANSAC(model_func, eval_func, data, num_points, num_iter, threshold, recalculate=False):
"""Apply RANSAC.
This RANSAC implementation will choose the best model based on the number of points in the consensus set. At evaluation time the model is created using num_points points. Then it will be recalculated u... |
def reflect(self, bind='__all__', app=None):
"""Reflects tables from the database.
.. versionchanged:: 0.12
Parameters were added
"""
self._execute_for_all_tables(app, bind, 'reflect', skip_tables=True) | def function[reflect, parameter[self, bind, app]]:
constant[Reflects tables from the database.
.. versionchanged:: 0.12
Parameters were added
]
call[name[self]._execute_for_all_tables, parameter[name[app], name[bind], constant[reflect]]] | keyword[def] identifier[reflect] ( identifier[self] , identifier[bind] = literal[string] , identifier[app] = keyword[None] ):
literal[string]
identifier[self] . identifier[_execute_for_all_tables] ( identifier[app] , identifier[bind] , literal[string] , identifier[skip_tables] = keyword[True] ) | def reflect(self, bind='__all__', app=None):
"""Reflects tables from the database.
.. versionchanged:: 0.12
Parameters were added
"""
self._execute_for_all_tables(app, bind, 'reflect', skip_tables=True) |
def backward_sampling_qmc(self, M):
"""QMC version of backward sampling.
Parameters
----------
M : int
number of trajectories
Note
----
Use this only on the history of a SQMC algorithm.
"""
self._check_h_orders()
u = q... | def function[backward_sampling_qmc, parameter[self, M]]:
constant[QMC version of backward sampling.
Parameters
----------
M : int
number of trajectories
Note
----
Use this only on the history of a SQMC algorithm.
]
call[name[s... | keyword[def] identifier[backward_sampling_qmc] ( identifier[self] , identifier[M] ):
literal[string]
identifier[self] . identifier[_check_h_orders] ()
identifier[u] = identifier[qmc] . identifier[sobol] ( identifier[M] , identifier[self] . identifier[T] )
identifier[hT] =... | def backward_sampling_qmc(self, M):
"""QMC version of backward sampling.
Parameters
----------
M : int
number of trajectories
Note
----
Use this only on the history of a SQMC algorithm.
"""
self._check_h_orders()
u = qmc.sobol(M, ... |
def needs_quotes(s):
"""Checks whether a string is a dot language ID.
It will check whether the string is solely composed
by the characters allowed in an ID or not.
If the string is one of the reserved keywords it will
need quotes too but the user will need to add them
manually.
"""
# If... | def function[needs_quotes, parameter[s]]:
constant[Checks whether a string is a dot language ID.
It will check whether the string is solely composed
by the characters allowed in an ID or not.
If the string is one of the reserved keywords it will
need quotes too but the user will need to add them... | keyword[def] identifier[needs_quotes] ( identifier[s] ):
literal[string]
keyword[if] identifier[s] keyword[in] identifier[DOT_KEYWORDS] :
keyword[return] keyword[False]
identifier[chars] =[ identifier[ord] ( identifier[c] ) keyword[for] identifier[c] keywo... | def needs_quotes(s):
"""Checks whether a string is a dot language ID.
It will check whether the string is solely composed
by the characters allowed in an ID or not.
If the string is one of the reserved keywords it will
need quotes too but the user will need to add them
manually.
"""
# If... |
def load(self):
"""
Load the definition of the rule, searching in the specified rule dirs first, then in the built-in definitions
:return: None
"""
file_name_valid = False
rule_type_valid = False
# Look for a locally-defined rule
fo... | def function[load, parameter[self]]:
constant[
Load the definition of the rule, searching in the specified rule dirs first, then in the built-in definitions
:return: None
]
variable[file_name_valid] assign[=] constant[False]
variable[rule_type_vali... | keyword[def] identifier[load] ( identifier[self] ):
literal[string]
identifier[file_name_valid] = keyword[False]
identifier[rule_type_valid] = keyword[False]
keyword[for] identifier[rule_dir] keyword[in] identifier[self] . identifier[rule_dirs] :
identif... | def load(self):
"""
Load the definition of the rule, searching in the specified rule dirs first, then in the built-in definitions
:return: None
"""
file_name_valid = False
rule_type_valid = False
# Look for a locally-defined rule
for rule_dir in self.r... |
def _poll_update_interval(self):
""" update the polling interval to be used next iteration """
# Increase by 1 second every 3 polls
if old_div(self.poll_count, 3) > self.poll_interval_level:
self.poll_interval_level += 1
self.poll_interval_s += 1
self.logger.i... | def function[_poll_update_interval, parameter[self]]:
constant[ update the polling interval to be used next iteration ]
if compare[call[name[old_div], parameter[name[self].poll_count, constant[3]]] greater[>] name[self].poll_interval_level] begin[:]
<ast.AugAssign object at 0x7da1b16095d0>
... | keyword[def] identifier[_poll_update_interval] ( identifier[self] ):
literal[string]
keyword[if] identifier[old_div] ( identifier[self] . identifier[poll_count] , literal[int] )> identifier[self] . identifier[poll_interval_level] :
identifier[self] . identifier[poll_interval_... | def _poll_update_interval(self):
""" update the polling interval to be used next iteration """
# Increase by 1 second every 3 polls
if old_div(self.poll_count, 3) > self.poll_interval_level:
self.poll_interval_level += 1
self.poll_interval_s += 1
self.logger.info('Increased polling i... |
def delete_cached_files(self, prefixes=[], suffixes=[]):
"""
Deletes any cached files matching the prefixes or suffixes given
"""
for filename in listdir(self.cache_directory_path):
delete = (
any([filename.endswith(ext) for ext in suffixes]) or
... | def function[delete_cached_files, parameter[self, prefixes, suffixes]]:
constant[
Deletes any cached files matching the prefixes or suffixes given
]
for taget[name[filename]] in starred[call[name[listdir], parameter[name[self].cache_directory_path]]] begin[:]
variable[del... | keyword[def] identifier[delete_cached_files] ( identifier[self] , identifier[prefixes] =[], identifier[suffixes] =[]):
literal[string]
keyword[for] identifier[filename] keyword[in] identifier[listdir] ( identifier[self] . identifier[cache_directory_path] ):
identifier[delete] =(
... | def delete_cached_files(self, prefixes=[], suffixes=[]):
"""
Deletes any cached files matching the prefixes or suffixes given
"""
for filename in listdir(self.cache_directory_path):
delete = any([filename.endswith(ext) for ext in suffixes]) or any([filename.startswith(pre) for pre in pre... |
def remove_diacritics(self_or_cls, identifier):
"""
Remove diacritics and accents from the input leaving other
unicode characters alone."""
chars = ''
for c in identifier:
replacement = unicodedata.normalize('NFKD', c).encode('ASCII', 'ignore')
if replacem... | def function[remove_diacritics, parameter[self_or_cls, identifier]]:
constant[
Remove diacritics and accents from the input leaving other
unicode characters alone.]
variable[chars] assign[=] constant[]
for taget[name[c]] in starred[name[identifier]] begin[:]
varia... | keyword[def] identifier[remove_diacritics] ( identifier[self_or_cls] , identifier[identifier] ):
literal[string]
identifier[chars] = literal[string]
keyword[for] identifier[c] keyword[in] identifier[identifier] :
identifier[replacement] = identifier[unicodedata] . identifi... | def remove_diacritics(self_or_cls, identifier):
"""
Remove diacritics and accents from the input leaving other
unicode characters alone."""
chars = ''
for c in identifier:
replacement = unicodedata.normalize('NFKD', c).encode('ASCII', 'ignore')
if replacement != '':
... |
def post_attention(self, token, x):
"""Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-attention and feed-forward
Retur... | def function[post_attention, parameter[self, token, x]]:
constant[Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-atten... | keyword[def] identifier[post_attention] ( identifier[self] , identifier[token] , identifier[x] ):
literal[string]
keyword[with] identifier[tf] . identifier[variable_scope] ( identifier[self] . identifier[name] + literal[string] , identifier[reuse] = identifier[tf] . identifier[AUTO_REUSE] ):
identi... | def post_attention(self, token, x):
"""Called after self-attention. The memory can be updated here.
Args:
token: Data returned by pre_attention, which can be used to carry over
state related to the current memory operation.
x: a Tensor of data after self-attention and feed-forward
Retur... |
def _expand_to_beam_size(data, beam_size, batch_size, state_info=None):
"""Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single NDArray/Symbol or nested container with NDArrays/Symbol
Each NDArray/Symbol should have shape (N, ...) when stat... | def function[_expand_to_beam_size, parameter[data, beam_size, batch_size, state_info]]:
constant[Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single NDArray/Symbol or nested container with NDArrays/Symbol
Each NDArray/Symbol should hav... | keyword[def] identifier[_expand_to_beam_size] ( identifier[data] , identifier[beam_size] , identifier[batch_size] , identifier[state_info] = keyword[None] ):
literal[string]
keyword[assert] keyword[not] identifier[state_info] keyword[or] identifier[isinstance] ( identifier[state_info] ,( identifier[typ... | def _expand_to_beam_size(data, beam_size, batch_size, state_info=None):
"""Tile all the states to have batch_size * beam_size on the batch axis.
Parameters
----------
data : A single NDArray/Symbol or nested container with NDArrays/Symbol
Each NDArray/Symbol should have shape (N, ...) when stat... |
def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None,
strict_slashes=False):
'''A helper method to register class instance or
functions as a handler to the application url
routes.
:param handler: function or class instance
:param uri: path of... | def function[add_route, parameter[self, handler, uri, methods, host, strict_slashes]]:
constant[A helper method to register class instance or
functions as a handler to the application url
routes.
:param handler: function or class instance
:param uri: path of the URL
:par... | keyword[def] identifier[add_route] ( identifier[self] , identifier[handler] , identifier[uri] , identifier[methods] = identifier[frozenset] ({ literal[string] }), identifier[host] = keyword[None] ,
identifier[strict_slashes] = keyword[False] ):
literal[string]
identifier[stream] = keyword[False]
... | def add_route(self, handler, uri, methods=frozenset({'GET'}), host=None, strict_slashes=False):
"""A helper method to register class instance or
functions as a handler to the application url
routes.
:param handler: function or class instance
:param uri: path of the URL
:para... |
def properties_from_mapping(self, bt_addr):
"""Retrieve properties (namespace, instance) for the specified bt address."""
for addr, properties in self.eddystone_mappings:
if addr == bt_addr:
return properties
return None | def function[properties_from_mapping, parameter[self, bt_addr]]:
constant[Retrieve properties (namespace, instance) for the specified bt address.]
for taget[tuple[[<ast.Name object at 0x7da20e957820>, <ast.Name object at 0x7da20e957100>]]] in starred[name[self].eddystone_mappings] begin[:]
... | keyword[def] identifier[properties_from_mapping] ( identifier[self] , identifier[bt_addr] ):
literal[string]
keyword[for] identifier[addr] , identifier[properties] keyword[in] identifier[self] . identifier[eddystone_mappings] :
keyword[if] identifier[addr] == identifier[bt_addr] :
... | def properties_from_mapping(self, bt_addr):
"""Retrieve properties (namespace, instance) for the specified bt address."""
for (addr, properties) in self.eddystone_mappings:
if addr == bt_addr:
return properties # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
... |
def parse_startup_message(self):
"""results in an OmapiStartupMessage
>>> d = b"\\0\\0\\0\\x64\\0\\0\\0\\x18"
>>> next(InBuffer(d).parse_startup_message()).validate()
"""
return parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int())) | def function[parse_startup_message, parameter[self]]:
constant[results in an OmapiStartupMessage
>>> d = b"\0\0\0\x64\0\0\0\x18"
>>> next(InBuffer(d).parse_startup_message()).validate()
]
return[call[name[parse_map], parameter[<ast.Lambda object at 0x7da20c9900a0>, call[name[parse_chain], parameter[n... | keyword[def] identifier[parse_startup_message] ( identifier[self] ):
literal[string]
keyword[return] identifier[parse_map] ( keyword[lambda] identifier[args] : identifier[OmapiStartupMessage] (* identifier[args] ), identifier[parse_chain] ( identifier[self] . identifier[parse_net32int] , keyword[lambda] ide... | def parse_startup_message(self):
"""results in an OmapiStartupMessage
>>> d = b"\\0\\0\\0\\x64\\0\\0\\0\\x18"
>>> next(InBuffer(d).parse_startup_message()).validate()
"""
return parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int())) |
def file_length(in_file):
'''Function to return the length of a file.'''
fid = open(in_file)
data = fid.readlines()
fid.close()
return len(data) | def function[file_length, parameter[in_file]]:
constant[Function to return the length of a file.]
variable[fid] assign[=] call[name[open], parameter[name[in_file]]]
variable[data] assign[=] call[name[fid].readlines, parameter[]]
call[name[fid].close, parameter[]]
return[call[name[len... | keyword[def] identifier[file_length] ( identifier[in_file] ):
literal[string]
identifier[fid] = identifier[open] ( identifier[in_file] )
identifier[data] = identifier[fid] . identifier[readlines] ()
identifier[fid] . identifier[close] ()
keyword[return] identifier[len] ( identifier[data] ) | def file_length(in_file):
"""Function to return the length of a file."""
fid = open(in_file)
data = fid.readlines()
fid.close()
return len(data) |
def parse_contents_summary(raw_json):
"""Parse a Confluence summary JSON list.
The method parses a JSON stream and returns an iterator
of diccionaries. Each dictionary is a content summary.
:param raw_json: JSON string to parse
:returns: a generator of parsed content summaries... | def function[parse_contents_summary, parameter[raw_json]]:
constant[Parse a Confluence summary JSON list.
The method parses a JSON stream and returns an iterator
of diccionaries. Each dictionary is a content summary.
:param raw_json: JSON string to parse
:returns: a generator ... | keyword[def] identifier[parse_contents_summary] ( identifier[raw_json] ):
literal[string]
identifier[summary] = identifier[json] . identifier[loads] ( identifier[raw_json] )
identifier[contents] = identifier[summary] [ literal[string] ]
keyword[for] identifier[c] keyword[in] i... | def parse_contents_summary(raw_json):
"""Parse a Confluence summary JSON list.
The method parses a JSON stream and returns an iterator
of diccionaries. Each dictionary is a content summary.
:param raw_json: JSON string to parse
:returns: a generator of parsed content summaries.
... |
def check(self, dsm, **kwargs):
"""
Check if matrix and its mediation matrix are compliant.
It means that number of dependencies for each (line, column) is either
0 if the mediation matrix (line, column) is 0, or >0 if the mediation
matrix (line, column) is 1.
Args:
... | def function[check, parameter[self, dsm]]:
constant[
Check if matrix and its mediation matrix are compliant.
It means that number of dependencies for each (line, column) is either
0 if the mediation matrix (line, column) is 0, or >0 if the mediation
matrix (line, column) is 1.
... | keyword[def] identifier[check] ( identifier[self] , identifier[dsm] ,** identifier[kwargs] ):
literal[string]
identifier[med_matrix] = identifier[CompleteMediation] . identifier[generate_mediation_matrix] ( identifier[dsm] )
keyword[return] identifier[CompleteMediation] . identif... | def check(self, dsm, **kwargs):
"""
Check if matrix and its mediation matrix are compliant.
It means that number of dependencies for each (line, column) is either
0 if the mediation matrix (line, column) is 0, or >0 if the mediation
matrix (line, column) is 1.
Args:
... |
def parse(self, data):
"""
populate instance with values and sub-sections
:param data: UTF-8 encoded manifest
:type data: bytes
"""
data = data.decode('utf-8')
self.linesep = detect_linesep(data)
# the first section is the main one for the manifest. It's... | def function[parse, parameter[self, data]]:
constant[
populate instance with values and sub-sections
:param data: UTF-8 encoded manifest
:type data: bytes
]
variable[data] assign[=] call[name[data].decode, parameter[constant[utf-8]]]
name[self].linesep assign[=] c... | keyword[def] identifier[parse] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[data] . identifier[decode] ( literal[string] )
identifier[self] . identifier[linesep] = identifier[detect_linesep] ( identifier[data] )
identif... | def parse(self, data):
"""
populate instance with values and sub-sections
:param data: UTF-8 encoded manifest
:type data: bytes
"""
data = data.decode('utf-8')
self.linesep = detect_linesep(data)
# the first section is the main one for the manifest. It's
# also where ... |
def select(self, fcn, *args, **kwds):
""" Return arrays from an hdf5 file that satisfy the given function
Parameters
----------
fcn : a function
A function that accepts the same number of argument as keys given
and returns a boolean array of the same length.
... | def function[select, parameter[self, fcn]]:
constant[ Return arrays from an hdf5 file that satisfy the given function
Parameters
----------
fcn : a function
A function that accepts the same number of argument as keys given
and returns a boolean array of the same ... | keyword[def] identifier[select] ( identifier[self] , identifier[fcn] ,* identifier[args] ,** identifier[kwds] ):
literal[string]
identifier[refs] ={}
identifier[data] ={}
keyword[for] identifier[arg] keyword[in] identifier[args] :
identifier[refs] [ ident... | def select(self, fcn, *args, **kwds):
""" Return arrays from an hdf5 file that satisfy the given function
Parameters
----------
fcn : a function
A function that accepts the same number of argument as keys given
and returns a boolean array of the same length.
... |
def remote(self, name='origin'):
""":return: Remote with the specified name
:raise ValueError: if no remote with such a name exists"""
r = Remote(self, name)
if not r.exists():
raise ValueError("Remote named '%s' didn't exist" % name)
return r | def function[remote, parameter[self, name]]:
constant[:return: Remote with the specified name
:raise ValueError: if no remote with such a name exists]
variable[r] assign[=] call[name[Remote], parameter[name[self], name[name]]]
if <ast.UnaryOp object at 0x7da1b1d47130> begin[:]
<... | keyword[def] identifier[remote] ( identifier[self] , identifier[name] = literal[string] ):
literal[string]
identifier[r] = identifier[Remote] ( identifier[self] , identifier[name] )
keyword[if] keyword[not] identifier[r] . identifier[exists] ():
keyword[raise] identifier[Va... | def remote(self, name='origin'):
""":return: Remote with the specified name
:raise ValueError: if no remote with such a name exists"""
r = Remote(self, name)
if not r.exists():
raise ValueError("Remote named '%s' didn't exist" % name) # depends on [control=['if'], data=[]]
return r |
def relative_deviation(h1, h2): # 18 us @array, 42 us @list \w 100 bins
r"""
Calculate the deviation between two histograms.
The relative deviation between two histograms :math:`H` and :math:`H'` of size :math:`m` is
defined as:
.. math::
d_{rd}(H, H') =
\frac{
... | def function[relative_deviation, parameter[h1, h2]]:
constant[
Calculate the deviation between two histograms.
The relative deviation between two histograms :math:`H` and :math:`H'` of size :math:`m` is
defined as:
.. math::
d_{rd}(H, H') =
\frac{
... | keyword[def] identifier[relative_deviation] ( identifier[h1] , identifier[h2] ):
literal[string]
identifier[h1] , identifier[h2] = identifier[__prepare_histogram] ( identifier[h1] , identifier[h2] )
identifier[numerator] = identifier[math] . identifier[sqrt] ( identifier[scipy] . identifier[sum] ( ide... | def relative_deviation(h1, h2): # 18 us @array, 42 us @list \w 100 bins
"\n Calculate the deviation between two histograms.\n \n The relative deviation between two histograms :math:`H` and :math:`H'` of size :math:`m` is\n defined as:\n \n .. math::\n \n d_{rd}(H, H') =\n \\f... |
def create_archive(archive, filenames, verbosity=0, program=None, interactive=True):
"""Create given archive with given files."""
util.check_new_filename(archive)
util.check_archive_filelist(filenames)
if verbosity >= 0:
util.log_info("Creating %s ..." % archive)
res = _create_archive(archiv... | def function[create_archive, parameter[archive, filenames, verbosity, program, interactive]]:
constant[Create given archive with given files.]
call[name[util].check_new_filename, parameter[name[archive]]]
call[name[util].check_archive_filelist, parameter[name[filenames]]]
if compare[name... | keyword[def] identifier[create_archive] ( identifier[archive] , identifier[filenames] , identifier[verbosity] = literal[int] , identifier[program] = keyword[None] , identifier[interactive] = keyword[True] ):
literal[string]
identifier[util] . identifier[check_new_filename] ( identifier[archive] )
iden... | def create_archive(archive, filenames, verbosity=0, program=None, interactive=True):
"""Create given archive with given files."""
util.check_new_filename(archive)
util.check_archive_filelist(filenames)
if verbosity >= 0:
util.log_info('Creating %s ...' % archive) # depends on [control=['if'], d... |
def __pathToTuple(self, path):
"""
Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
-------
tup_id : tuple
... | def function[__pathToTuple, parameter[self, path]]:
constant[
Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
------... | keyword[def] identifier[__pathToTuple] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] keyword[not] identifier[path] keyword[or] identifier[path] . identifier[count] ( literal[string] )> literal[int] :
keyword[raise] identifier[YTFS] . identifier[PathConvert... | def __pathToTuple(self, path):
"""
Convert directory or file path to its tuple identifier.
Parameters
----------
path : str
Path to convert. It can look like /, /directory, /directory/ or /directory/filename.
Returns
-------
tup_id : tuple
... |
def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory):
"""
Conversion of Facebook chat history.
"""
with colorize_output(nocolor):
try:
chat_history = _process_history(
path=path, thread=thread, timezones=timezones,
u... | def function[messages, parameter[path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory]]:
constant[
Conversion of Facebook chat history.
]
with call[name[colorize_output], parameter[name[nocolor]]] begin[:]
<ast.Try object at 0x7da18f58cd30>
if name[d... | keyword[def] identifier[messages] ( identifier[path] , identifier[thread] , identifier[fmt] , identifier[nocolor] , identifier[timezones] , identifier[utc] , identifier[noprogress] , identifier[resolve] , identifier[directory] ):
literal[string]
keyword[with] identifier[colorize_output] ( identifier[nocol... | def messages(path, thread, fmt, nocolor, timezones, utc, noprogress, resolve, directory):
"""
Conversion of Facebook chat history.
"""
with colorize_output(nocolor):
try:
chat_history = _process_history(path=path, thread=thread, timezones=timezones, utc=utc, noprogress=noprogress, re... |
def _on_process_started(self):
""" Logs process started """
comm('backend process started')
if self is None:
return
self.starting = False
self.running = True | def function[_on_process_started, parameter[self]]:
constant[ Logs process started ]
call[name[comm], parameter[constant[backend process started]]]
if compare[name[self] is constant[None]] begin[:]
return[None]
name[self].starting assign[=] constant[False]
name[self].runn... | keyword[def] identifier[_on_process_started] ( identifier[self] ):
literal[string]
identifier[comm] ( literal[string] )
keyword[if] identifier[self] keyword[is] keyword[None] :
keyword[return]
identifier[self] . identifier[starting] = keyword[False]
iden... | def _on_process_started(self):
""" Logs process started """
comm('backend process started')
if self is None:
return # depends on [control=['if'], data=[]]
self.starting = False
self.running = True |
def enable(profile='allprofiles'):
'''
.. versionadded:: 2015.5.0
Enable firewall profile
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
- privatepro... | def function[enable, parameter[profile]]:
constant[
.. versionadded:: 2015.5.0
Enable firewall profile
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
... | keyword[def] identifier[enable] ( identifier[profile] = literal[string] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , identifier[profile] , literal[string] , literal[string] ]
identifier[ret] = identifier[__salt__] [ literal[string] ]( identifier[cmd] , id... | def enable(profile='allprofiles'):
"""
.. versionadded:: 2015.5.0
Enable firewall profile
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
- privatepro... |
def get_best_fit_parameters_grouped(self):
"""Returns a dictionary of the best fit."""
result_dict = dict()
result_dict['ocv'] = [parameters['ocv'] for parameters in
self.best_fit_parameters]
for i in range(self.circuits):
result_dict['t' + str(... | def function[get_best_fit_parameters_grouped, parameter[self]]:
constant[Returns a dictionary of the best fit.]
variable[result_dict] assign[=] call[name[dict], parameter[]]
call[name[result_dict]][constant[ocv]] assign[=] <ast.ListComp object at 0x7da1b1969540>
for taget[name[i]] in sta... | keyword[def] identifier[get_best_fit_parameters_grouped] ( identifier[self] ):
literal[string]
identifier[result_dict] = identifier[dict] ()
identifier[result_dict] [ literal[string] ]=[ identifier[parameters] [ literal[string] ] keyword[for] identifier[parameters] keyword[in]
... | def get_best_fit_parameters_grouped(self):
"""Returns a dictionary of the best fit."""
result_dict = dict()
result_dict['ocv'] = [parameters['ocv'] for parameters in self.best_fit_parameters]
for i in range(self.circuits):
result_dict['t' + str(i)] = [parameters['t' + str(i)] for parameters in s... |
def prepare_mosaic(self, image, fov_deg, name=None):
"""Prepare a new (blank) mosaic image based on the pointing of
the parameter image
"""
header = image.get_header()
ra_deg, dec_deg = header['CRVAL1'], header['CRVAL2']
data_np = image.get_data()
#dtype = data_n... | def function[prepare_mosaic, parameter[self, image, fov_deg, name]]:
constant[Prepare a new (blank) mosaic image based on the pointing of
the parameter image
]
variable[header] assign[=] call[name[image].get_header, parameter[]]
<ast.Tuple object at 0x7da1b0dbc940> assign[=] tupl... | keyword[def] identifier[prepare_mosaic] ( identifier[self] , identifier[image] , identifier[fov_deg] , identifier[name] = keyword[None] ):
literal[string]
identifier[header] = identifier[image] . identifier[get_header] ()
identifier[ra_deg] , identifier[dec_deg] = identifier[header] [ lite... | def prepare_mosaic(self, image, fov_deg, name=None):
"""Prepare a new (blank) mosaic image based on the pointing of
the parameter image
"""
header = image.get_header()
(ra_deg, dec_deg) = (header['CRVAL1'], header['CRVAL2'])
data_np = image.get_data()
#dtype = data_np.dtype
dtype... |
def validate_url(self, original_string):
"""Returns the original string if it was valid, raises an argument
error if it's not.
"""
# nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python
# I preferred ... | def function[validate_url, parameter[self, original_string]]:
constant[Returns the original string if it was valid, raises an argument
error if it's not.
]
variable[pieces] assign[=] call[name[urlparse].urlparse, parameter[name[original_string]]]
<ast.Try object at 0x7da2054a55d0>
... | keyword[def] identifier[validate_url] ( identifier[self] , identifier[original_string] ):
literal[string]
identifier[pieces] = identifier[urlparse] . identifier[urlparse] ( identifier[original_string] )
keyword[try] :
keyword[if] identifier[self] .... | def validate_url(self, original_string):
"""Returns the original string if it was valid, raises an argument
error if it's not.
"""
# nipped from stack overflow: http://stackoverflow.com/questions/827557/how-do-you-validate-a-url-with-a-regular-expression-in-python
# I preferred this to the t... |
def setUpClassDef(self, service):
'''use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
'''
assert isinstance(service, WSDLTools.Service), \
'expecting WSDLTools.Service instance'
s = self._services[service.name].classd... | def function[setUpClassDef, parameter[self, service]]:
constant[use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
]
assert[call[name[isinstance], parameter[name[service], name[WSDLTools].Service]]]
variable[s] assign[=] call[name[self]... | keyword[def] identifier[setUpClassDef] ( identifier[self] , identifier[service] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[service] , identifier[WSDLTools] . identifier[Service] ), literal[string]
identifier[s] = identifier[self] . identifier[_services] [ ide... | def setUpClassDef(self, service):
"""use soapAction dict for WS-Action input, setup wsAction
dict for grabbing WS-Action output values.
"""
assert isinstance(service, WSDLTools.Service), 'expecting WSDLTools.Service instance'
s = self._services[service.name].classdef
(print >> s, 'class ... |
def output_raw(self, text):
"""
Output results in raw JSON format
"""
payload = json.loads(text)
out = json.dumps(payload, sort_keys=True, indent=self._indent, separators=(',', ': '))
print(self.colorize_json(out)) | def function[output_raw, parameter[self, text]]:
constant[
Output results in raw JSON format
]
variable[payload] assign[=] call[name[json].loads, parameter[name[text]]]
variable[out] assign[=] call[name[json].dumps, parameter[name[payload]]]
call[name[print], parameter[ca... | keyword[def] identifier[output_raw] ( identifier[self] , identifier[text] ):
literal[string]
identifier[payload] = identifier[json] . identifier[loads] ( identifier[text] )
identifier[out] = identifier[json] . identifier[dumps] ( identifier[payload] , identifier[sort_keys] = keyword[True] ... | def output_raw(self, text):
"""
Output results in raw JSON format
"""
payload = json.loads(text)
out = json.dumps(payload, sort_keys=True, indent=self._indent, separators=(',', ': '))
print(self.colorize_json(out)) |
def unlock(name,
zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example)
identifier=None,
max_concurrency=1,
ephemeral_lease=False,
profile=None,
scheme=None,
username=None,
password=None,... | def function[unlock, parameter[name, zk_hosts, identifier, max_concurrency, ephemeral_lease, profile, scheme, username, password, default_acl]]:
constant[
Remove lease from semaphore.
]
variable[ret] assign[=] dictionary[[<ast.Constant object at 0x7da18ede5d80>, <ast.Constant object at 0x7da18ed... | keyword[def] identifier[unlock] ( identifier[name] ,
identifier[zk_hosts] = keyword[None] ,
identifier[identifier] = keyword[None] ,
identifier[max_concurrency] = literal[int] ,
identifier[ephemeral_lease] = keyword[False] ,
identifier[profile] = keyword[None] ,
identifier[scheme] = keyword[None] ,
identifier[... | def unlock(name, zk_hosts=None, identifier=None, max_concurrency=1, ephemeral_lease=False, profile=None, scheme=None, username=None, password=None, default_acl=None): # in case you need to unlock without having run lock (failed execution for example)
'\n Remove lease from semaphore.\n '
ret = {'name': na... |
def ListMappedNetworkDrives():
'''
On Windows, returns a list of mapped network drives
:return: tuple(string, string, bool)
For each mapped netword drive, return 3 values tuple:
- the local drive
- the remote path-
- True if the mapping is enabled (warning: not r... | def function[ListMappedNetworkDrives, parameter[]]:
constant[
On Windows, returns a list of mapped network drives
:return: tuple(string, string, bool)
For each mapped netword drive, return 3 values tuple:
- the local drive
- the remote path-
- True if the map... | keyword[def] identifier[ListMappedNetworkDrives] ():
literal[string]
keyword[if] identifier[sys] . identifier[platform] != literal[string] :
keyword[raise] identifier[NotImplementedError]
identifier[drives_list] =[]
identifier[netuse] = identifier[_CallWindowsNetCommand] ([ literal[st... | def ListMappedNetworkDrives():
"""
On Windows, returns a list of mapped network drives
:return: tuple(string, string, bool)
For each mapped netword drive, return 3 values tuple:
- the local drive
- the remote path-
- True if the mapping is enabled (warning: not r... |
def read(key, root=''):
'''
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
'''
i... | def function[read, parameter[key, root]]:
constant[
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/e... | keyword[def] identifier[read] ( identifier[key] , identifier[root] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[key] , identifier[six] . identifier[string_types] ):
identifier[res] ={}
keyword[for] identifier[akey] keyword[in] ide... | def read(key, root=''):
"""
Read from SysFS
:param key: file or path in SysFS; if key is a list then root will be prefixed on each key
:return: the full (tree of) SysFS attributes under key
CLI example:
.. code-block:: bash
salt '*' sysfs.read class/net/em1/statistics
"""
if... |
def filter_missing(self):
"""Filter out individuals and SNPs that have too many missing to be \
considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* ind_mask
* tota... | def function[filter_missing, parameter[self]]:
constant[Filter out individuals and SNPs that have too many missing to be considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* in... | keyword[def] identifier[filter_missing] ( identifier[self] ):
literal[string]
identifier[missing] = keyword[None]
identifier[locus_count] = literal[int]
identifier[logging] . identifier[info] ( literal[string] )
identifier[self] . identifier[genotype_file] . id... | def filter_missing(self):
"""Filter out individuals and SNPs that have too many missing to be considered
:return: None
This must be run prior to actually parsing the genotypes because it
initializes the following instance members:
* ind_mask
* total_locu... |
def change_response(x, prob, index):
'''
change every response in x that matches 'index' by randomly sampling from prob
'''
#pdb.set_trace()
N = (x==index).sum()
#x[x==index]=9
x[x==index] = dist.sample(N) | def function[change_response, parameter[x, prob, index]]:
constant[
change every response in x that matches 'index' by randomly sampling from prob
]
variable[N] assign[=] call[compare[name[x] equal[==] name[index]].sum, parameter[]]
call[name[x]][compare[name[x] equal[==] name[index]]] a... | keyword[def] identifier[change_response] ( identifier[x] , identifier[prob] , identifier[index] ):
literal[string]
identifier[N] =( identifier[x] == identifier[index] ). identifier[sum] ()
identifier[x] [ identifier[x] == identifier[index] ]= identifier[dist] . identifier[sample] ( identifie... | def change_response(x, prob, index):
"""
change every response in x that matches 'index' by randomly sampling from prob
"""
#pdb.set_trace()
N = (x == index).sum()
#x[x==index]=9
x[x == index] = dist.sample(N) |
def centerdc_gen(self):
"""Return the centered frequency range as a generator.
::
>>> print(list(Range(8).centerdc_gen()))
[-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]
"""
for a in range(0, self.N):
yield (a-self.N/2) * self.df | def function[centerdc_gen, parameter[self]]:
constant[Return the centered frequency range as a generator.
::
>>> print(list(Range(8).centerdc_gen()))
[-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]
]
for taget[name[a]] in starred[call[name[range], parame... | keyword[def] identifier[centerdc_gen] ( identifier[self] ):
literal[string]
keyword[for] identifier[a] keyword[in] identifier[range] ( literal[int] , identifier[self] . identifier[N] ):
keyword[yield] ( identifier[a] - identifier[self] . identifier[N] / literal[int] )* identifier[se... | def centerdc_gen(self):
"""Return the centered frequency range as a generator.
::
>>> print(list(Range(8).centerdc_gen()))
[-0.5, -0.375, -0.25, -0.125, 0.0, 0.125, 0.25, 0.375]
"""
for a in range(0, self.N):
yield ((a - self.N / 2) * self.df) # depends on [co... |
def memory_read16(self, addr, num_halfwords, zone=None):
"""Reads memory from the target system in units of 16-bits.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to read from
num_halfwords (int): number of half words to read
zone (str): me... | def function[memory_read16, parameter[self, addr, num_halfwords, zone]]:
constant[Reads memory from the target system in units of 16-bits.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to read from
num_halfwords (int): number of half words to read
... | keyword[def] identifier[memory_read16] ( identifier[self] , identifier[addr] , identifier[num_halfwords] , identifier[zone] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[memory_read] ( identifier[addr] , identifier[num_halfwords] , identifier[zone] = identifier[z... | def memory_read16(self, addr, num_halfwords, zone=None):
"""Reads memory from the target system in units of 16-bits.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to read from
num_halfwords (int): number of half words to read
zone (str): memory... |
def set_section(self, section):
"""Set a section. If section already exists, overwrite the old one.
"""
if not isinstance(section, Section):
raise Exception("You")
try:
self.remove_section(section.name)
except:
pass
self._sections[sec... | def function[set_section, parameter[self, section]]:
constant[Set a section. If section already exists, overwrite the old one.
]
if <ast.UnaryOp object at 0x7da18eb54df0> begin[:]
<ast.Raise object at 0x7da18eb55f60>
<ast.Try object at 0x7da18eb54a60>
call[name[self]._section... | keyword[def] identifier[set_section] ( identifier[self] , identifier[section] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[section] , identifier[Section] ):
keyword[raise] identifier[Exception] ( literal[string] )
keyword[try] :
... | def set_section(self, section):
"""Set a section. If section already exists, overwrite the old one.
"""
if not isinstance(section, Section):
raise Exception('You') # depends on [control=['if'], data=[]]
try:
self.remove_section(section.name) # depends on [control=['try'], data=[]]
... |
def collect(self):
"""
Collector Passenger stats
"""
if not os.access(self.config["bin"], os.X_OK):
self.log.error("Path %s does not exist or is not executable",
self.config["bin"])
return {}
dict_stats = self.get_passenger_memo... | def function[collect, parameter[self]]:
constant[
Collector Passenger stats
]
if <ast.UnaryOp object at 0x7da18f7201c0> begin[:]
call[name[self].log.error, parameter[constant[Path %s does not exist or is not executable], call[name[self].config][constant[bin]]]]
re... | keyword[def] identifier[collect] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[access] ( identifier[self] . identifier[config] [ literal[string] ], identifier[os] . identifier[X_OK] ):
identifier[self] . identifier[log] . identifier[error]... | def collect(self):
"""
Collector Passenger stats
"""
if not os.access(self.config['bin'], os.X_OK):
self.log.error('Path %s does not exist or is not executable', self.config['bin'])
return {} # depends on [control=['if'], data=[]]
dict_stats = self.get_passenger_memory_stats... |
def check_gas_reserve(raiden):
""" Check periodically for gas reserve in the account """
while True:
has_enough_balance, estimated_required_balance = gas_reserve.has_enough_gas_reserve(
raiden,
channels_to_open=1,
)
estimated_required_balance_eth = Web3.fromWei(es... | def function[check_gas_reserve, parameter[raiden]]:
constant[ Check periodically for gas reserve in the account ]
while constant[True] begin[:]
<ast.Tuple object at 0x7da1b1711ba0> assign[=] call[name[gas_reserve].has_enough_gas_reserve, parameter[name[raiden]]]
variable[... | keyword[def] identifier[check_gas_reserve] ( identifier[raiden] ):
literal[string]
keyword[while] keyword[True] :
identifier[has_enough_balance] , identifier[estimated_required_balance] = identifier[gas_reserve] . identifier[has_enough_gas_reserve] (
identifier[raiden] ,
identif... | def check_gas_reserve(raiden):
""" Check periodically for gas reserve in the account """
while True:
(has_enough_balance, estimated_required_balance) = gas_reserve.has_enough_gas_reserve(raiden, channels_to_open=1)
estimated_required_balance_eth = Web3.fromWei(estimated_required_balance, 'ether'... |
def _stdout_filed(func):
"""
Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stdout.
"""
def wrapper(self, file=None):
if file:
return func(self, file=file)
... | def function[_stdout_filed, parameter[func]]:
constant[
Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stdout.
]
def function[wrapper, parameter[self, file]]:
... | keyword[def] identifier[_stdout_filed] ( identifier[func] ):
literal[string]
keyword[def] identifier[wrapper] ( identifier[self] , identifier[file] = keyword[None] ):
keyword[if] identifier[file] :
keyword[return] identifier[func] ( identifier[self] , identifier[file] = identifier[... | def _stdout_filed(func):
"""
Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stdout.
"""
def wrapper(self, file=None):
if file:
return func(self, file=file)... |
def encrypt(self, data, *recipients, **kwargs):
"""Encrypt the message contained in ``data`` to ``recipients``.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/fingerprint. Care should be ta... | def function[encrypt, parameter[self, data]]:
constant[Encrypt the message contained in ``data`` to ``recipients``.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/fingerprint. Care should b... | keyword[def] identifier[encrypt] ( identifier[self] , identifier[data] ,* identifier[recipients] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[_is_stream] ( identifier[data] ):
identifier[stream] = identifier[data]
keyword[else] :
identifier[s... | def encrypt(self, data, *recipients, **kwargs):
"""Encrypt the message contained in ``data`` to ``recipients``.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/fingerprint. Care should be taken ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.