code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def list_stack(profile=None):
'''
Return a list of available stack (heat stack-list)
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.list_stack profile=openstack1
'''
ret = {}
h_client = _auth(profile)
for stack in h_client.stacks.list():
... | def function[list_stack, parameter[profile]]:
constant[
Return a list of available stack (heat stack-list)
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.list_stack profile=openstack1
]
variable[ret] assign[=] dictionary[[], []]
var... | keyword[def] identifier[list_stack] ( identifier[profile] = keyword[None] ):
literal[string]
identifier[ret] ={}
identifier[h_client] = identifier[_auth] ( identifier[profile] )
keyword[for] identifier[stack] keyword[in] identifier[h_client] . identifier[stacks] . identifier[list] ():
... | def list_stack(profile=None):
"""
Return a list of available stack (heat stack-list)
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' heat.list_stack profile=openstack1
"""
ret = {}
h_client = _auth(profile)
for stack in h_client.stacks.list():
... |
def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with ... | def function[override_to_local_variable, parameter[enable]]:
constant[
Returns:
a context where all variables will be created as local.
]
if name[enable] begin[:]
def function[custom_getter, parameter[getter, name]]:
call[name[_replace_global_by_lo... | keyword[def] identifier[override_to_local_variable] ( identifier[enable] = keyword[True] ):
literal[string]
keyword[if] identifier[enable] :
keyword[def] identifier[custom_getter] ( identifier[getter] , identifier[name] ,* identifier[args] ,** identifier[kwargs] ):
identifier[_repl... | def override_to_local_variable(enable=True):
"""
Returns:
a context where all variables will be created as local.
"""
if enable:
def custom_getter(getter, name, *args, **kwargs):
_replace_global_by_local(kwargs)
return getter(name, *args, **kwargs)
with c... |
def authenticate_direct_credentials(self, username, password):
"""
Performs a direct bind, however using direct credentials. Can be used
if interfacing with an Active Directory domain controller which
authenticates using username@domain.com directly.
Performing this kind of look... | def function[authenticate_direct_credentials, parameter[self, username, password]]:
constant[
Performs a direct bind, however using direct credentials. Can be used
if interfacing with an Active Directory domain controller which
authenticates using username@domain.com directly.
P... | keyword[def] identifier[authenticate_direct_credentials] ( identifier[self] , identifier[username] , identifier[password] ):
literal[string]
identifier[bind_user] = literal[string] . identifier[format] (
identifier[self] . identifier[config] . identifier[get] ( literal[string] ),
... | def authenticate_direct_credentials(self, username, password):
"""
Performs a direct bind, however using direct credentials. Can be used
if interfacing with an Active Directory domain controller which
authenticates using username@domain.com directly.
Performing this kind of lookup l... |
def insert_one(self, validate=True):
"""Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
"""
kw = {}
kw['bypass_docu... | def function[insert_one, parameter[self, validate]]:
constant[Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
]
... | keyword[def] identifier[insert_one] ( identifier[self] , identifier[validate] = keyword[True] ):
literal[string]
identifier[kw] ={}
identifier[kw] [ literal[string] ]= keyword[not] identifier[validate]
identifier[collection] = identifier[self] . identifier[get_collection] ( identifier[kw] . identifie... | def insert_one(self, validate=True):
"""Insert this document.
The `validate` argument translates to the inverse of the `bypass_document_validation` PyMongo option.
https://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.insert_one
"""
kw = {}
kw['bypass_d... |
def update_db(self, giver, receiverkarma):
"""
Record a the giver of karma, the receiver of karma, and the karma
amount. Typically the count will be 1, but it can be any positive or
negative integer.
"""
for receiver in receiverkarma:
if receiver != giver:
... | def function[update_db, parameter[self, giver, receiverkarma]]:
constant[
Record a the giver of karma, the receiver of karma, and the karma
amount. Typically the count will be 1, but it can be any positive or
negative integer.
]
for taget[name[receiver]] in starred[name[r... | keyword[def] identifier[update_db] ( identifier[self] , identifier[giver] , identifier[receiverkarma] ):
literal[string]
keyword[for] identifier[receiver] keyword[in] identifier[receiverkarma] :
keyword[if] identifier[receiver] != identifier[giver] :
identifier[ur... | def update_db(self, giver, receiverkarma):
"""
Record a the giver of karma, the receiver of karma, and the karma
amount. Typically the count will be 1, but it can be any positive or
negative integer.
"""
for receiver in receiverkarma:
if receiver != giver:
uro... |
def stack1d(*points):
"""Fill out the columns of matrix with a series of points.
This is because ``np.hstack()`` will just make another 1D vector
out of them and ``np.vstack()`` will put them in the rows.
Args:
points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e.
arrays wit... | def function[stack1d, parameter[]]:
constant[Fill out the columns of matrix with a series of points.
This is because ``np.hstack()`` will just make another 1D vector
out of them and ``np.vstack()`` will put them in the rows.
Args:
points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e... | keyword[def] identifier[stack1d] (* identifier[points] ):
literal[string]
identifier[result] = identifier[np] . identifier[empty] (( literal[int] , identifier[len] ( identifier[points] )), identifier[order] = literal[string] )
keyword[for] identifier[index] , identifier[point] keyword[in] identifie... | def stack1d(*points):
"""Fill out the columns of matrix with a series of points.
This is because ``np.hstack()`` will just make another 1D vector
out of them and ``np.vstack()`` will put them in the rows.
Args:
points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e.
arrays wit... |
def custom_code(self, mask: str = '@###',
char: str = '@', digit: str = '#') -> str:
"""Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Placeholder for digits.
:... | def function[custom_code, parameter[self, mask, char, digit]]:
constant[Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Placeholder for digits.
:return: Custom code.
]
... | keyword[def] identifier[custom_code] ( identifier[self] , identifier[mask] : identifier[str] = literal[string] ,
identifier[char] : identifier[str] = literal[string] , identifier[digit] : identifier[str] = literal[string] )-> identifier[str] :
literal[string]
identifier[char_code] = identifier[ord... | def custom_code(self, mask: str='@###', char: str='@', digit: str='#') -> str:
"""Generate custom code using ascii uppercase and random integers.
:param mask: Mask of code.
:param char: Placeholder for characters.
:param digit: Placeholder for digits.
:return: Custom code.
"... |
def check_confirmations_or_resend(self, use_open_peers=False, **kw):
"""
check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers endpoint
"""
if self.confirmations() == 0:
self.send(use_open_peers, **kw) | def function[check_confirmations_or_resend, parameter[self, use_open_peers]]:
constant[
check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers endpoint
]
if compare[call[name[self].confirmations, parameter[]] equal[==] constant[0]] b... | keyword[def] identifier[check_confirmations_or_resend] ( identifier[self] , identifier[use_open_peers] = keyword[False] ,** identifier[kw] ):
literal[string]
keyword[if] identifier[self] . identifier[confirmations] ()== literal[int] :
identifier[self] . identifier[send] ( identifier[u... | def check_confirmations_or_resend(self, use_open_peers=False, **kw):
"""
check if a tx is confirmed, else resend it.
:param use_open_peers: select random peers fro api/peers endpoint
"""
if self.confirmations() == 0:
self.send(use_open_peers, **kw) # depends on [control=['if'],... |
def horizontal_padding(self, value):
"""
Setter for **self.__horizontal_padding** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format("horizontal_p... | def function[horizontal_padding, parameter[self, value]]:
constant[
Setter for **self.__horizontal_padding** attribute.
:param value: Attribute value.
:type value: int
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parame... | keyword[def] identifier[horizontal_padding] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[int] , literal[string] . ide... | def horizontal_padding(self, value):
"""
Setter for **self.__horizontal_padding** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format('horizontal_padding', valu... |
def gaussian_filter(data, sigma=4., truncate = 4., normalize=True, res_g=None):
"""
blurs data with a gaussian kernel of given sigmas
Parameters
----------
data: ndarray
2 or 3 dimensional array
sigma: scalar or tuple
the sigma of the gaussian
truncate: float
... | def function[gaussian_filter, parameter[data, sigma, truncate, normalize, res_g]]:
constant[
blurs data with a gaussian kernel of given sigmas
Parameters
----------
data: ndarray
2 or 3 dimensional array
sigma: scalar or tuple
the sigma of the gaussian
truncate: f... | keyword[def] identifier[gaussian_filter] ( identifier[data] , identifier[sigma] = literal[int] , identifier[truncate] = literal[int] , identifier[normalize] = keyword[True] , identifier[res_g] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[data] . identifier[sha... | def gaussian_filter(data, sigma=4.0, truncate=4.0, normalize=True, res_g=None):
"""
blurs data with a gaussian kernel of given sigmas
Parameters
----------
data: ndarray
2 or 3 dimensional array
sigma: scalar or tuple
the sigma of the gaussian
truncate: float
... |
def to_er7(self, encoding_chars=None, trailing_children=False):
"""
Return the ER7-encoded string
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_de... | def function[to_er7, parameter[self, encoding_chars, trailing_children]]:
constant[
Return the ER7-encoded string
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_char... | keyword[def] identifier[to_er7] ( identifier[self] , identifier[encoding_chars] = keyword[None] , identifier[trailing_children] = keyword[False] ):
literal[string]
keyword[if] identifier[encoding_chars] keyword[is] keyword[None] :
identifier[encoding_chars] = identifier[self] . iden... | def to_er7(self, encoding_chars=None, trailing_children=False):
"""
Return the ER7-encoded string
:type encoding_chars: ``dict``
:param encoding_chars: a dictionary containing the encoding chars or None to use the default
(see :func:`get_default_encoding_chars <hl7apy.get_defaul... |
def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format(
'Required' if arg.required else 'Optional',
'(s)' if arg.nargs != 1 else '')) | def function[_format_argument, parameter[arg]]:
constant[Format the output of a `click.Argument`.]
<ast.Yield object at 0x7da1b0e14820>
<ast.Yield object at 0x7da1b0e179a0>
<ast.Yield object at 0x7da1b0e15e40> | keyword[def] identifier[_format_argument] ( identifier[arg] ):
literal[string]
keyword[yield] literal[string] . identifier[format] ( identifier[arg] . identifier[human_readable_name] )
keyword[yield] literal[string]
keyword[yield] identifier[_indent] ( literal[string] . identifier[format] (
... | def _format_argument(arg):
"""Format the output of a `click.Argument`."""
yield '.. option:: {}'.format(arg.human_readable_name)
yield ''
yield _indent('{} argument{}'.format('Required' if arg.required else 'Optional', '(s)' if arg.nargs != 1 else '')) |
def cleanup(self):
"""
Cleanup resources used during execution
"""
if self.local_port is not None:
logger.debug(("Stopping ssh tunnel {0}:{1}:{2} for "
"{3}@{4}".format(self.local_port,
self.remote_address,
... | def function[cleanup, parameter[self]]:
constant[
Cleanup resources used during execution
]
if compare[name[self].local_port is_not constant[None]] begin[:]
call[name[logger].debug, parameter[call[constant[Stopping ssh tunnel {0}:{1}:{2} for {3}@{4}].format, parameter[nam... | keyword[def] identifier[cleanup] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[local_port] keyword[is] keyword[not] keyword[None] :
identifier[logger] . identifier[debug] (( literal[string]
literal[string] . identifier[format] ( ident... | def cleanup(self):
"""
Cleanup resources used during execution
"""
if self.local_port is not None:
logger.debug('Stopping ssh tunnel {0}:{1}:{2} for {3}@{4}'.format(self.local_port, self.remote_address, self.remote_port, self.username, self.address))
if self.forward is not None:
... |
def _set_monitor(self, v, load=False):
"""
Setter method for monitor, mapped from YANG variable /overlay_gateway/monitor (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_monitor is considered as a private
method. Backends looking to populate this variable shoul... | def function[_set_monitor, parameter[self, v, load]]:
constant[
Setter method for monitor, mapped from YANG variable /overlay_gateway/monitor (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_monitor is considered as a private
method. Backends looking to pop... | keyword[def] identifier[_set_monitor] ( 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_monitor(self, v, load=False):
"""
Setter method for monitor, mapped from YANG variable /overlay_gateway/monitor (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_monitor is considered as a private
method. Backends looking to populate this variable shoul... |
def find_saas_perform_iops_price(package, size, iops):
"""Find the SaaS IOPS price for the specified size and iops
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param iops: The number of IOPS for which a price is desired
:return:... | def function[find_saas_perform_iops_price, parameter[package, size, iops]]:
constant[Find the SaaS IOPS price for the specified size and iops
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param iops: The number of IOPS for which ... | keyword[def] identifier[find_saas_perform_iops_price] ( identifier[package] , identifier[size] , identifier[iops] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[package] [ literal[string] ]:
keyword[if] literal[string] keyword[not] keyword[in] identifier[item] keyw... | def find_saas_perform_iops_price(package, size, iops):
"""Find the SaaS IOPS price for the specified size and iops
:param package: The Storage As A Service product package
:param size: The volume size for which a price is desired
:param iops: The number of IOPS for which a price is desired
:return:... |
def principal_inertia_transform(self):
"""
A transform which moves the current mesh so the principal
inertia vectors are on the X,Y, and Z axis, and the centroid is
at the origin.
Returns
----------
transform : (4, 4) float
Homogenous transformation mat... | def function[principal_inertia_transform, parameter[self]]:
constant[
A transform which moves the current mesh so the principal
inertia vectors are on the X,Y, and Z axis, and the centroid is
at the origin.
Returns
----------
transform : (4, 4) float
Ho... | keyword[def] identifier[principal_inertia_transform] ( identifier[self] ):
literal[string]
identifier[order] = identifier[np] . identifier[argsort] ( identifier[self] . identifier[principal_inertia_components] )[ literal[int] :][::- literal[int] ]
identifier[vectors] = identifier[self] . i... | def principal_inertia_transform(self):
"""
A transform which moves the current mesh so the principal
inertia vectors are on the X,Y, and Z axis, and the centroid is
at the origin.
Returns
----------
transform : (4, 4) float
Homogenous transformation matrix
... |
def create(self):
"""Creates a new database"""
self.db_attrs = self.consul.create_db(
self.instance_name,
self.instance_type,
self.admin_username,
self.admin_password,
db_name=self.db_name,
storage_size_gb=se... | def function[create, parameter[self]]:
constant[Creates a new database]
name[self].db_attrs assign[=] call[name[self].consul.create_db, parameter[name[self].instance_name, name[self].instance_type, name[self].admin_username, name[self].admin_password]] | keyword[def] identifier[create] ( identifier[self] ):
literal[string]
identifier[self] . identifier[db_attrs] = identifier[self] . identifier[consul] . identifier[create_db] (
identifier[self] . identifier[instance_name] ,
identifier[self] . identifier[instance_type] ,
id... | def create(self):
"""Creates a new database"""
self.db_attrs = self.consul.create_db(self.instance_name, self.instance_type, self.admin_username, self.admin_password, db_name=self.db_name, storage_size_gb=self.storage_size, timeout_s=self.launch_timeout_s) |
def main(args_list=None):
"""
Script which loads variants and annotates them with overlapping genes
and predicted coding effects.
Example usage:
varcode
--vcf mutect.vcf \
--vcf strelka.vcf \
--maf tcga_brca.maf \
--variant chr1 498584 C G \
... | def function[main, parameter[args_list]]:
constant[
Script which loads variants and annotates them with overlapping genes
and predicted coding effects.
Example usage:
varcode
--vcf mutect.vcf --vcf strelka.vcf --maf tcga_brca.maf --variant chr... | keyword[def] identifier[main] ( identifier[args_list] = keyword[None] ):
literal[string]
identifier[print_version_info] ()
keyword[if] identifier[args_list] keyword[is] keyword[None] :
identifier[args_list] = identifier[sys] . identifier[argv] [ literal[int] :]
identifier[args] = ide... | def main(args_list=None):
"""
Script which loads variants and annotates them with overlapping genes
and predicted coding effects.
Example usage:
varcode
--vcf mutect.vcf --vcf strelka.vcf --maf tcga_brca.maf --variant chr1 498584 C G -... |
def _get_http_proxy_url():
'''
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
'''
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
user... | def function[_get_http_proxy_url, parameter[]]:
constant[
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
]
variable[http_proxy_url] assign[=] constant[]
variable[host] assign[=] call[call[name[__s... | keyword[def] identifier[_get_http_proxy_url] ():
literal[string]
identifier[http_proxy_url] = literal[string]
identifier[host] = identifier[__salt__] [ literal[string] ]( literal[string] )
identifier[port] = identifier[__salt__] [ literal[string] ]( literal[string] )
identifier[username] = ... | def _get_http_proxy_url():
"""
Returns the http_proxy_url if proxy_username, proxy_password, proxy_host, and proxy_port
config values are set.
Returns a string.
"""
http_proxy_url = ''
host = __salt__['config.option']('proxy_host')
port = __salt__['config.option']('proxy_port')
user... |
def set_value(self, value: str):
"""
Sets the displayed digits based on the value string.
:param value: a string containing an integer or float value
:return: None
"""
[digit.clear() for digit in self._digits]
grouped = self._group(value) # return the parts, rev... | def function[set_value, parameter[self, value]]:
constant[
Sets the displayed digits based on the value string.
:param value: a string containing an integer or float value
:return: None
]
<ast.ListComp object at 0x7da1b0f45060>
variable[grouped] assign[=] call[nam... | keyword[def] identifier[set_value] ( identifier[self] , identifier[value] : identifier[str] ):
literal[string]
[ identifier[digit] . identifier[clear] () keyword[for] identifier[digit] keyword[in] identifier[self] . identifier[_digits] ]
identifier[grouped] = identifier[self] . identifi... | def set_value(self, value: str):
"""
Sets the displayed digits based on the value string.
:param value: a string containing an integer or float value
:return: None
"""
[digit.clear() for digit in self._digits]
grouped = self._group(value) # return the parts, reversed
dig... |
def lon_lat_bins(bb, coord_bin_width):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested siz... | def function[lon_lat_bins, parameter[bb, coord_bin_width]]:
constant[
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coord... | keyword[def] identifier[lon_lat_bins] ( identifier[bb] , identifier[coord_bin_width] ):
literal[string]
identifier[west] , identifier[south] , identifier[east] , identifier[north] = identifier[bb]
identifier[west] = identifier[numpy] . identifier[floor] ( identifier[west] / identifier[coord_bin_width... | def lon_lat_bins(bb, coord_bin_width):
"""
Define bin edges for disaggregation histograms.
Given bins data as provided by :func:`collect_bin_data`, this function
finds edges of histograms, taking into account maximum and minimum values
of magnitude, distance and coordinates as well as requested siz... |
def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied \
arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg)
else:
... | def function[getMessage, parameter[self]]:
constant[
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied arguments with the message.
]
if call[name[isinstance], parameter[name[self].msg, name[numpy].ndarray]] begin... | keyword[def] identifier[getMessage] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[msg] , identifier[numpy] . identifier[ndarray] ):
identifier[msg] = identifier[self] . identifier[array2string] ( identifier[self] . identifier[... | def getMessage(self):
"""
Return the message for this LogRecord.
Return the message for this LogRecord after merging any user-supplied arguments with the message.
"""
if isinstance(self.msg, numpy.ndarray):
msg = self.array2string(self.msg) # depends on [control=['if'],... |
def delete_user(self, username):
"""Deletes a JIRA User.
:param username: Username to delete
:type username: str
:return: Success of user deletion
:rtype: bool
"""
url = self._options['server'] + '/rest/api/latest/user/?username=%s' % username
r = sel... | def function[delete_user, parameter[self, username]]:
constant[Deletes a JIRA User.
:param username: Username to delete
:type username: str
:return: Success of user deletion
:rtype: bool
]
variable[url] assign[=] binary_operation[call[name[self]._options][const... | keyword[def] identifier[delete_user] ( identifier[self] , identifier[username] ):
literal[string]
identifier[url] = identifier[self] . identifier[_options] [ literal[string] ]+ literal[string] % identifier[username]
identifier[r] = identifier[self] . identifier[_session] . identifier[de... | def delete_user(self, username):
"""Deletes a JIRA User.
:param username: Username to delete
:type username: str
:return: Success of user deletion
:rtype: bool
"""
url = self._options['server'] + '/rest/api/latest/user/?username=%s' % username
r = self._session.del... |
def attach_run_command(cmd):
"""
Run a command when attaching
Please do not call directly, this will execvp the command.
This is to be used in conjunction with the attach method
of a container.
"""
if isinstance(cmd, tuple):
return _lxc.attach_run_command(cmd)
el... | def function[attach_run_command, parameter[cmd]]:
constant[
Run a command when attaching
Please do not call directly, this will execvp the command.
This is to be used in conjunction with the attach method
of a container.
]
if call[name[isinstance], parameter[name[cmd... | keyword[def] identifier[attach_run_command] ( identifier[cmd] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[cmd] , identifier[tuple] ):
keyword[return] identifier[_lxc] . identifier[attach_run_command] ( identifier[cmd] )
keyword[elif] identifier[isinstance] ( identifi... | def attach_run_command(cmd):
"""
Run a command when attaching
Please do not call directly, this will execvp the command.
This is to be used in conjunction with the attach method
of a container.
"""
if isinstance(cmd, tuple):
return _lxc.attach_run_command(cmd) # dep... |
def update(gandi, resource, ssl, private_key, poll_cert):
""" Update a vhost.
Right now you can only activate ssl on the vhost.
"""
gandi.hostedcert.activate_ssl(resource, ssl, private_key, poll_cert) | def function[update, parameter[gandi, resource, ssl, private_key, poll_cert]]:
constant[ Update a vhost.
Right now you can only activate ssl on the vhost.
]
call[name[gandi].hostedcert.activate_ssl, parameter[name[resource], name[ssl], name[private_key], name[poll_cert]]] | keyword[def] identifier[update] ( identifier[gandi] , identifier[resource] , identifier[ssl] , identifier[private_key] , identifier[poll_cert] ):
literal[string]
identifier[gandi] . identifier[hostedcert] . identifier[activate_ssl] ( identifier[resource] , identifier[ssl] , identifier[private_key] , identi... | def update(gandi, resource, ssl, private_key, poll_cert):
""" Update a vhost.
Right now you can only activate ssl on the vhost.
"""
gandi.hostedcert.activate_ssl(resource, ssl, private_key, poll_cert) |
def aggregate(self, rankings, epsilon, max_iters):
"""
Description:
Minorization-Maximization algorithm which returns an
estimate of the ground-truth parameters, gamma for
the given data.
Parameters:
rankings: set of rankings to aggregate
... | def function[aggregate, parameter[self, rankings, epsilon, max_iters]]:
constant[
Description:
Minorization-Maximization algorithm which returns an
estimate of the ground-truth parameters, gamma for
the given data.
Parameters:
rankings: set of ran... | keyword[def] identifier[aggregate] ( identifier[self] , identifier[rankings] , identifier[epsilon] , identifier[max_iters] ):
literal[string]
identifier[w] = identifier[np] . identifier[zeros] (( identifier[self] . identifier[m] , identifier[self] . identifier[m] ))
keyword[... | def aggregate(self, rankings, epsilon, max_iters):
"""
Description:
Minorization-Maximization algorithm which returns an
estimate of the ground-truth parameters, gamma for
the given data.
Parameters:
rankings: set of rankings to aggregate
... |
def getArcs(domains, constraints):
"""
Return a dictionary mapping pairs (arcs) of constrained variables
@attention: Currently unused.
"""
arcs = {}
for x in constraints:
constraint, variables = x
if len(variables) == 2:
variable1, variable2 = variables
a... | def function[getArcs, parameter[domains, constraints]]:
constant[
Return a dictionary mapping pairs (arcs) of constrained variables
@attention: Currently unused.
]
variable[arcs] assign[=] dictionary[[], []]
for taget[name[x]] in starred[name[constraints]] begin[:]
<... | keyword[def] identifier[getArcs] ( identifier[domains] , identifier[constraints] ):
literal[string]
identifier[arcs] ={}
keyword[for] identifier[x] keyword[in] identifier[constraints] :
identifier[constraint] , identifier[variables] = identifier[x]
keyword[if] identifier[len] ( ... | def getArcs(domains, constraints):
"""
Return a dictionary mapping pairs (arcs) of constrained variables
@attention: Currently unused.
"""
arcs = {}
for x in constraints:
(constraint, variables) = x
if len(variables) == 2:
(variable1, variable2) = variables
... |
def inspect(self, *args, **kwargs):
"""
Recursively inspect all given SCSS files to find imported dependencies.
This does not return anything. Just fill internal buffers about
inspected files.
Note:
This will ignore orphan files (files that are not imported from
... | def function[inspect, parameter[self]]:
constant[
Recursively inspect all given SCSS files to find imported dependencies.
This does not return anything. Just fill internal buffers about
inspected files.
Note:
This will ignore orphan files (files that are not importe... | keyword[def] identifier[inspect] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[library_paths] = identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] )
keyword[for] identifier[sourcepath] keyword[in] identifier[args] :
... | def inspect(self, *args, **kwargs):
"""
Recursively inspect all given SCSS files to find imported dependencies.
This does not return anything. Just fill internal buffers about
inspected files.
Note:
This will ignore orphan files (files that are not imported from
... |
def database_exist(self):
"""Create databases for each engine and return a new :class:`.Mapper`.
"""
binds = {}
for key, engine in self.keys_engines():
key = key if key else 'default'
binds[key] = self._database_exist(engine)
return binds | def function[database_exist, parameter[self]]:
constant[Create databases for each engine and return a new :class:`.Mapper`.
]
variable[binds] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da2054a4b20>, <ast.Name object at 0x7da2054a70d0>]]] in starred[call[name[sel... | keyword[def] identifier[database_exist] ( identifier[self] ):
literal[string]
identifier[binds] ={}
keyword[for] identifier[key] , identifier[engine] keyword[in] identifier[self] . identifier[keys_engines] ():
identifier[key] = identifier[key] keyword[if] identifier[key] ... | def database_exist(self):
"""Create databases for each engine and return a new :class:`.Mapper`.
"""
binds = {}
for (key, engine) in self.keys_engines():
key = key if key else 'default'
binds[key] = self._database_exist(engine) # depends on [control=['for'], data=[]]
return bind... |
def addOutHeaderInfo(self, name, type, namespace, element_type=0,
mustUnderstand=0):
"""Add an output SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1
... | def function[addOutHeaderInfo, parameter[self, name, type, namespace, element_type, mustUnderstand]]:
constant[Add an output SOAP header description to the call info.]
variable[headerinfo] assign[=] call[name[HeaderInfo], parameter[name[name], name[type], name[namespace], name[element_type]]]
if... | keyword[def] identifier[addOutHeaderInfo] ( identifier[self] , identifier[name] , identifier[type] , identifier[namespace] , identifier[element_type] = literal[int] ,
identifier[mustUnderstand] = literal[int] ):
literal[string]
identifier[headerinfo] = identifier[HeaderInfo] ( identifier[name] , i... | def addOutHeaderInfo(self, name, type, namespace, element_type=0, mustUnderstand=0):
"""Add an output SOAP header description to the call info."""
headerinfo = HeaderInfo(name, type, namespace, element_type)
if mustUnderstand:
headerinfo.mustUnderstand = 1 # depends on [control=['if'], data=[]]
... |
def info(ctx, objects):
""" Obtain all kinds of information
"""
if not objects:
t = PrettyTable(["Key", "Value"])
t.align = "l"
info = ctx.peerplays.rpc.get_dynamic_global_properties()
for key in info:
t.add_row([key, info[key]])
click.echo(t.get_string(so... | def function[info, parameter[ctx, objects]]:
constant[ Obtain all kinds of information
]
if <ast.UnaryOp object at 0x7da1b106d6f0> begin[:]
variable[t] assign[=] call[name[PrettyTable], parameter[list[[<ast.Constant object at 0x7da1b106dc30>, <ast.Constant object at 0x7da1b106e9e0>]]... | keyword[def] identifier[info] ( identifier[ctx] , identifier[objects] ):
literal[string]
keyword[if] keyword[not] identifier[objects] :
identifier[t] = identifier[PrettyTable] ([ literal[string] , literal[string] ])
identifier[t] . identifier[align] = literal[string]
identifie... | def info(ctx, objects):
""" Obtain all kinds of information
"""
if not objects:
t = PrettyTable(['Key', 'Value'])
t.align = 'l'
info = ctx.peerplays.rpc.get_dynamic_global_properties()
for key in info:
t.add_row([key, info[key]]) # depends on [control=['for'], da... |
def obfuscatable_class(tokens, index, **kwargs):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a class name that can be safely
obfuscated.
"""
tok = tokens[index]
token_type = tok[0]
token_string = tok[1]
if index >... | def function[obfuscatable_class, parameter[tokens, index]]:
constant[
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a class name that can be safely
obfuscated.
]
variable[tok] assign[=] call[name[tokens]][name[index]]
... | keyword[def] identifier[obfuscatable_class] ( identifier[tokens] , identifier[index] ,** identifier[kwargs] ):
literal[string]
identifier[tok] = identifier[tokens] [ identifier[index] ]
identifier[token_type] = identifier[tok] [ literal[int] ]
identifier[token_string] = identifier[tok] [ literal[... | def obfuscatable_class(tokens, index, **kwargs):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a class name that can be safely
obfuscated.
"""
tok = tokens[index]
token_type = tok[0]
token_string = tok[1]
if index >... |
def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) | def function[state, parameter[self, state]]:
constant[Set state.]
name[self]._state assign[=] name[state]
call[name[self]._manager][name[ATTR_STATE]] assign[=] name[state]
call[name[_LOGGER].info, parameter[constant[state changed to %s], name[state]]] | keyword[def] identifier[state] ( identifier[self] , identifier[state] ):
literal[string]
identifier[self] . identifier[_state] = identifier[state]
identifier[self] . identifier[_manager] [ identifier[ATTR_STATE] ]= identifier[state]
identifier[_LOGGER] . identifier[info] ( liter... | def state(self, state):
"""Set state."""
self._state = state
self._manager[ATTR_STATE] = state
_LOGGER.info('state changed to %s', state) |
def get_labels(filename, logger=None):
"""Returns a dictionary of alternative sequence labels, or None
- filename - path to file containing tab-separated table of labels
Input files should be formatted as <key>\t<label>, one pair per line.
"""
labeldict = {}
if filename is not None:
if... | def function[get_labels, parameter[filename, logger]]:
constant[Returns a dictionary of alternative sequence labels, or None
- filename - path to file containing tab-separated table of labels
Input files should be formatted as <key> <label>, one pair per line.
]
variable[labeldict] assign[... | keyword[def] identifier[get_labels] ( identifier[filename] , identifier[logger] = keyword[None] ):
literal[string]
identifier[labeldict] ={}
keyword[if] identifier[filename] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[logger] :
identifier[logger] . identi... | def get_labels(filename, logger=None):
"""Returns a dictionary of alternative sequence labels, or None
- filename - path to file containing tab-separated table of labels
Input files should be formatted as <key> <label>, one pair per line.
"""
labeldict = {}
if filename is not None:
if ... |
def wrapAtom(xml, id, title, author=None, updated=None, author_uri=None,
alt=None, alt_type="text/html"):
"""
Create an Atom entry tag and embed the passed XML within it
"""
entryTag = etree.Element(ATOM + "entry", nsmap=ATOM_NSMAP)
titleTag = etree.SubElement(entryTag, ATOM + "title")... | def function[wrapAtom, parameter[xml, id, title, author, updated, author_uri, alt, alt_type]]:
constant[
Create an Atom entry tag and embed the passed XML within it
]
variable[entryTag] assign[=] call[name[etree].Element, parameter[binary_operation[name[ATOM] + constant[entry]]]]
variabl... | keyword[def] identifier[wrapAtom] ( identifier[xml] , identifier[id] , identifier[title] , identifier[author] = keyword[None] , identifier[updated] = keyword[None] , identifier[author_uri] = keyword[None] ,
identifier[alt] = keyword[None] , identifier[alt_type] = literal[string] ):
literal[string]
identi... | def wrapAtom(xml, id, title, author=None, updated=None, author_uri=None, alt=None, alt_type='text/html'):
"""
Create an Atom entry tag and embed the passed XML within it
"""
entryTag = etree.Element(ATOM + 'entry', nsmap=ATOM_NSMAP)
titleTag = etree.SubElement(entryTag, ATOM + 'title')
titleTag.... |
def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated.
"""
output_d... | def function[get_local_output_dir, parameter[]]:
constant[Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be... | keyword[def] identifier[get_local_output_dir] ():
literal[string]
identifier[output_dir] = identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] + identifier[str] ( identifier[uuid] . identifier[uuid4] ()))
keyword[if] keyword[not] identifier[os] . identifier[pat... | def get_local_output_dir():
"""Create a local output directory per execution.
We've seen occassional (1/100000) perm issues with lambda on temp
directory and changing unix execution users (2015-2018), so use a
per execution temp space. With firecracker lambdas this may be outdated.
"""
output_d... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'used_bytes') and self.used_bytes is not None:
_dict['used_bytes'] = self.used_bytes
return _dict | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da204621990> begin[:]
call[name[_dict]][constant[used_bytes]] assign[=] name[self].used_bytes
return[n... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[used_bytes] keyword[is] keyword[not] keyword[None] :
identifier[... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'used_bytes') and self.used_bytes is not None:
_dict['used_bytes'] = self.used_bytes # depends on [control=['if'], data=[]]
return _dict |
def write_unitth(suites, out_dir):
""" Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
"""
if not os.path.isdir(out_dir):
os.mkdir(out_dir)
fo... | def function[write_unitth, parameter[suites, out_dir]]:
constant[ Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
]
if <ast.UnaryOp object at 0x7da1b185dcf0> begin... | keyword[def] identifier[write_unitth] ( identifier[suites] , identifier[out_dir] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isdir] ( identifier[out_dir] ):
identifier[os] . identifier[mkdir] ( identifier[out_dir] )
keyword[for... | def write_unitth(suites, out_dir):
""" Write UnitTH-style test reports
Args:
suites (:obj:`dict`): dictionary of test suites
out_dir (:obj:`str`): path to save UnitTH-style test reports
"""
if not os.path.isdir(out_dir):
os.mkdir(out_dir) # depends on [control=... |
def _experience(self, previousState, action, previousAction, reward):
""" This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into play. If the
action... | def function[_experience, parameter[self, previousState, action, previousAction, reward]]:
constant[ This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into ... | keyword[def] identifier[_experience] ( identifier[self] , identifier[previousState] , identifier[action] , identifier[previousAction] , identifier[reward] ):
literal[string]
identifier[e] = identifier[self] . identifier[experimentation]
keyword[if] identifier[action] == identifier[previ... | def _experience(self, previousState, action, previousAction, reward):
""" This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into play. If the
actionInde... |
def award_group_principal_award_recipient(tag):
"""
Find the award group principal award recipient, one for each
item found in the get_funding_group section
"""
award_group_principal_award_recipient = []
principal_award_recipients = extract_nodes(tag, "principal-award-recipient")
for t in p... | def function[award_group_principal_award_recipient, parameter[tag]]:
constant[
Find the award group principal award recipient, one for each
item found in the get_funding_group section
]
variable[award_group_principal_award_recipient] assign[=] list[[]]
variable[principal_award_recipi... | keyword[def] identifier[award_group_principal_award_recipient] ( identifier[tag] ):
literal[string]
identifier[award_group_principal_award_recipient] =[]
identifier[principal_award_recipients] = identifier[extract_nodes] ( identifier[tag] , literal[string] )
keyword[for] identifier[t] keyword[... | def award_group_principal_award_recipient(tag):
"""
Find the award group principal award recipient, one for each
item found in the get_funding_group section
"""
award_group_principal_award_recipient = []
principal_award_recipients = extract_nodes(tag, 'principal-award-recipient')
for t in pr... |
def _load_cache(self, filename):
"""Load the cached page references from `<filename>.ptc`."""
try:
with open(filename + self.CACHE_EXTENSION, 'rb') as file:
prev_number_of_pages, prev_page_references = pickle.load(file)
except (IOError, TypeError):
prev_nu... | def function[_load_cache, parameter[self, filename]]:
constant[Load the cached page references from `<filename>.ptc`.]
<ast.Try object at 0x7da18f58f2b0>
return[tuple[[<ast.Name object at 0x7da18f58fa90>, <ast.Name object at 0x7da18f58c4f0>]]] | keyword[def] identifier[_load_cache] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[filename] + identifier[self] . identifier[CACHE_EXTENSION] , literal[string] ) keyword[as] identifier[file] :
... | def _load_cache(self, filename):
"""Load the cached page references from `<filename>.ptc`."""
try:
with open(filename + self.CACHE_EXTENSION, 'rb') as file:
(prev_number_of_pages, prev_page_references) = pickle.load(file) # depends on [control=['with'], data=['file']] # depends on [control... |
def t_asm(t):
r'\b[aA][sS][mM]\b'
global ASM, ASMLINENO, IN_STATE
t.lexer.begin('asm')
ASM = ''
ASMLINENO = t.lexer.lineno
IN_STATE = True | def function[t_asm, parameter[t]]:
constant[\b[aA][sS][mM]\b]
<ast.Global object at 0x7da20c76e8f0>
call[name[t].lexer.begin, parameter[constant[asm]]]
variable[ASM] assign[=] constant[]
variable[ASMLINENO] assign[=] name[t].lexer.lineno
variable[IN_STATE] assign[=] constant[... | keyword[def] identifier[t_asm] ( identifier[t] ):
literal[string]
keyword[global] identifier[ASM] , identifier[ASMLINENO] , identifier[IN_STATE]
identifier[t] . identifier[lexer] . identifier[begin] ( literal[string] )
identifier[ASM] = literal[string]
identifier[ASMLINENO] = identifier... | def t_asm(t):
"""\\b[aA][sS][mM]\\b"""
global ASM, ASMLINENO, IN_STATE
t.lexer.begin('asm')
ASM = ''
ASMLINENO = t.lexer.lineno
IN_STATE = True |
def _shrink(v, gamma):
"""Soft-shrinkage of an array with parameter gamma.
Parameters
----------
v : array
Array containing the values to be applied to the shrinkage operator
gamma : float
Shrinkage parameter.
Returns
-------
v... | def function[_shrink, parameter[v, gamma]]:
constant[Soft-shrinkage of an array with parameter gamma.
Parameters
----------
v : array
Array containing the values to be applied to the shrinkage operator
gamma : float
Shrinkage parameter.
Returns... | keyword[def] identifier[_shrink] ( identifier[v] , identifier[gamma] ):
literal[string]
identifier[pos] = identifier[v] > identifier[gamma]
identifier[neg] = identifier[v] <- identifier[gamma]
identifier[v] [ identifier[pos] ]-= identifier[gamma]
identifier[v] [ identi... | def _shrink(v, gamma):
"""Soft-shrinkage of an array with parameter gamma.
Parameters
----------
v : array
Array containing the values to be applied to the shrinkage operator
gamma : float
Shrinkage parameter.
Returns
-------
v : a... |
def get_ladders_metadata(session, parsed):
"""Get metadata for all ladders."""
ladders = {}
for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])
return ladders | def function[get_ladders_metadata, parameter[session, parsed]]:
constant[Get metadata for all ladders.]
variable[ladders] assign[=] dictionary[[], []]
for taget[name[ladder]] in starred[call[name[parsed].find_all, parameter[constant[a]]]] begin[:]
call[name[ladders]][name[ladder]... | keyword[def] identifier[get_ladders_metadata] ( identifier[session] , identifier[parsed] ):
literal[string]
identifier[ladders] ={}
keyword[for] identifier[ladder] keyword[in] identifier[parsed] . identifier[find_all] ( literal[string] , identifier[href] = identifier[re] . identifier[compile] ( ide... | def get_ladders_metadata(session, parsed):
"""Get metadata for all ladders."""
ladders = {}
for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
ladders[ladder.text] = get_ladder_metadata(session, ladder['href']) # depends on [control=['for'], data=['ladder']]
return ladders |
def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None,
realm=None, nonce=None, opaque=None, password=None,
request_digest=None, client_nonce=None):
'''
Builds an authorization request that may be sent as the valu... | def function[build_authorization_request, parameter[username, method, uri, nonce_count, digest_challenge, realm, nonce, opaque, password, request_digest, client_nonce]]:
constant[
Builds an authorization request that may be sent as the value of the 'Authorization'
header in an HTTP request.
Either ... | keyword[def] identifier[build_authorization_request] ( identifier[username] , identifier[method] , identifier[uri] , identifier[nonce_count] , identifier[digest_challenge] = keyword[None] ,
identifier[realm] = keyword[None] , identifier[nonce] = keyword[None] , identifier[opaque] = keyword[None] , identifier[passwor... | def build_authorization_request(username, method, uri, nonce_count, digest_challenge=None, realm=None, nonce=None, opaque=None, password=None, request_digest=None, client_nonce=None):
"""
Builds an authorization request that may be sent as the value of the 'Authorization'
header in an HTTP request.
Eit... |
def export(self, export_auto_config=False):
"""
Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: Also export auto configur... | def function[export, parameter[self, export_auto_config]]:
constant[
Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: ... | keyword[def] identifier[export] ( identifier[self] , identifier[export_auto_config] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_get] ( literal[string] , identifier[ApiClusterTemplate] , keyword[False] ,
identifier[params] = identifier[dict] ( identifier[exportA... | def export(self, export_auto_config=False):
"""
Export the cluster template for the given cluster. ccluster must have host
templates defined. It cluster does not have host templates defined it will
export host templates based on roles assignment.
@param export_auto_config: Also export auto configur... |
def _aggr_weighted_mean(inList, params):
""" Weighted mean uses params (must be the same size as inList) and
makes weighed mean of inList"""
assert(len(inList) == len(params))
# If all weights are 0, then the value is not defined, return None (missing)
weightsSum = sum(params)
if weightsSum == 0:
retur... | def function[_aggr_weighted_mean, parameter[inList, params]]:
constant[ Weighted mean uses params (must be the same size as inList) and
makes weighed mean of inList]
assert[compare[call[name[len], parameter[name[inList]]] equal[==] call[name[len], parameter[name[params]]]]]
variable[weightsSum] as... | keyword[def] identifier[_aggr_weighted_mean] ( identifier[inList] , identifier[params] ):
literal[string]
keyword[assert] ( identifier[len] ( identifier[inList] )== identifier[len] ( identifier[params] ))
identifier[weightsSum] = identifier[sum] ( identifier[params] )
keyword[if] identifier[weightsS... | def _aggr_weighted_mean(inList, params):
""" Weighted mean uses params (must be the same size as inList) and
makes weighed mean of inList"""
assert len(inList) == len(params)
# If all weights are 0, then the value is not defined, return None (missing)
weightsSum = sum(params)
if weightsSum == 0:
... |
def _results(r):
r"""Select from a tuple of(root, funccalls, iterations, flag)"""
x, funcalls, iterations, flag = r
return results(x, funcalls, iterations, flag == 0) | def function[_results, parameter[r]]:
constant[Select from a tuple of(root, funccalls, iterations, flag)]
<ast.Tuple object at 0x7da1b21b9390> assign[=] name[r]
return[call[name[results], parameter[name[x], name[funcalls], name[iterations], compare[name[flag] equal[==] constant[0]]]]] | keyword[def] identifier[_results] ( identifier[r] ):
literal[string]
identifier[x] , identifier[funcalls] , identifier[iterations] , identifier[flag] = identifier[r]
keyword[return] identifier[results] ( identifier[x] , identifier[funcalls] , identifier[iterations] , identifier[flag] == literal[int]... | def _results(r):
"""Select from a tuple of(root, funccalls, iterations, flag)"""
(x, funcalls, iterations, flag) = r
return results(x, funcalls, iterations, flag == 0) |
def _signed_bounds(self):
"""
Get lower bound and upper bound for `self` in signed arithmetic.
:return: a list of (lower_bound, upper_bound) tuples
"""
nsplit = self._nsplit()
if len(nsplit) == 1:
lb = nsplit[0].lower_bound
ub = nsplit[0].upper_b... | def function[_signed_bounds, parameter[self]]:
constant[
Get lower bound and upper bound for `self` in signed arithmetic.
:return: a list of (lower_bound, upper_bound) tuples
]
variable[nsplit] assign[=] call[name[self]._nsplit, parameter[]]
if compare[call[name[len], pa... | keyword[def] identifier[_signed_bounds] ( identifier[self] ):
literal[string]
identifier[nsplit] = identifier[self] . identifier[_nsplit] ()
keyword[if] identifier[len] ( identifier[nsplit] )== literal[int] :
identifier[lb] = identifier[nsplit] [ literal[int] ]. identifier[l... | def _signed_bounds(self):
"""
Get lower bound and upper bound for `self` in signed arithmetic.
:return: a list of (lower_bound, upper_bound) tuples
"""
nsplit = self._nsplit()
if len(nsplit) == 1:
lb = nsplit[0].lower_bound
ub = nsplit[0].upper_bound
lb = sel... |
def marshal_with_model(model, excludes=None, only=None, extends=None):
"""With this decorator, you can return ORM model instance, or ORM query in view function directly.
We'll transform these objects to standard python data structures, like Flask-RESTFul's `marshal_with` decorator.
And, you don't need defin... | def function[marshal_with_model, parameter[model, excludes, only, extends]]:
constant[With this decorator, you can return ORM model instance, or ORM query in view function directly.
We'll transform these objects to standard python data structures, like Flask-RESTFul's `marshal_with` decorator.
And, you ... | keyword[def] identifier[marshal_with_model] ( identifier[model] , identifier[excludes] = keyword[None] , identifier[only] = keyword[None] , identifier[extends] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[excludes] , identifier[six] . identifier[string_types] ):
... | def marshal_with_model(model, excludes=None, only=None, extends=None):
"""With this decorator, you can return ORM model instance, or ORM query in view function directly.
We'll transform these objects to standard python data structures, like Flask-RESTFul's `marshal_with` decorator.
And, you don't need defin... |
def session_to_hour(timestamp):
""":param timestamp: as string in YYYYMMDDHHmmSS format
:return string in YYYYMMDDHH format"""
t = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN)
return t.strftime(SYNERGY_HOURLY_PATTERN) | def function[session_to_hour, parameter[timestamp]]:
constant[:param timestamp: as string in YYYYMMDDHHmmSS format
:return string in YYYYMMDDHH format]
variable[t] assign[=] call[name[datetime].strptime, parameter[name[timestamp], name[SYNERGY_SESSION_PATTERN]]]
return[call[name[t].strftime, par... | keyword[def] identifier[session_to_hour] ( identifier[timestamp] ):
literal[string]
identifier[t] = identifier[datetime] . identifier[strptime] ( identifier[timestamp] , identifier[SYNERGY_SESSION_PATTERN] )
keyword[return] identifier[t] . identifier[strftime] ( identifier[SYNERGY_HOURLY_PATTERN] ) | def session_to_hour(timestamp):
""":param timestamp: as string in YYYYMMDDHHmmSS format
:return string in YYYYMMDDHH format"""
t = datetime.strptime(timestamp, SYNERGY_SESSION_PATTERN)
return t.strftime(SYNERGY_HOURLY_PATTERN) |
def search_webhook_for_facets(self, **kwargs): # noqa: E501
"""Lists the values of one or more facets over the customer's webhooks # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | def function[search_webhook_for_facets, parameter[self]]:
constant[Lists the values of one or more facets over the customer's webhooks # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | keyword[def] identifier[search_webhook_for_facets] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . ide... | def search_webhook_for_facets(self, **kwargs): # noqa: E501
"Lists the values of one or more facets over the customer's webhooks # noqa: E501\n\n # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n ... |
def create_local_copy(cookie_file):
"""Make a local copy of the sqlite cookie database and return the new filename.
This is necessary in case this database is still being written to while the user browses
to avoid sqlite locking errors.
"""
# if type of cookie_file is a list, use the first element i... | def function[create_local_copy, parameter[cookie_file]]:
constant[Make a local copy of the sqlite cookie database and return the new filename.
This is necessary in case this database is still being written to while the user browses
to avoid sqlite locking errors.
]
if call[name[isinstance], ... | keyword[def] identifier[create_local_copy] ( identifier[cookie_file] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[cookie_file] , identifier[list] ):
identifier[cookie_file] = identifier[cookie_file] [ literal[int] ]
keyword[if] identifier[os] . identifie... | def create_local_copy(cookie_file):
"""Make a local copy of the sqlite cookie database and return the new filename.
This is necessary in case this database is still being written to while the user browses
to avoid sqlite locking errors.
"""
# if type of cookie_file is a list, use the first element i... |
def _statuscode2string(status_code):
"""Return a short message for a CIM status code."""
try:
s = _STATUSCODE2STRING[status_code]
except KeyError:
s = _format("Invalid status code {0}", status_code)
return s | def function[_statuscode2string, parameter[status_code]]:
constant[Return a short message for a CIM status code.]
<ast.Try object at 0x7da1b0ef48b0>
return[name[s]] | keyword[def] identifier[_statuscode2string] ( identifier[status_code] ):
literal[string]
keyword[try] :
identifier[s] = identifier[_STATUSCODE2STRING] [ identifier[status_code] ]
keyword[except] identifier[KeyError] :
identifier[s] = identifier[_format] ( literal[string] , identifie... | def _statuscode2string(status_code):
"""Return a short message for a CIM status code."""
try:
s = _STATUSCODE2STRING[status_code] # depends on [control=['try'], data=[]]
except KeyError:
s = _format('Invalid status code {0}', status_code) # depends on [control=['except'], data=[]]
retu... |
def tempallow(ip=None, ttl=None, port=None, direction=None, comment=''):
'''
Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access... | def function[tempallow, parameter[ip, ttl, port, direction, comment]]:
constant[
Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ss... | keyword[def] identifier[tempallow] ( identifier[ip] = keyword[None] , identifier[ttl] = keyword[None] , identifier[port] = keyword[None] , identifier[direction] = keyword[None] , identifier[comment] = literal[string] ):
literal[string]
keyword[return] identifier[_tmp_access_rule] ( literal[string] , ident... | def tempallow(ip=None, ttl=None, port=None, direction=None, comment=''):
"""
Add an rule to the temporary ip allow list.
See :func:`_access_rule`.
1- Add an IP:
CLI Example:
.. code-block:: bash
salt '*' csf.tempallow 127.0.0.1 3600 port=22 direction='in' comment='# Temp dev ssh access... |
def set_data(self, xdata=[1,2,3,4,5], ydata=[1.7,2,3,4,3], eydata=None, **kwargs):
"""
This will handle the different types of supplied data and put everything
in a standard format for processing.
Parameters
----------
xdata, ydata
These can be a single a... | def function[set_data, parameter[self, xdata, ydata, eydata]]:
constant[
This will handle the different types of supplied data and put everything
in a standard format for processing.
Parameters
----------
xdata, ydata
These can be a single array of data o... | keyword[def] identifier[set_data] ( identifier[self] , identifier[xdata] =[ literal[int] , literal[int] , literal[int] , literal[int] , literal[int] ], identifier[ydata] =[ literal[int] , literal[int] , literal[int] , literal[int] , literal[int] ], identifier[eydata] = keyword[None] ,** identifier[kwargs] ):
... | def set_data(self, xdata=[1, 2, 3, 4, 5], ydata=[1.7, 2, 3, 4, 3], eydata=None, **kwargs):
"""
This will handle the different types of supplied data and put everything
in a standard format for processing.
Parameters
----------
xdata, ydata
These can be a sing... |
def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None):
"""
Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
------... | def function[fromlist, parameter[items, accessor, index, labels, dtype, npartitions, engine]]:
constant[
Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
-----... | keyword[def] identifier[fromlist] ( identifier[items] , identifier[accessor] = keyword[None] , identifier[index] = keyword[None] , identifier[labels] = keyword[None] , identifier[dtype] = keyword[None] , identifier[npartitions] = keyword[None] , identifier[engine] = keyword[None] ):
literal[string]
keyword... | def fromlist(items, accessor=None, index=None, labels=None, dtype=None, npartitions=None, engine=None):
"""
Load series data from a list with an optional accessor function.
Will call accessor function on each item from the list,
providing a generic interface for data loading.
Parameters
------... |
def open(self, path: str, mode: str='r') -> IO:
"""Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of the fi... | def function[open, parameter[self, path, mode]]:
constant[Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of... | keyword[def] identifier[open] ( identifier[self] , identifier[path] : identifier[str] , identifier[mode] : identifier[str] = literal[string] )-> identifier[IO] :
literal[string]
identifier[entry] = identifier[self] . identifier[path_map] . identifier[get] ( identifier[path] )
keyword[if] ... | def open(self, path: str, mode: str='r') -> IO:
"""Open an IO-like object for `path`.
.. note::
Mode *must* be either 'r' or 'w', as the underlying objects
do not understand the full range of modes.
:param path: The path to open.
:param mode: The mode of the file b... |
def console_fill_foreground(
con: tcod.console.Console,
r: Sequence[int],
g: Sequence[int],
b: Sequence[int],
) -> None:
"""Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*heigh... | def function[console_fill_foreground, parameter[con, r, g, b]]:
constant[Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*height.
g (Sequence[int]): An array of integers with a lengt... | keyword[def] identifier[console_fill_foreground] (
identifier[con] : identifier[tcod] . identifier[console] . identifier[Console] ,
identifier[r] : identifier[Sequence] [ identifier[int] ],
identifier[g] : identifier[Sequence] [ identifier[int] ],
identifier[b] : identifier[Sequence] [ identifier[int] ],
)-> keyw... | def console_fill_foreground(con: tcod.console.Console, r: Sequence[int], g: Sequence[int], b: Sequence[int]) -> None:
"""Fill the foregound of a console with r,g,b.
Args:
con (Console): Any Console instance.
r (Sequence[int]): An array of integers with a length of width*height.
g (Seque... |
def notification(self):
"""Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
try:
root = self.selenium.f... | def function[notification, parameter[self]]:
constant[Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object.
]
with call[name[self].selenium.context, parameter[name[self].selenium.CONTEXT_CHROME]] be... | keyword[def] identifier[notification] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[selenium] . identifier[context] ( identifier[self] . identifier[selenium] . identifier[CONTEXT_CHROME] ):
keyword[try] :
identifier[root] = identifi... | def notification(self):
"""Provide access to the currently displayed notification.
Returns:
:py:class:`BaseNotification`: FoxPuppet BaseNotification object.
"""
with self.selenium.context(self.selenium.CONTEXT_CHROME):
try:
root = self.selenium.find_element(*sel... |
def returnCSV(self, keys=None, limit=False, omitHeaderLine=False, quoteChar=None, eolChars='\r\n'):
r'''Return a list of dictionaries formated as a comma seperated values
(CSV) list in a string.
Each entry is on one line. By default, each value is seperated by
commas and each entry is f... | def function[returnCSV, parameter[self, keys, limit, omitHeaderLine, quoteChar, eolChars]]:
constant[Return a list of dictionaries formated as a comma seperated values
(CSV) list in a string.
Each entry is on one line. By default, each value is seperated by
commas and each entry is foll... | keyword[def] identifier[returnCSV] ( identifier[self] , identifier[keys] = keyword[None] , identifier[limit] = keyword[False] , identifier[omitHeaderLine] = keyword[False] , identifier[quoteChar] = keyword[None] , identifier[eolChars] = literal[string] ):
literal[string]
identifier[result] = litera... | def returnCSV(self, keys=None, limit=False, omitHeaderLine=False, quoteChar=None, eolChars='\r\n'):
"""Return a list of dictionaries formated as a comma seperated values
(CSV) list in a string.
Each entry is on one line. By default, each value is seperated by
commas and each entry is follow... |
def getFileKeys(self):
"""
Retrieve a list of file keys that have been read into the database.
This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys
in conjunction with the dictionary returned by the getFileObjects method.
... | def function[getFileKeys, parameter[self]]:
constant[
Retrieve a list of file keys that have been read into the database.
This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys
in conjunction with the dictionary returned by the getF... | keyword[def] identifier[getFileKeys] ( identifier[self] ):
literal[string]
identifier[files] = identifier[self] . identifier[getFileObjects] ()
identifier[files_list] =[]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[files] . identifier[iteritems] ()... | def getFileKeys(self):
"""
Retrieve a list of file keys that have been read into the database.
This is a utility method that can be used to programmatically access the GsshaPy file objects. Use these keys
in conjunction with the dictionary returned by the getFileObjects method.
Ret... |
def _consume_flags(self):
"""Read flags until we encounter the first token that isn't a flag."""
flags = []
while self._at_flag():
flag = self._unconsumed_args.pop()
if not self._check_for_help_request(flag):
flags.append(flag)
return flags | def function[_consume_flags, parameter[self]]:
constant[Read flags until we encounter the first token that isn't a flag.]
variable[flags] assign[=] list[[]]
while call[name[self]._at_flag, parameter[]] begin[:]
variable[flag] assign[=] call[name[self]._unconsumed_args.pop, parame... | keyword[def] identifier[_consume_flags] ( identifier[self] ):
literal[string]
identifier[flags] =[]
keyword[while] identifier[self] . identifier[_at_flag] ():
identifier[flag] = identifier[self] . identifier[_unconsumed_args] . identifier[pop] ()
keyword[if] keyword[not] identifier[se... | def _consume_flags(self):
"""Read flags until we encounter the first token that isn't a flag."""
flags = []
while self._at_flag():
flag = self._unconsumed_args.pop()
if not self._check_for_help_request(flag):
flags.append(flag) # depends on [control=['if'], data=[]] # depends o... |
def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comm... | def function[make_html_patterns, parameter[]]:
constant[Strongly inspired from idlelib.ColorDelegator.make_pat ]
variable[tags] assign[=] call[name[any], parameter[constant[builtin], list[[<ast.Constant object at 0x7da1b26adf30>, <ast.Constant object at 0x7da1b26acc10>, <ast.Constant object at 0x7da1b26... | keyword[def] identifier[make_html_patterns] ():
literal[string]
identifier[tags] = identifier[any] ( literal[string] ,[ literal[string] , literal[string] , literal[string] ])
identifier[keywords] = identifier[any] ( literal[string] ,[ literal[string] ])
identifier[string] = identifier[any] ( ... | def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any('builtin', ['<', '[\\?/]?>', '(?<=<).*?(?=[ >])'])
keywords = any('keyword', [' [\\w:-]*?(?==)'])
string = any('string', ['".*?"'])
comment = any('comment', ['<!--.*?-->'])
multiline_comment_start ... |
def setup(self):
"""Setup main window"""
logger.info("*** Start of MainWindow setup ***")
logger.info("Applying theme configuration...")
ui_theme = CONF.get('appearance', 'ui_theme')
color_scheme = CONF.get('appearance', 'selected')
if ui_theme == 'dark':
... | def function[setup, parameter[self]]:
constant[Setup main window]
call[name[logger].info, parameter[constant[*** Start of MainWindow setup ***]]]
call[name[logger].info, parameter[constant[Applying theme configuration...]]]
variable[ui_theme] assign[=] call[name[CONF].get, parameter[cons... | keyword[def] identifier[setup] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[ui_theme] = identifier[CONF] . identifier[get] ( literal[string] , literal[stri... | def setup(self):
"""Setup main window"""
logger.info('*** Start of MainWindow setup ***')
logger.info('Applying theme configuration...')
ui_theme = CONF.get('appearance', 'ui_theme')
color_scheme = CONF.get('appearance', 'selected')
if ui_theme == 'dark':
dark_qss = qdarkstyle.load_style... |
def fix_worksheet_status_inconsistencies(portal):
"""Walks through open worksheets and transition them to 'verified' or
'to_be_verified' if all their analyses are not in an open status
"""
logger.info("Fixing worksheet inconsistencies ...")
query = dict(portal_type="Worksheet",
revi... | def function[fix_worksheet_status_inconsistencies, parameter[portal]]:
constant[Walks through open worksheets and transition them to 'verified' or
'to_be_verified' if all their analyses are not in an open status
]
call[name[logger].info, parameter[constant[Fixing worksheet inconsistencies ...]]]... | keyword[def] identifier[fix_worksheet_status_inconsistencies] ( identifier[portal] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[query] = identifier[dict] ( identifier[portal_type] = literal[string] ,
identifier[review_state] =[ literal[string] , literal[... | def fix_worksheet_status_inconsistencies(portal):
"""Walks through open worksheets and transition them to 'verified' or
'to_be_verified' if all their analyses are not in an open status
"""
logger.info('Fixing worksheet inconsistencies ...')
query = dict(portal_type='Worksheet', review_state=['open',... |
def label(x, gr, preferred_languages=None):
"""
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found,... | def function[label, parameter[x, gr, preferred_languages]]:
constant[
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in or... | keyword[def] identifier[label] ( identifier[x] , identifier[gr] , identifier[preferred_languages] = keyword[None] ):
literal[string]
identifier[labels] ={ identifier[l] . identifier[language] : identifier[l]
keyword[for] identifier[labelProp] keyword[in] identifier[LABEL_PROPERTIES]
key... | def label(x, gr, preferred_languages=None):
"""
@param x : graph entity
@param gr (Graph): RDF graph
@param preferred_languages (iterable)
Return the best available label in the graph for the passed entity.
If a set of preferred languages is given, try them in order. If none is
found,... |
def ParseNetworkDataUsage(
self, parser_mediator, cache=None, database=None, table=None,
**unused_kwargs):
"""Parses the network data usage monitor table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
... | def function[ParseNetworkDataUsage, parameter[self, parser_mediator, cache, database, table]]:
constant[Parses the network data usage monitor table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Op... | keyword[def] identifier[ParseNetworkDataUsage] (
identifier[self] , identifier[parser_mediator] , identifier[cache] = keyword[None] , identifier[database] = keyword[None] , identifier[table] = keyword[None] ,
** identifier[unused_kwargs] ):
literal[string]
identifier[self] . identifier[_ParseGUIDTable] (
... | def ParseNetworkDataUsage(self, parser_mediator, cache=None, database=None, table=None, **unused_kwargs):
"""Parses the network data usage monitor table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (O... |
def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue
if ancestor is dom.documentElemen... | def function[remove_nesting, parameter[dom, tag_name]]:
constant[
Unwrap items in the node list that have ancestors with the same tag.
]
for taget[name[node]] in starred[call[name[dom].getElementsByTagName, parameter[name[tag_name]]]] begin[:]
for taget[name[ancestor]] in starred... | keyword[def] identifier[remove_nesting] ( identifier[dom] , identifier[tag_name] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[dom] . identifier[getElementsByTagName] ( identifier[tag_name] ):
keyword[for] identifier[ancestor] keyword[in] identifier[ancestors] ( ide... | def remove_nesting(dom, tag_name):
"""
Unwrap items in the node list that have ancestors with the same tag.
"""
for node in dom.getElementsByTagName(tag_name):
for ancestor in ancestors(node):
if ancestor is node:
continue # depends on [control=['if'], data=[]]
... |
def normalizeX(value):
"""
Normalizes x coordinate.
* **value** must be an :ref:`type-int-float`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)):
raise TypeError("X coordinates must be instances of "
":ref:`type-i... | def function[normalizeX, parameter[value]]:
constant[
Normalizes x coordinate.
* **value** must be an :ref:`type-int-float`.
* Returned value is the same type as the input value.
]
if <ast.UnaryOp object at 0x7da2041d9bd0> begin[:]
<ast.Raise object at 0x7da2041d8c70>
return... | keyword[def] identifier[normalizeX] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] ,( identifier[int] , identifier[float] )):
keyword[raise] identifier[TypeError] ( literal[string]
literal[string]
% identifier[type] ... | def normalizeX(value):
"""
Normalizes x coordinate.
* **value** must be an :ref:`type-int-float`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)):
raise TypeError('X coordinates must be instances of :ref:`type-int-float`, not %s.' % type(... |
def Extract_Checkpoints(self):
'''
Extract the checkpoints and store in self.tracking_data
'''
# Make sure page is available
if self.page is None:
raise Exception("The HTML data was not fetched due to some reasons")
soup = BeautifulSoup(self.page,'html.parser')
if 'Delivery information not found' i... | def function[Extract_Checkpoints, parameter[self]]:
constant[
Extract the checkpoints and store in self.tracking_data
]
if compare[name[self].page is constant[None]] begin[:]
<ast.Raise object at 0x7da204623fd0>
variable[soup] assign[=] call[name[BeautifulSoup], parameter[name[self]... | keyword[def] identifier[Extract_Checkpoints] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[page] keyword[is] keyword[None] :
keyword[raise] identifier[Exception] ( literal[string] )
identifier[soup] = identifier[BeautifulSoup] ( identifier[self] . identifier[pa... | def Extract_Checkpoints(self):
"""
Extract the checkpoints and store in self.tracking_data
""" # Make sure page is available
if self.page is None:
raise Exception('The HTML data was not fetched due to some reasons') # depends on [control=['if'], data=[]]
soup = BeautifulSoup(self.page, 'html.... |
def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number... | def function[add_nio, parameter[self, nio, port_number]]:
constant[
Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
]
if compare[name[port_number] in name[self]._nios] begin[:]
<ast.Raise... | keyword[def] identifier[add_nio] ( identifier[self] , identifier[nio] , identifier[port_number] ):
literal[string]
keyword[if] identifier[port_number] keyword[in] identifier[self] . identifier[_nios] :
keyword[raise] identifier[DynamipsError] ( literal[string] . identifier[format]... | def add_nio(self, nio, port_number):
"""
Adds a NIO as new port on Ethernet switch.
:param nio: NIO instance to add
:param port_number: port to allocate for the NIO
"""
if port_number in self._nios:
raise DynamipsError("Port {} isn't free".format(port_number)) # depends... |
def _convert_volume_from(self, volume_from):
"""
:param volume_from:
:return:
"""
if ':' in volume_from:
container, permissions = volume_from.split(':')
else:
container = volume_from
permissions = 'rw'
if permissions not in ('r... | def function[_convert_volume_from, parameter[self, volume_from]]:
constant[
:param volume_from:
:return:
]
if compare[constant[:] in name[volume_from]] begin[:]
<ast.Tuple object at 0x7da204622260> assign[=] call[name[volume_from].split, parameter[constant[:]]]
... | keyword[def] identifier[_convert_volume_from] ( identifier[self] , identifier[volume_from] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[volume_from] :
identifier[container] , identifier[permissions] = identifier[volume_from] . identifier[split] ( literal[str... | def _convert_volume_from(self, volume_from):
"""
:param volume_from:
:return:
"""
if ':' in volume_from:
(container, permissions) = volume_from.split(':') # depends on [control=['if'], data=['volume_from']]
else:
container = volume_from
permissions = 'rw'
... |
def _upsert_persons(cursor, person_ids, lookup_func):
"""Upsert's user info into the database.
The model contains the user info as part of the role values.
"""
person_ids = list(set(person_ids)) # cleanse data
# Check for existing records to update.
cursor.execute("SELECT personid from persons... | def function[_upsert_persons, parameter[cursor, person_ids, lookup_func]]:
constant[Upsert's user info into the database.
The model contains the user info as part of the role values.
]
variable[person_ids] assign[=] call[name[list], parameter[call[name[set], parameter[name[person_ids]]]]]
... | keyword[def] identifier[_upsert_persons] ( identifier[cursor] , identifier[person_ids] , identifier[lookup_func] ):
literal[string]
identifier[person_ids] = identifier[list] ( identifier[set] ( identifier[person_ids] ))
identifier[cursor] . identifier[execute] ( literal[string] ,
( identifie... | def _upsert_persons(cursor, person_ids, lookup_func):
"""Upsert's user info into the database.
The model contains the user info as part of the role values.
"""
person_ids = list(set(person_ids)) # cleanse data
# Check for existing records to update.
cursor.execute('SELECT personid from persons ... |
def _remove_whitespace(text):
"""Remove excess whitespace from the ends of a given input string."""
# while True:
# old_text = text
# text = text.replace(' ', ' ')
# if text == old_text:
# return text
non_spaces = re.finditer(r'[^ ]', text)
... | def function[_remove_whitespace, parameter[text]]:
constant[Remove excess whitespace from the ends of a given input string.]
variable[non_spaces] assign[=] call[name[re].finditer, parameter[constant[[^ ]], name[text]]]
if <ast.UnaryOp object at 0x7da1b0473490> begin[:]
return[name[text]]... | keyword[def] identifier[_remove_whitespace] ( identifier[text] ):
literal[string]
identifier[non_spaces] = identifier[re] . identifier[finditer] ( literal[string] , identifier[text] )
keyword[if] keyword[not] identifier[non_spaces] :
... | def _remove_whitespace(text):
"""Remove excess whitespace from the ends of a given input string."""
# while True:
# old_text = text
# text = text.replace(' ', ' ')
# if text == old_text:
# return text
non_spaces = re.finditer('[^ ]', text)
if not non_spaces:
... |
def unserialize(wd: WordDictionary, text: Dict):
"""
Transforms back a serialized value of `serialize()`
"""
if not isinstance(text, Mapping):
raise ValueError('Text has not the right format')
try:
t = text['type']
if t == 'string':
return text['value']
... | def function[unserialize, parameter[wd, text]]:
constant[
Transforms back a serialized value of `serialize()`
]
if <ast.UnaryOp object at 0x7da20c7c9cc0> begin[:]
<ast.Raise object at 0x7da20c7cba90>
<ast.Try object at 0x7da20c7c8d00> | keyword[def] identifier[unserialize] ( identifier[wd] : identifier[WordDictionary] , identifier[text] : identifier[Dict] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[text] , identifier[Mapping] ):
keyword[raise] identifier[ValueError] ( literal[string] )
... | def unserialize(wd: WordDictionary, text: Dict):
"""
Transforms back a serialized value of `serialize()`
"""
if not isinstance(text, Mapping):
raise ValueError('Text has not the right format') # depends on [control=['if'], data=[]]
try:
t = text['type']
if t == 'string':
... |
def get_command_history(self, issued_command):
"""
Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .CommandHistory
"""
... | def function[get_command_history, parameter[self, issued_command]]:
constant[
Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .Comma... | keyword[def] identifier[get_command_history] ( identifier[self] , identifier[issued_command] ):
literal[string]
identifier[entry] = identifier[issued_command] . identifier[_proto] . identifier[commandQueueEntry]
identifier[key] = identifier[self] . identifier[_cache_key] ( identi... | def get_command_history(self, issued_command):
"""
Gets locally cached CommandHistory for the specified command.
:param .IssuedCommand issued_command: object representing a
previously issued command.
:rtype: .CommandHistory
"""
#pyli... |
def parse(self, stride=None):
"""Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1... | def function[parse, parameter[self, stride]]:
constant[Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a... | keyword[def] identifier[parse] ( identifier[self] , identifier[stride] = keyword[None] ):
literal[string]
keyword[if] identifier[stride] keyword[is] keyword[None] :
identifier[stride] = identifier[self] . identifier[stride]
identifier[self] . identifier[corrupted_lineno] =... | def parse(self, stride=None):
"""Read and cache the file as a numpy array.
Store every *stride* line of data; if ``None`` then the class default is used.
The array is returned with column-first indexing, i.e. for a data file with
columns X Y1 Y2 Y3 ... the array a will be a[0] = X, a[1] = ... |
def parse(filename):
"""Parses file content into events stream"""
for event, elt in et.iterparse(filename, events= ('start', 'end', 'comment', 'pi'), huge_tree=True):
if event == 'start':
obj = _elt2obj(elt)
obj['type'] = ENTER
yield obj
if elt.text:
... | def function[parse, parameter[filename]]:
constant[Parses file content into events stream]
for taget[tuple[[<ast.Name object at 0x7da1b00230d0>, <ast.Name object at 0x7da1b0021420>]]] in starred[call[name[et].iterparse, parameter[name[filename]]]] begin[:]
if compare[name[event] equal[==... | keyword[def] identifier[parse] ( identifier[filename] ):
literal[string]
keyword[for] identifier[event] , identifier[elt] keyword[in] identifier[et] . identifier[iterparse] ( identifier[filename] , identifier[events] =( literal[string] , literal[string] , literal[string] , literal[string] ), identifier[... | def parse(filename):
"""Parses file content into events stream"""
for (event, elt) in et.iterparse(filename, events=('start', 'end', 'comment', 'pi'), huge_tree=True):
if event == 'start':
obj = _elt2obj(elt)
obj['type'] = ENTER
yield obj
if elt.text:
... |
def zip(self, store=False, store_params=None):
"""
Returns a zip file of the current transformation. This is different from
the zip function that lives on the Filestack Client
*returns* [Filestack.Transform]
"""
params = locals()
params.pop('store')
param... | def function[zip, parameter[self, store, store_params]]:
constant[
Returns a zip file of the current transformation. This is different from
the zip function that lives on the Filestack Client
*returns* [Filestack.Transform]
]
variable[params] assign[=] call[name[locals],... | keyword[def] identifier[zip] ( identifier[self] , identifier[store] = keyword[False] , identifier[store_params] = keyword[None] ):
literal[string]
identifier[params] = identifier[locals] ()
identifier[params] . identifier[pop] ( literal[string] )
identifier[params] . identifier[po... | def zip(self, store=False, store_params=None):
"""
Returns a zip file of the current transformation. This is different from
the zip function that lives on the Filestack Client
*returns* [Filestack.Transform]
"""
params = locals()
params.pop('store')
params.pop('store_par... |
def inject(self, inst, **renames):
"""Injects dependencies and propagates dependency injector"""
if renames:
di = self.clone(**renames)
else:
di = self
pro = di._provides
inst.__injections_source__ = di
deps = getattr(inst, '__injections__', None)
... | def function[inject, parameter[self, inst]]:
constant[Injects dependencies and propagates dependency injector]
if name[renames] begin[:]
variable[di] assign[=] call[name[self].clone, parameter[]]
variable[pro] assign[=] name[di]._provides
name[inst].__injections_source__ ... | keyword[def] identifier[inject] ( identifier[self] , identifier[inst] ,** identifier[renames] ):
literal[string]
keyword[if] identifier[renames] :
identifier[di] = identifier[self] . identifier[clone] (** identifier[renames] )
keyword[else] :
identifier[di] = ide... | def inject(self, inst, **renames):
"""Injects dependencies and propagates dependency injector"""
if renames:
di = self.clone(**renames) # depends on [control=['if'], data=[]]
else:
di = self
pro = di._provides
inst.__injections_source__ = di
deps = getattr(inst, '__injections__'... |
def union_update(self, *others):
r"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. How... | def function[union_update, parameter[self]]:
constant[Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the... | keyword[def] identifier[union_update] ( identifier[self] ,* identifier[others] ):
literal[string]
identifier[_elements] = identifier[self] . identifier[_elements]
identifier[_total] = identifier[self] . identifier[_total]
keyword[for] identifier[other] keyword[in] identifier[... | def union_update(self, *others):
"""Update the multiset, adding elements from all others using the maximum multiplicity.
>>> ms = Multiset('aab')
>>> ms.union_update('bc')
>>> sorted(ms)
['a', 'a', 'b', 'c']
You can also use the ``|=`` operator for the same effect. However,... |
def extend(self, items):
""" Adds @items to the end of the list
-> #int length of list after operation
"""
if items:
if self.serialized:
items = list(map(self._dumps, items))
self._client.rpush(self.key_prefix, *items) | def function[extend, parameter[self, items]]:
constant[ Adds @items to the end of the list
-> #int length of list after operation
]
if name[items] begin[:]
if name[self].serialized begin[:]
variable[items] assign[=] call[name[list], parameter[c... | keyword[def] identifier[extend] ( identifier[self] , identifier[items] ):
literal[string]
keyword[if] identifier[items] :
keyword[if] identifier[self] . identifier[serialized] :
identifier[items] = identifier[list] ( identifier[map] ( identifier[self] . identifier[_d... | def extend(self, items):
""" Adds @items to the end of the list
-> #int length of list after operation
"""
if items:
if self.serialized:
items = list(map(self._dumps, items)) # depends on [control=['if'], data=[]]
self._client.rpush(self.key_prefix, *items) # de... |
def remove(self, id):
""" Remove a prefix.
"""
# find prefix
c.prefix = Prefix.get(int(id))
if 'confirmed' not in request.params:
return render('/prefix_remove_confirm.html')
c.prefix.remove()
redirect(url(controller='prefix', action='list')) | def function[remove, parameter[self, id]]:
constant[ Remove a prefix.
]
name[c].prefix assign[=] call[name[Prefix].get, parameter[call[name[int], parameter[name[id]]]]]
if compare[constant[confirmed] <ast.NotIn object at 0x7da2590d7190> name[request].params] begin[:]
return[call[... | keyword[def] identifier[remove] ( identifier[self] , identifier[id] ):
literal[string]
identifier[c] . identifier[prefix] = identifier[Prefix] . identifier[get] ( identifier[int] ( identifier[id] ))
keyword[if] literal[string] keyword[not] keyword[in] identifier[request] . i... | def remove(self, id):
""" Remove a prefix.
"""
# find prefix
c.prefix = Prefix.get(int(id))
if 'confirmed' not in request.params:
return render('/prefix_remove_confirm.html') # depends on [control=['if'], data=[]]
c.prefix.remove()
redirect(url(controller='prefix', action='list'... |
def __get_supported_file_types_string(self):
"""
Returns the supported file types dialog string.
"""
languages = ["All Files (*)"]
for language in self.__languages_model.languages:
languages.append("{0} Files ({1})".format(language.name,
... | def function[__get_supported_file_types_string, parameter[self]]:
constant[
Returns the supported file types dialog string.
]
variable[languages] assign[=] list[[<ast.Constant object at 0x7da1b0911870>]]
for taget[name[language]] in starred[name[self].__languages_model.languages]... | keyword[def] identifier[__get_supported_file_types_string] ( identifier[self] ):
literal[string]
identifier[languages] =[ literal[string] ]
keyword[for] identifier[language] keyword[in] identifier[self] . identifier[__languages_model] . identifier[languages] :
identifier[l... | def __get_supported_file_types_string(self):
"""
Returns the supported file types dialog string.
"""
languages = ['All Files (*)']
for language in self.__languages_model.languages:
languages.append('{0} Files ({1})'.format(language.name, ' '.join(language.extensions.split('|')).repla... |
def seq_sha512(seq, normalize=True):
"""returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67... | def function[seq_sha512, parameter[seq, normalize]]:
constant[returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
... | keyword[def] identifier[seq_sha512] ( identifier[seq] , identifier[normalize] = keyword[True] ):
literal[string]
identifier[seq] = identifier[normalize_sequence] ( identifier[seq] ) keyword[if] identifier[normalize] keyword[else] identifier[seq]
identifier[bseq] = identifier[seq] . identifier[enc... | def seq_sha512(seq, normalize=True):
"""returns unicode sequence sha512 hexdigest for sequence `seq`.
>>> seq_sha512('')
'cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e'
>>> seq_sha512('ACGT')
'68a178f7c740c5c240aa67... |
def __getNetworkStateDirectory(self, extraDataDir):
"""
extraDataDir:
Model's extra data directory path
Returns: Absolute directory path for saving CLA Network
"""
if self.__restoringFromV1:
if self.getInferenceType() == InferenceType.TemporalNextStep:
leafName =... | def function[__getNetworkStateDirectory, parameter[self, extraDataDir]]:
constant[
extraDataDir:
Model's extra data directory path
Returns: Absolute directory path for saving CLA Network
]
if name[self].__restoringFromV1 begin[:]
if compare[call[name[se... | keyword[def] identifier[__getNetworkStateDirectory] ( identifier[self] , identifier[extraDataDir] ):
literal[string]
keyword[if] identifier[self] . identifier[__restoringFromV1] :
keyword[if] identifier[self] . identifier[getInferenceType] ()== identifier[InferenceType] . identifier[TemporalNextSt... | def __getNetworkStateDirectory(self, extraDataDir):
"""
extraDataDir:
Model's extra data directory path
Returns: Absolute directory path for saving CLA Network
"""
if self.__restoringFromV1:
if self.getInferenceType() == InferenceType.TemporalNextStep:
leaf... |
def to_query(self):
"""
Returns a json-serializable representation.
"""
return {
self.name: {
'lang': self.lang,
'script': self.script,
'params': self.script_params
}
} | def function[to_query, parameter[self]]:
constant[
Returns a json-serializable representation.
]
return[dictionary[[<ast.Attribute object at 0x7da20c7cb1f0>], [<ast.Dict object at 0x7da20c7caa70>]]] | keyword[def] identifier[to_query] ( identifier[self] ):
literal[string]
keyword[return] {
identifier[self] . identifier[name] :{
literal[string] : identifier[self] . identifier[lang] ,
literal[string] : identifier[self] . identifier[script] ,
literal[string] : id... | def to_query(self):
"""
Returns a json-serializable representation.
"""
return {self.name: {'lang': self.lang, 'script': self.script, 'params': self.script_params}} |
def put_conf(self, configuration, test=False):
"""Send the configuration to the satellite
HTTP request to the satellite (POST /push_configuration)
If test is True, store the configuration internally
:param configuration: The conf to send (data depend on the satellite)
:type con... | def function[put_conf, parameter[self, configuration, test]]:
constant[Send the configuration to the satellite
HTTP request to the satellite (POST /push_configuration)
If test is True, store the configuration internally
:param configuration: The conf to send (data depend on the satelli... | keyword[def] identifier[put_conf] ( identifier[self] , identifier[configuration] , identifier[test] = keyword[False] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[self] . identifier[name] , identifier[self] . identifier[alive] , identifier[self] . identifi... | def put_conf(self, configuration, test=False):
"""Send the configuration to the satellite
HTTP request to the satellite (POST /push_configuration)
If test is True, store the configuration internally
:param configuration: The conf to send (data depend on the satellite)
:type configu... |
def _get_adjtime_timezone():
'''
Return the timezone in /etc/adjtime of the system clock
'''
adjtime_file = '/etc/adjtime'
if os.path.exists(adjtime_file):
cmd = ['tail', '-n', '1', adjtime_file]
return __salt__['cmd.run'](cmd, python_shell=False)
elif os.path.exists('/dev/rtc'):... | def function[_get_adjtime_timezone, parameter[]]:
constant[
Return the timezone in /etc/adjtime of the system clock
]
variable[adjtime_file] assign[=] constant[/etc/adjtime]
if call[name[os].path.exists, parameter[name[adjtime_file]]] begin[:]
variable[cmd] assign[=] list... | keyword[def] identifier[_get_adjtime_timezone] ():
literal[string]
identifier[adjtime_file] = literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[adjtime_file] ):
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , identifier[... | def _get_adjtime_timezone():
"""
Return the timezone in /etc/adjtime of the system clock
"""
adjtime_file = '/etc/adjtime'
if os.path.exists(adjtime_file):
cmd = ['tail', '-n', '1', adjtime_file]
return __salt__['cmd.run'](cmd, python_shell=False) # depends on [control=['if'], data=... |
def get_params(self, deep=True):
"""Get parameters for this estimator.
Parameters
----------
deep : bool, optional (default=True)
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------... | def function[get_params, parameter[self, deep]]:
constant[Get parameters for this estimator.
Parameters
----------
deep : bool, optional (default=True)
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
R... | keyword[def] identifier[get_params] ( identifier[self] , identifier[deep] = keyword[True] ):
literal[string]
identifier[params] = identifier[super] ( identifier[LGBMModel] , identifier[self] ). identifier[get_params] ( identifier[deep] = identifier[deep] )
identifier[params] . identifier[u... | def get_params(self, deep=True):
"""Get parameters for this estimator.
Parameters
----------
deep : bool, optional (default=True)
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
... |
def Fold(seglist1, seglist2):
"""
An iterator that generates the results of taking the intersection
of seglist1 with each segment in seglist2 in turn. In each result,
the segment start and stop values are adjusted to be with respect
to the start of the corresponding segment in seglist2. See also
the segmentlist... | def function[Fold, parameter[seglist1, seglist2]]:
constant[
An iterator that generates the results of taking the intersection
of seglist1 with each segment in seglist2 in turn. In each result,
the segment start and stop values are adjusted to be with respect
to the start of the corresponding segment in se... | keyword[def] identifier[Fold] ( identifier[seglist1] , identifier[seglist2] ):
literal[string]
keyword[for] identifier[seg] keyword[in] identifier[seglist2] :
keyword[yield] ( identifier[seglist1] & identifier[segments] . identifier[segmentlist] ([ identifier[seg] ])). identifier[shift] (- identifier[seg] ... | def Fold(seglist1, seglist2):
"""
An iterator that generates the results of taking the intersection
of seglist1 with each segment in seglist2 in turn. In each result,
the segment start and stop values are adjusted to be with respect
to the start of the corresponding segment in seglist2. See also
the segmentl... |
def Chueh_Prausnitz_Vc(zs, Vcs, nus):
r'''Calculates critical volume of a mixture according to
mixing rules in [1]_ with an interaction parameter.
.. math::
V_{cm} = \sum_i^n \theta_i V_{ci} + \sum_i^n\sum_j^n(\theta_i \theta_j \nu_{ij})V_{ref}
\theta = \frac{x_i V_{ci}^{2/3}}{\sum_{j=1}^n ... | def function[Chueh_Prausnitz_Vc, parameter[zs, Vcs, nus]]:
constant[Calculates critical volume of a mixture according to
mixing rules in [1]_ with an interaction parameter.
.. math::
V_{cm} = \sum_i^n \theta_i V_{ci} + \sum_i^n\sum_j^n(\theta_i \theta_j \nu_{ij})V_{ref}
\theta = \frac{x... | keyword[def] identifier[Chueh_Prausnitz_Vc] ( identifier[zs] , identifier[Vcs] , identifier[nus] ):
literal[string]
keyword[if] keyword[not] identifier[none_and_length_check] ([ identifier[zs] , identifier[Vcs] ]):
keyword[raise] identifier[Exception] ( literal[string] )
identifier[denomi... | def Chueh_Prausnitz_Vc(zs, Vcs, nus):
"""Calculates critical volume of a mixture according to
mixing rules in [1]_ with an interaction parameter.
.. math::
V_{cm} = \\sum_i^n \\theta_i V_{ci} + \\sum_i^n\\sum_j^n(\\theta_i \\theta_j \\nu_{ij})V_{ref}
\\theta = \\frac{x_i V_{ci}^{2/3}}{\\sum... |
def parse_headers(fp, _class=http.client.HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct byte... | def function[parse_headers, parameter[fp, _class]]:
constant[Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the co... | keyword[def] identifier[parse_headers] ( identifier[fp] , identifier[_class] = identifier[http] . identifier[client] . identifier[HTTPMessage] ):
literal[string]
identifier[headers] =[]
keyword[while] keyword[True] :
identifier[line] = identifier[fp] . identifier[readline] ( identifier[http] . identifier[c... | def parse_headers(fp, _class=http.client.HTTPMessage):
"""Parses only RFC2822 headers from a file pointer.
email Parser wants to see strings rather than bytes.
But a TextIOWrapper around self.rfile would buffer too many bytes
from the stream, bytes which we later need to read as bytes.
So we read the correct b... |
def sentences(self, nb=3, ext_word_list=None):
"""
Generate an array of sentences
:example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.']
Keyword arguments:
:param nb: how many sentences to return
:param ext_word_list: a list of words you would like to h... | def function[sentences, parameter[self, nb, ext_word_list]]:
constant[
Generate an array of sentences
:example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.']
Keyword arguments:
:param nb: how many sentences to return
:param ext_word_list: a list of words... | keyword[def] identifier[sentences] ( identifier[self] , identifier[nb] = literal[int] , identifier[ext_word_list] = keyword[None] ):
literal[string]
keyword[return] [ identifier[self] . identifier[sentence] ( identifier[ext_word_list] = identifier[ext_word_list] )
keyword[for] identifier[... | def sentences(self, nb=3, ext_word_list=None):
"""
Generate an array of sentences
:example ['Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.']
Keyword arguments:
:param nb: how many sentences to return
:param ext_word_list: a list of words you would like to have ... |
def substring_index(str, delim, count):
"""
Returns the substring from string str before count occurrences of the delimiter delim.
If count is positive, everything the left of the final delimiter (counting from left) is
returned. If count is negative, every to the right of the final delimiter (counting ... | def function[substring_index, parameter[str, delim, count]]:
constant[
Returns the substring from string str before count occurrences of the delimiter delim.
If count is positive, everything the left of the final delimiter (counting from left) is
returned. If count is negative, every to the right of... | keyword[def] identifier[substring_index] ( identifier[str] , identifier[delim] , identifier[count] ):
literal[string]
identifier[sc] = identifier[SparkContext] . identifier[_active_spark_context]
keyword[return] identifier[Column] ( identifier[sc] . identifier[_jvm] . identifier[functions] . identif... | def substring_index(str, delim, count):
"""
Returns the substring from string str before count occurrences of the delimiter delim.
If count is positive, everything the left of the final delimiter (counting from left) is
returned. If count is negative, every to the right of the final delimiter (counting ... |
def fix_music(file_name):
'''
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
'''
setup()
if not Py3:
file_name = file_name.encode('utf-8')
tags = File(file_name)
log.log(file_name)
... | def function[fix_music, parameter[file_name]]:
constant[
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
]
call[name[setup], parameter[]]
if <ast.UnaryOp object at 0x7da1b27bb520> begin[:]
... | keyword[def] identifier[fix_music] ( identifier[file_name] ):
literal[string]
identifier[setup] ()
keyword[if] keyword[not] identifier[Py3] :
identifier[file_name] = identifier[file_name] . identifier[encode] ( literal[string] )
identifier[tags] = identifier[File] ( identifier[file_... | def fix_music(file_name):
"""
Searches for '.mp3' files in directory (optionally recursive)
and checks whether they already contain album art and album name tags or not.
"""
setup()
if not Py3:
file_name = file_name.encode('utf-8') # depends on [control=['if'], data=[]]
tags = File(... |
def update_pop(self):
"""Assigns fitnesses to particles that are within bounds."""
valid_particles = []
invalid_particles = []
for part in self.population:
if any(x > 1 or x < -1 for x in part):
invalid_particles.append(part)
else:
... | def function[update_pop, parameter[self]]:
constant[Assigns fitnesses to particles that are within bounds.]
variable[valid_particles] assign[=] list[[]]
variable[invalid_particles] assign[=] list[[]]
for taget[name[part]] in starred[name[self].population] begin[:]
if call... | keyword[def] identifier[update_pop] ( identifier[self] ):
literal[string]
identifier[valid_particles] =[]
identifier[invalid_particles] =[]
keyword[for] identifier[part] keyword[in] identifier[self] . identifier[population] :
keyword[if] identifier[any] ( identifi... | def update_pop(self):
"""Assigns fitnesses to particles that are within bounds."""
valid_particles = []
invalid_particles = []
for part in self.population:
if any((x > 1 or x < -1 for x in part)):
invalid_particles.append(part) # depends on [control=['if'], data=[]]
else:
... |
def _st_decode(self, msg):
"""ST: Temperature update."""
group = int(msg[4:5])
temperature = int(msg[7:10])
if group == 0:
temperature -= 60
elif group == 1:
temperature -= 40
return {'group': group, 'device': int(msg[5:7])-1,
'temp... | def function[_st_decode, parameter[self, msg]]:
constant[ST: Temperature update.]
variable[group] assign[=] call[name[int], parameter[call[name[msg]][<ast.Slice object at 0x7da18eb577c0>]]]
variable[temperature] assign[=] call[name[int], parameter[call[name[msg]][<ast.Slice object at 0x7da18eb54... | keyword[def] identifier[_st_decode] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[group] = identifier[int] ( identifier[msg] [ literal[int] : literal[int] ])
identifier[temperature] = identifier[int] ( identifier[msg] [ literal[int] : literal[int] ])
keyword[i... | def _st_decode(self, msg):
"""ST: Temperature update."""
group = int(msg[4:5])
temperature = int(msg[7:10])
if group == 0:
temperature -= 60 # depends on [control=['if'], data=[]]
elif group == 1:
temperature -= 40 # depends on [control=['if'], data=[]]
return {'group': group, ... |
def run(self):
"""
Actual run method that starts the processing of jobs and initiates the status polling, or
performs job cancelling or cleaning, depending on the task parameters.
"""
task = self.task
self._outputs = self.output()
# create the job dashboard inter... | def function[run, parameter[self]]:
constant[
Actual run method that starts the processing of jobs and initiates the status polling, or
performs job cancelling or cleaning, depending on the task parameters.
]
variable[task] assign[=] name[self].task
name[self]._outputs as... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[task] = identifier[self] . identifier[task]
identifier[self] . identifier[_outputs] = identifier[self] . identifier[output] ()
identifier[self] . identifier[dashboard] = identifier[task] . ide... | def run(self):
"""
Actual run method that starts the processing of jobs and initiates the status polling, or
performs job cancelling or cleaning, depending on the task parameters.
"""
task = self.task
self._outputs = self.output()
# create the job dashboard interface
self.das... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.