code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _collect_valid_settings(meta, clsdict):
"""
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded.
"""
enum_members = clsdict['__members__']
valid_settings = []
for member in enum_members:
... | def function[_collect_valid_settings, parameter[meta, clsdict]]:
constant[
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded.
]
variable[enum_members] assign[=] call[name[clsdict]][constant[__members__]]
... | keyword[def] identifier[_collect_valid_settings] ( identifier[meta] , identifier[clsdict] ):
literal[string]
identifier[enum_members] = identifier[clsdict] [ literal[string] ]
identifier[valid_settings] =[]
keyword[for] identifier[member] keyword[in] identifier[enum_members] :
... | def _collect_valid_settings(meta, clsdict):
"""
Return a sequence containing the enumeration values that are valid
assignment values. Return-only values are excluded.
"""
enum_members = clsdict['__members__']
valid_settings = []
for member in enum_members:
valid_settings.... |
def security_group_rule_delete(auth=None, **kwargs):
'''
Delete a security group
name_or_id
The unique ID of the security group rule
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_rule_delete name_or_id=1dcac318a83b4610b7a7f7ba01465548
'''
cloud = ge... | def function[security_group_rule_delete, parameter[auth]]:
constant[
Delete a security group
name_or_id
The unique ID of the security group rule
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_rule_delete name_or_id=1dcac318a83b4610b7a7f7ba01465548
]
... | keyword[def] identifier[security_group_rule_delete] ( identifier[auth] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[cloud] = identifier[get_operator_cloud] ( identifier[auth] )
identifier[kwargs] = identifier[_clean_kwargs] (** identifier[kwargs] )
keyword[return] identif... | def security_group_rule_delete(auth=None, **kwargs):
"""
Delete a security group
name_or_id
The unique ID of the security group rule
CLI Example:
.. code-block:: bash
salt '*' neutronng.security_group_rule_delete name_or_id=1dcac318a83b4610b7a7f7ba01465548
"""
cloud = ge... |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.validate_extent():
new_step = self.parent.step_fc_summary
else:
new_step = sel... | def function[get_next_step, parameter[self]]:
constant[Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
]
if call[name[self].validate_extent, parameter[]] begin[:]
variable[new_step] ... | keyword[def] identifier[get_next_step] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[validate_extent] ():
identifier[new_step] = identifier[self] . identifier[parent] . identifier[step_fc_summary]
keyword[else] :
identifier[new_... | def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.validate_extent():
new_step = self.parent.step_fc_summary # depends on [control=['if'], data=[]]
else:
... |
def _close_subspans(self, start: int, stop: int) -> None:
"""Close all sub-spans of (start, stop)."""
ss, se = self._span
for spans in self._type_to_spans.values():
b = bisect(spans, [start])
for i, (s, e) in enumerate(spans[b:bisect(spans, [stop], b)]):
i... | def function[_close_subspans, parameter[self, start, stop]]:
constant[Close all sub-spans of (start, stop).]
<ast.Tuple object at 0x7da1b025fe20> assign[=] name[self]._span
for taget[name[spans]] in starred[call[name[self]._type_to_spans.values, parameter[]]] begin[:]
variable[b]... | keyword[def] identifier[_close_subspans] ( identifier[self] , identifier[start] : identifier[int] , identifier[stop] : identifier[int] )-> keyword[None] :
literal[string]
identifier[ss] , identifier[se] = identifier[self] . identifier[_span]
keyword[for] identifier[spans] keyword[in] i... | def _close_subspans(self, start: int, stop: int) -> None:
"""Close all sub-spans of (start, stop)."""
(ss, se) = self._span
for spans in self._type_to_spans.values():
b = bisect(spans, [start])
for (i, (s, e)) in enumerate(spans[b:bisect(spans, [stop], b)]):
if e <= stop:
... |
def report_view(self, request, key, period):
"""
Processes the reporting action.
"""
if not self.has_change_permission(request, None):
raise PermissionDenied
reporters = self.get_reporters()
try:
reporter = reporters[key]
except KeyError:... | def function[report_view, parameter[self, request, key, period]]:
constant[
Processes the reporting action.
]
if <ast.UnaryOp object at 0x7da1b16145b0> begin[:]
<ast.Raise object at 0x7da1b1616650>
variable[reporters] assign[=] call[name[self].get_reporters, parameter[]]
... | keyword[def] identifier[report_view] ( identifier[self] , identifier[request] , identifier[key] , identifier[period] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_change_permission] ( identifier[request] , keyword[None] ):
keyword[raise] identifier[P... | def report_view(self, request, key, period):
"""
Processes the reporting action.
"""
if not self.has_change_permission(request, None):
raise PermissionDenied # depends on [control=['if'], data=[]]
reporters = self.get_reporters()
try:
reporter = reporters[key] # depends... |
def view_tickets(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view"
api_path = "/api/v2/views/{id}/tickets.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[view_tickets, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view]
variable[api_path] assign[=] constant[/api/v2/views/{id}/tickets.json]
variable[api_path] assign[=] call[name[api_path].format, parameter[]]
return[call[... | keyword[def] identifier[view_tickets] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[return] identif... | def view_tickets(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/views#list-tickets-from-a-view"""
api_path = '/api/v2/views/{id}/tickets.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def create_rbd_image(service, pool, image, sizemb):
"""Create a new RADOS block device."""
cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service,
'--pool', pool]
check_call(cmd) | def function[create_rbd_image, parameter[service, pool, image, sizemb]]:
constant[Create a new RADOS block device.]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da18dc9b310>, <ast.Constant object at 0x7da18dc99c60>, <ast.Name object at 0x7da18dc9bdf0>, <ast.Constant object at 0x7da18dc98fd0>... | keyword[def] identifier[create_rbd_image] ( identifier[service] , identifier[pool] , identifier[image] , identifier[sizemb] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , identifier[image] , literal[string] , identifier[str] ( identifier[sizemb] ), literal[string] , identifier[se... | def create_rbd_image(service, pool, image, sizemb):
"""Create a new RADOS block device."""
cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service, '--pool', pool]
check_call(cmd) |
def set_x(self, x):
"Set x position"
if(x>=0):
self.x=x
else:
self.x=self.w+x | def function[set_x, parameter[self, x]]:
constant[Set x position]
if compare[name[x] greater_or_equal[>=] constant[0]] begin[:]
name[self].x assign[=] name[x] | keyword[def] identifier[set_x] ( identifier[self] , identifier[x] ):
literal[string]
keyword[if] ( identifier[x] >= literal[int] ):
identifier[self] . identifier[x] = identifier[x]
keyword[else] :
identifier[self] . identifier[x] = identifier[self] . identifier[w... | def set_x(self, x):
"""Set x position"""
if x >= 0:
self.x = x # depends on [control=['if'], data=['x']]
else:
self.x = self.w + x |
def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
"""
Query time series.
@param query: Query string.
@param from_time: Start of the period to query (optional).
@param to_time: End of the period to query (default = now).
@return: A list of ApiTimeSeriesResponse.
... | def function[query_timeseries, parameter[self, query, from_time, to_time, by_post]]:
constant[
Query time series.
@param query: Query string.
@param from_time: Start of the period to query (optional).
@param to_time: End of the period to query (default = now).
@return: A list of ApiTimeSerie... | keyword[def] identifier[query_timeseries] ( identifier[self] , identifier[query] , identifier[from_time] = keyword[None] , identifier[to_time] = keyword[None] , identifier[by_post] = keyword[False] ):
literal[string]
keyword[return] identifier[timeseries] . identifier[query_timeseries] ( identifier[self] ... | def query_timeseries(self, query, from_time=None, to_time=None, by_post=False):
"""
Query time series.
@param query: Query string.
@param from_time: Start of the period to query (optional).
@param to_time: End of the period to query (default = now).
@return: A list of ApiTimeSeriesResponse.
... |
def validate_df(df, dm, con=None):
"""
Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ (checking that req'd colum... | def function[validate_df, parameter[df, dm, con]]:
constant[
Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ ... | keyword[def] identifier[validate_df] ( identifier[df] , identifier[dm] , identifier[con] = keyword[None] ):
literal[string]
identifier[required_one] ={}
identifier[cols] = identifier[df] . identifier[columns]
identifier[invalid_cols] =[ identifier[col] keyword[for] identifier[col] keywor... | def validate_df(df, dm, con=None):
"""
Take in a DataFrame and corresponding data model.
Run all validations for that DataFrame.
Output is the original DataFrame with some new columns
that contain the validation output.
Validation columns start with:
presence_pass_ (checking that req'd colum... |
def kana2alphabet(text):
"""Convert Hiragana to hepburn-style alphabets
Parameters
----------
text : str
Hiragana string.
Return
------
str
Hepburn-style alphabets string.
Examples
--------
>>> print(jaconv.kana2alphabet('ใพใฟใใ'))
mamisan
"""
text = ... | def function[kana2alphabet, parameter[text]]:
constant[Convert Hiragana to hepburn-style alphabets
Parameters
----------
text : str
Hiragana string.
Return
------
str
Hepburn-style alphabets string.
Examples
--------
>>> print(jaconv.kana2alphabet('ใพใฟใใ'))
... | keyword[def] identifier[kana2alphabet] ( identifier[text] ):
literal[string]
identifier[text] = identifier[text] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] )
identifier[... | def kana2alphabet(text):
"""Convert Hiragana to hepburn-style alphabets
Parameters
----------
text : str
Hiragana string.
Return
------
str
Hepburn-style alphabets string.
Examples
--------
>>> print(jaconv.kana2alphabet('ใพใฟใใ'))
mamisan
"""
text = ... |
def try_to_get(self, symbol):
""" Gets a Symbol based on name, which may or may not exist.
Parameters
----------
symbol : str
Returns
-------
Symbol or None.
Note
----
Use .get(), if the symbol shou... | def function[try_to_get, parameter[self, symbol]]:
constant[ Gets a Symbol based on name, which may or may not exist.
Parameters
----------
symbol : str
Returns
-------
Symbol or None.
Note
----
Use .get(), if t... | keyword[def] identifier[try_to_get] ( identifier[self] , identifier[symbol] ):
literal[string]
identifier[syms] = identifier[self] . identifier[ses] . identifier[query] ( identifier[Symbol] ). identifier[filter] ( identifier[Symbol] . identifier[name] == identifier[symbol] ). identifier[all] ()
... | def try_to_get(self, symbol):
""" Gets a Symbol based on name, which may or may not exist.
Parameters
----------
symbol : str
Returns
-------
Symbol or None.
Note
----
Use .get(), if the symbol should exist, and an ... |
def sense_ttb(self, target):
"""Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps.
"""
log.debug("polling for NFC-B technology")
if target.brty not in ("1... | def function[sense_ttb, parameter[self, target]]:
constant[Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps.
]
call[name[log].debug, parameter[constant[polling fo... | keyword[def] identifier[sense_ttb] ( identifier[self] , identifier[target] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] )
keyword[if] identifier[target] . identifier[brty] keyword[not] keyword[in] ( literal[string] , literal[string] , literal[string] ):
... | def sense_ttb(self, target):
"""Sense for a Type B Target is supported for 106, 212 and 424
kbps. However, there may not be any target that understands the
activation command in other than 106 kbps.
"""
log.debug('polling for NFC-B technology')
if target.brty not in ('106B', '212B',... |
def joint_entropy(X, Y, base=2):
"""Calculates the joint entropy, H(X,Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the joint entropy
Y: array-like (# samples)
An array of values for which to compute the joint entropy
... | def function[joint_entropy, parameter[X, Y, base]]:
constant[Calculates the joint entropy, H(X,Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the joint entropy
Y: array-like (# samples)
An array of values for which t... | keyword[def] identifier[joint_entropy] ( identifier[X] , identifier[Y] , identifier[base] = literal[int] ):
literal[string]
identifier[X_Y] =[ literal[string] . identifier[format] ( identifier[x] , identifier[y] ) keyword[for] identifier[x] , identifier[y] keyword[in] identifier[zip] ( identifier[X] , i... | def joint_entropy(X, Y, base=2):
"""Calculates the joint entropy, H(X,Y), in the given base
Parameters
----------
X: array-like (# samples)
An array of values for which to compute the joint entropy
Y: array-like (# samples)
An array of values for which to compute the joint entropy
... |
def getback(config, force=False):
"""Goes back to the master branch, deletes the current branch locally
and remotely."""
repo = config.repo
active_branch = repo.active_branch
if active_branch.name == "master":
error_out("You're already on the master branch.")
if repo.is_dirty():
... | def function[getback, parameter[config, force]]:
constant[Goes back to the master branch, deletes the current branch locally
and remotely.]
variable[repo] assign[=] name[config].repo
variable[active_branch] assign[=] name[repo].active_branch
if compare[name[active_branch].name equal[... | keyword[def] identifier[getback] ( identifier[config] , identifier[force] = keyword[False] ):
literal[string]
identifier[repo] = identifier[config] . identifier[repo]
identifier[active_branch] = identifier[repo] . identifier[active_branch]
keyword[if] identifier[active_branch] . identifier[na... | def getback(config, force=False):
"""Goes back to the master branch, deletes the current branch locally
and remotely."""
repo = config.repo
active_branch = repo.active_branch
if active_branch.name == 'master':
error_out("You're already on the master branch.") # depends on [control=['if'], d... |
def close(self):
"""
Disable al operations and close the underlying file-like object, if any
"""
if callable(getattr(self._file, 'close', None)):
self._iterator.close()
self._iterator = None
self._unconsumed = None
self.closed = True | def function[close, parameter[self]]:
constant[
Disable al operations and close the underlying file-like object, if any
]
if call[name[callable], parameter[call[name[getattr], parameter[name[self]._file, constant[close], constant[None]]]]] begin[:]
call[name[self]._iterat... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
keyword[if] identifier[callable] ( identifier[getattr] ( identifier[self] . identifier[_file] , literal[string] , keyword[None] )):
identifier[self] . identifier[_iterator] . identifier[close] ()
identifier[... | def close(self):
"""
Disable al operations and close the underlying file-like object, if any
"""
if callable(getattr(self._file, 'close', None)):
self._iterator.close() # depends on [control=['if'], data=[]]
self._iterator = None
self._unconsumed = None
self.closed = True |
def write(self, oprot):
'''
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_objects_list_item.OnlineDatabaseObjectsListItem
'''
oprot.wr... | def function[write, parameter[self, oprot]]:
constant[
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_objects_list_item.OnlineDatabaseObjectsListItem
... | keyword[def] identifier[write] ( identifier[self] , identifier[oprot] ):
literal[string]
identifier[oprot] . identifier[write_struct_begin] ( literal[string] )
identifier[oprot] . identifier[write_field_begin] ( identifier[name] = literal[string] , identifier[type] = literal[int] , ident... | def write(self, oprot):
"""
Write this object to the given output protocol and return self.
:type oprot: thryft.protocol._output_protocol._OutputProtocol
:rtype: pastpy.gen.database.impl.online.online_database_objects_list_item.OnlineDatabaseObjectsListItem
"""
oprot.write_struc... |
def get_project_collection(self, collection_id):
"""GetProjectCollection.
[Preview API] Get project collection with the specified id or name.
:param str collection_id:
:rtype: :class:`<TeamProjectCollection> <azure.devops.v5_1.core.models.TeamProjectCollection>`
"""
route... | def function[get_project_collection, parameter[self, collection_id]]:
constant[GetProjectCollection.
[Preview API] Get project collection with the specified id or name.
:param str collection_id:
:rtype: :class:`<TeamProjectCollection> <azure.devops.v5_1.core.models.TeamProjectCollection>... | keyword[def] identifier[get_project_collection] ( identifier[self] , identifier[collection_id] ):
literal[string]
identifier[route_values] ={}
keyword[if] identifier[collection_id] keyword[is] keyword[not] keyword[None] :
identifier[route_values] [ literal[string] ]= ident... | def get_project_collection(self, collection_id):
"""GetProjectCollection.
[Preview API] Get project collection with the specified id or name.
:param str collection_id:
:rtype: :class:`<TeamProjectCollection> <azure.devops.v5_1.core.models.TeamProjectCollection>`
"""
route_values ... |
def delete_old_host(self, hostname):
"""Remove all records for the host.
:param str hostname: Hostname to remove
:rtype: bool
"""
host = Host(self.session, name=hostname)
return host.delete() | def function[delete_old_host, parameter[self, hostname]]:
constant[Remove all records for the host.
:param str hostname: Hostname to remove
:rtype: bool
]
variable[host] assign[=] call[name[Host], parameter[name[self].session]]
return[call[name[host].delete, parameter[]]] | keyword[def] identifier[delete_old_host] ( identifier[self] , identifier[hostname] ):
literal[string]
identifier[host] = identifier[Host] ( identifier[self] . identifier[session] , identifier[name] = identifier[hostname] )
keyword[return] identifier[host] . identifier[delete] () | def delete_old_host(self, hostname):
"""Remove all records for the host.
:param str hostname: Hostname to remove
:rtype: bool
"""
host = Host(self.session, name=hostname)
return host.delete() |
def symbolize(number):
"""Convert `number` to a foot/endnote symbol."""
repeat, index = divmod(number - 1, len(SYMBOLS))
return SYMBOLS[index] * (1 + repeat) | def function[symbolize, parameter[number]]:
constant[Convert `number` to a foot/endnote symbol.]
<ast.Tuple object at 0x7da18eb57be0> assign[=] call[name[divmod], parameter[binary_operation[name[number] - constant[1]], call[name[len], parameter[name[SYMBOLS]]]]]
return[binary_operation[call[name[SYM... | keyword[def] identifier[symbolize] ( identifier[number] ):
literal[string]
identifier[repeat] , identifier[index] = identifier[divmod] ( identifier[number] - literal[int] , identifier[len] ( identifier[SYMBOLS] ))
keyword[return] identifier[SYMBOLS] [ identifier[index] ]*( literal[int] + identifier[r... | def symbolize(number):
"""Convert `number` to a foot/endnote symbol."""
(repeat, index) = divmod(number - 1, len(SYMBOLS))
return SYMBOLS[index] * (1 + repeat) |
def dafgs(n=125):
# The 125 may be a hard set,
# I got strange errors that occasionally happened without it
"""
Return (get) the summary for the current array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgs_c.html
:param n: Optional length N for result Array.
... | def function[dafgs, parameter[n]]:
constant[
Return (get) the summary for the current array in the current DAF.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgs_c.html
:param n: Optional length N for result Array.
:return: Summary for current array.
:rtype: Array of floats
... | keyword[def] identifier[dafgs] ( identifier[n] = literal[int] ):
literal[string]
identifier[retarray] = identifier[stypes] . identifier[emptyDoubleVector] ( literal[int] )
identifier[libspice] . identifier[dafgs_c] ( identifier[retarray] )
keyword[return] identifier[stypes] . identifier[c... | def dafgs(n=125):
# The 125 may be a hard set,
# I got strange errors that occasionally happened without it
'\n Return (get) the summary for the current array in the current DAF.\n\n http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafgs_c.html\n\n :param n: Optional length N for result Arra... |
def fontsize(self, fontsize=None):
'''
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
'''
if fontsize is not None:
self._canvas.fontsize = fontsize
else:
return self... | def function[fontsize, parameter[self, fontsize]]:
constant[
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
]
if compare[name[fontsize] is_not constant[None]] begin[:]
name[self]._c... | keyword[def] identifier[fontsize] ( identifier[self] , identifier[fontsize] = keyword[None] ):
literal[string]
keyword[if] identifier[fontsize] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[_canvas] . identifier[fontsize] = identifier[fontsize]
ke... | def fontsize(self, fontsize=None):
"""
Set or return size of current font.
:param fontsize: Size of font.
:return: Size of font (if fontsize was not specified)
"""
if fontsize is not None:
self._canvas.fontsize = fontsize # depends on [control=['if'], data=['fontsize']]... |
def get_project_build(account_project):
"""Get the details of the latest Appveyor build."""
url = make_url("/projects/{account_project}", account_project=account_project)
response = requests.get(url, headers=make_auth_headers())
return response.json() | def function[get_project_build, parameter[account_project]]:
constant[Get the details of the latest Appveyor build.]
variable[url] assign[=] call[name[make_url], parameter[constant[/projects/{account_project}]]]
variable[response] assign[=] call[name[requests].get, parameter[name[url]]]
retu... | keyword[def] identifier[get_project_build] ( identifier[account_project] ):
literal[string]
identifier[url] = identifier[make_url] ( literal[string] , identifier[account_project] = identifier[account_project] )
identifier[response] = identifier[requests] . identifier[get] ( identifier[url] , identifie... | def get_project_build(account_project):
"""Get the details of the latest Appveyor build."""
url = make_url('/projects/{account_project}', account_project=account_project)
response = requests.get(url, headers=make_auth_headers())
return response.json() |
def bin_stream(stream, content_type, status='200 OK',
headers=None):
"""Utility method for constructing a binary response.
:param Any stream: The response body stream
:param str content_type: The content-type of the response
:param str status: The HTTP status line
... | def function[bin_stream, parameter[stream, content_type, status, headers]]:
constant[Utility method for constructing a binary response.
:param Any stream: The response body stream
:param str content_type: The content-type of the response
:param str status: The HTTP status line
:... | keyword[def] identifier[bin_stream] ( identifier[stream] , identifier[content_type] , identifier[status] = literal[string] ,
identifier[headers] = keyword[None] ):
literal[string]
identifier[def_headers] =[( literal[string] , identifier[content_type] )]
keyword[if] identifier[headers] :
... | def bin_stream(stream, content_type, status='200 OK', headers=None):
"""Utility method for constructing a binary response.
:param Any stream: The response body stream
:param str content_type: The content-type of the response
:param str status: The HTTP status line
:param list[tuple[... |
def use_defaults(self, data=None):
"""
Prepare/modify data for plotting
"""
if data is None:
data = self.data
return self.geom.use_defaults(data) | def function[use_defaults, parameter[self, data]]:
constant[
Prepare/modify data for plotting
]
if compare[name[data] is constant[None]] begin[:]
variable[data] assign[=] name[self].data
return[call[name[self].geom.use_defaults, parameter[name[data]]]] | keyword[def] identifier[use_defaults] ( identifier[self] , identifier[data] = keyword[None] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] :
identifier[data] = identifier[self] . identifier[data]
keyword[return] identifier[self] . identifier[geo... | def use_defaults(self, data=None):
"""
Prepare/modify data for plotting
"""
if data is None:
data = self.data # depends on [control=['if'], data=['data']]
return self.geom.use_defaults(data) |
def bind(self, **kwargs):
'''
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
'''
d = dict(self.__dict__)
for k in d.keys():
if k[0] == '_':
del d[k]
elif k.startsw... | def function[bind, parameter[self]]:
constant[
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
]
variable[d] assign[=] call[name[dict], parameter[name[self].__dict__]]
for taget[name[k]] in starred[call[n... | keyword[def] identifier[bind] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[d] = identifier[dict] ( identifier[self] . identifier[__dict__] )
keyword[for] identifier[k] keyword[in] identifier[d] . identifier[keys] ():
keyword[if] identifier[k] [ l... | def bind(self, **kwargs):
"""
creates a copy of the object without the
cached results and with the given keyword
arguments as properties.
"""
d = dict(self.__dict__)
for k in d.keys():
if k[0] == '_':
del d[k] # depends on [control=['if'], data=[]]
... |
def get_locale():
"""Get locale.
Searches for locale in the following the order:
- User has specified a concrete language in the query string.
- Current session has a language set.
- User has a language set in the profile.
- Headers of the HTTP request.
- Default language from ``BABEL_DEFA... | def function[get_locale, parameter[]]:
constant[Get locale.
Searches for locale in the following the order:
- User has specified a concrete language in the query string.
- Current session has a language set.
- User has a language set in the profile.
- Headers of the HTTP request.
- Def... | keyword[def] identifier[get_locale] ():
literal[string]
identifier[locales] =[ identifier[x] [ literal[int] ] keyword[for] identifier[x] keyword[in]
identifier[current_app] . identifier[extensions] [ literal[string] ]. identifier[get_languages] ()]
keyword[if] literal[string] keyword[i... | def get_locale():
"""Get locale.
Searches for locale in the following the order:
- User has specified a concrete language in the query string.
- Current session has a language set.
- User has a language set in the profile.
- Headers of the HTTP request.
- Default language from ``BABEL_DEFA... |
def convolve(input, weights, mask=None, slow=False):
"""2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Parts of the input whic... | def function[convolve, parameter[input, weights, mask, slow]]:
constant[2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Par... | keyword[def] identifier[convolve] ( identifier[input] , identifier[weights] , identifier[mask] = keyword[None] , identifier[slow] = keyword[False] ):
literal[string]
keyword[assert] ( identifier[len] ( identifier[input] . identifier[shape] )== literal[int] )
keyword[assert] ( identifier[len] ( identi... | def convolve(input, weights, mask=None, slow=False):
"""2 dimensional convolution.
This is a Python implementation of what will be written in Fortran.
Borders are handled with reflection.
Masking is supported in the following way:
* Masked points are skipped.
* Parts of the input whic... |
def _register_stements(self, statements: List["HdlStatement"],
target: List["HdlStatement"]):
"""
Append statements to this container under conditions specified
by condSet
"""
for stm in flatten(statements):
assert stm.parentStm is None, stm... | def function[_register_stements, parameter[self, statements, target]]:
constant[
Append statements to this container under conditions specified
by condSet
]
for taget[name[stm]] in starred[call[name[flatten], parameter[name[statements]]]] begin[:]
assert[compare[name[stm]... | keyword[def] identifier[_register_stements] ( identifier[self] , identifier[statements] : identifier[List] [ literal[string] ],
identifier[target] : identifier[List] [ literal[string] ]):
literal[string]
keyword[for] identifier[stm] keyword[in] identifier[flatten] ( identifier[statements] ):
... | def _register_stements(self, statements: List['HdlStatement'], target: List['HdlStatement']):
"""
Append statements to this container under conditions specified
by condSet
"""
for stm in flatten(statements):
assert stm.parentStm is None, stm
stm._set_parent_stm(self)
... |
def RIBVRFRouteLimitExceeded_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
RIBVRFRouteLimitExceeded = ET.SubElement(config, "RIBVRFRouteLimitExceeded", xmlns="http://brocade.com/ns/brocade-notification-stream")
... | def function[RIBVRFRouteLimitExceeded_originator_switch_info_switchIpV4Address, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[RIBVRFRouteLimitExceeded] assign[=] call[name[ET].SubElement, parameter... | keyword[def] identifier[RIBVRFRouteLimitExceeded_originator_switch_info_switchIpV4Address] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[RIBVRFRouteLimitExceeded] = identifier[ET] . iden... | def RIBVRFRouteLimitExceeded_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
RIBVRFRouteLimitExceeded = ET.SubElement(config, 'RIBVRFRouteLimitExceeded', xmlns='http://brocade.com/ns/brocade-notification-stream')
originator_switc... |
def overwrite_view_source(project, dir_path):
"""In the project's index.html built file, replace the top "source"
link with a link to the documentation's home, which is mkdoc's home
Args:
project (str): project to update
dir_path (pathlib.Path): this file's path
"""
project_html_lo... | def function[overwrite_view_source, parameter[project, dir_path]]:
constant[In the project's index.html built file, replace the top "source"
link with a link to the documentation's home, which is mkdoc's home
Args:
project (str): project to update
dir_path (pathlib.Path): this file's pa... | keyword[def] identifier[overwrite_view_source] ( identifier[project] , identifier[dir_path] ):
literal[string]
identifier[project_html_location] = identifier[dir_path] / identifier[project] / identifier[HTML_LOCATION]
keyword[if] keyword[not] identifier[project_html_location] . identifier[exists] ... | def overwrite_view_source(project, dir_path):
"""In the project's index.html built file, replace the top "source"
link with a link to the documentation's home, which is mkdoc's home
Args:
project (str): project to update
dir_path (pathlib.Path): this file's path
"""
project_html_loc... |
def append_volume(runtime, source, target, writable=False):
# type: (List[Text], Text, Text, bool) -> None
"""Add binding arguments to the runtime list."""
runtime.append(u"--volume={}:{}:{}".format(
docker_windows_path_adjust(source), target,
"rw" if writable else "ro")) | def function[append_volume, parameter[runtime, source, target, writable]]:
constant[Add binding arguments to the runtime list.]
call[name[runtime].append, parameter[call[constant[--volume={}:{}:{}].format, parameter[call[name[docker_windows_path_adjust], parameter[name[source]]], name[target], <ast.IfEx... | keyword[def] identifier[append_volume] ( identifier[runtime] , identifier[source] , identifier[target] , identifier[writable] = keyword[False] ):
literal[string]
identifier[runtime] . identifier[append] ( literal[string] . identifier[format] (
identifier[docker_windows_path_adjust] ( iden... | def append_volume(runtime, source, target, writable=False):
# type: (List[Text], Text, Text, bool) -> None
'Add binding arguments to the runtime list.'
runtime.append(u'--volume={}:{}:{}'.format(docker_windows_path_adjust(source), target, 'rw' if writable else 'ro')) |
def validate_all_keys_in_obj(obj_name, obj, validation_fun):
"""Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the va... | def function[validate_all_keys_in_obj, parameter[obj_name, obj, validation_fun]]:
constant[Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): f... | keyword[def] identifier[validate_all_keys_in_obj] ( identifier[obj_name] , identifier[obj] , identifier[validation_fun] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[obj] . identifier[items] ():
identifier[validation_fun] ( identifier[obj_name] , ide... | def validate_all_keys_in_obj(obj_name, obj, validation_fun):
"""Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the va... |
def read(calc_id, username=None):
"""
:param calc_id: a calculation ID
:param username: if given, restrict the search to the user's calculations
:returns: the associated DataStore instance
"""
if isinstance(calc_id, str) or calc_id < 0 and not username:
# get the last calculation in the ... | def function[read, parameter[calc_id, username]]:
constant[
:param calc_id: a calculation ID
:param username: if given, restrict the search to the user's calculations
:returns: the associated DataStore instance
]
if <ast.BoolOp object at 0x7da18f813730> begin[:]
return[call[name[... | keyword[def] identifier[read] ( identifier[calc_id] , identifier[username] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[calc_id] , identifier[str] ) keyword[or] identifier[calc_id] < literal[int] keyword[and] keyword[not] identifier[username] :
keywo... | def read(calc_id, username=None):
"""
:param calc_id: a calculation ID
:param username: if given, restrict the search to the user's calculations
:returns: the associated DataStore instance
"""
if isinstance(calc_id, str) or (calc_id < 0 and (not username)):
# get the last calculation in ... |
def effsnr(snr, reduced_x2, fac=250.):
"""Calculate the effective SNR statistic. See (S5y1 paper) for definition.
"""
snr = numpy.array(snr, ndmin=1, dtype=numpy.float64)
rchisq = numpy.array(reduced_x2, ndmin=1, dtype=numpy.float64)
esnr = snr / (1 + snr ** 2 / fac) ** 0.25 / rchisq ** 0.25
# ... | def function[effsnr, parameter[snr, reduced_x2, fac]]:
constant[Calculate the effective SNR statistic. See (S5y1 paper) for definition.
]
variable[snr] assign[=] call[name[numpy].array, parameter[name[snr]]]
variable[rchisq] assign[=] call[name[numpy].array, parameter[name[reduced_x2]]]
... | keyword[def] identifier[effsnr] ( identifier[snr] , identifier[reduced_x2] , identifier[fac] = literal[int] ):
literal[string]
identifier[snr] = identifier[numpy] . identifier[array] ( identifier[snr] , identifier[ndmin] = literal[int] , identifier[dtype] = identifier[numpy] . identifier[float64] )
id... | def effsnr(snr, reduced_x2, fac=250.0):
"""Calculate the effective SNR statistic. See (S5y1 paper) for definition.
"""
snr = numpy.array(snr, ndmin=1, dtype=numpy.float64)
rchisq = numpy.array(reduced_x2, ndmin=1, dtype=numpy.float64)
esnr = snr / (1 + snr ** 2 / fac) ** 0.25 / rchisq ** 0.25
# ... |
def Chemistry(self):
''' Get cells chemistry '''
length = self.bus.read_byte_data(self.address, 0x79)
chem = []
for n in range(length):
chem.append(self.bus.read_byte_data(self.address, 0x7A + n))
return chem | def function[Chemistry, parameter[self]]:
constant[ Get cells chemistry ]
variable[length] assign[=] call[name[self].bus.read_byte_data, parameter[name[self].address, constant[121]]]
variable[chem] assign[=] list[[]]
for taget[name[n]] in starred[call[name[range], parameter[name[length]]... | keyword[def] identifier[Chemistry] ( identifier[self] ):
literal[string]
identifier[length] = identifier[self] . identifier[bus] . identifier[read_byte_data] ( identifier[self] . identifier[address] , literal[int] )
identifier[chem] =[]
keyword[for] identifier[n] keyword[in] id... | def Chemistry(self):
""" Get cells chemistry """
length = self.bus.read_byte_data(self.address, 121)
chem = []
for n in range(length):
chem.append(self.bus.read_byte_data(self.address, 122 + n)) # depends on [control=['for'], data=['n']]
return chem |
def send(self, data):
"""
Sends a packet of data through this connection mode.
This method returns a coroutine.
"""
if not self._connected:
raise ConnectionError('Not connected')
return self._send_queue.put(data) | def function[send, parameter[self, data]]:
constant[
Sends a packet of data through this connection mode.
This method returns a coroutine.
]
if <ast.UnaryOp object at 0x7da1b26ad300> begin[:]
<ast.Raise object at 0x7da1b26afd30>
return[call[name[self]._send_queue.put... | keyword[def] identifier[send] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_connected] :
keyword[raise] identifier[ConnectionError] ( literal[string] )
keyword[return] identifier[self] . identifier[_send_q... | def send(self, data):
"""
Sends a packet of data through this connection mode.
This method returns a coroutine.
"""
if not self._connected:
raise ConnectionError('Not connected') # depends on [control=['if'], data=[]]
return self._send_queue.put(data) |
def trace(self, context, obj):
"""Enumerate the children of the given object, as would be visible and utilized by dispatch."""
root = obj
if isroutine(obj):
yield Crumb(self, root, endpoint=True, handler=obj, options=opts(obj))
return
for name, attr in getmembers(obj if isclass(obj) else obj.__cl... | def function[trace, parameter[self, context, obj]]:
constant[Enumerate the children of the given object, as would be visible and utilized by dispatch.]
variable[root] assign[=] name[obj]
if call[name[isroutine], parameter[name[obj]]] begin[:]
<ast.Yield object at 0x7da1b10a7340>
... | keyword[def] identifier[trace] ( identifier[self] , identifier[context] , identifier[obj] ):
literal[string]
identifier[root] = identifier[obj]
keyword[if] identifier[isroutine] ( identifier[obj] ):
keyword[yield] identifier[Crumb] ( identifier[self] , identifier[root] , identifier[endpoint] = keyw... | def trace(self, context, obj):
"""Enumerate the children of the given object, as would be visible and utilized by dispatch."""
root = obj
if isroutine(obj):
yield Crumb(self, root, endpoint=True, handler=obj, options=opts(obj))
return # depends on [control=['if'], data=[]]
for (name, at... |
def GetZipInfoByPathSpec(self, path_spec):
"""Retrieves the ZIP info for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect.
"... | def function[GetZipInfoByPathSpec, parameter[self, path_spec]]:
constant[Retrieves the ZIP info for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path sp... | keyword[def] identifier[GetZipInfoByPathSpec] ( identifier[self] , identifier[path_spec] ):
literal[string]
identifier[location] = identifier[getattr] ( identifier[path_spec] , literal[string] , keyword[None] )
keyword[if] identifier[location] keyword[is] keyword[None] :
keyword[raise] iden... | def GetZipInfoByPathSpec(self, path_spec):
"""Retrieves the ZIP info for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
zipfile.ZipInfo: a ZIP info object or None if not available.
Raises:
PathSpecError: if the path specification is incorrect.
"... |
def multi_groupby(self, key_fn):
"""
Like a groupby but expect the key_fn to return multiple keys for
each element.
"""
result_dict = defaultdict(list)
for x in self:
for key in key_fn(x):
result_dict[key].append(x)
# convert result l... | def function[multi_groupby, parameter[self, key_fn]]:
constant[
Like a groupby but expect the key_fn to return multiple keys for
each element.
]
variable[result_dict] assign[=] call[name[defaultdict], parameter[name[list]]]
for taget[name[x]] in starred[name[self]] begin[... | keyword[def] identifier[multi_groupby] ( identifier[self] , identifier[key_fn] ):
literal[string]
identifier[result_dict] = identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[x] keyword[in] identifier[self] :
keyword[for] identifier[key] keyword[in] id... | def multi_groupby(self, key_fn):
"""
Like a groupby but expect the key_fn to return multiple keys for
each element.
"""
result_dict = defaultdict(list)
for x in self:
for key in key_fn(x):
result_dict[key].append(x) # depends on [control=['for'], data=['key']] #... |
def from_raw_seed(cls, raw_seed):
"""Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the ... | def function[from_raw_seed, parameter[cls, raw_seed]]:
constant[Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary seque... | keyword[def] identifier[from_raw_seed] ( identifier[cls] , identifier[raw_seed] ):
literal[string]
identifier[signing_key] = identifier[ed25519] . identifier[SigningKey] ( identifier[raw_seed] )
identifier[verifying_key] = identifier[signing_key] . identifier[get_verifying_key] ()
... | def from_raw_seed(cls, raw_seed):
"""Generate a :class:`Keypair` object via a sequence of bytes.
Typically these bytes are random, such as the usage of
:func:`os.urandom` in :meth:`Keypair.random`. However this class method
allows you to use an arbitrary sequence of bytes, provided the sequ... |
def db_wb004(self, value=None):
""" Corresponds to IDD Field `db_wb004`
mean coincident dry-bulb temperature to
Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_wb004`
Unit: C
... | def function[db_wb004, parameter[self, value]]:
constant[ Corresponds to IDD Field `db_wb004`
mean coincident dry-bulb temperature to
Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_wb004`
... | keyword[def] identifier[db_wb004] ( identifier[self] , identifier[value] = keyword[None] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[try] :
identifier[value] = identifier[float] ( identifier[value] )
... | def db_wb004(self, value=None):
""" Corresponds to IDD Field `db_wb004`
mean coincident dry-bulb temperature to
Wet-bulb temperature corresponding to 0.4% annual cumulative frequency of occurrence
Args:
value (float): value for IDD Field `db_wb004`
Unit: C
... |
def _get_parameter_string(self) -> str:
""" Depending on if an argument has a type, the style for default values
changes. E.g.
def fun(x=5)
def fun(x : int = 5)
"""
parameters = []
for parameter in self.parameters:
name = parameter["name"]
... | def function[_get_parameter_string, parameter[self]]:
constant[ Depending on if an argument has a type, the style for default values
changes. E.g.
def fun(x=5)
def fun(x : int = 5)
]
variable[parameters] assign[=] list[[]]
for taget[name[parameter]] in starr... | keyword[def] identifier[_get_parameter_string] ( identifier[self] )-> identifier[str] :
literal[string]
identifier[parameters] =[]
keyword[for] identifier[parameter] keyword[in] identifier[self] . identifier[parameters] :
identifier[name] = identifier[parameter] [ literal[s... | def _get_parameter_string(self) -> str:
""" Depending on if an argument has a type, the style for default values
changes. E.g.
def fun(x=5)
def fun(x : int = 5)
"""
parameters = []
for parameter in self.parameters:
name = parameter['name']
if parameter['... |
def load_from_file(self, fname=None):
"""Update rcParams from user-defined settings
This function updates the instance with what is found in `fname`
Parameters
----------
fname: str
Path to the yaml configuration file. Possible keys of the
dictionary are... | def function[load_from_file, parameter[self, fname]]:
constant[Update rcParams from user-defined settings
This function updates the instance with what is found in `fname`
Parameters
----------
fname: str
Path to the yaml configuration file. Possible keys of the
... | keyword[def] identifier[load_from_file] ( identifier[self] , identifier[fname] = keyword[None] ):
literal[string]
identifier[fname] = identifier[fname] keyword[or] identifier[psyplot_fname] ()
keyword[if] identifier[fname] keyword[and] identifier[os] . identifier[path] . identifier[ex... | def load_from_file(self, fname=None):
"""Update rcParams from user-defined settings
This function updates the instance with what is found in `fname`
Parameters
----------
fname: str
Path to the yaml configuration file. Possible keys of the
dictionary are def... |
def unexpo(intpart, fraction, expo):
"""Remove the exponent by changing intpart and fraction."""
if expo > 0: # Move the point left
f = len(fraction)
intpart, fraction = intpart + fraction[:expo], fraction[expo:]
if expo > f:
intpart = intpart + '0'*(expo-f)
elif expo < 0... | def function[unexpo, parameter[intpart, fraction, expo]]:
constant[Remove the exponent by changing intpart and fraction.]
if compare[name[expo] greater[>] constant[0]] begin[:]
variable[f] assign[=] call[name[len], parameter[name[fraction]]]
<ast.Tuple object at 0x7da20c9... | keyword[def] identifier[unexpo] ( identifier[intpart] , identifier[fraction] , identifier[expo] ):
literal[string]
keyword[if] identifier[expo] > literal[int] :
identifier[f] = identifier[len] ( identifier[fraction] )
identifier[intpart] , identifier[fraction] = identifier[intpart] + ide... | def unexpo(intpart, fraction, expo):
"""Remove the exponent by changing intpart and fraction."""
if expo > 0: # Move the point left
f = len(fraction)
(intpart, fraction) = (intpart + fraction[:expo], fraction[expo:])
if expo > f:
intpart = intpart + '0' * (expo - f) # depen... |
def match(self, context, line):
"""Match lines prefixed with a hash ("#") mark that don't look like text."""
stripped = line.stripped
return stripped.startswith('#') and not stripped.startswith('#{') | def function[match, parameter[self, context, line]]:
constant[Match lines prefixed with a hash ("#") mark that don't look like text.]
variable[stripped] assign[=] name[line].stripped
return[<ast.BoolOp object at 0x7da20c6a8760>] | keyword[def] identifier[match] ( identifier[self] , identifier[context] , identifier[line] ):
literal[string]
identifier[stripped] = identifier[line] . identifier[stripped]
keyword[return] identifier[stripped] . identifier[startswith] ( literal[string] ) keyword[and] keyword[not] identifier[stripped] . ... | def match(self, context, line):
"""Match lines prefixed with a hash ("#") mark that don't look like text."""
stripped = line.stripped
return stripped.startswith('#') and (not stripped.startswith('#{')) |
async def analysis(self, board: chess.Board, limit: Optional[Limit] = None, *, multipv: Optional[int] = None, game: object = None, info: Info = INFO_ALL, root_moves: Optional[Iterable[chess.Move]] = None, options: ConfigMapping = {}) -> "AnalysisResult":
"""
Starts analysing a position.
:param ... | <ast.AsyncFunctionDef object at 0x7da1b17e3610> | keyword[async] keyword[def] identifier[analysis] ( identifier[self] , identifier[board] : identifier[chess] . identifier[Board] , identifier[limit] : identifier[Optional] [ identifier[Limit] ]= keyword[None] ,*, identifier[multipv] : identifier[Optional] [ identifier[int] ]= keyword[None] , identifier[game] : identi... | async def analysis(self, board: chess.Board, limit: Optional[Limit]=None, *, multipv: Optional[int]=None, game: object=None, info: Info=INFO_ALL, root_moves: Optional[Iterable[chess.Move]]=None, options: ConfigMapping={}) -> 'AnalysisResult':
"""
Starts analysing a position.
:param board: The posit... |
def grok_state(self, obj):
"""Determine the desired state of this
resource based on data present"""
if 'state' in obj:
my_state = obj['state'].lower()
if my_state != 'absent' and my_state != 'present':
raise aomi_excep \
.Validation('st... | def function[grok_state, parameter[self, obj]]:
constant[Determine the desired state of this
resource based on data present]
if compare[constant[state] in name[obj]] begin[:]
variable[my_state] assign[=] call[call[name[obj]][constant[state]].lower, parameter[]]
if... | keyword[def] identifier[grok_state] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[obj] :
identifier[my_state] = identifier[obj] [ literal[string] ]. identifier[lower] ()
keyword[if] identifier[my_state] != li... | def grok_state(self, obj):
"""Determine the desired state of this
resource based on data present"""
if 'state' in obj:
my_state = obj['state'].lower()
if my_state != 'absent' and my_state != 'present':
raise aomi_excep.Validation('state must be either "absent" or "present"') ... |
def result(self, timeout=None):
"""If the operation succeeded, return its result. If it failed,
re-raise its exception.
This method takes a ``timeout`` argument for compatibility with
`concurrent.futures.Future` but it is an error to call it
before the `Future` is done, so the ... | def function[result, parameter[self, timeout]]:
constant[If the operation succeeded, return its result. If it failed,
re-raise its exception.
This method takes a ``timeout`` argument for compatibility with
`concurrent.futures.Future` but it is an error to call it
before the `Fu... | keyword[def] identifier[result] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[self] . identifier[_clear_tb_log] ()
keyword[if] identifier[self] . identifier[_result] keyword[is] keyword[not] keyword[None] :
keyword[return] identifi... | def result(self, timeout=None):
"""If the operation succeeded, return its result. If it failed,
re-raise its exception.
This method takes a ``timeout`` argument for compatibility with
`concurrent.futures.Future` but it is an error to call it
before the `Future` is done, so the ``ti... |
def to_commandline(o):
"""
Turns the object into a commandline string. However, first checks whether a string represents
a internal value placeholder (@{...}).
:param o: the object to turn into commandline
:type o: object
:return: the commandline
:rtype: str
"""
if isinstance(o, str... | def function[to_commandline, parameter[o]]:
constant[
Turns the object into a commandline string. However, first checks whether a string represents
a internal value placeholder (@{...}).
:param o: the object to turn into commandline
:type o: object
:return: the commandline
:rtype: str
... | keyword[def] identifier[to_commandline] ( identifier[o] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[o] , identifier[str] ) keyword[and] identifier[o] . identifier[startswith] ( literal[string] ) keyword[and] identifier[o] . identifier[endswith] ( literal[string] ):
keywor... | def to_commandline(o):
"""
Turns the object into a commandline string. However, first checks whether a string represents
a internal value placeholder (@{...}).
:param o: the object to turn into commandline
:type o: object
:return: the commandline
:rtype: str
"""
if isinstance(o, str... |
def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
'''
Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
Args:
... | def function[remove_cert_binding, parameter[name, site, hostheader, ipaddress, port]]:
constant[
Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding ... | keyword[def] identifier[remove_cert_binding] ( identifier[name] , identifier[site] , identifier[hostheader] = literal[string] , identifier[ipaddress] = literal[string] , identifier[port] = literal[int] ):
literal[string]
identifier[name] = identifier[six] . identifier[text_type] ( identifier[name] ). ident... | def remove_cert_binding(name, site, hostheader='', ipaddress='*', port=443):
"""
Remove a certificate from an IIS Web Binding.
.. versionadded:: 2016.11.0
.. note::
This function only removes the certificate from the web binding. It does
not remove the web binding itself.
Args:
... |
async def get_buttons(self):
"""
Returns `buttons`, but will make an API call to find the
input chat (needed for the buttons) unless it's already cached.
"""
if not self.buttons and self.reply_markup:
chat = await self.get_input_chat()
if not chat:
... | <ast.AsyncFunctionDef object at 0x7da20e956fe0> | keyword[async] keyword[def] identifier[get_buttons] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[buttons] keyword[and] identifier[self] . identifier[reply_markup] :
identifier[chat] = keyword[await] identifier[self] . identifier[get... | async def get_buttons(self):
"""
Returns `buttons`, but will make an API call to find the
input chat (needed for the buttons) unless it's already cached.
"""
if not self.buttons and self.reply_markup:
chat = await self.get_input_chat()
if not chat:
return # d... |
def _EnvOpen(var, mode):
"""Open a file descriptor identified by an environment variable."""
value = os.getenv(var)
if value is None:
raise ValueError("%s is not set" % var)
fd = int(value)
# If running on Windows, convert the file handle to a C file descriptor; see:
# https://groups.google.com/forum/... | def function[_EnvOpen, parameter[var, mode]]:
constant[Open a file descriptor identified by an environment variable.]
variable[value] assign[=] call[name[os].getenv, parameter[name[var]]]
if compare[name[value] is constant[None]] begin[:]
<ast.Raise object at 0x7da1b138a5f0>
vari... | keyword[def] identifier[_EnvOpen] ( identifier[var] , identifier[mode] ):
literal[string]
identifier[value] = identifier[os] . identifier[getenv] ( identifier[var] )
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] % identifier[var] )... | def _EnvOpen(var, mode):
"""Open a file descriptor identified by an environment variable."""
value = os.getenv(var)
if value is None:
raise ValueError('%s is not set' % var) # depends on [control=['if'], data=[]]
fd = int(value)
# If running on Windows, convert the file handle to a C file d... |
def create_file_service(self):
'''
Creates a FileService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.file.fileservice.FileService`
'''
try:
from azure.storage.file.fileservi... | def function[create_file_service, parameter[self]]:
constant[
Creates a FileService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.file.fileservice.FileService`
]
<ast.Try object at 0x7da20c99... | keyword[def] identifier[create_file_service] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[from] identifier[azure] . identifier[storage] . identifier[file] . identifier[fileservice] keyword[import] identifier[FileService]
keyword[return] identifier[File... | def create_file_service(self):
"""
Creates a FileService object with the settings specified in the
CloudStorageAccount.
:return: A service object.
:rtype: :class:`~azure.storage.file.fileservice.FileService`
"""
try:
from azure.storage.file.fileservice import Fi... |
def lnlike(self, X):
"""
Use a softened version of the interpolant as a likelihood.
"""
return -3.5*np.log(self._interpolant(X[0], X[1], grid=False)) | def function[lnlike, parameter[self, X]]:
constant[
Use a softened version of the interpolant as a likelihood.
]
return[binary_operation[<ast.UnaryOp object at 0x7da1b258b640> * call[name[np].log, parameter[call[name[self]._interpolant, parameter[call[name[X]][constant[0]], call[name[X]][con... | keyword[def] identifier[lnlike] ( identifier[self] , identifier[X] ):
literal[string]
keyword[return] - literal[int] * identifier[np] . identifier[log] ( identifier[self] . identifier[_interpolant] ( identifier[X] [ literal[int] ], identifier[X] [ literal[int] ], identifier[grid] = keyword[False] )... | def lnlike(self, X):
"""
Use a softened version of the interpolant as a likelihood.
"""
return -3.5 * np.log(self._interpolant(X[0], X[1], grid=False)) |
def w_state(qubits: Union[int, Qubits]) -> State:
"""Return a W state on N qubits"""
N, qubits = qubits_count_tuple(qubits)
ket = np.zeros(shape=[2] * N)
for n in range(N):
idx = np.zeros(shape=N, dtype=int)
idx[n] += 1
ket[tuple(idx)] = 1 / sqrt(N)
return State(ket, qubits) | def function[w_state, parameter[qubits]]:
constant[Return a W state on N qubits]
<ast.Tuple object at 0x7da20c6c63e0> assign[=] call[name[qubits_count_tuple], parameter[name[qubits]]]
variable[ket] assign[=] call[name[np].zeros, parameter[]]
for taget[name[n]] in starred[call[name[range]... | keyword[def] identifier[w_state] ( identifier[qubits] : identifier[Union] [ identifier[int] , identifier[Qubits] ])-> identifier[State] :
literal[string]
identifier[N] , identifier[qubits] = identifier[qubits_count_tuple] ( identifier[qubits] )
identifier[ket] = identifier[np] . identifier[zeros] ( id... | def w_state(qubits: Union[int, Qubits]) -> State:
"""Return a W state on N qubits"""
(N, qubits) = qubits_count_tuple(qubits)
ket = np.zeros(shape=[2] * N)
for n in range(N):
idx = np.zeros(shape=N, dtype=int)
idx[n] += 1
ket[tuple(idx)] = 1 / sqrt(N) # depends on [control=['for... |
def _create_bitstream(file_path, local_file, item_id, log_ind=None):
"""
Create a bitstream in the given item.
:param file_path: full path to the local file
:type file_path: string
:param local_file: name of the local file
:type local_file: string
:param log_ind: (optional) any additional m... | def function[_create_bitstream, parameter[file_path, local_file, item_id, log_ind]]:
constant[
Create a bitstream in the given item.
:param file_path: full path to the local file
:type file_path: string
:param local_file: name of the local file
:type local_file: string
:param log_ind: (... | keyword[def] identifier[_create_bitstream] ( identifier[file_path] , identifier[local_file] , identifier[item_id] , identifier[log_ind] = keyword[None] ):
literal[string]
identifier[checksum] = identifier[_streaming_file_md5] ( identifier[file_path] )
identifier[upload_token] = identifier[session] . i... | def _create_bitstream(file_path, local_file, item_id, log_ind=None):
"""
Create a bitstream in the given item.
:param file_path: full path to the local file
:type file_path: string
:param local_file: name of the local file
:type local_file: string
:param log_ind: (optional) any additional m... |
def _request(self, path, key, data, method, key_is_cik, extra_headers={}):
"""Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
data: A string for t... | def function[_request, parameter[self, path, key, data, method, key_is_cik, extra_headers]]:
constant[Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
... | keyword[def] identifier[_request] ( identifier[self] , identifier[path] , identifier[key] , identifier[data] , identifier[method] , identifier[key_is_cik] , identifier[extra_headers] ={}):
literal[string]
keyword[if] identifier[method] == literal[string] :
keyword[if] identifier[len]... | def _request(self, path, key, data, method, key_is_cik, extra_headers={}):
"""Generically shared HTTP request method.
Args:
path: The API endpoint to interact with.
key: A string for the key used by the device for the API. Either a CIK or token.
data: A string for the p... |
def _stderr_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stderr)
sys.stderr.flush() | def function[_stderr_raw, parameter[self, s]]:
constant[Writes the string to stdout]
call[name[print], parameter[name[s]]]
call[name[sys].stderr.flush, parameter[]] | keyword[def] identifier[_stderr_raw] ( identifier[self] , identifier[s] ):
literal[string]
identifier[print] ( identifier[s] , identifier[end] = literal[string] , identifier[file] = identifier[sys] . identifier[stderr] )
identifier[sys] . identifier[stderr] . identifier[flush] () | def _stderr_raw(self, s):
"""Writes the string to stdout"""
print(s, end='', file=sys.stderr)
sys.stderr.flush() |
def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inner ... | def function[avg_grads, parameter[tower_grads]]:
constant[Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over... | keyword[def] identifier[avg_grads] ( identifier[tower_grads] ):
literal[string]
identifier[average_grads] =[]
keyword[for] identifier[grad_and_vars] keyword[in] identifier[zip] (* identifier[tower_grads] ):
identifier[grads] =[]
keyword[for] identifier[g] , identifier[_] keyword[in] id... | def avg_grads(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list
is over individual gradients. The inne... |
def search_obsgroups_sql_builder(search):
"""
Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given
:class:`meteorpi_model.ObservationGroupSearch`. This can then be used to retrieve the results of the search,
materialise them into :class:`meteorpi_model.ObservationGroup` instanc... | def function[search_obsgroups_sql_builder, parameter[search]]:
constant[
Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given
:class:`meteorpi_model.ObservationGroupSearch`. This can then be used to retrieve the results of the search,
materialise them into :class:`meteorpi_... | keyword[def] identifier[search_obsgroups_sql_builder] ( identifier[search] ):
literal[string]
identifier[b] = identifier[SQLBuilder] ( identifier[tables] = literal[string] , identifier[where_clauses] =[])
identifier[b] . identifier[add_sql] ( identifier[search] . identifier[obstory_name] , literal[str... | def search_obsgroups_sql_builder(search):
"""
Create and populate an instance of :class:`meteorpi_db.SQLBuilder` for a given
:class:`meteorpi_model.ObservationGroupSearch`. This can then be used to retrieve the results of the search,
materialise them into :class:`meteorpi_model.ObservationGroup` instanc... |
def setPrefix(self, p, u=None):
"""
Set the element namespace prefix.
@param p: A new prefix for the element.
@type p: basestring
@param u: A namespace URI to be mapped to the prefix.
@type u: basestring
@return: self
@rtype: L{Element}
"""
... | def function[setPrefix, parameter[self, p, u]]:
constant[
Set the element namespace prefix.
@param p: A new prefix for the element.
@type p: basestring
@param u: A namespace URI to be mapped to the prefix.
@type u: basestring
@return: self
@rtype: L{Elemen... | keyword[def] identifier[setPrefix] ( identifier[self] , identifier[p] , identifier[u] = keyword[None] ):
literal[string]
identifier[self] . identifier[prefix] = identifier[p]
keyword[if] identifier[p] keyword[is] keyword[not] keyword[None] keyword[and] identifier[u] keyword[is] ke... | def setPrefix(self, p, u=None):
"""
Set the element namespace prefix.
@param p: A new prefix for the element.
@type p: basestring
@param u: A namespace URI to be mapped to the prefix.
@type u: basestring
@return: self
@rtype: L{Element}
"""
self.pr... |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
self.used = True
data["title"] = f.readline().strip()
data["symmetry"] = f.readline().split()[0]
if data["symmetry"] != "C1":
raise NotImplementedError("Only C1 symmetry is supported.")
symbols ... | def function[read, parameter[self, line, f, data]]:
constant[See :meth:`PunchParser.read`]
name[self].used assign[=] constant[True]
call[name[data]][constant[title]] assign[=] call[call[name[f].readline, parameter[]].strip, parameter[]]
call[name[data]][constant[symmetry]] assign[=] call... | keyword[def] identifier[read] ( identifier[self] , identifier[line] , identifier[f] , identifier[data] ):
literal[string]
identifier[self] . identifier[used] = keyword[True]
identifier[data] [ literal[string] ]= identifier[f] . identifier[readline] (). identifier[strip] ()
identi... | def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
self.used = True
data['title'] = f.readline().strip()
data['symmetry'] = f.readline().split()[0]
if data['symmetry'] != 'C1':
raise NotImplementedError('Only C1 symmetry is supported.') # depends on [control=['if'], data=[]]
... |
def make_requester(self, my_args=None):
"""
make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy
"""
LOGGER.debug("natsd.Driver.make_requester")
if my_args is None:
... | def function[make_requester, parameter[self, my_args]]:
constant[
make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy
]
call[name[LOGGER].debug, parameter[constant[natsd.Driver.make... | keyword[def] identifier[make_requester] ( identifier[self] , identifier[my_args] = keyword[None] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] identifier[my_args] keyword[is] keyword[None] :
keyword[raise] identifier[exceptions] ... | def make_requester(self, my_args=None):
"""
make a new requester instance and handle it from driver
:param my_args: dict like {request_q}. Default : None
:return: created requester proxy
"""
LOGGER.debug('natsd.Driver.make_requester')
if my_args is None:
raise excepti... |
def ReadDictionary(self, file):
"""Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
"""
fil = dict... | def function[ReadDictionary, parameter[self, file]]:
constant[Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
... | keyword[def] identifier[ReadDictionary] ( identifier[self] , identifier[file] ):
literal[string]
identifier[fil] = identifier[dictfile] . identifier[DictFile] ( identifier[file] )
identifier[state] ={}
identifier[state] [ literal[string] ]= literal[string]
identifier[... | def ReadDictionary(self, file):
"""Parse a dictionary file.
Reads a RADIUS dictionary file and merges its contents into the
class instance.
:param file: Name of dictionary file to parse or a file-like object
:type file: string or file-like object
"""
fil = dictfile.Dict... |
def uuid3(namespace, name):
"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""
import md5
hash = md5.md5(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=3) | def function[uuid3, parameter[namespace, name]]:
constant[Generate a UUID from the MD5 hash of a namespace UUID and a name.]
import module[md5]
variable[hash] assign[=] call[call[name[md5].md5, parameter[binary_operation[name[namespace].bytes + name[name]]]].digest, parameter[]]
return[call[name... | keyword[def] identifier[uuid3] ( identifier[namespace] , identifier[name] ):
literal[string]
keyword[import] identifier[md5]
identifier[hash] = identifier[md5] . identifier[md5] ( identifier[namespace] . identifier[bytes] + identifier[name] ). identifier[digest] ()
keyword[return] identifier[U... | def uuid3(namespace, name):
"""Generate a UUID from the MD5 hash of a namespace UUID and a name."""
import md5
hash = md5.md5(namespace.bytes + name).digest()
return UUID(bytes=hash[:16], version=3) |
def check_data_is_empty(data):
# type: (bytes) -> bool
"""Check if data is empty via MD5
:param bytes data: data to check
:rtype: bool
:return: if data is empty
"""
contentmd5 = compute_md5_for_data_asbase64(data)
datalen = len(data)
if datalen == _MAX_PAGE_SIZE_BYTES:
if con... | def function[check_data_is_empty, parameter[data]]:
constant[Check if data is empty via MD5
:param bytes data: data to check
:rtype: bool
:return: if data is empty
]
variable[contentmd5] assign[=] call[name[compute_md5_for_data_asbase64], parameter[name[data]]]
variable[datalen] ... | keyword[def] identifier[check_data_is_empty] ( identifier[data] ):
literal[string]
identifier[contentmd5] = identifier[compute_md5_for_data_asbase64] ( identifier[data] )
identifier[datalen] = identifier[len] ( identifier[data] )
keyword[if] identifier[datalen] == identifier[_MAX_PAGE_SIZE_BYTE... | def check_data_is_empty(data):
# type: (bytes) -> bool
'Check if data is empty via MD5\n :param bytes data: data to check\n :rtype: bool\n :return: if data is empty\n '
contentmd5 = compute_md5_for_data_asbase64(data)
datalen = len(data)
if datalen == _MAX_PAGE_SIZE_BYTES:
if con... |
def loop_cocoa(kernel):
"""Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
"""
import matplotlib
if matplotlib.__version__ < '1.1.0':
kernel.log.warn(
"MacOSX backend in matplotlib %s doesn't have a Timer, "
"falling back ... | def function[loop_cocoa, parameter[kernel]]:
constant[Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
]
import module[matplotlib]
if compare[name[matplotlib].__version__ less[<] constant[1.1.0]] begin[:]
call[name[kernel].... | keyword[def] identifier[loop_cocoa] ( identifier[kernel] ):
literal[string]
keyword[import] identifier[matplotlib]
keyword[if] identifier[matplotlib] . identifier[__version__] < literal[string] :
identifier[kernel] . identifier[log] . identifier[warn] (
literal[string]
l... | def loop_cocoa(kernel):
"""Start the kernel, coordinating with the Cocoa CFRunLoop event loop
via the matplotlib MacOSX backend.
"""
import matplotlib
if matplotlib.__version__ < '1.1.0':
kernel.log.warn("MacOSX backend in matplotlib %s doesn't have a Timer, falling back on Tk for CFRunLoop ... |
def _construct_word_token(self, d: Dict, nlp) -> List[Dict]:
"""
Construct a word token
Args:
d: Dict
nlp
Returns: List[Dict]
"""
result = []
if len(d["token"]) == 1:
if tf_transfer(d["match_all_forms"]):
this_... | def function[_construct_word_token, parameter[self, d, nlp]]:
constant[
Construct a word token
Args:
d: Dict
nlp
Returns: List[Dict]
]
variable[result] assign[=] list[[]]
if compare[call[name[len], parameter[call[name[d]][constant[token]]]... | keyword[def] identifier[_construct_word_token] ( identifier[self] , identifier[d] : identifier[Dict] , identifier[nlp] )-> identifier[List] [ identifier[Dict] ]:
literal[string]
identifier[result] =[]
keyword[if] identifier[len] ( identifier[d] [ literal[string] ])== literal[int] :
... | def _construct_word_token(self, d: Dict, nlp) -> List[Dict]:
"""
Construct a word token
Args:
d: Dict
nlp
Returns: List[Dict]
"""
result = []
if len(d['token']) == 1:
if tf_transfer(d['match_all_forms']):
this_token = {attrs.LEMMA:... |
def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get("version", utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]["namespaces"]
return _lxml_el_to_data(premis_lxml_el, "premis", nsmap) | def function[premis_to_data, parameter[premis_lxml_el]]:
constant[Transform a PREMIS ``lxml._Element`` instance to a Python tuple.]
variable[premis_version] assign[=] call[name[premis_lxml_el].get, parameter[constant[version], name[utils].PREMIS_VERSION]]
variable[nsmap] assign[=] call[call[name... | keyword[def] identifier[premis_to_data] ( identifier[premis_lxml_el] ):
literal[string]
identifier[premis_version] = identifier[premis_lxml_el] . identifier[get] ( literal[string] , identifier[utils] . identifier[PREMIS_VERSION] )
identifier[nsmap] = identifier[utils] . identifier[PREMIS_VERSIONS_MAP]... | def premis_to_data(premis_lxml_el):
"""Transform a PREMIS ``lxml._Element`` instance to a Python tuple."""
premis_version = premis_lxml_el.get('version', utils.PREMIS_VERSION)
nsmap = utils.PREMIS_VERSIONS_MAP[premis_version]['namespaces']
return _lxml_el_to_data(premis_lxml_el, 'premis', nsmap) |
def _normalize_lang_attrs(self, text, strip):
"""Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It removes all embe... | def function[_normalize_lang_attrs, parameter[self, text, strip]]:
constant[Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
... | keyword[def] identifier[_normalize_lang_attrs] ( identifier[self] , identifier[text] , identifier[strip] ):
literal[string]
identifier[uninitialized] =- literal[int]
identifier[attrib] = identifier[uninitialized]
keyword[while] literal[string] keyword[in] identifier[text] :
... | def _normalize_lang_attrs(self, text, strip):
"""Remove embedded bracketed attributes.
This (potentially) bitwise-ands bracketed attributes together and adds
to the end.
This is applied to a single alternative at a time -- not to a
parenthesized list.
It removes all embedded... |
def get_modules_list(self, pattern=None):
'''
Return module map references.
:return:
'''
if pattern and '*' not in pattern:
pattern = '*{0}*'.format(pattern)
modules = []
for m_name, m_path in self._modules_map.items():
m_path = m_path.spli... | def function[get_modules_list, parameter[self, pattern]]:
constant[
Return module map references.
:return:
]
if <ast.BoolOp object at 0x7da1b26accd0> begin[:]
variable[pattern] assign[=] call[constant[*{0}*].format, parameter[name[pattern]]]
variable[modul... | keyword[def] identifier[get_modules_list] ( identifier[self] , identifier[pattern] = keyword[None] ):
literal[string]
keyword[if] identifier[pattern] keyword[and] literal[string] keyword[not] keyword[in] identifier[pattern] :
identifier[pattern] = literal[string] . identifier[for... | def get_modules_list(self, pattern=None):
"""
Return module map references.
:return:
"""
if pattern and '*' not in pattern:
pattern = '*{0}*'.format(pattern) # depends on [control=['if'], data=[]]
modules = []
for (m_name, m_path) in self._modules_map.items():
m_... |
def human_duration(time1, time2=None, precision=0, short=False):
""" Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).... | def function[human_duration, parameter[time1, time2, precision, short]]:
constant[ Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to... | keyword[def] identifier[human_duration] ( identifier[time1] , identifier[time2] = keyword[None] , identifier[precision] = literal[int] , identifier[short] = keyword[False] ):
literal[string]
keyword[if] identifier[time2] keyword[is] keyword[None] :
identifier[time2] = identifier[time] . identif... | def human_duration(time1, time2=None, precision=0, short=False):
""" Return a human-readable representation of a time delta.
@param time1: Relative time value.
@param time2: Time base (C{None} for now; 0 for a duration in C{time1}).
@param precision: How many time units to return (0 = all).... |
async def click(self):
"""
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `telethon.tl.custom.message.Message` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
... | <ast.AsyncFunctionDef object at 0x7da1b21d4ac0> | keyword[async] keyword[def] identifier[click] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[button] , identifier[types] . identifier[KeyboardButton] ):
keyword[return] keyword[await] identifier[self] . identifier[_client] .... | async def click(self):
"""
Emulates the behaviour of clicking this button.
If it's a normal :tl:`KeyboardButton` with text, a message will be
sent, and the sent `telethon.tl.custom.message.Message` returned.
If it's an inline :tl:`KeyboardButtonCallback` with text and data,
... |
def _track_change(self, name, value, formatter=None):
"""Track that a change happened.
This function is only needed for manually recording changes that are
not captured by changes to properties of this object that are tracked
automatically. Classes that inherit from `emulation_mixin` s... | def function[_track_change, parameter[self, name, value, formatter]]:
constant[Track that a change happened.
This function is only needed for manually recording changes that are
not captured by changes to properties of this object that are tracked
automatically. Classes that inherit fr... | keyword[def] identifier[_track_change] ( identifier[self] , identifier[name] , identifier[value] , identifier[formatter] = keyword[None] ):
literal[string]
identifier[self] . identifier[_emulation_log] . identifier[track_change] ( identifier[self] . identifier[_emulation_address] , identifier[name... | def _track_change(self, name, value, formatter=None):
"""Track that a change happened.
This function is only needed for manually recording changes that are
not captured by changes to properties of this object that are tracked
automatically. Classes that inherit from `emulation_mixin` shoul... |
def auto():
"""set colouring on if STDOUT is a terminal device, off otherwise"""
try:
Style.enabled = False
Style.enabled = sys.stdout.isatty()
except (AttributeError, TypeError):
pass | def function[auto, parameter[]]:
constant[set colouring on if STDOUT is a terminal device, off otherwise]
<ast.Try object at 0x7da1b0851ff0> | keyword[def] identifier[auto] ():
literal[string]
keyword[try] :
identifier[Style] . identifier[enabled] = keyword[False]
identifier[Style] . identifier[enabled] = identifier[sys] . identifier[stdout] . identifier[isatty] ()
keyword[except] ( identifier[AttributeError] , identifier[TypeError] ):
keyw... | def auto():
"""set colouring on if STDOUT is a terminal device, off otherwise"""
try:
Style.enabled = False
Style.enabled = sys.stdout.isatty() # depends on [control=['try'], data=[]]
except (AttributeError, TypeError):
pass # depends on [control=['except'], data=[]] |
def _set_level_1(self, v, load=False):
"""
Setter method for level_1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/isis/level_1 (container)
If this variable is read-only (config: false) ... | def function[_set_level_1, parameter[self, v, load]]:
constant[
Setter method for level_1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/isis/level_1 (container)
If this variable is r... | keyword[def] identifier[_set_level_1] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identi... | def _set_level_1(self, v, load=False):
"""
Setter method for level_1, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv6/af_ipv6_unicast/af_ipv6_attributes/af_common_attributes/redistribute/isis/level_1 (container)
If this variable is read-only (config: false) ... |
def niftilist_to_array(img_filelist, outdtype=None):
"""
From the list of absolute paths to nifti files, creates a Numpy array
with the data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti files must have
the same shape.
... | def function[niftilist_to_array, parameter[img_filelist, outdtype]]:
constant[
From the list of absolute paths to nifti files, creates a Numpy array
with the data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti files must have
... | keyword[def] identifier[niftilist_to_array] ( identifier[img_filelist] , identifier[outdtype] = keyword[None] ):
literal[string]
keyword[try] :
identifier[first_img] = identifier[img_filelist] [ literal[int] ]
identifier[vol] = identifier[get_img_data] ( identifier[first_img] )
keywo... | def niftilist_to_array(img_filelist, outdtype=None):
"""
From the list of absolute paths to nifti files, creates a Numpy array
with the data.
Parameters
----------
img_filelist: list of str
List of absolute file paths to nifti files. All nifti files must have
the same shape.
... |
def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True):
"""
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
"""
rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync)
if not rc:
zonefile_hash = get_zonefile_data_has... | def function[add_atlas_zonefile_data, parameter[zonefile_text, zonefile_dir, fsync]]:
constant[
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
]
variable[rc] assign[=] call[name[store_atlas_zonefile_data], parameter[name[zonefile_text], name[zonefile_... | keyword[def] identifier[add_atlas_zonefile_data] ( identifier[zonefile_text] , identifier[zonefile_dir] , identifier[fsync] = keyword[True] ):
literal[string]
identifier[rc] = identifier[store_atlas_zonefile_data] ( identifier[zonefile_text] , identifier[zonefile_dir] , identifier[fsync] = identifier[fsyn... | def add_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=True):
"""
Add a zone file to the atlas zonefiles
Return True on success
Return False on error
"""
rc = store_atlas_zonefile_data(zonefile_text, zonefile_dir, fsync=fsync)
if not rc:
zonefile_hash = get_zonefile_data_hash... |
def rolling_window(array, window=(0,), asteps=None, wsteps=None, axes=None, toend=True):
"""Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters
... | def function[rolling_window, parameter[array, window, asteps, wsteps, axes, toend]]:
constant[Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters... | keyword[def] identifier[rolling_window] ( identifier[array] , identifier[window] =( literal[int] ,), identifier[asteps] = keyword[None] , identifier[wsteps] = keyword[None] , identifier[axes] = keyword[None] , identifier[toend] = keyword[True] ):
literal[string]
identifier[array] = identifi... | def rolling_window(array, window=(0,), asteps=None, wsteps=None, axes=None, toend=True):
"""Create a view of `array` which for every point gives the n-dimensional
neighbourhood of size window. New dimensions are added at the end of
`array` or after the corresponding original dimension.
Parameters
-... |
def lines(self):
"""Iterate over all of the rows as text lines"""
# Yield the section header
if self.name != 'Root':
yield ('Section', '|'.join([self.value] + self.property_names))
# Yield all of the rows for terms in the section
for row in self.rows:
te... | def function[lines, parameter[self]]:
constant[Iterate over all of the rows as text lines]
if compare[name[self].name not_equal[!=] constant[Root]] begin[:]
<ast.Yield object at 0x7da20c6e6860>
for taget[name[row]] in starred[name[self].rows] begin[:]
<ast.Tuple o... | keyword[def] identifier[lines] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[name] != literal[string] :
keyword[yield] ( literal[string] , literal[string] . identifier[join] ([ identifier[self] . identifier[value] ]+ identifier[self] . ident... | def lines(self):
"""Iterate over all of the rows as text lines"""
# Yield the section header
if self.name != 'Root':
yield ('Section', '|'.join([self.value] + self.property_names)) # depends on [control=['if'], data=[]]
# Yield all of the rows for terms in the section
for row in self.rows:
... |
def _symlink_or_copy_grabix(in_file, out_file, data):
"""We cannot symlink in CWL, but may be able to use inputs or copy
"""
if cwlutils.is_cwl_run(data):
# Has grabix indexes, we're okay to go
if utils.file_exists(in_file + ".gbi"):
out_file = in_file
else:
u... | def function[_symlink_or_copy_grabix, parameter[in_file, out_file, data]]:
constant[We cannot symlink in CWL, but may be able to use inputs or copy
]
if call[name[cwlutils].is_cwl_run, parameter[name[data]]] begin[:]
if call[name[utils].file_exists, parameter[binary_operation[name[in... | keyword[def] identifier[_symlink_or_copy_grabix] ( identifier[in_file] , identifier[out_file] , identifier[data] ):
literal[string]
keyword[if] identifier[cwlutils] . identifier[is_cwl_run] ( identifier[data] ):
keyword[if] identifier[utils] . identifier[file_exists] ( identifier[in_file] +... | def _symlink_or_copy_grabix(in_file, out_file, data):
"""We cannot symlink in CWL, but may be able to use inputs or copy
"""
if cwlutils.is_cwl_run(data):
# Has grabix indexes, we're okay to go
if utils.file_exists(in_file + '.gbi'):
out_file = in_file # depends on [control=['if... |
def power_ratio(events, dat, s_freq, limits, ratio_thresh):
"""Estimate the ratio in power between spindle band and lower frequencies.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the origin... | def function[power_ratio, parameter[events, dat, s_freq, limits, ratio_thresh]]:
constant[Estimate the ratio in power between spindle band and lower frequencies.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')... | keyword[def] identifier[power_ratio] ( identifier[events] , identifier[dat] , identifier[s_freq] , identifier[limits] , identifier[ratio_thresh] ):
literal[string]
identifier[ratio] = identifier[empty] ( identifier[events] . identifier[shape] [ literal[int] ])
keyword[for] identifier[i] , identifier[... | def power_ratio(events, dat, s_freq, limits, ratio_thresh):
"""Estimate the ratio in power between spindle band and lower frequencies.
Parameters
----------
events : ndarray (dtype='int')
N x 3 matrix with start, peak, end samples
dat : ndarray (dtype='float')
vector with the origin... |
def _run_scapy(self, scapy_all):
"""Call scapy.all.sniff to extract PCAP files."""
# if not self._flag_a:
# self._flag_a = True
# warnings.warn(f"'Extractor(engine=scapy)' object is not iterable; "
# "so 'auto=False' will be ignored", AttributeWarning,... | def function[_run_scapy, parameter[self, scapy_all]]:
constant[Call scapy.all.sniff to extract PCAP files.]
if <ast.BoolOp object at 0x7da1b0654910> begin[:]
call[name[warnings].warn, parameter[<ast.JoinedStr object at 0x7da1b0654b80>, name[AttributeWarning]]]
name[self]._expkg a... | keyword[def] identifier[_run_scapy] ( identifier[self] , identifier[scapy_all] ):
literal[string]
keyword[if] identifier[self] . identifier[_exlyr] != literal[string] keyword[or] identifier[self] . identifier[_exptl] != literal[string] :
identifi... | def _run_scapy(self, scapy_all):
"""Call scapy.all.sniff to extract PCAP files."""
# if not self._flag_a:
# self._flag_a = True
# warnings.warn(f"'Extractor(engine=scapy)' object is not iterable; "
# "so 'auto=False' will be ignored", AttributeWarning, stacklevel=stacklev... |
def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package ... | def function[fix_pin, parameter[self, line]]:
constant[
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
]
variable[dep] assign[=] call[name[Dependency], ... | keyword[def] identifier[fix_pin] ( identifier[self] , identifier[line] ):
literal[string]
identifier[dep] = identifier[Dependency] ( identifier[line] )
keyword[if] identifier[dep] . identifier[valid] :
keyword[if] identifier[dep] . identifier[package] keyword[in] identifie... | def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package in self.ignore:
... |
def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext("event_type")
if event_type != "compression":
raise AttributeError(
'... | def function[compression_details, parameter[self]]:
constant[Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
]
variable[event_type] assign[=] call[name[self].findtext, parameter[constant[event_type]]]
if compar... | keyword[def] identifier[compression_details] ( identifier[self] ):
literal[string]
identifier[event_type] = identifier[self] . identifier[findtext] ( literal[string] )
keyword[if] identifier[event_type] != literal[string] :
keyword[raise] identifier[AttributeError] (
... | def compression_details(self):
"""Return as a 3-tuple, this PREMIS compression event's program,
version, and algorithm used to perform the compression.
"""
event_type = self.findtext('event_type')
if event_type != 'compression':
raise AttributeError('PREMIS events of type "{}" have n... |
def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text
"""Serialize the CWL document into a string, ready for printing."""
rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8')
if not rdf:
return u""
return rdf.decode('utf-8') | def function[printrdf, parameter[wflow, ctx, style]]:
constant[Serialize the CWL document into a string, ready for printing.]
variable[rdf] assign[=] call[call[name[gather], parameter[name[wflow], name[ctx]]].serialize, parameter[]]
if <ast.UnaryOp object at 0x7da2041dad70> begin[:]
retu... | keyword[def] identifier[printrdf] ( identifier[wflow] , identifier[ctx] , identifier[style] ):
literal[string]
identifier[rdf] = identifier[gather] ( identifier[wflow] , identifier[ctx] ). identifier[serialize] ( identifier[format] = identifier[style] , identifier[encoding] = literal[string] )
keyword... | def printrdf(wflow, ctx, style): # type: (Process, ContextType, Text) -> Text
'Serialize the CWL document into a string, ready for printing.'
rdf = gather(wflow, ctx).serialize(format=style, encoding='utf-8')
if not rdf:
return u'' # depends on [control=['if'], data=[]]
return rdf.decode('utf-... |
def log_error(self, msg, *args):
"""Log an error or print in stdout if no logger."""
if self._logger is not None:
self._logger.error(msg, *args)
else:
print(msg % args) | def function[log_error, parameter[self, msg]]:
constant[Log an error or print in stdout if no logger.]
if compare[name[self]._logger is_not constant[None]] begin[:]
call[name[self]._logger.error, parameter[name[msg], <ast.Starred object at 0x7da20e960100>]] | keyword[def] identifier[log_error] ( identifier[self] , identifier[msg] ,* identifier[args] ):
literal[string]
keyword[if] identifier[self] . identifier[_logger] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[_logger] . identifier[error] ( identifier[msg] ,*... | def log_error(self, msg, *args):
"""Log an error or print in stdout if no logger."""
if self._logger is not None:
self._logger.error(msg, *args) # depends on [control=['if'], data=[]]
else:
print(msg % args) |
def analyze_event_rate(scan_base, combine_n_readouts=1000, time_line_absolute=True, output_pdf=None, output_file=None):
''' Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data i... | def function[analyze_event_rate, parameter[scan_base, combine_n_readouts, time_line_absolute, output_pdf, output_file]]:
constant[ Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the ... | keyword[def] identifier[analyze_event_rate] ( identifier[scan_base] , identifier[combine_n_readouts] = literal[int] , identifier[time_line_absolute] = keyword[True] , identifier[output_pdf] = keyword[None] , identifier[output_file] = keyword[None] ):
literal[string]
identifier[time_stamp] =[]
identifi... | def analyze_event_rate(scan_base, combine_n_readouts=1000, time_line_absolute=True, output_pdf=None, output_file=None):
""" Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data i... |
def post_path(self, path: str, path_data: Union[dict, None], post_data: Any) -> dict:
"""Modifies the ESI by an endpoint URL.
This method is not marked "private" as it _can_ be used
by consuming code, but it's probably easier to call the
`get_op` method instead.
Args:
... | def function[post_path, parameter[self, path, path_data, post_data]]:
constant[Modifies the ESI by an endpoint URL.
This method is not marked "private" as it _can_ be used
by consuming code, but it's probably easier to call the
`get_op` method instead.
Args:
path: r... | keyword[def] identifier[post_path] ( identifier[self] , identifier[path] : identifier[str] , identifier[path_data] : identifier[Union] [ identifier[dict] , keyword[None] ], identifier[post_data] : identifier[Any] )-> identifier[dict] :
literal[string]
identifier[path] = identifier[self] . identifie... | def post_path(self, path: str, path_data: Union[dict, None], post_data: Any) -> dict:
"""Modifies the ESI by an endpoint URL.
This method is not marked "private" as it _can_ be used
by consuming code, but it's probably easier to call the
`get_op` method instead.
Args:
p... |
def rootChild_resetPassword(self, req, webViewer):
"""
Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524.
"""
from xmanti... | def function[rootChild_resetPassword, parameter[self, req, webViewer]]:
constant[
Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524.
... | keyword[def] identifier[rootChild_resetPassword] ( identifier[self] , identifier[req] , identifier[webViewer] ):
literal[string]
keyword[from] identifier[xmantissa] . identifier[ixmantissa] keyword[import] identifier[IWebTranslator] , identifier[IPreferenceAggregator]
keyword[return] ... | def rootChild_resetPassword(self, req, webViewer):
"""
Redirect authenticated users to their settings page (hopefully they
have one) when they try to reset their password.
This is the wrong way for this functionality to be implemented. See
#2524.
"""
from xmantissa.ixma... |
def distance(self, x, y):
"""
Computes distance measure between vectors x and y. Returns float.
"""
if scipy.sparse.issparse(x):
x = x.toarray().ravel()
y = y.toarray().ravel()
return 1.0 - numpy.dot(x, y) | def function[distance, parameter[self, x, y]]:
constant[
Computes distance measure between vectors x and y. Returns float.
]
if call[name[scipy].sparse.issparse, parameter[name[x]]] begin[:]
variable[x] assign[=] call[call[name[x].toarray, parameter[]].ravel, parameter[]]... | keyword[def] identifier[distance] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[scipy] . identifier[sparse] . identifier[issparse] ( identifier[x] ):
identifier[x] = identifier[x] . identifier[toarray] (). identifier[ravel] ()
... | def distance(self, x, y):
"""
Computes distance measure between vectors x and y. Returns float.
"""
if scipy.sparse.issparse(x):
x = x.toarray().ravel()
y = y.toarray().ravel() # depends on [control=['if'], data=[]]
return 1.0 - numpy.dot(x, y) |
def _subgraph_parse(
self, node, pathnode, extra_blocks
): # pylint: disable=unused-argument
"""parse the body and any `else` block of `if` and `for` statements"""
loose_ends = []
self.tail = node
self.dispatch_list(node.body)
loose_ends.append(self.tail)
for... | def function[_subgraph_parse, parameter[self, node, pathnode, extra_blocks]]:
constant[parse the body and any `else` block of `if` and `for` statements]
variable[loose_ends] assign[=] list[[]]
name[self].tail assign[=] name[node]
call[name[self].dispatch_list, parameter[name[node].body]]... | keyword[def] identifier[_subgraph_parse] (
identifier[self] , identifier[node] , identifier[pathnode] , identifier[extra_blocks]
):
literal[string]
identifier[loose_ends] =[]
identifier[self] . identifier[tail] = identifier[node]
identifier[self] . identifier[dispatch_list] ( i... | def _subgraph_parse(self, node, pathnode, extra_blocks): # pylint: disable=unused-argument
'parse the body and any `else` block of `if` and `for` statements'
loose_ends = []
self.tail = node
self.dispatch_list(node.body)
loose_ends.append(self.tail)
for extra in extra_blocks:
self.tail ... |
def open_browser(self):
"""Open the URL of SABnzbd inside a browser."""
webbrowser.open(
"http://{host}:{port}/".format(host=self.host, port=self.port)) | def function[open_browser, parameter[self]]:
constant[Open the URL of SABnzbd inside a browser.]
call[name[webbrowser].open, parameter[call[constant[http://{host}:{port}/].format, parameter[]]]] | keyword[def] identifier[open_browser] ( identifier[self] ):
literal[string]
identifier[webbrowser] . identifier[open] (
literal[string] . identifier[format] ( identifier[host] = identifier[self] . identifier[host] , identifier[port] = identifier[self] . identifier[port] )) | def open_browser(self):
"""Open the URL of SABnzbd inside a browser."""
webbrowser.open('http://{host}:{port}/'.format(host=self.host, port=self.port)) |
async def observations(self):
"""Retrieve current weather observation."""
observations = []
raw_stations = await self.retrieve(url=API_OBSERVATION_STATIONS,
headers={'Referer': 'http://www.ipma.pt'})
if not raw_stations:
return obse... | <ast.AsyncFunctionDef object at 0x7da1b26ac1c0> | keyword[async] keyword[def] identifier[observations] ( identifier[self] ):
literal[string]
identifier[observations] =[]
identifier[raw_stations] = keyword[await] identifier[self] . identifier[retrieve] ( identifier[url] = identifier[API_OBSERVATION_STATIONS] ,
identifier[header... | async def observations(self):
"""Retrieve current weather observation."""
observations = []
raw_stations = await self.retrieve(url=API_OBSERVATION_STATIONS, headers={'Referer': 'http://www.ipma.pt'})
if not raw_stations:
return observations # depends on [control=['if'], data=[]]
raw_observa... |
def copy_tree(src, dst):
"""Copy directory tree"""
for root, subdirs, files in os.walk(src):
current_dest = root.replace(src, dst)
if not os.path.exists(current_dest):
os.makedirs(current_dest)
for f in files:
shutil.copy(os.path.join(root, f), os.path.join(curren... | def function[copy_tree, parameter[src, dst]]:
constant[Copy directory tree]
for taget[tuple[[<ast.Name object at 0x7da2043463b0>, <ast.Name object at 0x7da204347e20>, <ast.Name object at 0x7da204345b70>]]] in starred[call[name[os].walk, parameter[name[src]]]] begin[:]
variable[current_de... | keyword[def] identifier[copy_tree] ( identifier[src] , identifier[dst] ):
literal[string]
keyword[for] identifier[root] , identifier[subdirs] , identifier[files] keyword[in] identifier[os] . identifier[walk] ( identifier[src] ):
identifier[current_dest] = identifier[root] . identifier[replace] ... | def copy_tree(src, dst):
"""Copy directory tree"""
for (root, subdirs, files) in os.walk(src):
current_dest = root.replace(src, dst)
if not os.path.exists(current_dest):
os.makedirs(current_dest) # depends on [control=['if'], data=[]]
for f in files:
shutil.copy(... |
def post(self, request, bot_id, format=None):
"""
Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
return super(S... | def function[post, parameter[self, request, bot_id, format]]:
constant[
Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
]
... | keyword[def] identifier[post] ( identifier[self] , identifier[request] , identifier[bot_id] , identifier[format] = keyword[None] ):
literal[string]
keyword[return] identifier[super] ( identifier[StateList] , identifier[self] ). identifier[post] ( identifier[request] , identifier[bot_id] , identifi... | def post(self, request, bot_id, format=None):
"""
Add a new state
---
serializer: StateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
return super(StateList... |
def get_template_names(self):
"""
datagrid็้ป่ฎคๆจกๆฟ
"""
names = super(EasyUICreateView, self).get_template_names()
names.append('easyui/form.html')
return names | def function[get_template_names, parameter[self]]:
constant[
datagrid็้ป่ฎคๆจกๆฟ
]
variable[names] assign[=] call[call[name[super], parameter[name[EasyUICreateView], name[self]]].get_template_names, parameter[]]
call[name[names].append, parameter[constant[easyui/form.html]]]
return... | keyword[def] identifier[get_template_names] ( identifier[self] ):
literal[string]
identifier[names] = identifier[super] ( identifier[EasyUICreateView] , identifier[self] ). identifier[get_template_names] ()
identifier[names] . identifier[append] ( literal[string] )
keyword[return]... | def get_template_names(self):
"""
datagrid็้ป่ฎคๆจกๆฟ
"""
names = super(EasyUICreateView, self).get_template_names()
names.append('easyui/form.html')
return names |
def remove_network_from_bgp_speaker(self, speaker_id, body=None):
"""Removes a network from BGP speaker."""
return self.put((self.bgp_speaker_path % speaker_id) +
"/remove_gateway_network", body=body) | def function[remove_network_from_bgp_speaker, parameter[self, speaker_id, body]]:
constant[Removes a network from BGP speaker.]
return[call[name[self].put, parameter[binary_operation[binary_operation[name[self].bgp_speaker_path <ast.Mod object at 0x7da2590d6920> name[speaker_id]] + constant[/remove_gateway_... | keyword[def] identifier[remove_network_from_bgp_speaker] ( identifier[self] , identifier[speaker_id] , identifier[body] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[put] (( identifier[self] . identifier[bgp_speaker_path] % identifier[speaker_id] )+
lite... | def remove_network_from_bgp_speaker(self, speaker_id, body=None):
"""Removes a network from BGP speaker."""
return self.put(self.bgp_speaker_path % speaker_id + '/remove_gateway_network', body=body) |
def radang(x, y):
'''return (radius, angle) of a vector(x, y)'''
if x == 0:
if y == 0:
return 0, 0
return abs(y), 90+180*(y<0)
if y == 0:
return abs(x), 180*(x<0)
r = math.sqrt(x*x+y*y)
a = math.degrees(math.atan(y/x))
if x < 0:
a += 180
... | def function[radang, parameter[x, y]]:
constant[return (radius, angle) of a vector(x, y)]
if compare[name[x] equal[==] constant[0]] begin[:]
if compare[name[y] equal[==] constant[0]] begin[:]
return[tuple[[<ast.Constant object at 0x7da18ede69e0>, <ast.Constant object at 0x7da... | keyword[def] identifier[radang] ( identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[x] == literal[int] :
keyword[if] identifier[y] == literal[int] :
keyword[return] literal[int] , literal[int]
keyword[return] identifier[abs] ( identifier[y] ), ... | def radang(x, y):
"""return (radius, angle) of a vector(x, y)"""
if x == 0:
if y == 0:
return (0, 0) # depends on [control=['if'], data=[]]
return (abs(y), 90 + 180 * (y < 0)) # depends on [control=['if'], data=[]]
if y == 0:
return (abs(x), 180 * (x < 0)) # depends on... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.