code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _format_output(selected_number, raw_data):
"""Format data to get a readable output"""
tmp_data = {}
data = collections.defaultdict(lambda: 0)
balance = raw_data.pop('balance')
for number in raw_data.keys():
tmp_data = dict([(k, int(v) if v is not None else "No limit")
... | def function[_format_output, parameter[selected_number, raw_data]]:
constant[Format data to get a readable output]
variable[tmp_data] assign[=] dictionary[[], []]
variable[data] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b179c7f0>]]
variable[balan... | keyword[def] identifier[_format_output] ( identifier[selected_number] , identifier[raw_data] ):
literal[string]
identifier[tmp_data] ={}
identifier[data] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] : literal[int] )
identifier[balance] = identifier[raw_data] . identifier[... | def _format_output(selected_number, raw_data):
"""Format data to get a readable output"""
tmp_data = {}
data = collections.defaultdict(lambda : 0)
balance = raw_data.pop('balance')
for number in raw_data.keys():
tmp_data = dict([(k, int(v) if v is not None else 'No limit') for (k, v) in raw_... |
def fetch_raw(self, **kw):
"""
Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
This fetch should b... | def function[fetch_raw, parameter[self]]:
constant[
Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
... | keyword[def] identifier[fetch_raw] ( identifier[self] ,** identifier[kw] ):
literal[string]
identifier[self] . identifier[sockopt] . identifier[update] ( identifier[kw] )
keyword[with] identifier[SMCSocketProtocol] ( identifier[self] ,** identifier[self] . identifier[sockopt] ) keyword[as... | def fetch_raw(self, **kw):
"""
Fetch the records for this query. This fetch type will return the
results in raw dict format. It is possible to limit the number of
receives on the socket that return results before exiting by providing
max_recv.
This fetch should be us... |
def update(self, value=0):
"""
Update the value of the progress and update progress bar.
Parameters
-----------
value : integer
The current iteration of the progress
"""
self._deltas.append(time.time())
self.value = value
self._percen... | def function[update, parameter[self, value]]:
constant[
Update the value of the progress and update progress bar.
Parameters
-----------
value : integer
The current iteration of the progress
]
call[name[self]._deltas.append, parameter[call[name[time].... | keyword[def] identifier[update] ( identifier[self] , identifier[value] = literal[int] ):
literal[string]
identifier[self] . identifier[_deltas] . identifier[append] ( identifier[time] . identifier[time] ())
identifier[self] . identifier[value] = identifier[value]
identifier[self... | def update(self, value=0):
"""
Update the value of the progress and update progress bar.
Parameters
-----------
value : integer
The current iteration of the progress
"""
self._deltas.append(time.time())
self.value = value
self._percent = 100.0 * self.... |
def word_literals(self):
"""The list of literals per word in ``words`` layer."""
literals = []
for word_synsets in self.synsets:
word_literals = set()
for synset in word_synsets:
for variant in synset.get(SYN_VARIANTS):
if LITERAL in va... | def function[word_literals, parameter[self]]:
constant[The list of literals per word in ``words`` layer.]
variable[literals] assign[=] list[[]]
for taget[name[word_synsets]] in starred[name[self].synsets] begin[:]
variable[word_literals] assign[=] call[name[set], parameter[]]
... | keyword[def] identifier[word_literals] ( identifier[self] ):
literal[string]
identifier[literals] =[]
keyword[for] identifier[word_synsets] keyword[in] identifier[self] . identifier[synsets] :
identifier[word_literals] = identifier[set] ()
keyword[for] identif... | def word_literals(self):
"""The list of literals per word in ``words`` layer."""
literals = []
for word_synsets in self.synsets:
word_literals = set()
for synset in word_synsets:
for variant in synset.get(SYN_VARIANTS):
if LITERAL in variant:
w... |
def open_new_window(self, switch_to=True):
""" Opens a new browser tab/window and switches to it by default. """
self.driver.execute_script("window.open('');")
time.sleep(0.01)
if switch_to:
self.switch_to_window(len(self.driver.window_handles) - 1) | def function[open_new_window, parameter[self, switch_to]]:
constant[ Opens a new browser tab/window and switches to it by default. ]
call[name[self].driver.execute_script, parameter[constant[window.open('');]]]
call[name[time].sleep, parameter[constant[0.01]]]
if name[switch_to] begin[:]... | keyword[def] identifier[open_new_window] ( identifier[self] , identifier[switch_to] = keyword[True] ):
literal[string]
identifier[self] . identifier[driver] . identifier[execute_script] ( literal[string] )
identifier[time] . identifier[sleep] ( literal[int] )
keyword[if] identifi... | def open_new_window(self, switch_to=True):
""" Opens a new browser tab/window and switches to it by default. """
self.driver.execute_script("window.open('');")
time.sleep(0.01)
if switch_to:
self.switch_to_window(len(self.driver.window_handles) - 1) # depends on [control=['if'], data=[]] |
def proto_0201(theABF):
"""protocol: membrane test."""
abf=ABF(theABF)
abf.log.info("analyzing as a membrane test")
plot=ABFplot(abf)
plot.figure_height,plot.figure_width=SQUARESIZE/2,SQUARESIZE/2
plot.figure_sweeps()
# save it
plt.tight_layout()
frameAndSave(abf,"membrane test")
... | def function[proto_0201, parameter[theABF]]:
constant[protocol: membrane test.]
variable[abf] assign[=] call[name[ABF], parameter[name[theABF]]]
call[name[abf].log.info, parameter[constant[analyzing as a membrane test]]]
variable[plot] assign[=] call[name[ABFplot], parameter[name[abf]]]
... | keyword[def] identifier[proto_0201] ( identifier[theABF] ):
literal[string]
identifier[abf] = identifier[ABF] ( identifier[theABF] )
identifier[abf] . identifier[log] . identifier[info] ( literal[string] )
identifier[plot] = identifier[ABFplot] ( identifier[abf] )
identifier[plot] . identifi... | def proto_0201(theABF):
"""protocol: membrane test."""
abf = ABF(theABF)
abf.log.info('analyzing as a membrane test')
plot = ABFplot(abf)
(plot.figure_height, plot.figure_width) = (SQUARESIZE / 2, SQUARESIZE / 2)
plot.figure_sweeps()
# save it
plt.tight_layout()
frameAndSave(abf, 'me... |
def set_alpn_protos(self, protos):
"""
Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.
:param protos: A list of the protocols to be offered to the server.
This list ... | def function[set_alpn_protos, parameter[self, protos]]:
constant[
Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.
:param protos: A list of the protocols to be offered to the ser... | keyword[def] identifier[set_alpn_protos] ( identifier[self] , identifier[protos] ):
literal[string]
identifier[protostr] = literal[string] . identifier[join] (
identifier[chain] . identifier[from_iterable] (( identifier[int2byte] ( identifier[len] ( identifier[p] )), iden... | def set_alpn_protos(self, protos):
"""
Specify the protocols that the client is prepared to speak after the
TLS connection has been negotiated using Application Layer Protocol
Negotiation.
:param protos: A list of the protocols to be offered to the server.
This list shou... |
def write_gtfs(feed: "Feed", path: Path, ndigits: int = 6) -> None:
"""
Export the given feed to the given path.
If the path end in '.zip', then write the feed as a zip archive.
Otherwise assume the path is a directory, and write the feed as a
collection of CSV files to that directory, creating the ... | def function[write_gtfs, parameter[feed, path, ndigits]]:
constant[
Export the given feed to the given path.
If the path end in '.zip', then write the feed as a zip archive.
Otherwise assume the path is a directory, and write the feed as a
collection of CSV files to that directory, creating the ... | keyword[def] identifier[write_gtfs] ( identifier[feed] : literal[string] , identifier[path] : identifier[Path] , identifier[ndigits] : identifier[int] = literal[int] )-> keyword[None] :
literal[string]
identifier[path] = identifier[Path] ( identifier[path] )
keyword[if] identifier[path] . identifier... | def write_gtfs(feed: 'Feed', path: Path, ndigits: int=6) -> None:
"""
Export the given feed to the given path.
If the path end in '.zip', then write the feed as a zip archive.
Otherwise assume the path is a directory, and write the feed as a
collection of CSV files to that directory, creating the di... |
def get_description(self, name: str) -> str:
"""
Return the description, or a help string of variable identified by |name|.
"""
if name not in self._vars:
raise ConfigError(f"{self.name}.{name} not defined.")
return self._vars[name].description | def function[get_description, parameter[self, name]]:
constant[
Return the description, or a help string of variable identified by |name|.
]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self]._vars] begin[:]
<ast.Raise object at 0x7da18f810bb0>
return[call[... | keyword[def] identifier[get_description] ( identifier[self] , identifier[name] : identifier[str] )-> identifier[str] :
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_vars] :
keyword[raise] identifier[ConfigError] ( literal[stri... | def get_description(self, name: str) -> str:
"""
Return the description, or a help string of variable identified by |name|.
"""
if name not in self._vars:
raise ConfigError(f'{self.name}.{name} not defined.') # depends on [control=['if'], data=['name']]
return self._vars[name].descr... |
def visit_snippet(self, node):
"""
HTML document generator visit handler
"""
lang = self.highlightlang
linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-... | def function[visit_snippet, parameter[self, node]]:
constant[
HTML document generator visit handler
]
variable[lang] assign[=] name[self].highlightlang
variable[linenos] assign[=] compare[call[name[node].rawsource.count, parameter[constant[
]]] greater_or_equal[>=] binary_operation[name[... | keyword[def] identifier[visit_snippet] ( identifier[self] , identifier[node] ):
literal[string]
identifier[lang] = identifier[self] . identifier[highlightlang]
identifier[linenos] = identifier[node] . identifier[rawsource] . identifier[count] ( literal[string] )>= identifier[self] . identifier[highli... | def visit_snippet(self, node):
"""
HTML document generator visit handler
"""
lang = self.highlightlang
linenos = node.rawsource.count('\n') >= self.highlightlinenothreshold - 1
fname = node['filename']
highlight_args = node.get('highlight_args', {})
if 'language' in node:
# code-... |
def _PrintCheckDependencyStatus(
self, dependency, result, status_message, verbose_output=True):
"""Prints the check dependency status.
Args:
dependency (DependencyDefinition): dependency definition.
result (bool): True if the Python module is available and conforms to
the minimum... | def function[_PrintCheckDependencyStatus, parameter[self, dependency, result, status_message, verbose_output]]:
constant[Prints the check dependency status.
Args:
dependency (DependencyDefinition): dependency definition.
result (bool): True if the Python module is available and conforms to
... | keyword[def] identifier[_PrintCheckDependencyStatus] (
identifier[self] , identifier[dependency] , identifier[result] , identifier[status_message] , identifier[verbose_output] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[result] keyword[or] identifier[dependency] . identifier... | def _PrintCheckDependencyStatus(self, dependency, result, status_message, verbose_output=True):
"""Prints the check dependency status.
Args:
dependency (DependencyDefinition): dependency definition.
result (bool): True if the Python module is available and conforms to
the minimum requir... |
def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
"""
Find addresses matching the command parameters.
"""
generator = AddressGenerator(seed, security_level, checksum)
if count is None:
... | def function[_find_addresses, parameter[self, seed, index, count, security_level, checksum]]:
constant[
Find addresses matching the command parameters.
]
variable[generator] assign[=] call[name[AddressGenerator], parameter[name[seed], name[security_level], name[checksum]]]
if com... | keyword[def] identifier[_find_addresses] ( identifier[self] , identifier[seed] , identifier[index] , identifier[count] , identifier[security_level] , identifier[checksum] ):
literal[string]
identifier[generator] = identifier[AddressGenerator] ( identifier[seed] , identifier[security_level] , ident... | def _find_addresses(self, seed, index, count, security_level, checksum):
# type: (Seed, int, Optional[int], int, bool) -> List[Address]
'\n Find addresses matching the command parameters.\n '
generator = AddressGenerator(seed, security_level, checksum)
if count is None:
# Connect t... |
def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {}
re... | def function[_send_remote, parameter[self, url, data, headers, callback]]:
constant[
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
]
if compare[name[headers] is constant[None... | keyword[def] identifier[_send_remote] ( identifier[self] , identifier[url] , identifier[data] , identifier[headers] = keyword[None] , identifier[callback] = keyword[None] ):
literal[string]
keyword[if] identifier[headers] keyword[is] keyword[None] :
identifier[headers] ={}
... | def _send_remote(self, url, data, headers=None, callback=None):
"""
Initialise a Tornado AsyncClient and send the request to the sentry
server. If the callback is a callable, it will be called with the
response.
"""
if headers is None:
headers = {} # depends on [control=... |
def user_can_edit_news(user):
"""
Check if the user has permission to edit any of the registered NewsItem
types.
"""
newsitem_models = [model.get_newsitem_model()
for model in NEWSINDEX_MODEL_CLASSES]
if user.is_active and user.is_superuser:
# admin can edit news ... | def function[user_can_edit_news, parameter[user]]:
constant[
Check if the user has permission to edit any of the registered NewsItem
types.
]
variable[newsitem_models] assign[=] <ast.ListComp object at 0x7da1b0f06410>
if <ast.BoolOp object at 0x7da1b0f3a110> begin[:]
return[c... | keyword[def] identifier[user_can_edit_news] ( identifier[user] ):
literal[string]
identifier[newsitem_models] =[ identifier[model] . identifier[get_newsitem_model] ()
keyword[for] identifier[model] keyword[in] identifier[NEWSINDEX_MODEL_CLASSES] ]
keyword[if] identifier[user] . identifier[is... | def user_can_edit_news(user):
"""
Check if the user has permission to edit any of the registered NewsItem
types.
"""
newsitem_models = [model.get_newsitem_model() for model in NEWSINDEX_MODEL_CLASSES]
if user.is_active and user.is_superuser:
# admin can edit news iff any news types exist... |
def query(cls, url=urljoin(config.API_URL, 'stac/search'), **kwargs):
""" Get request """
logger.debug('Query URL: %s, Body: %s' % (url, json.dumps(kwargs)))
response = requests.post(url, data=json.dumps(kwargs))
# API error
if response.status_code != 200:
raise SatSe... | def function[query, parameter[cls, url]]:
constant[ Get request ]
call[name[logger].debug, parameter[binary_operation[constant[Query URL: %s, Body: %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b26afbe0>, <ast.Call object at 0x7da1b26ad870>]]]]]
variable[response] assig... | keyword[def] identifier[query] ( identifier[cls] , identifier[url] = identifier[urljoin] ( identifier[config] . identifier[API_URL] , literal[string] ),** identifier[kwargs] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] %( identifier[url] , identifier[json] . identifie... | def query(cls, url=urljoin(config.API_URL, 'stac/search'), **kwargs):
""" Get request """
logger.debug('Query URL: %s, Body: %s' % (url, json.dumps(kwargs)))
response = requests.post(url, data=json.dumps(kwargs))
# API error
if response.status_code != 200:
raise SatSearchError(response.text)... |
def genesis_signing_lockset(genesis, privkey):
"""
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
"""
v = VoteBlock(0, 0, genesis.hash)
v.sign(privkey)
ls = LockSet(num_eligible_votes=1)
ls.add(v)
asse... | def function[genesis_signing_lockset, parameter[genesis, privkey]]:
constant[
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
]
variable[v] assign[=] call[name[VoteBlock], parameter[constant[0], constant[0], na... | keyword[def] identifier[genesis_signing_lockset] ( identifier[genesis] , identifier[privkey] ):
literal[string]
identifier[v] = identifier[VoteBlock] ( literal[int] , literal[int] , identifier[genesis] . identifier[hash] )
identifier[v] . identifier[sign] ( identifier[privkey] )
identifier[ls] = ... | def genesis_signing_lockset(genesis, privkey):
"""
in order to avoid a complicated bootstrapping, we define
the genesis_signing_lockset as a lockset with one vote by any validator.
"""
v = VoteBlock(0, 0, genesis.hash)
v.sign(privkey)
ls = LockSet(num_eligible_votes=1)
ls.add(v)
asse... |
def child_sequence(self, child):
"""Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:raises AstroidError: If no ... | def function[child_sequence, parameter[self, child]]:
constant[Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:... | keyword[def] identifier[child_sequence] ( identifier[self] , identifier[child] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[self] . identifier[_astroid_fields] :
identifier[node_or_sequence] = identifier[getattr] ( identifier[self] , identifier[field] )
... | def child_sequence(self, child):
"""Search for the sequence that contains this child.
:param child: The child node to search sequences for.
:type child: NodeNG
:returns: The sequence containing the given child node.
:rtype: iterable(NodeNG)
:raises AstroidError: If no sequ... |
def share_secret(threshold, nshares, secret, identifier, hash_id=Hash.SHA256):
"""
Create nshares of the secret. threshold specifies the number of shares
needed for reconstructing the secret value. A 0-16 bytes identifier must
be provided. Optionally the secret is hashed with the algorithm specified
... | def function[share_secret, parameter[threshold, nshares, secret, identifier, hash_id]]:
constant[
Create nshares of the secret. threshold specifies the number of shares
needed for reconstructing the secret value. A 0-16 bytes identifier must
be provided. Optionally the secret is hashed with the algo... | keyword[def] identifier[share_secret] ( identifier[threshold] , identifier[nshares] , identifier[secret] , identifier[identifier] , identifier[hash_id] = identifier[Hash] . identifier[SHA256] ):
literal[string]
keyword[if] identifier[identifier] keyword[is] keyword[None] :
keyword[raise] ident... | def share_secret(threshold, nshares, secret, identifier, hash_id=Hash.SHA256):
"""
Create nshares of the secret. threshold specifies the number of shares
needed for reconstructing the secret value. A 0-16 bytes identifier must
be provided. Optionally the secret is hashed with the algorithm specified
... |
def _api_model_patch_replace(conn, restApiId, modelName, path, value):
'''
the replace patch operation on a Model resource
'''
response = conn.update_model(restApiId=restApiId, modelName=modelName,
patchOperations=[{'op': 'replace', 'path': path, 'value': value}])
re... | def function[_api_model_patch_replace, parameter[conn, restApiId, modelName, path, value]]:
constant[
the replace patch operation on a Model resource
]
variable[response] assign[=] call[name[conn].update_model, parameter[]]
return[name[response]] | keyword[def] identifier[_api_model_patch_replace] ( identifier[conn] , identifier[restApiId] , identifier[modelName] , identifier[path] , identifier[value] ):
literal[string]
identifier[response] = identifier[conn] . identifier[update_model] ( identifier[restApiId] = identifier[restApiId] , identifier[mode... | def _api_model_patch_replace(conn, restApiId, modelName, path, value):
"""
the replace patch operation on a Model resource
"""
response = conn.update_model(restApiId=restApiId, modelName=modelName, patchOperations=[{'op': 'replace', 'path': path, 'value': value}])
return response |
def __parse_json_data(self, data):
"""Process Json data
:@param data
:@type data: json/dict
:throws TypeError
"""
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data)
e... | def function[__parse_json_data, parameter[self, data]]:
constant[Process Json data
:@param data
:@type data: json/dict
:throws TypeError
]
if <ast.BoolOp object at 0x7da18eb54e20> begin[:]
name[self]._raw_data assign[=] name[data]
name[se... | keyword[def] identifier[__parse_json_data] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ) keyword[or] identifier[isinstance] ( identifier[data] , identifier[list] ):
identifier[self] . identifier[_ra... | def __parse_json_data(self, data):
"""Process Json data
:@param data
:@type data: json/dict
:throws TypeError
"""
if isinstance(data, dict) or isinstance(data, list):
self._raw_data = data
self._json_data = copy.deepcopy(self._raw_data) # depends on [control=['... |
def _read_header(self):
"""
When a CSV file is given, extracts header information the file.
Otherwise, this header data must be explicitly given when the object
is instantiated.
"""
if not self.filename or self.header_types:
return
rows = csv.reader(op... | def function[_read_header, parameter[self]]:
constant[
When a CSV file is given, extracts header information the file.
Otherwise, this header data must be explicitly given when the object
is instantiated.
]
if <ast.BoolOp object at 0x7da1b0f2a8f0> begin[:]
return[... | keyword[def] identifier[_read_header] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[filename] keyword[or] identifier[self] . identifier[header_types] :
keyword[return]
identifier[rows] = identifier[csv] . identifier[reader] (... | def _read_header(self):
"""
When a CSV file is given, extracts header information the file.
Otherwise, this header data must be explicitly given when the object
is instantiated.
"""
if not self.filename or self.header_types:
return # depends on [control=['if'], data=[]]
... |
def _store_equal_samples(self, ncpus):
"""
sample quartets evenly across splits of the starting tree, and fills
in remaining samples with random quartet samples. Uses a hash dict to
not sample the same quartet twice, so for very large trees this can
take a few minutes to find ... | def function[_store_equal_samples, parameter[self, ncpus]]:
constant[
sample quartets evenly across splits of the starting tree, and fills
in remaining samples with random quartet samples. Uses a hash dict to
not sample the same quartet twice, so for very large trees this can
... | keyword[def] identifier[_store_equal_samples] ( identifier[self] , identifier[ncpus] ):
literal[string]
identifier[breaks] = literal[int]
keyword[if] identifier[self] . identifier[params] . identifier[nquartets] < literal[int] :
identifier[breaks] = literal[int]
... | def _store_equal_samples(self, ncpus):
"""
sample quartets evenly across splits of the starting tree, and fills
in remaining samples with random quartet samples. Uses a hash dict to
not sample the same quartet twice, so for very large trees this can
take a few minutes to find mill... |
def _interpolated_template(self, templateid):
"""Return an interpolator for the given template"""
phase, y = self._get_template_by_id(templateid)
# double-check that phase ranges from 0 to 1
assert phase.min() >= 0
assert phase.max() <= 1
# at the start and end points, ... | def function[_interpolated_template, parameter[self, templateid]]:
constant[Return an interpolator for the given template]
<ast.Tuple object at 0x7da1b05ee410> assign[=] call[name[self]._get_template_by_id, parameter[name[templateid]]]
assert[compare[call[name[phase].min, parameter[]] greater_or_equ... | keyword[def] identifier[_interpolated_template] ( identifier[self] , identifier[templateid] ):
literal[string]
identifier[phase] , identifier[y] = identifier[self] . identifier[_get_template_by_id] ( identifier[templateid] )
keyword[assert] identifier[phase] . identifier[min] ()... | def _interpolated_template(self, templateid):
"""Return an interpolator for the given template"""
(phase, y) = self._get_template_by_id(templateid)
# double-check that phase ranges from 0 to 1
assert phase.min() >= 0
assert phase.max() <= 1
# at the start and end points, we need to add ~5 points... |
def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
"""Internal helper to return the values of a dictionary, sorted by key.
"""
for _, value in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value | def function[_dict_values_sorted_by_key, parameter[dictionary]]:
constant[Internal helper to return the values of a dictionary, sorted by key.
]
for taget[tuple[[<ast.Name object at 0x7da1b0b810f0>, <ast.Name object at 0x7da1b0b80820>]]] in starred[call[name[sorted], parameter[call[name[dictionary].... | keyword[def] identifier[_dict_values_sorted_by_key] ( identifier[dictionary] ):
literal[string]
keyword[for] identifier[_] , identifier[value] keyword[in] identifier[sorted] ( identifier[dictionary] . identifier[iteritems] (), identifier[key] = identifier[operator] . identifier[itemgetter] ( literal[in... | def _dict_values_sorted_by_key(dictionary):
# This should be a yield from instead.
'Internal helper to return the values of a dictionary, sorted by key.\n '
for (_, value) in sorted(dictionary.iteritems(), key=operator.itemgetter(0)):
yield value # depends on [control=['for'], data=[]] |
def get_show_function_result(self, ddoc_id, show_name, doc_id):
"""
Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
and need data to be... | def function[get_show_function_result, parameter[self, ddoc_id, show_name, doc_id]]:
constant[
Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
... | keyword[def] identifier[get_show_function_result] ( identifier[self] , identifier[ddoc_id] , identifier[show_name] , identifier[doc_id] ):
literal[string]
identifier[ddoc] = identifier[DesignDocument] ( identifier[self] , identifier[ddoc_id] )
identifier[headers] ={ literal[string] : liter... | def get_show_function_result(self, ddoc_id, show_name, doc_id):
"""
Retrieves a formatted document from the specified database
based on the show function provided. Show functions, for example,
are used when you want to access Cloudant directly from a browser,
and need data to be ret... |
def density2d(data,
channels=[0,1],
bins=1024,
gate_fraction=0.65,
xscale='logicle',
yscale='logicle',
sigma=10.0,
full_output=False):
"""
Gate that preserves events in the region with highest density.
Gate ou... | def function[density2d, parameter[data, channels, bins, gate_fraction, xscale, yscale, sigma, full_output]]:
constant[
Gate that preserves events in the region with highest density.
Gate out all events in `data` but those near regions of highest
density for the two specified channels.
Paramete... | keyword[def] identifier[density2d] ( identifier[data] ,
identifier[channels] =[ literal[int] , literal[int] ],
identifier[bins] = literal[int] ,
identifier[gate_fraction] = literal[int] ,
identifier[xscale] = literal[string] ,
identifier[yscale] = literal[string] ,
identifier[sigma] = literal[int] ,
identifier... | def density2d(data, channels=[0, 1], bins=1024, gate_fraction=0.65, xscale='logicle', yscale='logicle', sigma=10.0, full_output=False):
"""
Gate that preserves events in the region with highest density.
Gate out all events in `data` but those near regions of highest
density for the two specified channe... |
def prerequisites(self):
"""
Iterates through the inputs of the pipelinen and determines the
all prerequisite pipelines
"""
# Loop through the inputs to the pipeline and add the instancemethods
# for the pipelines to generate each of the processed inputs
prereqs =... | def function[prerequisites, parameter[self]]:
constant[
Iterates through the inputs of the pipelinen and determines the
all prerequisite pipelines
]
variable[prereqs] assign[=] call[name[defaultdict], parameter[name[set]]]
for taget[name[input]] in starred[name[self].inpu... | keyword[def] identifier[prerequisites] ( identifier[self] ):
literal[string]
identifier[prereqs] = identifier[defaultdict] ( identifier[set] )
keyword[for] identifier[input] keyword[in] identifier[self] . identifier[inputs] :
identifier[spec] = identifier[... | def prerequisites(self):
"""
Iterates through the inputs of the pipelinen and determines the
all prerequisite pipelines
"""
# Loop through the inputs to the pipeline and add the instancemethods
# for the pipelines to generate each of the processed inputs
prereqs = defaultdict(set... |
def _simplify_arguments(arguments):
"""
If positional or keyword arguments are empty return only one or the other.
"""
if len(arguments.args) == 0:
return arguments.kwargs
elif len(arguments.kwargs) == 0:
return arguments.args
else:
return arguments | def function[_simplify_arguments, parameter[arguments]]:
constant[
If positional or keyword arguments are empty return only one or the other.
]
if compare[call[name[len], parameter[name[arguments].args]] equal[==] constant[0]] begin[:]
return[name[arguments].kwargs] | keyword[def] identifier[_simplify_arguments] ( identifier[arguments] ):
literal[string]
keyword[if] identifier[len] ( identifier[arguments] . identifier[args] )== literal[int] :
keyword[return] identifier[arguments] . identifier[kwargs]
keyword[elif] identifier[len] ( identifier[arguments... | def _simplify_arguments(arguments):
"""
If positional or keyword arguments are empty return only one or the other.
"""
if len(arguments.args) == 0:
return arguments.kwargs # depends on [control=['if'], data=[]]
elif len(arguments.kwargs) == 0:
return arguments.args # depends on [co... |
def get_relationship_bundle(manager, relationship_id=None, legacy=True):
"""
:param manager: Neo4jDBSessionManager
:param relationship_id: Internal Neo4j id
:param legacy: Backwards compatibility
:type relationship_id: int
:type legacy: bool
:rtype: dictionary
"""
q = """
M... | def function[get_relationship_bundle, parameter[manager, relationship_id, legacy]]:
constant[
:param manager: Neo4jDBSessionManager
:param relationship_id: Internal Neo4j id
:param legacy: Backwards compatibility
:type relationship_id: int
:type legacy: bool
:rtype: dictionary
]
... | keyword[def] identifier[get_relationship_bundle] ( identifier[manager] , identifier[relationship_id] = keyword[None] , identifier[legacy] = keyword[True] ):
literal[string]
identifier[q] = literal[string]
keyword[with] identifier[manager] . identifier[session] keyword[as] identifier[s] :
... | def get_relationship_bundle(manager, relationship_id=None, legacy=True):
"""
:param manager: Neo4jDBSessionManager
:param relationship_id: Internal Neo4j id
:param legacy: Backwards compatibility
:type relationship_id: int
:type legacy: bool
:rtype: dictionary
"""
q = '\n MA... |
def find_mip(self, direction, mechanism, purview, allow_neg=False):
"""Find the ratio minimum information partition for a mechanism
over a purview.
Args:
direction (str): |CAUSE| or |EFFECT|
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview... | def function[find_mip, parameter[self, direction, mechanism, purview, allow_neg]]:
constant[Find the ratio minimum information partition for a mechanism
over a purview.
Args:
direction (str): |CAUSE| or |EFFECT|
mechanism (tuple[int]): A mechanism.
purview (t... | keyword[def] identifier[find_mip] ( identifier[self] , identifier[direction] , identifier[mechanism] , identifier[purview] , identifier[allow_neg] = keyword[False] ):
literal[string]
identifier[alpha_min] = identifier[float] ( literal[string] )
identifier[probability] = identifier[self] . ... | def find_mip(self, direction, mechanism, purview, allow_neg=False):
"""Find the ratio minimum information partition for a mechanism
over a purview.
Args:
direction (str): |CAUSE| or |EFFECT|
mechanism (tuple[int]): A mechanism.
purview (tuple[int]): A purview.
... |
def f_restore_default(self):
""" Restores the default value in all explored parameters and sets the
v_idx property back to -1 and v_crun to None."""
self._idx = -1
self._crun = None
for param in self._explored_parameters.values():
if param is not None:
... | def function[f_restore_default, parameter[self]]:
constant[ Restores the default value in all explored parameters and sets the
v_idx property back to -1 and v_crun to None.]
name[self]._idx assign[=] <ast.UnaryOp object at 0x7da18f720af0>
name[self]._crun assign[=] constant[None]
... | keyword[def] identifier[f_restore_default] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_idx] =- literal[int]
identifier[self] . identifier[_crun] = keyword[None]
keyword[for] identifier[param] keyword[in] identifier[self] . identifier[_explored_paramet... | def f_restore_default(self):
""" Restores the default value in all explored parameters and sets the
v_idx property back to -1 and v_crun to None."""
self._idx = -1
self._crun = None
for param in self._explored_parameters.values():
if param is not None:
param._restore_default(... |
def authenticateRequest(self, request, service_request, *args, **kwargs):
"""
Authenticates the request against the service.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>}
"""
username = password = None
if 'Credentials' in requ... | def function[authenticateRequest, parameter[self, request, service_request]]:
constant[
Authenticates the request against the service.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>}
]
variable[username] assign[=] constant[None]
... | keyword[def] identifier[authenticateRequest] ( identifier[self] , identifier[request] , identifier[service_request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[username] = identifier[password] = keyword[None]
keyword[if] literal[string] keyword[in] identif... | def authenticateRequest(self, request, service_request, *args, **kwargs):
"""
Authenticates the request against the service.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>}
"""
username = password = None
if 'Credentials' in request.headers:
... |
def _update_imageinfo(self):
"""
calls get_imageinfo() if data image missing info
"""
missing = self._missing_imageinfo()
deferred = self.flags.get('defer_imageinfo')
continuing = self.data.get('continue')
if missing and not deferred and not continuing:
... | def function[_update_imageinfo, parameter[self]]:
constant[
calls get_imageinfo() if data image missing info
]
variable[missing] assign[=] call[name[self]._missing_imageinfo, parameter[]]
variable[deferred] assign[=] call[name[self].flags.get, parameter[constant[defer_imageinfo]]... | keyword[def] identifier[_update_imageinfo] ( identifier[self] ):
literal[string]
identifier[missing] = identifier[self] . identifier[_missing_imageinfo] ()
identifier[deferred] = identifier[self] . identifier[flags] . identifier[get] ( literal[string] )
identifier[continuing] = id... | def _update_imageinfo(self):
"""
calls get_imageinfo() if data image missing info
"""
missing = self._missing_imageinfo()
deferred = self.flags.get('defer_imageinfo')
continuing = self.data.get('continue')
if missing and (not deferred) and (not continuing):
self.get_imageinfo... |
def TriggersPost(self, parameters):
"""
Create a trigger on CommonSense.
If TriggersPost was successful the result, including the trigger_id, can be obtained from getResponse().
@param parameters (dictionary) - Parameters of the trigger to create.
... | def function[TriggersPost, parameter[self, parameters]]:
constant[
Create a trigger on CommonSense.
If TriggersPost was successful the result, including the trigger_id, can be obtained from getResponse().
@param parameters (dictionary) - Parameters of the trigger... | keyword[def] identifier[TriggersPost] ( identifier[self] , identifier[parameters] ):
literal[string]
keyword[if] identifier[self] . identifier[__SenseApiCall__] ( literal[string] , literal[string] , identifier[parameters] = identifier[parameters] ):
keyword[return] keyword[True]
... | def TriggersPost(self, parameters):
"""
Create a trigger on CommonSense.
If TriggersPost was successful the result, including the trigger_id, can be obtained from getResponse().
@param parameters (dictionary) - Parameters of the trigger to create.
... |
def submit_ham(self, params):
"""For submitting a ham comment to Akismet."""
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required)
response = self._request(... | def function[submit_ham, parameter[self, params]]:
constant[For submitting a ham comment to Akismet.]
for taget[name[required]] in starred[list[[<ast.Constant object at 0x7da204960820>, <ast.Constant object at 0x7da204960c70>, <ast.Constant object at 0x7da204961360>]]] begin[:]
if compar... | keyword[def] identifier[submit_ham] ( identifier[self] , identifier[params] ):
literal[string]
keyword[for] identifier[required] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
keyword[if] identifier[required] keyword[not] keyword[in] identifier[par... | def submit_ham(self, params):
"""For submitting a ham comment to Akismet."""
# Check required params for submit-ham
for required in ['blog', 'user_ip', 'user_agent']:
if required not in params:
raise MissingParams(required) # depends on [control=['if'], data=['required']] # depends on ... |
def _expandGLQ(self, zeros, lmax, lmax_calc):
"""Evaluate the coefficients on a Gauss-Legendre quadrature grid."""
if self.normalization == '4pi':
norm = 1
elif self.normalization == 'schmidt':
norm = 2
elif self.normalization == 'unnorm':
norm = 3
... | def function[_expandGLQ, parameter[self, zeros, lmax, lmax_calc]]:
constant[Evaluate the coefficients on a Gauss-Legendre quadrature grid.]
if compare[name[self].normalization equal[==] constant[4pi]] begin[:]
variable[norm] assign[=] constant[1]
if compare[name[zeros] is constan... | keyword[def] identifier[_expandGLQ] ( identifier[self] , identifier[zeros] , identifier[lmax] , identifier[lmax_calc] ):
literal[string]
keyword[if] identifier[self] . identifier[normalization] == literal[string] :
identifier[norm] = literal[int]
keyword[elif] identifier[se... | def _expandGLQ(self, zeros, lmax, lmax_calc):
"""Evaluate the coefficients on a Gauss-Legendre quadrature grid."""
if self.normalization == '4pi':
norm = 1 # depends on [control=['if'], data=[]]
elif self.normalization == 'schmidt':
norm = 2 # depends on [control=['if'], data=[]]
elif ... |
def log_download(self, log_num, filename):
'''download a log file'''
print("Downloading log %u as %s" % (log_num, filename))
self.download_lognum = log_num
self.download_file = open(filename, "wb")
self.master.mav.log_request_data_send(self.target_system,
... | def function[log_download, parameter[self, log_num, filename]]:
constant[download a log file]
call[name[print], parameter[binary_operation[constant[Downloading log %u as %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b2345bd0>, <ast.Name object at 0x7da1b2344490>]]]]]
na... | keyword[def] identifier[log_download] ( identifier[self] , identifier[log_num] , identifier[filename] ):
literal[string]
identifier[print] ( literal[string] %( identifier[log_num] , identifier[filename] ))
identifier[self] . identifier[download_lognum] = identifier[log_num]
ident... | def log_download(self, log_num, filename):
"""download a log file"""
print('Downloading log %u as %s' % (log_num, filename))
self.download_lognum = log_num
self.download_file = open(filename, 'wb')
self.master.mav.log_request_data_send(self.target_system, self.target_component, log_num, 0, 429496729... |
def feedback_summaries(self):
"""
Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
"""
if self._feedback_summaries is None:
... | def function[feedback_summaries, parameter[self]]:
constant[
Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
]
if compare[name[... | keyword[def] identifier[feedback_summaries] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_feedback_summaries] keyword[is] keyword[None] :
identifier[self] . identifier[_feedback_summaries] = identifier[FeedbackSummaryList] (
identifier... | def feedback_summaries(self):
"""
Access the feedback_summaries
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryList
"""
if self._feedback_summaries is None:
self... |
def write(self):
"""
Create or update a Wiki Page on Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A WikiPage must have a 'space' attribute before you can write it to Assembla.")
self.api = self.space.api
if self.get('id'): # We are modi... | def function[write, parameter[self]]:
constant[
Create or update a Wiki Page on Assembla
]
if <ast.UnaryOp object at 0x7da2044c0e80> begin[:]
<ast.Raise object at 0x7da2044c1270>
name[self].api assign[=] name[self].space.api
if call[name[self].get, parameter[const... | keyword[def] identifier[write] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[raise] identifier[AttributeError] ( literal[string] )
identifier[self] . identifier[api] = identifier[self] . i... | def write(self):
"""
Create or update a Wiki Page on Assembla
"""
if not hasattr(self, 'space'):
raise AttributeError("A WikiPage must have a 'space' attribute before you can write it to Assembla.") # depends on [control=['if'], data=[]]
self.api = self.space.api
if self.get('id... |
def start(debug=False, host='127.0.0.1'):
""" starts a nago agent (daemon) process """
if debug:
debug = True
nago.protocols.httpserver.app.run(debug=debug, host=host) | def function[start, parameter[debug, host]]:
constant[ starts a nago agent (daemon) process ]
if name[debug] begin[:]
variable[debug] assign[=] constant[True]
call[name[nago].protocols.httpserver.app.run, parameter[]] | keyword[def] identifier[start] ( identifier[debug] = keyword[False] , identifier[host] = literal[string] ):
literal[string]
keyword[if] identifier[debug] :
identifier[debug] = keyword[True]
identifier[nago] . identifier[protocols] . identifier[httpserver] . identifier[app] . identifier[run]... | def start(debug=False, host='127.0.0.1'):
""" starts a nago agent (daemon) process """
if debug:
debug = True # depends on [control=['if'], data=[]]
nago.protocols.httpserver.app.run(debug=debug, host=host) |
def handle_editor_command(self, cli, document):
"""
Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it in vim, then come
... | def function[handle_editor_command, parameter[self, cli, document]]:
constant[
Editor command is any query that is prefixed or suffixed
by a '\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \e"<enter> to edit it... | keyword[def] identifier[handle_editor_command] ( identifier[self] , identifier[cli] , identifier[document] ):
literal[string]
identifier[saved_callables] = identifier[cli] . identifier[application] . identifier[pre_run_callables]
keyword[while] identifier[speci... | def handle_editor_command(self, cli, document):
"""
Editor command is any query that is prefixed or suffixed
by a '\\e'. The reason for a while loop is because a user
might edit a query multiple times.
For eg:
"select * from \\e"<enter> to edit it in vim, then come
ba... |
def check_status(self, ignore=(), status=None):
"""
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
"""
self.SH... | def function[check_status, parameter[self, ignore, status]]:
constant[
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
... | keyword[def] identifier[check_status] ( identifier[self] , identifier[ignore] =(), identifier[status] = keyword[None] ):
literal[string]
identifier[self] . identifier[SHARD_CHECKS] =[
{ literal[string] : literal[string] , literal[string] : identifier[self] . identifier[_check_shard_count] }... | def check_status(self, ignore=(), status=None):
"""
Checks status of each collection and shard to make sure that:
a) Cluster state is active
b) Number of docs matches across replicas for a given shard.
Returns a dict of results for custom alerting.
"""
self.SHARD_CHEC... |
def _create_figure(kwargs: Mapping[str, Any]) -> dict:
"""Create basic dictionary object with figure properties."""
return {
"$schema": "https://vega.github.io/schema/vega/v3.json",
"width": kwargs.pop("width", DEFAULT_WIDTH),
"height": kwargs.pop("height", DEFAULT_HEIGHT),
"padd... | def function[_create_figure, parameter[kwargs]]:
constant[Create basic dictionary object with figure properties.]
return[dictionary[[<ast.Constant object at 0x7da18f8105b0>, <ast.Constant object at 0x7da18f8110c0>, <ast.Constant object at 0x7da18f811480>, <ast.Constant object at 0x7da18f811a80>], [<ast.Cons... | keyword[def] identifier[_create_figure] ( identifier[kwargs] : identifier[Mapping] [ identifier[str] , identifier[Any] ])-> identifier[dict] :
literal[string]
keyword[return] {
literal[string] : literal[string] ,
literal[string] : identifier[kwargs] . identifier[pop] ( literal[string] , identifie... | def _create_figure(kwargs: Mapping[str, Any]) -> dict:
"""Create basic dictionary object with figure properties."""
return {'$schema': 'https://vega.github.io/schema/vega/v3.json', 'width': kwargs.pop('width', DEFAULT_WIDTH), 'height': kwargs.pop('height', DEFAULT_HEIGHT), 'padding': kwargs.pop('padding', DEFAU... |
def in_domain(self, points):
"""
Returns ``True`` if all of the given points are in the domain,
``False`` otherwise.
:param np.ndarray points: An `np.ndarray` of type `self.dtype`.
:rtype: `bool`
"""
array_view = self.to_regular_array(points)
non_negativ... | def function[in_domain, parameter[self, points]]:
constant[
Returns ``True`` if all of the given points are in the domain,
``False`` otherwise.
:param np.ndarray points: An `np.ndarray` of type `self.dtype`.
:rtype: `bool`
]
variable[array_view] assign[=] call[n... | keyword[def] identifier[in_domain] ( identifier[self] , identifier[points] ):
literal[string]
identifier[array_view] = identifier[self] . identifier[to_regular_array] ( identifier[points] )
identifier[non_negative] = identifier[np] . identifier[all] ( identifier[np] . identifier[greater_eq... | def in_domain(self, points):
"""
Returns ``True`` if all of the given points are in the domain,
``False`` otherwise.
:param np.ndarray points: An `np.ndarray` of type `self.dtype`.
:rtype: `bool`
"""
array_view = self.to_regular_array(points)
non_negative = np.all(n... |
def filterbank_log(sr, n_freq, n_bins=84, bins_per_octave=12,
fmin=None, spread=0.125): # pragma: no cover
"""[np] Approximate a constant-Q filter bank for a fixed-window STFT.
Each filter is a log-normal window centered at the corresponding frequency.
Note: `logfrequency` in librosa 0... | def function[filterbank_log, parameter[sr, n_freq, n_bins, bins_per_octave, fmin, spread]]:
constant[[np] Approximate a constant-Q filter bank for a fixed-window STFT.
Each filter is a log-normal window centered at the corresponding frequency.
Note: `logfrequency` in librosa 0.4 (deprecated), so copy-... | keyword[def] identifier[filterbank_log] ( identifier[sr] , identifier[n_freq] , identifier[n_bins] = literal[int] , identifier[bins_per_octave] = literal[int] ,
identifier[fmin] = keyword[None] , identifier[spread] = literal[int] ):
literal[string]
keyword[if] identifier[fmin] keyword[is] keyword[None... | def filterbank_log(sr, n_freq, n_bins=84, bins_per_octave=12, fmin=None, spread=0.125): # pragma: no cover
'[np] Approximate a constant-Q filter bank for a fixed-window STFT.\n\n Each filter is a log-normal window centered at the corresponding frequency.\n\n Note: `logfrequency` in librosa 0.4 (deprecated), ... |
def language_callback(lexer, match):
"""Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as
plpgsql if inside a DO statement and no LANGUAGE has been found.
"""
l = None
m = language_re.match(lexer.text[match.end():match.end()+100])
... | def function[language_callback, parameter[lexer, match]]:
constant[Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as
plpgsql if inside a DO statement and no LANGUAGE has been found.
]
variable[l] assign[=] constant[None]
va... | keyword[def] identifier[language_callback] ( identifier[lexer] , identifier[match] ):
literal[string]
identifier[l] = keyword[None]
identifier[m] = identifier[language_re] . identifier[match] ( identifier[lexer] . identifier[text] [ identifier[match] . identifier[end] (): identifier[match] . identifi... | def language_callback(lexer, match):
"""Parse the content of a $-string using a lexer
The lexer is chosen looking for a nearby LANGUAGE or assumed as
plpgsql if inside a DO statement and no LANGUAGE has been found.
"""
l = None
m = language_re.match(lexer.text[match.end():match.end() + 100])
... |
def compute_message_authenticator(radius_packet, packed_req_authenticator,
shared_secret):
"""
Computes the "Message-Authenticator" of a given RADIUS packet.
"""
data = prepare_packed_data(radius_packet, packed_req_authenticator)
radius_hmac... | def function[compute_message_authenticator, parameter[radius_packet, packed_req_authenticator, shared_secret]]:
constant[
Computes the "Message-Authenticator" of a given RADIUS packet.
]
variable[data] assign[=] call[name[prepare_packed_data], parameter[name[radius_packet], name[packed_r... | keyword[def] identifier[compute_message_authenticator] ( identifier[radius_packet] , identifier[packed_req_authenticator] ,
identifier[shared_secret] ):
literal[string]
identifier[data] = identifier[prepare_packed_data] ( identifier[radius_packet] , identifier[packed_req_authenticator] )
... | def compute_message_authenticator(radius_packet, packed_req_authenticator, shared_secret):
"""
Computes the "Message-Authenticator" of a given RADIUS packet.
"""
data = prepare_packed_data(radius_packet, packed_req_authenticator)
radius_hmac = hmac.new(shared_secret, data, hashlib.md5)
r... |
def _Rzderiv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | def function[_Rzderiv, parameter[self, R, z, phi, t]]:
constant[
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t... | keyword[def] identifier[_Rzderiv] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
identifier[sqrtbz] = identifier[nu] . identifier[sqrt] ( identifier[self] . identifier[_b2] + identifier[z] ** literal[int] )
... | def _Rzderiv(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_Rzderiv
PURPOSE:
evaluate the mixed R,z derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:... |
def mill(it, label='', hide=None, expected_size=None, every=1):
"""Progress iterator. Prints a mill while iterating over the items."""
def _mill_char(_i):
if _i >= count:
return ' '
else:
return MILL_CHARS[(_i // every) % len(MILL_CHARS)]
def _show(_i):
if n... | def function[mill, parameter[it, label, hide, expected_size, every]]:
constant[Progress iterator. Prints a mill while iterating over the items.]
def function[_mill_char, parameter[_i]]:
if compare[name[_i] greater_or_equal[>=] name[count]] begin[:]
return[constant[ ]]
... | keyword[def] identifier[mill] ( identifier[it] , identifier[label] = literal[string] , identifier[hide] = keyword[None] , identifier[expected_size] = keyword[None] , identifier[every] = literal[int] ):
literal[string]
keyword[def] identifier[_mill_char] ( identifier[_i] ):
keyword[if] identifie... | def mill(it, label='', hide=None, expected_size=None, every=1):
"""Progress iterator. Prints a mill while iterating over the items."""
def _mill_char(_i):
if _i >= count:
return ' ' # depends on [control=['if'], data=[]]
else:
return MILL_CHARS[_i // every % len(MILL_CH... |
def p_NonAnyType_interface(p):
"""NonAnyType : IDENTIFIER TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.InterfaceType(name=p[1]), p[2]) | def function[p_NonAnyType_interface, parameter[p]]:
constant[NonAnyType : IDENTIFIER TypeSuffix]
call[name[p]][constant[0]] assign[=] call[name[helper].unwrapTypeSuffix, parameter[call[name[model].InterfaceType, parameter[]], call[name[p]][constant[2]]]] | keyword[def] identifier[p_NonAnyType_interface] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[helper] . identifier[unwrapTypeSuffix] ( identifier[model] . identifier[InterfaceType] ( identifier[name] = identifier[p] [ literal[int] ]), identifier[p] [ literal[int] ]) | def p_NonAnyType_interface(p):
"""NonAnyType : IDENTIFIER TypeSuffix"""
p[0] = helper.unwrapTypeSuffix(model.InterfaceType(name=p[1]), p[2]) |
def rollback(self):
"""Implementation of NAPALM method rollback."""
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) | def function[rollback, parameter[self]]:
constant[Implementation of NAPALM method rollback.]
variable[commands] assign[=] list[[]]
call[name[commands].append, parameter[constant[configure replace flash:rollback-0]]]
call[name[commands].append, parameter[constant[write memory]]]
c... | keyword[def] identifier[rollback] ( identifier[self] ):
literal[string]
identifier[commands] =[]
identifier[commands] . identifier[append] ( literal[string] )
identifier[commands] . identifier[append] ( literal[string] )
identifier[self] . identifier[device] . identifier[... | def rollback(self):
"""Implementation of NAPALM method rollback."""
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) |
def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1 | def function[_incr_executions, parameter[self]]:
constant[Increment the number of executions for the current connection.]
<ast.AugAssign object at 0x7da2041d9450> | keyword[def] identifier[_incr_executions] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_pool_manager] . identifier[get_connection] ( identifier[self] . identifier[pid] , identifier[self] . identifier[_conn] ). identifier[executions] += literal[int] | def _incr_executions(self):
"""Increment the number of executions for the current connection."""
self._pool_manager.get_connection(self.pid, self._conn).executions += 1 |
def transformer_tall_pretrain_lm_tpu_adafactor():
"""Hparams for transformer on LM pretraining (with 64k vocab) on TPU."""
hparams = transformer_tall_pretrain_lm()
update_hparams_for_tpu(hparams)
hparams.max_length = 1024
# For multi-problem on TPU we need it in absolute examples.
hparams.batch_size = 8
h... | def function[transformer_tall_pretrain_lm_tpu_adafactor, parameter[]]:
constant[Hparams for transformer on LM pretraining (with 64k vocab) on TPU.]
variable[hparams] assign[=] call[name[transformer_tall_pretrain_lm], parameter[]]
call[name[update_hparams_for_tpu], parameter[name[hparams]]]
... | keyword[def] identifier[transformer_tall_pretrain_lm_tpu_adafactor] ():
literal[string]
identifier[hparams] = identifier[transformer_tall_pretrain_lm] ()
identifier[update_hparams_for_tpu] ( identifier[hparams] )
identifier[hparams] . identifier[max_length] = literal[int]
identifier[hparams] . ide... | def transformer_tall_pretrain_lm_tpu_adafactor():
"""Hparams for transformer on LM pretraining (with 64k vocab) on TPU."""
hparams = transformer_tall_pretrain_lm()
update_hparams_for_tpu(hparams)
hparams.max_length = 1024
# For multi-problem on TPU we need it in absolute examples.
hparams.batch_... |
def make_hash(keys, **kwargs):
"""
Creates a perfect hash function from the given keys. For a
description of the keyword arguments see :py:func:`hash_parameters`.
>>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
>>> hf = make_hash(l)
>>> hf(19)
1
>>> hash_parameters(... | def function[make_hash, parameter[keys]]:
constant[
Creates a perfect hash function from the given keys. For a
description of the keyword arguments see :py:func:`hash_parameters`.
>>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
>>> hf = make_hash(l)
>>> hf(19)
1
... | keyword[def] identifier[make_hash] ( identifier[keys] ,** identifier[kwargs] ):
literal[string]
identifier[params] = identifier[hash_parameters] ( identifier[keys] ,** identifier[kwargs] )
identifier[t] = identifier[params] . identifier[t]
identifier[r] = identifier[params] . identifier[r]
... | def make_hash(keys, **kwargs):
"""
Creates a perfect hash function from the given keys. For a
description of the keyword arguments see :py:func:`hash_parameters`.
>>> l = (0, 3, 4, 7 ,10, 13, 15, 18, 19, 21, 22, 24, 26, 29, 30, 34)
>>> hf = make_hash(l)
>>> hf(19)
1
>>> hash_parameters(... |
def _CreateOutputModule(self, options):
"""Creates the output module.
Args:
options (argparse.Namespace): command line arguments.
Returns:
OutputModule: output module.
Raises:
RuntimeError: if the output module cannot be created.
"""
formatter_mediator = formatters_mediator.... | def function[_CreateOutputModule, parameter[self, options]]:
constant[Creates the output module.
Args:
options (argparse.Namespace): command line arguments.
Returns:
OutputModule: output module.
Raises:
RuntimeError: if the output module cannot be created.
]
variable... | keyword[def] identifier[_CreateOutputModule] ( identifier[self] , identifier[options] ):
literal[string]
identifier[formatter_mediator] = identifier[formatters_mediator] . identifier[FormatterMediator] (
identifier[data_location] = identifier[self] . identifier[_data_location] )
keyword[try] :
... | def _CreateOutputModule(self, options):
"""Creates the output module.
Args:
options (argparse.Namespace): command line arguments.
Returns:
OutputModule: output module.
Raises:
RuntimeError: if the output module cannot be created.
"""
formatter_mediator = formatters_mediator.... |
def from_hdf5(hdf5, anno_id=None):
"""
Converts an HDF5 file to a RAMON object. Returns an object that is a child-
-class of RAMON (though it's determined at run-time what type is returned).
Accessing multiple IDs from the same file is not supported, because it's
not dramatically faster to access e... | def function[from_hdf5, parameter[hdf5, anno_id]]:
constant[
Converts an HDF5 file to a RAMON object. Returns an object that is a child-
-class of RAMON (though it's determined at run-time what type is returned).
Accessing multiple IDs from the same file is not supported, because it's
not drama... | keyword[def] identifier[from_hdf5] ( identifier[hdf5] , identifier[anno_id] = keyword[None] ):
literal[string]
keyword[if] identifier[anno_id] keyword[is] keyword[None] :
keyword[return] identifier[from_hdf5] ( identifier[hdf5] , identifier[list] ( identifier[hdf5] . identifier[keys] ())[... | def from_hdf5(hdf5, anno_id=None):
"""
Converts an HDF5 file to a RAMON object. Returns an object that is a child-
-class of RAMON (though it's determined at run-time what type is returned).
Accessing multiple IDs from the same file is not supported, because it's
not dramatically faster to access e... |
def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in l:
... | def function[remove_link, parameter[self, obj, attr]]:
constant[
removes link from obj.attr
]
variable[name] assign[=] call[name[repr], parameter[name[self]]]
if <ast.UnaryOp object at 0x7da20c7c9270> begin[:]
return[name[self]]
variable[l] assign[=] call[name[sel... | keyword[def] identifier[remove_link] ( identifier[self] , identifier[obj] , identifier[attr] = keyword[None] ):
literal[string]
identifier[name] = identifier[repr] ( identifier[self] )
keyword[if] keyword[not] identifier[name] :
keyword[return] identifier[self]
id... | def remove_link(self, obj, attr=None):
"""
removes link from obj.attr
"""
name = repr(self)
if not name:
return self # depends on [control=['if'], data=[]]
l = self.__class__._get_links()
v = WeakAttrLink(None, obj) if attr is None else WeakAttrLink(obj, attr)
if name in... |
def crosstalk_correction(pathway_definitions,
random_seed=2015,
gene_set=set(),
all_genes=True,
max_iters=1000):
"""A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
... | def function[crosstalk_correction, parameter[pathway_definitions, random_seed, gene_set, all_genes, max_iters]]:
constant[A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
pathway_definitions : dict(str -> set(str))
The original pathway definitions.
... | keyword[def] identifier[crosstalk_correction] ( identifier[pathway_definitions] ,
identifier[random_seed] = literal[int] ,
identifier[gene_set] = identifier[set] (),
identifier[all_genes] = keyword[True] ,
identifier[max_iters] = literal[int] ):
literal[string]
identifier[np] . identifier[random] . ide... | def crosstalk_correction(pathway_definitions, random_seed=2015, gene_set=set(), all_genes=True, max_iters=1000):
"""A wrapper function around the maximum impact estimation algorithm.
Parameters
-----------
pathway_definitions : dict(str -> set(str))
The original pathway definitions.
A p... |
def __get_window(self, hWnd):
"""
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
"""
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process( self.get_process... | def function[__get_window, parameter[self, hWnd]]:
constant[
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
]
variable[window] assign[=] call[name[Window], parameter[name[hWnd]]]
if compare[call... | keyword[def] identifier[__get_window] ( identifier[self] , identifier[hWnd] ):
literal[string]
identifier[window] = identifier[Window] ( identifier[hWnd] )
keyword[if] identifier[window] . identifier[get_pid] ()== identifier[self] . identifier[get_pid] ():
identifier[window] ... | def __get_window(self, hWnd):
"""
User internally to get another Window from this one.
It'll try to copy the parent Process and Thread references if possible.
"""
window = Window(hWnd)
if window.get_pid() == self.get_pid():
window.set_process(self.get_process()) # depends on... |
def _ParseMRUListExEntryValue(
self, parser_mediator, registry_key, entry_index, entry_number,
values_dict, value_strings, parent_path_segments, codepage='cp1252'):
"""Parses the MRUListEx entry value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and... | def function[_ParseMRUListExEntryValue, parameter[self, parser_mediator, registry_key, entry_index, entry_number, values_dict, value_strings, parent_path_segments, codepage]]:
constant[Parses the MRUListEx entry value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
... | keyword[def] identifier[_ParseMRUListExEntryValue] (
identifier[self] , identifier[parser_mediator] , identifier[registry_key] , identifier[entry_index] , identifier[entry_number] ,
identifier[values_dict] , identifier[value_strings] , identifier[parent_path_segments] , identifier[codepage] = literal[string] ):
... | def _ParseMRUListExEntryValue(self, parser_mediator, registry_key, entry_index, entry_number, values_dict, value_strings, parent_path_segments, codepage='cp1252'):
"""Parses the MRUListEx entry value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other compon... |
def set_heater(self, heater):
"""Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
"""
if type(heater) != int and heater not in range(0, 101):
raise InvalidInput("Heater value ... | def function[set_heater, parameter[self, heater]]:
constant[Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
]
if <ast.BoolOp object at 0x7da204566950> begin[:]
<ast.Raise object ... | keyword[def] identifier[set_heater] ( identifier[self] , identifier[heater] ):
literal[string]
keyword[if] identifier[type] ( identifier[heater] )!= identifier[int] keyword[and] identifier[heater] keyword[not] keyword[in] identifier[range] ( literal[int] , literal[int] ):
keyword... | def set_heater(self, heater):
"""Set the heater config.
:param heater: Value to set the heater
:type heater: int [0-100]
:returns: None
:raises: InvalidInput
"""
if type(heater) != int and heater not in range(0, 101):
raise InvalidInput('Heater value must be int ... |
def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None,
ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
... | def function[subset_gctoo, parameter[gctoo, row_bool, col_bool, rid, cid, ridx, cidx, exclude_rid, exclude_cid]]:
constant[ Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
row_bool (list of bo... | keyword[def] identifier[subset_gctoo] ( identifier[gctoo] , identifier[row_bool] = keyword[None] , identifier[col_bool] = keyword[None] , identifier[rid] = keyword[None] , identifier[cid] = keyword[None] ,
identifier[ridx] = keyword[None] , identifier[cidx] = keyword[None] , identifier[exclude_rid] = keyword[None] ,... | def subset_gctoo(gctoo, row_bool=None, col_bool=None, rid=None, cid=None, ridx=None, cidx=None, exclude_rid=None, exclude_cid=None):
""" Extract a subset of data from a GCToo object in a variety of ways.
The order of rows and columns will be preserved.
Args:
gctoo (GCToo object)
row_bool (l... |
def pdf(cls, uuid):
"""Return a PDF of the invoice identified by the UUID
This is a raw string, which can be written to a file with:
`
with open('invoice.pdf', 'w') as invoice_file:
invoice_file.write(recurly.Invoice.pdf(uuid))
`
"""
url = ur... | def function[pdf, parameter[cls, uuid]]:
constant[Return a PDF of the invoice identified by the UUID
This is a raw string, which can be written to a file with:
`
with open('invoice.pdf', 'w') as invoice_file:
invoice_file.write(recurly.Invoice.pdf(uuid))
`
... | keyword[def] identifier[pdf] ( identifier[cls] , identifier[uuid] ):
literal[string]
identifier[url] = identifier[urljoin] ( identifier[base_uri] (), identifier[cls] . identifier[member_path] %( identifier[uuid] ,))
identifier[pdf_response] = identifier[cls] . identifier[http_request] ( id... | def pdf(cls, uuid):
"""Return a PDF of the invoice identified by the UUID
This is a raw string, which can be written to a file with:
`
with open('invoice.pdf', 'w') as invoice_file:
invoice_file.write(recurly.Invoice.pdf(uuid))
`
"""
url = urljoin(ba... |
def dicom_to_nifti(dicom_input, output_file=None):
"""
This is the main dicom to nifti conversion fuction for philips images.
As input philips images are required. It will then determine the type of images and do the correct conversion
Examples: See unit test
:param output_file: file path to the o... | def function[dicom_to_nifti, parameter[dicom_input, output_file]]:
constant[
This is the main dicom to nifti conversion fuction for philips images.
As input philips images are required. It will then determine the type of images and do the correct conversion
Examples: See unit test
:param outpu... | keyword[def] identifier[dicom_to_nifti] ( identifier[dicom_input] , identifier[output_file] = keyword[None] ):
literal[string]
keyword[assert] identifier[common] . identifier[is_philips] ( identifier[dicom_input] )
keyword[if] identifier[common] . identifier[is_multiframe_dicom] ( identifier[dicom... | def dicom_to_nifti(dicom_input, output_file=None):
"""
This is the main dicom to nifti conversion fuction for philips images.
As input philips images are required. It will then determine the type of images and do the correct conversion
Examples: See unit test
:param output_file: file path to the o... |
def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
'''
Wrapper to call a given func on a syndic, best effort to get the one you asked for
'''
if kwargs is None:
kwargs = {}
successful = False
# Call for each master
for master, syndic_f... | def function[_call_syndic, parameter[self, func, args, kwargs, master_id]]:
constant[
Wrapper to call a given func on a syndic, best effort to get the one you asked for
]
if compare[name[kwargs] is constant[None]] begin[:]
variable[kwargs] assign[=] dictionary[[], []]
... | keyword[def] identifier[_call_syndic] ( identifier[self] , identifier[func] , identifier[args] =(), identifier[kwargs] = keyword[None] , identifier[master_id] = keyword[None] ):
literal[string]
keyword[if] identifier[kwargs] keyword[is] keyword[None] :
identifier[kwargs] ={}
... | def _call_syndic(self, func, args=(), kwargs=None, master_id=None):
"""
Wrapper to call a given func on a syndic, best effort to get the one you asked for
"""
if kwargs is None:
kwargs = {} # depends on [control=['if'], data=['kwargs']]
successful = False
# Call for each master
... |
def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i]
if ten:
summ += 1
res.appe... | def function[plus_one_v1, parameter[digits]]:
constant[
:type digits: List[int]
:rtype: List[int]
]
call[name[digits]][<ast.UnaryOp object at 0x7da1b20784c0>] assign[=] binary_operation[call[name[digits]][<ast.UnaryOp object at 0x7da1b2078a60>] + constant[1]]
variable[res] assign[=] ... | keyword[def] identifier[plus_one_v1] ( identifier[digits] ):
literal[string]
identifier[digits] [- literal[int] ]= identifier[digits] [- literal[int] ]+ literal[int]
identifier[res] =[]
identifier[ten] = literal[int]
identifier[i] = identifier[len] ( identifier[digits] )- literal[int]
... | def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits) - 1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i] # depends on [control=['if'], data=['i']]
i... |
def unlock(self):
"""Unlock this Workspace."""
r = fapi.unlock_workspace(self.namespace, self.name, self.api_url)
fapi._check_response_code(r, 204)
self.data['workspace']['isLocked'] = False
return self | def function[unlock, parameter[self]]:
constant[Unlock this Workspace.]
variable[r] assign[=] call[name[fapi].unlock_workspace, parameter[name[self].namespace, name[self].name, name[self].api_url]]
call[name[fapi]._check_response_code, parameter[name[r], constant[204]]]
call[call[name[se... | keyword[def] identifier[unlock] ( identifier[self] ):
literal[string]
identifier[r] = identifier[fapi] . identifier[unlock_workspace] ( identifier[self] . identifier[namespace] , identifier[self] . identifier[name] , identifier[self] . identifier[api_url] )
identifier[fapi] . identifier[_c... | def unlock(self):
"""Unlock this Workspace."""
r = fapi.unlock_workspace(self.namespace, self.name, self.api_url)
fapi._check_response_code(r, 204)
self.data['workspace']['isLocked'] = False
return self |
def sort_merge(in_file, data, out_dir=None):
"""Sort and merge a BED file, collapsing gene names.
Output is a 3 or 4 column file (the 4th column values go comma-separated).
"""
out_file = "%s-sortmerge.bed" % os.path.splitext(in_file)[0]
bedtools = config_utils.get_program("bedtools", data, defau... | def function[sort_merge, parameter[in_file, data, out_dir]]:
constant[Sort and merge a BED file, collapsing gene names.
Output is a 3 or 4 column file (the 4th column values go comma-separated).
]
variable[out_file] assign[=] binary_operation[constant[%s-sortmerge.bed] <ast.Mod object at 0x7d... | keyword[def] identifier[sort_merge] ( identifier[in_file] , identifier[data] , identifier[out_dir] = keyword[None] ):
literal[string]
identifier[out_file] = literal[string] % identifier[os] . identifier[path] . identifier[splitext] ( identifier[in_file] )[ literal[int] ]
identifier[bedtools] = identif... | def sort_merge(in_file, data, out_dir=None):
"""Sort and merge a BED file, collapsing gene names.
Output is a 3 or 4 column file (the 4th column values go comma-separated).
"""
out_file = '%s-sortmerge.bed' % os.path.splitext(in_file)[0]
bedtools = config_utils.get_program('bedtools', data, defau... |
def from_regular_array(self, A):
"""
Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
:rtype: `np.ndarray`
... | def function[from_regular_array, parameter[self, A]]:
constant[
Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
... | keyword[def] identifier[from_regular_array] ( identifier[self] , identifier[A] ):
literal[string]
identifier[dims] = identifier[A] . identifier[shape] [:- literal[int] ]
keyword[return] identifier[A] . identifier[reshape] (( identifier[np] . identifier[prod] ( identifier[dims] ),- literal... | def from_regular_array(self, A):
"""
Converts from an array of type `int` where the last index
is assumed to have length `self.n_elements` to an array
of type `self.d_type` with one fewer index.
:param np.ndarray A: An `np.array` of type `int`.
:rtype: `np.ndarray`
... |
def header_class_for_version(cls, version):
"""
>>> HeaderFactory.header_class_for_version(2.0)
Traceback (most recent call last):
...
pylas.errors.FileVersionNotSupported: 2.0
>>> HeaderFactory.header_class_for_version(1.2)
<class 'pylas.headers.rawheader.RawHe... | def function[header_class_for_version, parameter[cls, version]]:
constant[
>>> HeaderFactory.header_class_for_version(2.0)
Traceback (most recent call last):
...
pylas.errors.FileVersionNotSupported: 2.0
>>> HeaderFactory.header_class_for_version(1.2)
<class 'py... | keyword[def] identifier[header_class_for_version] ( identifier[cls] , identifier[version] ):
literal[string]
keyword[try] :
keyword[return] identifier[cls] . identifier[_version_to_header] [ identifier[str] ( identifier[version] )]
keyword[except] identifier[KeyError] :
... | def header_class_for_version(cls, version):
"""
>>> HeaderFactory.header_class_for_version(2.0)
Traceback (most recent call last):
...
pylas.errors.FileVersionNotSupported: 2.0
>>> HeaderFactory.header_class_for_version(1.2)
<class 'pylas.headers.rawheader.RawHeader... |
def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
k = k.contiguous().view... | def function[icnr, parameter[x, scale, init]]:
constant[ICNR init of `x`, with `scale` and `init` function.]
<ast.Tuple object at 0x7da1b202bd60> assign[=] name[x].shape
variable[ni2] assign[=] call[name[int], parameter[binary_operation[name[ni] / binary_operation[name[scale] ** constant[2]]]]]
... | keyword[def] identifier[icnr] ( identifier[x] , identifier[scale] = literal[int] , identifier[init] = identifier[nn] . identifier[init] . identifier[kaiming_normal_] ):
literal[string]
identifier[ni] , identifier[nf] , identifier[h] , identifier[w] = identifier[x] . identifier[shape]
identifier[ni2] ... | def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"""ICNR init of `x`, with `scale` and `init` function."""
(ni, nf, h, w) = x.shape
ni2 = int(ni / scale ** 2)
k = init(torch.zeros([ni2, nf, h, w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale ** 2)
k = k.c... |
def get_mutually_unstable_correlation_triples(graph: BELGraph) -> Iterable[NodeTriple]:
"""Yield triples of nodes (A, B, C) such that ``A neg B``, ``B neg C``, and ``C neg A``."""
cg = get_correlation_graph(graph)
for a, b, c in get_correlation_triangles(cg):
if all(NEGATIVE_CORRELATION in x for x ... | def function[get_mutually_unstable_correlation_triples, parameter[graph]]:
constant[Yield triples of nodes (A, B, C) such that ``A neg B``, ``B neg C``, and ``C neg A``.]
variable[cg] assign[=] call[name[get_correlation_graph], parameter[name[graph]]]
for taget[tuple[[<ast.Name object at 0x7da1b... | keyword[def] identifier[get_mutually_unstable_correlation_triples] ( identifier[graph] : identifier[BELGraph] )-> identifier[Iterable] [ identifier[NodeTriple] ]:
literal[string]
identifier[cg] = identifier[get_correlation_graph] ( identifier[graph] )
keyword[for] identifier[a] , identifier[b] , ide... | def get_mutually_unstable_correlation_triples(graph: BELGraph) -> Iterable[NodeTriple]:
"""Yield triples of nodes (A, B, C) such that ``A neg B``, ``B neg C``, and ``C neg A``."""
cg = get_correlation_graph(graph)
for (a, b, c) in get_correlation_triangles(cg):
if all((NEGATIVE_CORRELATION in x for ... |
def list(self, pagination=True, page_size=None, page=None, **queryparams):
"""
Retrieves a list of objects.
By default uses local cache and remote pagination
If pagination is used and no page is requested (the default), all the
remote objects are retrieved and appended in a sin... | def function[list, parameter[self, pagination, page_size, page]]:
constant[
Retrieves a list of objects.
By default uses local cache and remote pagination
If pagination is used and no page is requested (the default), all the
remote objects are retrieved and appended in a single... | keyword[def] identifier[list] ( identifier[self] , identifier[pagination] = keyword[True] , identifier[page_size] = keyword[None] , identifier[page] = keyword[None] ,** identifier[queryparams] ):
literal[string]
keyword[if] identifier[page_size] keyword[and] identifier[pagination] :
... | def list(self, pagination=True, page_size=None, page=None, **queryparams):
"""
Retrieves a list of objects.
By default uses local cache and remote pagination
If pagination is used and no page is requested (the default), all the
remote objects are retrieved and appended in a single ... |
def init_output_formatters(output_verbosity='normal', stderr=sys.stderr, logfile=None, debug_logfile=None):
"""
Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, defaul... | def function[init_output_formatters, parameter[output_verbosity, stderr, logfile, debug_logfile]]:
constant[
Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, defau... | keyword[def] identifier[init_output_formatters] ( identifier[output_verbosity] = literal[string] , identifier[stderr] = identifier[sys] . identifier[stderr] , identifier[logfile] = keyword[None] , identifier[debug_logfile] = keyword[None] ):
literal[string]
keyword[if] identifier[output_verbosity] keywo... | def init_output_formatters(output_verbosity='normal', stderr=sys.stderr, logfile=None, debug_logfile=None):
"""
Initialize the CLI logging scheme.
:param output_verbosity: 'quiet','normal','verbose', or 'debug' controls the output to stdout and its format
:param stderr: stream for stderr output, defaul... |
def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
obs = BinnedAnalysis.BinnedObs(irfs=args.irfs,
expCube=args.expcube,
srcMaps=args.cmap,
... | def function[run_analysis, parameter[self, argv]]:
constant[Run this analysis]
variable[args] assign[=] call[name[self]._parser.parse_args, parameter[name[argv]]]
variable[obs] assign[=] call[name[BinnedAnalysis].BinnedObs, parameter[]]
if name[args].no_psf begin[:]
varia... | keyword[def] identifier[run_analysis] ( identifier[self] , identifier[argv] ):
literal[string]
identifier[args] = identifier[self] . identifier[_parser] . identifier[parse_args] ( identifier[argv] )
identifier[obs] = identifier[BinnedAnalysis] . identifier[BinnedObs] ( identifier[irfs] = i... | def run_analysis(self, argv):
"""Run this analysis"""
args = self._parser.parse_args(argv)
obs = BinnedAnalysis.BinnedObs(irfs=args.irfs, expCube=args.expcube, srcMaps=args.cmap, binnedExpMap=args.bexpmap)
if args.no_psf:
performConvolution = False # depends on [control=['if'], data=[]]
els... |
def save(name, filter=False):
'''
Save the register to <salt cachedir>/thorium/saves/<name>, or to an
absolute path.
If an absolute path is specified, then the directory will be created
non-recursively if it doesn't exist.
USAGE:
.. code-block:: yaml
foo:
file.save
... | def function[save, parameter[name, filter]]:
constant[
Save the register to <salt cachedir>/thorium/saves/<name>, or to an
absolute path.
If an absolute path is specified, then the directory will be created
non-recursively if it doesn't exist.
USAGE:
.. code-block:: yaml
foo:... | keyword[def] identifier[save] ( identifier[name] , identifier[filter] = keyword[False] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] :{},
literal[string] : literal[string] ,
literal[string] : keyword[True] }
keyword[if] identifier[name] . id... | def save(name, filter=False):
"""
Save the register to <salt cachedir>/thorium/saves/<name>, or to an
absolute path.
If an absolute path is specified, then the directory will be created
non-recursively if it doesn't exist.
USAGE:
.. code-block:: yaml
foo:
file.save
... |
def perf_stats(returns, factor_returns=None, positions=None,
transactions=None, turnover_denom='AGB'):
"""
Calculates various performance metrics of a strategy, for use in
plotting.show_perf_stats.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, n... | def function[perf_stats, parameter[returns, factor_returns, positions, transactions, turnover_denom]]:
constant[
Calculates various performance metrics of a strategy, for use in
plotting.show_perf_stats.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncum... | keyword[def] identifier[perf_stats] ( identifier[returns] , identifier[factor_returns] = keyword[None] , identifier[positions] = keyword[None] ,
identifier[transactions] = keyword[None] , identifier[turnover_denom] = literal[string] ):
literal[string]
identifier[stats] = identifier[pd] . identifier[Serie... | def perf_stats(returns, factor_returns=None, positions=None, transactions=None, turnover_denom='AGB'):
"""
Calculates various performance metrics of a strategy, for use in
plotting.show_perf_stats.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
... |
def symmetric_difference(self, other):
"""
Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.
Args:
other (:class:`FrameSet`):
Returns:
:class:`FrameSet`:
"""
other = self._cast_to_fr... | def function[symmetric_difference, parameter[self, other]]:
constant[
Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.
Args:
other (:class:`FrameSet`):
Returns:
:class:`FrameSet`:
]
... | keyword[def] identifier[symmetric_difference] ( identifier[self] , identifier[other] ):
literal[string]
identifier[other] = identifier[self] . identifier[_cast_to_frameset] ( identifier[other] )
keyword[if] identifier[other] keyword[is] identifier[NotImplemented] :
keyword[... | def symmetric_difference(self, other):
"""
Returns a new :class:`FrameSet` that contains all the elements in either
`self` or `other`, but not both.
Args:
other (:class:`FrameSet`):
Returns:
:class:`FrameSet`:
"""
other = self._cast_to_frameset(o... |
def entify_main(args):
'''
Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application.
'''
# Recovering the logger
# Calling the logger when being imported
i3visiotools.logger.setupLogger(loggerName="entify", verbosity=... | def function[entify_main, parameter[args]]:
constant[
Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application.
]
call[name[i3visiotools].logger.setupLogger, parameter[]]
variable[logger] assign[=]... | keyword[def] identifier[entify_main] ( identifier[args] ):
literal[string]
identifier[i3visiotools] . identifier[logger] . identifier[setupLogger] ( identifier[loggerName] = literal[string] , identifier[verbosity] = identifier[args] . identifier[verbose] , identifier[logFolder] = identifier[args] . identifie... | def entify_main(args):
"""
Main function. This function is created in this way so as to let other applications make use of the full configuration capabilities of the application.
""" # Recovering the logger
# Calling the logger when being imported
i3visiotools.logger.setupLogger(loggerName='entify', v... |
def list_formats(format_type, backend=None):
"""
Returns list of supported formats for a particular
backend.
"""
if backend is None:
backend = Store.current_backend
mode = Store.renderers[backend].mode if backend in Store.renderers else None
else:
split = backend.split(':... | def function[list_formats, parameter[format_type, backend]]:
constant[
Returns list of supported formats for a particular
backend.
]
if compare[name[backend] is constant[None]] begin[:]
variable[backend] assign[=] name[Store].current_backend
variable[mode] ass... | keyword[def] identifier[list_formats] ( identifier[format_type] , identifier[backend] = keyword[None] ):
literal[string]
keyword[if] identifier[backend] keyword[is] keyword[None] :
identifier[backend] = identifier[Store] . identifier[current_backend]
identifier[mode] = identifier[Stor... | def list_formats(format_type, backend=None):
"""
Returns list of supported formats for a particular
backend.
"""
if backend is None:
backend = Store.current_backend
mode = Store.renderers[backend].mode if backend in Store.renderers else None # depends on [control=['if'], data=['back... |
def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() | def function[get_evidence_by_hash, parameter[self, evidence_hash]]:
constant[Look up an evidence by its hash.]
return[call[call[call[name[self].session.query, parameter[name[Evidence]]].filter, parameter[compare[name[Evidence].sha512 equal[==] name[evidence_hash]]]].one_or_none, parameter[]]] | keyword[def] identifier[get_evidence_by_hash] ( identifier[self] , identifier[evidence_hash] : identifier[str] )-> identifier[Optional] [ identifier[Evidence] ]:
literal[string]
keyword[return] identifier[self] . identifier[session] . identifier[query] ( identifier[Evidence] ). identifier[filter] ... | def get_evidence_by_hash(self, evidence_hash: str) -> Optional[Evidence]:
"""Look up an evidence by its hash."""
return self.session.query(Evidence).filter(Evidence.sha512 == evidence_hash).one_or_none() |
def schedule_in(secs, target=None, args=(), kwargs=None):
"""insert a greenlet into the scheduler to run after a set time
If provided a function, it is wrapped in a new greenlet
:param secs: the number of seconds to wait before running the target
:type unixtime: int or float
:param target: what to... | def function[schedule_in, parameter[secs, target, args, kwargs]]:
constant[insert a greenlet into the scheduler to run after a set time
If provided a function, it is wrapped in a new greenlet
:param secs: the number of seconds to wait before running the target
:type unixtime: int or float
:par... | keyword[def] identifier[schedule_in] ( identifier[secs] , identifier[target] = keyword[None] , identifier[args] =(), identifier[kwargs] = keyword[None] ):
literal[string]
keyword[return] identifier[schedule_at] ( identifier[time] . identifier[time] ()+ identifier[secs] , identifier[target] , identifier[ar... | def schedule_in(secs, target=None, args=(), kwargs=None):
"""insert a greenlet into the scheduler to run after a set time
If provided a function, it is wrapped in a new greenlet
:param secs: the number of seconds to wait before running the target
:type unixtime: int or float
:param target: what to... |
def task(func, **config):
"""Declare a function or method to be a Yaz task
@yaz.task
def talk(message: str = "Hello World!"):
return message
Or... group multiple tasks together
class Tools(yaz.Plugin):
@yaz.task
def say(self, message: str = "Hello World!"):
ret... | def function[task, parameter[func]]:
constant[Declare a function or method to be a Yaz task
@yaz.task
def talk(message: str = "Hello World!"):
return message
Or... group multiple tasks together
class Tools(yaz.Plugin):
@yaz.task
def say(self, message: str = "Hello Worl... | keyword[def] identifier[task] ( identifier[func] ,** identifier[config] ):
literal[string]
keyword[if] identifier[func] . identifier[__name__] == identifier[func] . identifier[__qualname__] :
keyword[assert] keyword[not] identifier[func] . identifier[__qualname__] keyword[in] identifier[_task... | def task(func, **config):
"""Declare a function or method to be a Yaz task
@yaz.task
def talk(message: str = "Hello World!"):
return message
Or... group multiple tasks together
class Tools(yaz.Plugin):
@yaz.task
def say(self, message: str = "Hello World!"):
ret... |
def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.string_types) and obj in seq and len(seq) > 200:
index = seq.find(obj)
start_index = index - 50
if start_... | def function[assert_not_in, parameter[obj, seq, message, extra]]:
constant[Raises an AssertionError if obj is in iter.]
if <ast.BoolOp object at 0x7da1b0f50c70> begin[:]
variable[index] assign[=] call[name[seq].find, parameter[name[obj]]]
variable[start_index] assign[=] b... | keyword[def] identifier[assert_not_in] ( identifier[obj] , identifier[seq] , identifier[message] = keyword[None] , identifier[extra] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[seq] , identifier[six] . identifier[string_types] ) keyword[and] identifier[obj] ke... | def assert_not_in(obj, seq, message=None, extra=None):
"""Raises an AssertionError if obj is in iter."""
# for very long strings, provide a truncated error
if isinstance(seq, six.string_types) and obj in seq and (len(seq) > 200):
index = seq.find(obj)
start_index = index - 50
if star... |
def computeParams(self, params):
"""Computes the parameters depending on :math:`\lambda`.
Notes
-----
It needs to be called again if :math:`\lambda` changes during
evolution.
Parameters
----------
params:
A dictionary of the manually set para... | def function[computeParams, parameter[self, params]]:
constant[Computes the parameters depending on :math:`\lambda`.
Notes
-----
It needs to be called again if :math:`\lambda` changes during
evolution.
Parameters
----------
params:
A dictiona... | keyword[def] identifier[computeParams] ( identifier[self] , identifier[params] ):
literal[string]
identifier[self] . identifier[mu] = identifier[params] . identifier[get] ( literal[string] , identifier[int] ( identifier[self] . identifier[lambda_] / literal[int] ))
identifier[rweights] = i... | def computeParams(self, params):
"""Computes the parameters depending on :math:`\\lambda`.
Notes
-----
It needs to be called again if :math:`\\lambda` changes during
evolution.
Parameters
----------
params:
A dictionary of the manually set parame... |
def propagateRst(obj):
"""
Propagate reset "rst" signal
to all subcomponents
"""
rst = obj.rst
for u in obj._units:
_tryConnect(~rst, u, 'rst_n')
_tryConnect(rst, u, 'rst') | def function[propagateRst, parameter[obj]]:
constant[
Propagate reset "rst" signal
to all subcomponents
]
variable[rst] assign[=] name[obj].rst
for taget[name[u]] in starred[name[obj]._units] begin[:]
call[name[_tryConnect], parameter[<ast.UnaryOp object at 0x7da1b03f... | keyword[def] identifier[propagateRst] ( identifier[obj] ):
literal[string]
identifier[rst] = identifier[obj] . identifier[rst]
keyword[for] identifier[u] keyword[in] identifier[obj] . identifier[_units] :
identifier[_tryConnect] (~ identifier[rst] , identifier[u] , literal[string] )
... | def propagateRst(obj):
"""
Propagate reset "rst" signal
to all subcomponents
"""
rst = obj.rst
for u in obj._units:
_tryConnect(~rst, u, 'rst_n')
_tryConnect(rst, u, 'rst') # depends on [control=['for'], data=['u']] |
def update_additional_charge(self, *, recurring_billing_id, description, plan_value, plan_tax, plan_tax_return_base,
currency):
"""
Updates the information from an additional charge in an invoice.
Args:
recurring_billing_id: Identifier of the additio... | def function[update_additional_charge, parameter[self]]:
constant[
Updates the information from an additional charge in an invoice.
Args:
recurring_billing_id: Identifier of the additional charge.
description:
plan_value:
plan_tax:
pla... | keyword[def] identifier[update_additional_charge] ( identifier[self] ,*, identifier[recurring_billing_id] , identifier[description] , identifier[plan_value] , identifier[plan_tax] , identifier[plan_tax_return_base] ,
identifier[currency] ):
literal[string]
identifier[payload] ={
literal[s... | def update_additional_charge(self, *, recurring_billing_id, description, plan_value, plan_tax, plan_tax_return_base, currency):
"""
Updates the information from an additional charge in an invoice.
Args:
recurring_billing_id: Identifier of the additional charge.
description:
... |
def _finalize_profiles(self):
"""
Deal with the first walks by joining profiles to other stops within walking distance.
"""
for stop, stop_profile in self._stop_profiles.items():
assert (isinstance(stop_profile, NodeProfileMultiObjective))
neighbor_label_bags = []... | def function[_finalize_profiles, parameter[self]]:
constant[
Deal with the first walks by joining profiles to other stops within walking distance.
]
for taget[tuple[[<ast.Name object at 0x7da1b000e020>, <ast.Name object at 0x7da1b000e080>]]] in starred[call[name[self]._stop_profiles.item... | keyword[def] identifier[_finalize_profiles] ( identifier[self] ):
literal[string]
keyword[for] identifier[stop] , identifier[stop_profile] keyword[in] identifier[self] . identifier[_stop_profiles] . identifier[items] ():
keyword[assert] ( identifier[isinstance] ( identifier[stop_pro... | def _finalize_profiles(self):
"""
Deal with the first walks by joining profiles to other stops within walking distance.
"""
for (stop, stop_profile) in self._stop_profiles.items():
assert isinstance(stop_profile, NodeProfileMultiObjective)
neighbor_label_bags = []
walk_du... |
def _microtime():
'''
Return a Unix timestamp as a string of digits
:return:
'''
val1, val2 = math.modf(time.time())
val2 = int(val2)
return '{0:f}{1}'.format(val1, val2) | def function[_microtime, parameter[]]:
constant[
Return a Unix timestamp as a string of digits
:return:
]
<ast.Tuple object at 0x7da2047e9000> assign[=] call[name[math].modf, parameter[call[name[time].time, parameter[]]]]
variable[val2] assign[=] call[name[int], parameter[name[val2]]... | keyword[def] identifier[_microtime] ():
literal[string]
identifier[val1] , identifier[val2] = identifier[math] . identifier[modf] ( identifier[time] . identifier[time] ())
identifier[val2] = identifier[int] ( identifier[val2] )
keyword[return] literal[string] . identifier[format] ( identifier[va... | def _microtime():
"""
Return a Unix timestamp as a string of digits
:return:
"""
(val1, val2) = math.modf(time.time())
val2 = int(val2)
return '{0:f}{1}'.format(val1, val2) |
def Update(self, data):
"""Updates a Beta distribution.
data: pair of int (heads, tails)
"""
heads, tails = data
self.alpha += heads
self.beta += tails | def function[Update, parameter[self, data]]:
constant[Updates a Beta distribution.
data: pair of int (heads, tails)
]
<ast.Tuple object at 0x7da20c991030> assign[=] name[data]
<ast.AugAssign object at 0x7da20c9930a0>
<ast.AugAssign object at 0x7da20c990250> | keyword[def] identifier[Update] ( identifier[self] , identifier[data] ):
literal[string]
identifier[heads] , identifier[tails] = identifier[data]
identifier[self] . identifier[alpha] += identifier[heads]
identifier[self] . identifier[beta] += identifier[tails] | def Update(self, data):
"""Updates a Beta distribution.
data: pair of int (heads, tails)
"""
(heads, tails) = data
self.alpha += heads
self.beta += tails |
def lookup_ids(self, keys):
"""Lookup the integer ID associated with each (namespace, key) in the
keys list"""
keys_len = len(keys)
ids = {namespace_key: None for namespace_key in keys}
start = 0
bulk_insert = self.bulk_insert
query = 'SELECT namespace, key, id FR... | def function[lookup_ids, parameter[self, keys]]:
constant[Lookup the integer ID associated with each (namespace, key) in the
keys list]
variable[keys_len] assign[=] call[name[len], parameter[name[keys]]]
variable[ids] assign[=] <ast.DictComp object at 0x7da1b24b7b50>
variable[sta... | keyword[def] identifier[lookup_ids] ( identifier[self] , identifier[keys] ):
literal[string]
identifier[keys_len] = identifier[len] ( identifier[keys] )
identifier[ids] ={ identifier[namespace_key] : keyword[None] keyword[for] identifier[namespace_key] keyword[in] identifier[keys] }
... | def lookup_ids(self, keys):
"""Lookup the integer ID associated with each (namespace, key) in the
keys list"""
keys_len = len(keys)
ids = {namespace_key: None for namespace_key in keys}
start = 0
bulk_insert = self.bulk_insert
query = 'SELECT namespace, key, id FROM gauged_keys WHERE '
... |
def reply_bytes(self, request):
"""Take a `Request` and return an OP_MSG message as bytes."""
flags = struct.pack("<I", self._flags)
payload_type = struct.pack("<b", 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_i... | def function[reply_bytes, parameter[self, request]]:
constant[Take a `Request` and return an OP_MSG message as bytes.]
variable[flags] assign[=] call[name[struct].pack, parameter[constant[<I], name[self]._flags]]
variable[payload_type] assign[=] call[name[struct].pack, parameter[constant[<b], co... | keyword[def] identifier[reply_bytes] ( identifier[self] , identifier[request] ):
literal[string]
identifier[flags] = identifier[struct] . identifier[pack] ( literal[string] , identifier[self] . identifier[_flags] )
identifier[payload_type] = identifier[struct] . identifier[pack] ( literal[... | def reply_bytes(self, request):
"""Take a `Request` and return an OP_MSG message as bytes."""
flags = struct.pack('<I', self._flags)
payload_type = struct.pack('<b', 0)
payload_data = bson.BSON.encode(self.doc)
data = b''.join([flags, payload_type, payload_data])
reply_id = random.randint(0, 100... |
def _default_transform_fn(self, model, content, content_type, accept):
"""Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Args:
model (obj)... | def function[_default_transform_fn, parameter[self, model, content, content_type, accept]]:
constant[Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Ar... | keyword[def] identifier[_default_transform_fn] ( identifier[self] , identifier[model] , identifier[content] , identifier[content_type] , identifier[accept] ):
literal[string]
keyword[try] :
identifier[data] = identifier[self] . identifier[_input_fn] ( identifier[content] , identifier[c... | def _default_transform_fn(self, model, content, content_type, accept):
"""Make predictions against the model and return a serialized response.
This serves as the default implementation of transform_fn, used when the user has not
implemented one themselves.
Args:
model (obj): mo... |
def to_url(request):
"""Serialize as a URL for a GET request."""
scheme, netloc, path, query, fragment = urlsplit(to_utf8(request.url))
query = parse_qs(query)
for key, value in request.data_and_params.iteritems():
query.setdefault(key, []).append(value)
query = url... | def function[to_url, parameter[request]]:
constant[Serialize as a URL for a GET request.]
<ast.Tuple object at 0x7da20c6e54e0> assign[=] call[name[urlsplit], parameter[call[name[to_utf8], parameter[name[request].url]]]]
variable[query] assign[=] call[name[parse_qs], parameter[name[query]]]
... | keyword[def] identifier[to_url] ( identifier[request] ):
literal[string]
identifier[scheme] , identifier[netloc] , identifier[path] , identifier[query] , identifier[fragment] = identifier[urlsplit] ( identifier[to_utf8] ( identifier[request] . identifier[url] ))
identifier[query] = identif... | def to_url(request):
"""Serialize as a URL for a GET request."""
(scheme, netloc, path, query, fragment) = urlsplit(to_utf8(request.url))
query = parse_qs(query)
for (key, value) in request.data_and_params.iteritems():
query.setdefault(key, []).append(value) # depends on [control=['for'], data=... |
def disassemble_bytes(orig_msg, orig_msg_nocr, code, lasti=-1, cur_line=0,
start_line=-1, end_line=None, relative_pos=False,
varnames=(), names=(), constants=(), cells=(),
freevars=(), linestarts={}, highlight='light',
start_offset=... | def function[disassemble_bytes, parameter[orig_msg, orig_msg_nocr, code, lasti, cur_line, start_line, end_line, relative_pos, varnames, names, constants, cells, freevars, linestarts, highlight, start_offset, end_offset]]:
constant[Disassemble byte string of code. If end_line is negative
it counts the number... | keyword[def] identifier[disassemble_bytes] ( identifier[orig_msg] , identifier[orig_msg_nocr] , identifier[code] , identifier[lasti] =- literal[int] , identifier[cur_line] = literal[int] ,
identifier[start_line] =- literal[int] , identifier[end_line] = keyword[None] , identifier[relative_pos] = keyword[False] ,
ide... | def disassemble_bytes(orig_msg, orig_msg_nocr, code, lasti=-1, cur_line=0, start_line=-1, end_line=None, relative_pos=False, varnames=(), names=(), constants=(), cells=(), freevars=(), linestarts={}, highlight='light', start_offset=0, end_offset=None):
"""Disassemble byte string of code. If end_line is negative
... |
def profile(message=None, verbose=False):
"""Decorator for profiling a function.
TODO: Support `@profile` syntax (without parens). This would involve
inspecting the args. In this case `profile` would receive a single
argument, which is the function to be decorated.
"""
import functools
fro... | def function[profile, parameter[message, verbose]]:
constant[Decorator for profiling a function.
TODO: Support `@profile` syntax (without parens). This would involve
inspecting the args. In this case `profile` would receive a single
argument, which is the function to be decorated.
]
import... | keyword[def] identifier[profile] ( identifier[message] = keyword[None] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[import] identifier[functools]
keyword[from] identifier[harrison] . identifier[registered_timer] keyword[import] identifier[RegisteredTimer]
key... | def profile(message=None, verbose=False):
"""Decorator for profiling a function.
TODO: Support `@profile` syntax (without parens). This would involve
inspecting the args. In this case `profile` would receive a single
argument, which is the function to be decorated.
"""
import functools
fro... |
def get_observations_for_site(self, site_id, frequency='hourly'):
"""
Get observations for the provided site
Returns hourly observations for the previous 24 hours
"""
data = self.__call_api(site_id,{"res":frequency}, OBSERVATION_URL)
params = da... | def function[get_observations_for_site, parameter[self, site_id, frequency]]:
constant[
Get observations for the provided site
Returns hourly observations for the previous 24 hours
]
variable[data] assign[=] call[name[self].__call_api, parameter[name[site_id], dictio... | keyword[def] identifier[get_observations_for_site] ( identifier[self] , identifier[site_id] , identifier[frequency] = literal[string] ):
literal[string]
identifier[data] = identifier[self] . identifier[__call_api] ( identifier[site_id] ,{ literal[string] : identifier[frequency] }, identifi... | def get_observations_for_site(self, site_id, frequency='hourly'):
"""
Get observations for the provided site
Returns hourly observations for the previous 24 hours
"""
data = self.__call_api(site_id, {'res': frequency}, OBSERVATION_URL)
params = data['SiteRep']['Wx']['Par... |
def load_dataframe(self, df_loader_name):
"""
Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes
we may want to just directly load a particular DataFrame.
"""
logger.debug("loading dataframe: {}".format(df_loader_name))
# Get the DataFrameLo... | def function[load_dataframe, parameter[self, df_loader_name]]:
constant[
Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes
we may want to just directly load a particular DataFrame.
]
call[name[logger].debug, parameter[call[constant[loading datafram... | keyword[def] identifier[load_dataframe] ( identifier[self] , identifier[df_loader_name] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[df_loader_name] ))
identifier[df_loaders] =[ identifier[df_loader] keyword[for] i... | def load_dataframe(self, df_loader_name):
"""
Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes
we may want to just directly load a particular DataFrame.
"""
logger.debug('loading dataframe: {}'.format(df_loader_name))
# Get the DataFrameLoader object ... |
def _replace_auth_key(
user,
key,
enc='ssh-rsa',
comment='',
options=None,
config='.ssh/authorized_keys'):
'''
Replace an existing key
'''
auth_line = _format_auth_line(key, enc, comment, options or [])
lines = []
full = _get_config_file(user, co... | def function[_replace_auth_key, parameter[user, key, enc, comment, options, config]]:
constant[
Replace an existing key
]
variable[auth_line] assign[=] call[name[_format_auth_line], parameter[name[key], name[enc], name[comment], <ast.BoolOp object at 0x7da18ede5d50>]]
variable[lines] ass... | keyword[def] identifier[_replace_auth_key] (
identifier[user] ,
identifier[key] ,
identifier[enc] = literal[string] ,
identifier[comment] = literal[string] ,
identifier[options] = keyword[None] ,
identifier[config] = literal[string] ):
literal[string]
identifier[auth_line] = identifier[_format_auth_... | def _replace_auth_key(user, key, enc='ssh-rsa', comment='', options=None, config='.ssh/authorized_keys'):
"""
Replace an existing key
"""
auth_line = _format_auth_line(key, enc, comment, options or [])
lines = []
full = _get_config_file(user, config)
try:
# open the file for both rea... |
def _generate_examples(self, archive_paths, objects_getter, bboxes_getter,
prefixes=None):
"""Yields examples."""
trainable_classes = set(
self.info.features['objects_trainable']['label'].names)
for i, archive_path in enumerate(archive_paths):
prefix = prefixes[i] if p... | def function[_generate_examples, parameter[self, archive_paths, objects_getter, bboxes_getter, prefixes]]:
constant[Yields examples.]
variable[trainable_classes] assign[=] call[name[set], parameter[call[call[name[self].info.features][constant[objects_trainable]]][constant[label]].names]]
for tag... | keyword[def] identifier[_generate_examples] ( identifier[self] , identifier[archive_paths] , identifier[objects_getter] , identifier[bboxes_getter] ,
identifier[prefixes] = keyword[None] ):
literal[string]
identifier[trainable_classes] = identifier[set] (
identifier[self] . identifier[info] . identif... | def _generate_examples(self, archive_paths, objects_getter, bboxes_getter, prefixes=None):
"""Yields examples."""
trainable_classes = set(self.info.features['objects_trainable']['label'].names)
for (i, archive_path) in enumerate(archive_paths):
prefix = prefixes[i] if prefixes else None
obje... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.