code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _loop_use_cache(self, helper_function, num, fragment):
""" Synthesize all fragments using the cache """
self.log([u"Examining fragment %d (cache)...", num])
fragment_info = (fragment.language, fragment.filtered_text)
if self.cache.is_cached(fragment_info):
self.log(u"Frag... | def function[_loop_use_cache, parameter[self, helper_function, num, fragment]]:
constant[ Synthesize all fragments using the cache ]
call[name[self].log, parameter[list[[<ast.Constant object at 0x7da1b1882680>, <ast.Name object at 0x7da1b1881120>]]]]
variable[fragment_info] assign[=] tuple[[<ast... | keyword[def] identifier[_loop_use_cache] ( identifier[self] , identifier[helper_function] , identifier[num] , identifier[fragment] ):
literal[string]
identifier[self] . identifier[log] ([ literal[string] , identifier[num] ])
identifier[fragment_info] =( identifier[fragment] . identifier[la... | def _loop_use_cache(self, helper_function, num, fragment):
""" Synthesize all fragments using the cache """
self.log([u'Examining fragment %d (cache)...', num])
fragment_info = (fragment.language, fragment.filtered_text)
if self.cache.is_cached(fragment_info):
self.log(u'Fragment cached: retriev... |
def get_settings(self, index=None, name=None, params=None):
"""
Retrieve settings for one or more (or all) indices.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
... | def function[get_settings, parameter[self, index, name, params]]:
constant[
Retrieve settings for one or more (or all) indices.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html>`_
:arg index: A comma-separated list of index names; use `_all` or ... | keyword[def] identifier[get_settings] ( identifier[self] , identifier[index] = keyword[None] , identifier[name] = keyword[None] , identifier[params] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[transport] . identifier[perform_request] (
literal[string] ... | def get_settings(self, index=None, name=None, params=None):
"""
Retrieve settings for one or more (or all) indices.
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/indices-get-settings.html>`_
:arg index: A comma-separated list of index names; use `_all` or empty
... |
def crypto_sign(message, sk):
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = ffi.new("unsigned l... | def function[crypto_sign, parameter[message, sk]]:
constant[
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
]
variable[signed] assign[=] call[name[ffi].new, parameter[constant[unsigne... | keyword[def] identifier[crypto_sign] ( identifier[message] , identifier[sk] ):
literal[string]
identifier[signed] = identifier[ffi] . identifier[new] ( literal[string] , identifier[len] ( identifier[message] )+ identifier[crypto_sign_BYTES] )
identifier[signed_len] = identifier[ffi] . identifier[new] ... | def crypto_sign(message, sk):
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new('unsigned char[]', len(message) + crypto_sign_BYTES)
signed_len = ffi.new('unsigned l... |
def __range(a, bins):
'''Compute the histogram range of the values in the array a according to
scipy.stats.histogram.'''
a = numpy.asarray(a)
a_max = a.max()
a_min = a.min()
s = 0.5 * (a_max - a_min) / float(bins - 1)
return (a_min - s, a_max + s) | def function[__range, parameter[a, bins]]:
constant[Compute the histogram range of the values in the array a according to
scipy.stats.histogram.]
variable[a] assign[=] call[name[numpy].asarray, parameter[name[a]]]
variable[a_max] assign[=] call[name[a].max, parameter[]]
variable[a_mi... | keyword[def] identifier[__range] ( identifier[a] , identifier[bins] ):
literal[string]
identifier[a] = identifier[numpy] . identifier[asarray] ( identifier[a] )
identifier[a_max] = identifier[a] . identifier[max] ()
identifier[a_min] = identifier[a] . identifier[min] ()
identifier[s] = liter... | def __range(a, bins):
"""Compute the histogram range of the values in the array a according to
scipy.stats.histogram."""
a = numpy.asarray(a)
a_max = a.max()
a_min = a.min()
s = 0.5 * (a_max - a_min) / float(bins - 1)
return (a_min - s, a_max + s) |
def make(self):
""" reads through the definitions and generates an python class for each
definition """
log.setLevel(self.log_level)
created = []
prop_list = [item for item in self.defs if item.type == 'uri']
log.debug(" creating properties ... ")
for prop in prop... | def function[make, parameter[self]]:
constant[ reads through the definitions and generates an python class for each
definition ]
call[name[log].setLevel, parameter[name[self].log_level]]
variable[created] assign[=] list[[]]
variable[prop_list] assign[=] <ast.ListComp object at 0x... | keyword[def] identifier[make] ( identifier[self] ):
literal[string]
identifier[log] . identifier[setLevel] ( identifier[self] . identifier[log_level] )
identifier[created] =[]
identifier[prop_list] =[ identifier[item] keyword[for] identifier[item] keyword[in] identifier[self] ... | def make(self):
""" reads through the definitions and generates an python class for each
definition """
log.setLevel(self.log_level)
created = []
prop_list = [item for item in self.defs if item.type == 'uri']
log.debug(' creating properties ... ')
for prop in prop_list:
make_prop... |
def wcparams(mol, type_):
"""
Calculate Wildman-Crippen logP
Wildman S., Crippen G., Prediction of Physicochemical Parameters by Atomic
Contribution, J. Chem. Inf. Model. 39 (1999) 868-873
"""
try:
assign_wctype(mol)
except:
return "N/A"
scores = []
for i, atom in mol... | def function[wcparams, parameter[mol, type_]]:
constant[
Calculate Wildman-Crippen logP
Wildman S., Crippen G., Prediction of Physicochemical Parameters by Atomic
Contribution, J. Chem. Inf. Model. 39 (1999) 868-873
]
<ast.Try object at 0x7da1b2446230>
variable[scores] assign[=] list... | keyword[def] identifier[wcparams] ( identifier[mol] , identifier[type_] ):
literal[string]
keyword[try] :
identifier[assign_wctype] ( identifier[mol] )
keyword[except] :
keyword[return] literal[string]
identifier[scores] =[]
keyword[for] identifier[i] , identifier[atom] ... | def wcparams(mol, type_):
"""
Calculate Wildman-Crippen logP
Wildman S., Crippen G., Prediction of Physicochemical Parameters by Atomic
Contribution, J. Chem. Inf. Model. 39 (1999) 868-873
"""
try:
assign_wctype(mol) # depends on [control=['try'], data=[]]
except:
return 'N/... |
def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
"""
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
... | def function[add_item, parameter[self, path, name, icon, url, order, permission, active_regex]]:
constant[
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
... | keyword[def] identifier[add_item] ( identifier[self] , identifier[path] , identifier[name] , identifier[icon] = keyword[None] , identifier[url] = keyword[None] , identifier[order] = keyword[None] , identifier[permission] = keyword[None] , identifier[active_regex] = keyword[None] ):
literal[string]
... | def add_item(self, path, name, icon=None, url=None, order=None, permission=None, active_regex=None):
"""
Add new menu item to menu
:param path: Path of menu
:param name: Display name
:param icon: CSS icon
:param url: link to page
:param order: Sort order
:par... |
def get_user_data(self):
"""
Extracts user data, either from user session or from
database (for each User, an InfoObject is used to
store data of a certain kind (e.g., user customization,
saved searches, etc.). If for a given user,
no InfoObject exists for a given type of... | def function[get_user_data, parameter[self]]:
constant[
Extracts user data, either from user session or from
database (for each User, an InfoObject is used to
store data of a certain kind (e.g., user customization,
saved searches, etc.). If for a given user,
no InfoObject... | keyword[def] identifier[get_user_data] ( identifier[self] ):
literal[string]
identifier[settings] = identifier[self] . identifier[request] . identifier[session] . identifier[get] (... | def get_user_data(self):
"""
Extracts user data, either from user session or from
database (for each User, an InfoObject is used to
store data of a certain kind (e.g., user customization,
saved searches, etc.). If for a given user,
no InfoObject exists for a given type of use... |
def _remove_vlan_from_all_sp_templates(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN config from all SP Templates that have it."""
sp_template_info_list = (
CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].sp_template_list.values())
vlan_name = self.make_vlan_name(vlan_id)
virtio_port_... | def function[_remove_vlan_from_all_sp_templates, parameter[self, handle, vlan_id, ucsm_ip]]:
constant[Deletes VLAN config from all SP Templates that have it.]
variable[sp_template_info_list] assign[=] call[call[name[CONF].ml2_cisco_ucsm.ucsms][name[ucsm_ip]].sp_template_list.values, parameter[]]
... | keyword[def] identifier[_remove_vlan_from_all_sp_templates] ( identifier[self] , identifier[handle] , identifier[vlan_id] , identifier[ucsm_ip] ):
literal[string]
identifier[sp_template_info_list] =(
identifier[CONF] . identifier[ml2_cisco_ucsm] . identifier[ucsms] [ identifier[ucsm_ip] ].... | def _remove_vlan_from_all_sp_templates(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN config from all SP Templates that have it."""
sp_template_info_list = CONF.ml2_cisco_ucsm.ucsms[ucsm_ip].sp_template_list.values()
vlan_name = self.make_vlan_name(vlan_id)
virtio_port_list = CONF.ml2_cisco_ucsm.ucsms... |
def _strip_unsafe_kubernetes_special_chars(string):
"""
Kubernetes only supports lowercase alphanumeric characters and "-" and "." in
the pod name
However, there are special rules about how "-" and "." can be used so let's
only keep
alphanumeric chars see here for detail... | def function[_strip_unsafe_kubernetes_special_chars, parameter[string]]:
constant[
Kubernetes only supports lowercase alphanumeric characters and "-" and "." in
the pod name
However, there are special rules about how "-" and "." can be used so let's
only keep
alphanumeric... | keyword[def] identifier[_strip_unsafe_kubernetes_special_chars] ( identifier[string] ):
literal[string]
keyword[return] literal[string] . identifier[join] ( identifier[ch] . identifier[lower] () keyword[for] identifier[ind] , identifier[ch] keyword[in] identifier[enumerate] ( identifier[string]... | def _strip_unsafe_kubernetes_special_chars(string):
"""
Kubernetes only supports lowercase alphanumeric characters and "-" and "." in
the pod name
However, there are special rules about how "-" and "." can be used so let's
only keep
alphanumeric chars see here for detail:
... |
def add_net(self, net):
""" Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector."""
self.sanity_check_net(net)
... | def function[add_net, parameter[self, net]]:
constant[ Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector.]
call[name[s... | keyword[def] identifier[add_net] ( identifier[self] , identifier[net] ):
literal[string]
identifier[self] . identifier[sanity_check_net] ( identifier[net] )
identifier[self] . identifier[logic] . identifier[add] ( identifier[net] ) | def add_net(self, net):
""" Add a net to the logic of the block.
The passed net, which must be of type LogicNet, is checked and then
added to the block. No wires are added by this member, they must be
added seperately with add_wirevector."""
self.sanity_check_net(net)
self.logic.ad... |
def obfn_gvar(self):
"""Variable to be evaluated in computing regularisation term,
depending on 'gEvalY' option value.
"""
if self.opt['gEvalY']:
return self.Y
else:
return self.cnst_A(None, self.Xf) - self.cnst_c() | def function[obfn_gvar, parameter[self]]:
constant[Variable to be evaluated in computing regularisation term,
depending on 'gEvalY' option value.
]
if call[name[self].opt][constant[gEvalY]] begin[:]
return[name[self].Y] | keyword[def] identifier[obfn_gvar] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[opt] [ literal[string] ]:
keyword[return] identifier[self] . identifier[Y]
keyword[else] :
keyword[return] identifier[self] . identifier[cnst_A]... | def obfn_gvar(self):
"""Variable to be evaluated in computing regularisation term,
depending on 'gEvalY' option value.
"""
if self.opt['gEvalY']:
return self.Y # depends on [control=['if'], data=[]]
else:
return self.cnst_A(None, self.Xf) - self.cnst_c() |
def _get_all_tags(conn, load_balancer_names=None):
'''
Retrieve all the metadata tags associated with your ELB(s).
:type load_balancer_names: list
:param load_balancer_names: An optional list of load balancer names.
:rtype: list
:return: A list of :class:`boto.ec2.elb.tag.Tag` objects
'''
... | def function[_get_all_tags, parameter[conn, load_balancer_names]]:
constant[
Retrieve all the metadata tags associated with your ELB(s).
:type load_balancer_names: list
:param load_balancer_names: An optional list of load balancer names.
:rtype: list
:return: A list of :class:`boto.ec2.elb... | keyword[def] identifier[_get_all_tags] ( identifier[conn] , identifier[load_balancer_names] = keyword[None] ):
literal[string]
identifier[params] ={}
keyword[if] identifier[load_balancer_names] :
identifier[conn] . identifier[build_list_params] ( identifier[params] , identifier[load_balancer... | def _get_all_tags(conn, load_balancer_names=None):
"""
Retrieve all the metadata tags associated with your ELB(s).
:type load_balancer_names: list
:param load_balancer_names: An optional list of load balancer names.
:rtype: list
:return: A list of :class:`boto.ec2.elb.tag.Tag` objects
"""
... |
def setup_client(self):
"""The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
Note:
If ... | def function[setup_client, parameter[self]]:
constant[The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
... | keyword[def] identifier[setup_client] ( identifier[self] ):
literal[string]
identifier[params] ={
literal[string] : identifier[self] . identifier[authorization_redirect_uri] ,
literal[string] : literal[string] ,
}
keyword[for] identifier[op] k... | def setup_client(self):
"""The command registers the client for communication protection. This
will be used to obtain an access token via the Get Client Token
command. The access token will be passed as a protection_access_token
parameter to other commands.
Note:
If you ... |
def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False):
"""
Combine send and receive measurement into single function.
This offers a retry mechanism: Overall timeout time is divided by
number of retries. Additional ICMPecho packets are sent to those
addresses from which we have no... | def function[multi_ping, parameter[dest_addrs, timeout, retry, ignore_lookup_errors]]:
constant[
Combine send and receive measurement into single function.
This offers a retry mechanism: Overall timeout time is divided by
number of retries. Additional ICMPecho packets are sent to those
addresse... | keyword[def] identifier[multi_ping] ( identifier[dest_addrs] , identifier[timeout] , identifier[retry] = literal[int] , identifier[ignore_lookup_errors] = keyword[False] ):
literal[string]
identifier[retry] = identifier[int] ( identifier[retry] )
keyword[if] identifier[retry] < literal[int] :
... | def multi_ping(dest_addrs, timeout, retry=0, ignore_lookup_errors=False):
"""
Combine send and receive measurement into single function.
This offers a retry mechanism: Overall timeout time is divided by
number of retries. Additional ICMPecho packets are sent to those
addresses from which we have no... |
def delete(self, group_id, session):
'''taobao.crm.group.delete 删除分组
将该分组下的所有会员移除出该组,同时删除该分组。注:删除分组为异步任务,必须先调用taobao.crm.grouptask.check 确保涉及属性上没有任务。'''
request = TOPRequest('taobao.crm.group.delete')
request['group_id'] = group_id
self.create(self.execute(request, sessi... | def function[delete, parameter[self, group_id, session]]:
constant[taobao.crm.group.delete 删除分组
将该分组下的所有会员移除出该组,同时删除该分组。注:删除分组为异步任务,必须先调用taobao.crm.grouptask.check 确保涉及属性上没有任务。]
variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.crm.group.delete]]]
call... | keyword[def] identifier[delete] ( identifier[self] , identifier[group_id] , identifier[session] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
identifier[request] [ literal[string] ]= identifier[group_id]
identifier[self] . identifier[create] ... | def delete(self, group_id, session):
"""taobao.crm.group.delete 删除分组
将该分组下的所有会员移除出该组,同时删除该分组。注:删除分组为异步任务,必须先调用taobao.crm.grouptask.check 确保涉及属性上没有任务。"""
request = TOPRequest('taobao.crm.group.delete')
request['group_id'] = group_id
self.create(self.execute(request, session), fields=['is... |
def _add_reference(self, obj, ident=0):
"""
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
"""
log_debug(
"## New reference handle 0x{0:X}: {1} -> {2}".format(
len(self.reference... | def function[_add_reference, parameter[self, obj, ident]]:
constant[
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
]
call[name[log_debug], parameter[call[constant[## New reference handle 0x{0:X}: {1} -> {2... | keyword[def] identifier[_add_reference] ( identifier[self] , identifier[obj] , identifier[ident] = literal[int] ):
literal[string]
identifier[log_debug] (
literal[string] . identifier[format] (
identifier[len] ( identifier[self] . identifier[references] )+ identifier[self] . ident... | def _add_reference(self, obj, ident=0):
"""
Adds a read reference to the marshaler storage
:param obj: Reference to add
:param ident: Log indentation level
"""
log_debug('## New reference handle 0x{0:X}: {1} -> {2}'.format(len(self.references) + self.BASE_REFERENCE_IDX, type(obj... |
def xAxisIsMinor(self):
'''
Returns True if the minor axis is parallel to the X axis, boolean.
'''
return min(self.radius.x, self.radius.y) == self.radius.x | def function[xAxisIsMinor, parameter[self]]:
constant[
Returns True if the minor axis is parallel to the X axis, boolean.
]
return[compare[call[name[min], parameter[name[self].radius.x, name[self].radius.y]] equal[==] name[self].radius.x]] | keyword[def] identifier[xAxisIsMinor] ( identifier[self] ):
literal[string]
keyword[return] identifier[min] ( identifier[self] . identifier[radius] . identifier[x] , identifier[self] . identifier[radius] . identifier[y] )== identifier[self] . identifier[radius] . identifier[x] | def xAxisIsMinor(self):
"""
Returns True if the minor axis is parallel to the X axis, boolean.
"""
return min(self.radius.x, self.radius.y) == self.radius.x |
def space_angle(phi1, theta1, phi2, theta2):
"""Also called Great-circle-distance --
use long-ass formula from wikipedia (last in section):
https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
Space angle only makes sense in lon-lat, so convert zenith -> latitude.
"""
from... | def function[space_angle, parameter[phi1, theta1, phi2, theta2]]:
constant[Also called Great-circle-distance --
use long-ass formula from wikipedia (last in section):
https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
Space angle only makes sense in lon-lat, so convert zenit... | keyword[def] identifier[space_angle] ( identifier[phi1] , identifier[theta1] , identifier[phi2] , identifier[theta2] ):
literal[string]
keyword[from] identifier[numpy] keyword[import] identifier[pi] , identifier[sin] , identifier[cos] , identifier[arctan2] , identifier[sqrt] , identifier[square]
i... | def space_angle(phi1, theta1, phi2, theta2):
"""Also called Great-circle-distance --
use long-ass formula from wikipedia (last in section):
https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas
Space angle only makes sense in lon-lat, so convert zenith -> latitude.
"""
from... |
def dispatch():
"""
This methods runs the wheel. It is used to connect signal with their handlers, based on the aliases.
:return:
"""
aliases = SignalDispatcher.signals.keys()
for alias in aliases:
handlers = SignalDispatcher.handlers.get(alias)
... | def function[dispatch, parameter[]]:
constant[
This methods runs the wheel. It is used to connect signal with their handlers, based on the aliases.
:return:
]
variable[aliases] assign[=] call[name[SignalDispatcher].signals.keys, parameter[]]
for taget[name[alias]] in sta... | keyword[def] identifier[dispatch] ():
literal[string]
identifier[aliases] = identifier[SignalDispatcher] . identifier[signals] . identifier[keys] ()
keyword[for] identifier[alias] keyword[in] identifier[aliases] :
identifier[handlers] = identifier[SignalDispatcher] . ident... | def dispatch():
"""
This methods runs the wheel. It is used to connect signal with their handlers, based on the aliases.
:return:
"""
aliases = SignalDispatcher.signals.keys()
for alias in aliases:
handlers = SignalDispatcher.handlers.get(alias)
signal = SignalDispat... |
def subject(sid, subjects_path=None, meta_data=None, default_alignment='MSMAll'):
'''
subject(sid) yields a HCP Subject object for the subject with the given subject id; sid may be a
path to a subject or a subject id, in which case the subject paths are searched for it.
subject(None, path) yields a no... | def function[subject, parameter[sid, subjects_path, meta_data, default_alignment]]:
constant[
subject(sid) yields a HCP Subject object for the subject with the given subject id; sid may be a
path to a subject or a subject id, in which case the subject paths are searched for it.
subject(None, path)... | keyword[def] identifier[subject] ( identifier[sid] , identifier[subjects_path] = keyword[None] , identifier[meta_data] = keyword[None] , identifier[default_alignment] = literal[string] ):
literal[string]
keyword[if] identifier[subjects_path] keyword[is] keyword[None] :
keyword[if] identifier[o... | def subject(sid, subjects_path=None, meta_data=None, default_alignment='MSMAll'):
"""
subject(sid) yields a HCP Subject object for the subject with the given subject id; sid may be a
path to a subject or a subject id, in which case the subject paths are searched for it.
subject(None, path) yields a no... |
def _get_adc_value(self, channel, average=None):
'''Read ADC
'''
conf = self.SCAN_OFF | self.SINGLE_ENDED | ((0x1e) & (channel << 1))
self._intf.write(self._base_addr + self.MAX_1239_ADD, array('B', pack('B', conf)))
def read_data():
ret = self._intf.read(self._base_... | def function[_get_adc_value, parameter[self, channel, average]]:
constant[Read ADC
]
variable[conf] assign[=] binary_operation[binary_operation[name[self].SCAN_OFF <ast.BitOr object at 0x7da2590d6aa0> name[self].SINGLE_ENDED] <ast.BitOr object at 0x7da2590d6aa0> binary_operation[constant[30] <as... | keyword[def] identifier[_get_adc_value] ( identifier[self] , identifier[channel] , identifier[average] = keyword[None] ):
literal[string]
identifier[conf] = identifier[self] . identifier[SCAN_OFF] | identifier[self] . identifier[SINGLE_ENDED] |(( literal[int] )&( identifier[channel] << literal[int]... | def _get_adc_value(self, channel, average=None):
"""Read ADC
"""
conf = self.SCAN_OFF | self.SINGLE_ENDED | 30 & channel << 1
self._intf.write(self._base_addr + self.MAX_1239_ADD, array('B', pack('B', conf)))
def read_data():
ret = self._intf.read(self._base_addr + self.MAX_1239_ADD | 1... |
def get_products(self, product_ids):
"""
This function (and backend API) is being obsoleted. Don't use it anymore.
"""
if self.product_set_id is None:
raise ValueError('product_set_id must be specified')
data = {'ids': product_ids}
return self.client.get(self.... | def function[get_products, parameter[self, product_ids]]:
constant[
This function (and backend API) is being obsoleted. Don't use it anymore.
]
if compare[name[self].product_set_id is constant[None]] begin[:]
<ast.Raise object at 0x7da1b10e42e0>
variable[data] assign[=] d... | keyword[def] identifier[get_products] ( identifier[self] , identifier[product_ids] ):
literal[string]
keyword[if] identifier[self] . identifier[product_set_id] keyword[is] keyword[None] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[data] ={ literal... | def get_products(self, product_ids):
"""
This function (and backend API) is being obsoleted. Don't use it anymore.
"""
if self.product_set_id is None:
raise ValueError('product_set_id must be specified') # depends on [control=['if'], data=[]]
data = {'ids': product_ids}
return s... |
def unmarshall_value(self, value):
"""
Unmarshalls a Crash object read from the database.
@type value: str
@param value: Object to convert.
@rtype: L{Crash}
@return: Converted object.
"""
value = str(value)
if self.escapeValues:
val... | def function[unmarshall_value, parameter[self, value]]:
constant[
Unmarshalls a Crash object read from the database.
@type value: str
@param value: Object to convert.
@rtype: L{Crash}
@return: Converted object.
]
variable[value] assign[=] call[name[str... | keyword[def] identifier[unmarshall_value] ( identifier[self] , identifier[value] ):
literal[string]
identifier[value] = identifier[str] ( identifier[value] )
keyword[if] identifier[self] . identifier[escapeValues] :
identifier[value] = identifier[value] . identifier[decode] (... | def unmarshall_value(self, value):
"""
Unmarshalls a Crash object read from the database.
@type value: str
@param value: Object to convert.
@rtype: L{Crash}
@return: Converted object.
"""
value = str(value)
if self.escapeValues:
value = value.decod... |
def _list_vlans_by_name(self, name):
"""Returns a list of IDs of VLANs which match the given VLAN name.
:param string name: a VLAN name
:returns: List of matching IDs
"""
results = self.list_vlans(name=name, mask='id')
return [result['id'] for result in results] | def function[_list_vlans_by_name, parameter[self, name]]:
constant[Returns a list of IDs of VLANs which match the given VLAN name.
:param string name: a VLAN name
:returns: List of matching IDs
]
variable[results] assign[=] call[name[self].list_vlans, parameter[]]
return[<as... | keyword[def] identifier[_list_vlans_by_name] ( identifier[self] , identifier[name] ):
literal[string]
identifier[results] = identifier[self] . identifier[list_vlans] ( identifier[name] = identifier[name] , identifier[mask] = literal[string] )
keyword[return] [ identifier[result] [ literal[... | def _list_vlans_by_name(self, name):
"""Returns a list of IDs of VLANs which match the given VLAN name.
:param string name: a VLAN name
:returns: List of matching IDs
"""
results = self.list_vlans(name=name, mask='id')
return [result['id'] for result in results] |
def calc_delta_c(c200):
"""Calculate characteristic overdensity from concentration.
Parameters
----------
c200 : ndarray or float
Cluster concentration parameter.
Returns
----------
ndarray or float
Cluster characteristic overdensity, of same type as c200.
"""
top =... | def function[calc_delta_c, parameter[c200]]:
constant[Calculate characteristic overdensity from concentration.
Parameters
----------
c200 : ndarray or float
Cluster concentration parameter.
Returns
----------
ndarray or float
Cluster characteristic overdensity, of same ... | keyword[def] identifier[calc_delta_c] ( identifier[c200] ):
literal[string]
identifier[top] =( literal[int] / literal[int] )* identifier[c200] ** literal[int]
identifier[bottom] = identifier[np] . identifier[log] ( literal[int] + identifier[c200] )-( identifier[c200] /( literal[int] + identifier[c200... | def calc_delta_c(c200):
"""Calculate characteristic overdensity from concentration.
Parameters
----------
c200 : ndarray or float
Cluster concentration parameter.
Returns
----------
ndarray or float
Cluster characteristic overdensity, of same type as c200.
"""
top =... |
def destroy(self):
"""
Destroy this transport
"""
self.setOnMessageReceivedCallback(None)
self.setOnNodeConnectedCallback(None)
self.setOnNodeDisconnectedCallback(None)
self.setOnReadonlyNodeConnectedCallback(None)
self.setOnReadonlyNodeDisconnectedCallba... | def function[destroy, parameter[self]]:
constant[
Destroy this transport
]
call[name[self].setOnMessageReceivedCallback, parameter[constant[None]]]
call[name[self].setOnNodeConnectedCallback, parameter[constant[None]]]
call[name[self].setOnNodeDisconnectedCallback, parame... | keyword[def] identifier[destroy] ( identifier[self] ):
literal[string]
identifier[self] . identifier[setOnMessageReceivedCallback] ( keyword[None] )
identifier[self] . identifier[setOnNodeConnectedCallback] ( keyword[None] )
identifier[self] . identifier[setOnNodeDisconnectedCall... | def destroy(self):
"""
Destroy this transport
"""
self.setOnMessageReceivedCallback(None)
self.setOnNodeConnectedCallback(None)
self.setOnNodeDisconnectedCallback(None)
self.setOnReadonlyNodeConnectedCallback(None)
self.setOnReadonlyNodeDisconnectedCallback(None)
for node in ... |
def write_frames(self, channel_id, frames_out):
"""Marshal and write multiple outgoing pamqp frames to the Socket.
:param int channel_id: Channel ID/
:param list frames_out: Amqp frames.
:return:
"""
data_out = EMPTY_BUFFER
for single_frame in frames_out:
... | def function[write_frames, parameter[self, channel_id, frames_out]]:
constant[Marshal and write multiple outgoing pamqp frames to the Socket.
:param int channel_id: Channel ID/
:param list frames_out: Amqp frames.
:return:
]
variable[data_out] assign[=] name[EMPTY_BUFFE... | keyword[def] identifier[write_frames] ( identifier[self] , identifier[channel_id] , identifier[frames_out] ):
literal[string]
identifier[data_out] = identifier[EMPTY_BUFFER]
keyword[for] identifier[single_frame] keyword[in] identifier[frames_out] :
identifier[data_out] += ... | def write_frames(self, channel_id, frames_out):
"""Marshal and write multiple outgoing pamqp frames to the Socket.
:param int channel_id: Channel ID/
:param list frames_out: Amqp frames.
:return:
"""
data_out = EMPTY_BUFFER
for single_frame in frames_out:
data_out +... |
def _populate_ranking_payoff_arrays(payoff_arrays, scores, costs):
"""
Populate the ndarrays in `payoff_arrays` with the payoff values of
the ranking game given `scores` and `costs`.
Parameters
----------
payoff_arrays : tuple(ndarray(float, ndim=2))
Tuple of 2 ndarrays of shape (n, n).... | def function[_populate_ranking_payoff_arrays, parameter[payoff_arrays, scores, costs]]:
constant[
Populate the ndarrays in `payoff_arrays` with the payoff values of
the ranking game given `scores` and `costs`.
Parameters
----------
payoff_arrays : tuple(ndarray(float, ndim=2))
Tuple... | keyword[def] identifier[_populate_ranking_payoff_arrays] ( identifier[payoff_arrays] , identifier[scores] , identifier[costs] ):
literal[string]
identifier[n] = identifier[payoff_arrays] [ literal[int] ]. identifier[shape] [ literal[int] ]
keyword[for] identifier[p] , identifier[payoff_array] keywor... | def _populate_ranking_payoff_arrays(payoff_arrays, scores, costs):
"""
Populate the ndarrays in `payoff_arrays` with the payoff values of
the ranking game given `scores` and `costs`.
Parameters
----------
payoff_arrays : tuple(ndarray(float, ndim=2))
Tuple of 2 ndarrays of shape (n, n).... |
def update(client, revision, no_output, siblings, paths):
"""Update existing files by rerunning their outdated workflow."""
graph = Graph(client)
outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths)
outputs = {node for node in outputs if graph.need_update(node)}
if not output... | def function[update, parameter[client, revision, no_output, siblings, paths]]:
constant[Update existing files by rerunning their outdated workflow.]
variable[graph] assign[=] call[name[Graph], parameter[name[client]]]
variable[outputs] assign[=] call[name[graph].build, parameter[]]
varia... | keyword[def] identifier[update] ( identifier[client] , identifier[revision] , identifier[no_output] , identifier[siblings] , identifier[paths] ):
literal[string]
identifier[graph] = identifier[Graph] ( identifier[client] )
identifier[outputs] = identifier[graph] . identifier[build] ( identifier[revisi... | def update(client, revision, no_output, siblings, paths):
"""Update existing files by rerunning their outdated workflow."""
graph = Graph(client)
outputs = graph.build(revision=revision, can_be_cwl=no_output, paths=paths)
outputs = {node for node in outputs if graph.need_update(node)}
if not outputs... |
def match_regex(self, regex: Pattern, required: bool = False,
meaning: str = "") -> str:
"""Parse input based on a regular expression .
Args:
regex: Compiled regular expression object.
required: Should the exception be raised on unexpected input?
... | def function[match_regex, parameter[self, regex, required, meaning]]:
constant[Parse input based on a regular expression .
Args:
regex: Compiled regular expression object.
required: Should the exception be raised on unexpected input?
meaning: Meaning of `regex` (for ... | keyword[def] identifier[match_regex] ( identifier[self] , identifier[regex] : identifier[Pattern] , identifier[required] : identifier[bool] = keyword[False] ,
identifier[meaning] : identifier[str] = literal[string] )-> identifier[str] :
literal[string]
identifier[mo] = identifier[regex] . identifi... | def match_regex(self, regex: Pattern, required: bool=False, meaning: str='') -> str:
"""Parse input based on a regular expression .
Args:
regex: Compiled regular expression object.
required: Should the exception be raised on unexpected input?
meaning: Meaning of `regex` ... |
async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
p, module = findModule(path, False)
if module is not None and hasattr(module, '_instance') and ... | <ast.AsyncFunctionDef object at 0x7da20c7c8e50> | keyword[async] keyword[def] identifier[reload_modules] ( identifier[self] , identifier[pathlist] ):
literal[string]
identifier[loadedModules] =[]
identifier[failures] =[]
keyword[for] identifier[path] keyword[in] identifier[pathlist] :
identifier[p] , identifier[m... | async def reload_modules(self, pathlist):
"""
Reload modules with a full path in the pathlist
"""
loadedModules = []
failures = []
for path in pathlist:
(p, module) = findModule(path, False)
if module is not None and hasattr(module, '_instance') and (module._instance.stat... |
def rgbline(x, y, red, green, blue, alpha=1, linestyles="solid",
linewidth=2.5):
"""Get a RGB coloured line for plotting.
Args:
x (list): x-axis data.
y (list): y-axis data (can be multidimensional array).
red (list): Red data (must have same shape as ``y``).
green (... | def function[rgbline, parameter[x, y, red, green, blue, alpha, linestyles, linewidth]]:
constant[Get a RGB coloured line for plotting.
Args:
x (list): x-axis data.
y (list): y-axis data (can be multidimensional array).
red (list): Red data (must have same shape as ``y``).
gr... | keyword[def] identifier[rgbline] ( identifier[x] , identifier[y] , identifier[red] , identifier[green] , identifier[blue] , identifier[alpha] = literal[int] , identifier[linestyles] = literal[string] ,
identifier[linewidth] = literal[int] ):
literal[string]
identifier[y] = identifier[np] . identifier[arra... | def rgbline(x, y, red, green, blue, alpha=1, linestyles='solid', linewidth=2.5):
"""Get a RGB coloured line for plotting.
Args:
x (list): x-axis data.
y (list): y-axis data (can be multidimensional array).
red (list): Red data (must have same shape as ``y``).
green (list): Green... |
def register_handler(self, name, handler, esc_strings):
"""Register a handler instance by name with esc_strings."""
self._handlers[name] = handler
for esc_str in esc_strings:
self._esc_handlers[esc_str] = handler | def function[register_handler, parameter[self, name, handler, esc_strings]]:
constant[Register a handler instance by name with esc_strings.]
call[name[self]._handlers][name[name]] assign[=] name[handler]
for taget[name[esc_str]] in starred[name[esc_strings]] begin[:]
call[name[se... | keyword[def] identifier[register_handler] ( identifier[self] , identifier[name] , identifier[handler] , identifier[esc_strings] ):
literal[string]
identifier[self] . identifier[_handlers] [ identifier[name] ]= identifier[handler]
keyword[for] identifier[esc_str] keyword[in] identifier[... | def register_handler(self, name, handler, esc_strings):
"""Register a handler instance by name with esc_strings."""
self._handlers[name] = handler
for esc_str in esc_strings:
self._esc_handlers[esc_str] = handler # depends on [control=['for'], data=['esc_str']] |
def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, ">0", "Critical height of water"])
return np.sqrt(gravity.magnitude * HeightWaterCritical) | def function[vel_horizontal, parameter[HeightWaterCritical]]:
constant[Return the horizontal velocity.]
call[name[ut].check_range, parameter[list[[<ast.Name object at 0x7da1b23465c0>, <ast.Constant object at 0x7da1b2347b50>, <ast.Constant object at 0x7da1b2347820>]]]]
return[call[name[np].sqrt, para... | keyword[def] identifier[vel_horizontal] ( identifier[HeightWaterCritical] ):
literal[string]
identifier[ut] . identifier[check_range] ([ identifier[HeightWaterCritical] , literal[string] , literal[string] ])
keyword[return] identifier[np] . identifier[sqrt] ( identifier[gravity] . identifier[mag... | def vel_horizontal(HeightWaterCritical):
"""Return the horizontal velocity."""
#Checking input validity
ut.check_range([HeightWaterCritical, '>0', 'Critical height of water'])
return np.sqrt(gravity.magnitude * HeightWaterCritical) |
def tell(self):
"""Return the current position in the stream (ignoring bit
position)
:returns: int for the position in the stream
"""
res = self._stream.tell()
if len(self._bits) > 0:
res -= 1
return res | def function[tell, parameter[self]]:
constant[Return the current position in the stream (ignoring bit
position)
:returns: int for the position in the stream
]
variable[res] assign[=] call[name[self]._stream.tell, parameter[]]
if compare[call[name[len], parameter[name[sel... | keyword[def] identifier[tell] ( identifier[self] ):
literal[string]
identifier[res] = identifier[self] . identifier[_stream] . identifier[tell] ()
keyword[if] identifier[len] ( identifier[self] . identifier[_bits] )> literal[int] :
identifier[res] -= literal[int]
ke... | def tell(self):
"""Return the current position in the stream (ignoring bit
position)
:returns: int for the position in the stream
"""
res = self._stream.tell()
if len(self._bits) > 0:
res -= 1 # depends on [control=['if'], data=[]]
return res |
def delete(self, query_id=None, **kwargs): # pragma: no cover
"""Delete a query job.
Uses the DELETE HTTP method to delete a query job. After calling
this endpoint, it is an error to poll for query results using
the queryId specified here.
Args:
query_id (str): Spe... | def function[delete, parameter[self, query_id]]:
constant[Delete a query job.
Uses the DELETE HTTP method to delete a query job. After calling
this endpoint, it is an error to poll for query results using
the queryId specified here.
Args:
query_id (str): Specifies t... | keyword[def] identifier[delete] ( identifier[self] , identifier[query_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[path] = literal[string] . identifier[format] ( identifier[query_id] )
identifier[r] = identifier[self] . identifier[_httpclient] . identifier[reque... | def delete(self, query_id=None, **kwargs): # pragma: no cover
'Delete a query job.\n\n Uses the DELETE HTTP method to delete a query job. After calling\n this endpoint, it is an error to poll for query results using\n the queryId specified here.\n\n Args:\n query_id (str): Sp... |
def translations_generator_to_dataframe(translations_generator):
"""
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
"""
return dataframe_from_generator... | def function[translations_generator_to_dataframe, parameter[translations_generator]]:
constant[
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
]
re... | keyword[def] identifier[translations_generator_to_dataframe] ( identifier[translations_generator] ):
literal[string]
keyword[return] identifier[dataframe_from_generator] (
identifier[element_class] = identifier[Translation] ,
identifier[variant_and_elements_generator] = identifier[translations_g... | def translations_generator_to_dataframe(translations_generator):
"""
Given a generator of (Variant, [Translation]) pairs,
returns a DataFrame of translated protein fragments with columns
for each field of a Translation object (and chr/pos/ref/alt per variant).
"""
return dataframe_from_generator... |
def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) | def function[commit, parameter[self]]:
constant[Store changes on current instance in database and index it.]
return[call[call[name[super], parameter[name[Deposit], name[self]]].commit, parameter[<ast.Starred object at 0x7da1aff1fd60>]]] | keyword[def] identifier[commit] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[Deposit] , identifier[self] ). identifier[commit] (* identifier[args] ,** identifier[kwargs] ) | def commit(self, *args, **kwargs):
"""Store changes on current instance in database and index it."""
return super(Deposit, self).commit(*args, **kwargs) |
def constraint(self):
"""Constraint string"""
constraint_arr = []
if self._not_null:
constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL")
if self._unique:
constraint_arr.append("UNIQUE")
return " ".join(constraint_arr) | def function[constraint, parameter[self]]:
constant[Constraint string]
variable[constraint_arr] assign[=] list[[]]
if name[self]._not_null begin[:]
call[name[constraint_arr].append, parameter[<ast.IfExp object at 0x7da18bccb040>]]
if name[self]._unique begin[:]
... | keyword[def] identifier[constraint] ( identifier[self] ):
literal[string]
identifier[constraint_arr] =[]
keyword[if] identifier[self] . identifier[_not_null] :
identifier[constraint_arr] . identifier[append] ( literal[string] keyword[if] identifier[self] . identifier[_pk] ... | def constraint(self):
"""Constraint string"""
constraint_arr = []
if self._not_null:
constraint_arr.append('PRIMARY KEY' if self._pk else 'NOT NULL') # depends on [control=['if'], data=[]]
if self._unique:
constraint_arr.append('UNIQUE') # depends on [control=['if'], data=[]]
retur... |
def set_chuid(ctx, management_key, pin):
"""
Generate and set a CHUID on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.update_chuid() | def function[set_chuid, parameter[ctx, management_key, pin]]:
constant[
Generate and set a CHUID on the YubiKey.
]
variable[controller] assign[=] call[name[ctx].obj][constant[controller]]
call[name[_ensure_authenticated], parameter[name[ctx], name[controller], name[pin], name[management_... | keyword[def] identifier[set_chuid] ( identifier[ctx] , identifier[management_key] , identifier[pin] ):
literal[string]
identifier[controller] = identifier[ctx] . identifier[obj] [ literal[string] ]
identifier[_ensure_authenticated] ( identifier[ctx] , identifier[controller] , identifier[pin] , identif... | def set_chuid(ctx, management_key, pin):
"""
Generate and set a CHUID on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.update_chuid() |
def find_nearest_color_index(r, g, b, color_table=None, method='euclid'):
''' Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…255
Retur... | def function[find_nearest_color_index, parameter[r, g, b, color_table, method]]:
constant[ Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…2... | keyword[def] identifier[find_nearest_color_index] ( identifier[r] , identifier[g] , identifier[b] , identifier[color_table] = keyword[None] , identifier[method] = literal[string] ):
literal[string]
identifier[shortest_distance] = literal[int] * literal[int] * literal[int]
identifier[index] = literal[... | def find_nearest_color_index(r, g, b, color_table=None, method='euclid'):
""" Given three integers representing R, G, and B,
return the nearest color index.
Arguments:
r: int - of range 0…255
g: int - of range 0…255
b: int - of range 0…255
Retur... |
def detuning_combinations(lists):
r"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for... | def function[detuning_combinations, parameter[lists]]:
constant[This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
]
variable[Nl] assign[=] call[name[... | keyword[def] identifier[detuning_combinations] ( identifier[lists] ):
literal[string]
identifier[Nl] = identifier[len] ( identifier[lists] )
identifier[comb] =[[ identifier[i] ] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[lists] [ literal[int] ])]
keyword[for] identi... | def detuning_combinations(lists):
"""This function recieves a list of length Nl with the number of
transitions each laser induces. It returns the cartesian product of all
these posibilities as a list of all possible combinations.
"""
Nl = len(lists)
comb = [[i] for i in range(lists[0])]
for ... |
def _parse_modes(mode_string, unary_modes=""):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _pa... | def function[_parse_modes, parameter[mode_string, unary_modes]]:
constant[
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Disca... | keyword[def] identifier[_parse_modes] ( identifier[mode_string] , identifier[unary_modes] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[mode_string] keyword[or] keyword[not] identifier[mode_string] [ literal[int] ] keyword[in] literal[string] :
keyword[return... | def _parse_modes(mode_string, unary_modes=''):
"""
Parse the mode_string and return a list of triples.
If no string is supplied return an empty list.
>>> _parse_modes('')
[]
If no sign is supplied, return an empty list.
>>> _parse_modes('ab')
[]
Discard unused args.
>>> _pa... |
def getReadGroupSetByName(self, name):
"""
Returns a ReadGroupSet with the specified name, or raises a
ReadGroupSetNameNotFoundException if it does not exist.
"""
if name not in self._readGroupSetNameMap:
raise exceptions.ReadGroupSetNameNotFoundException(name)
... | def function[getReadGroupSetByName, parameter[self, name]]:
constant[
Returns a ReadGroupSet with the specified name, or raises a
ReadGroupSetNameNotFoundException if it does not exist.
]
if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self]._readGroupSetNameMap] ... | keyword[def] identifier[getReadGroupSetByName] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_readGroupSetNameMap] :
keyword[raise] identifier[exceptions] . identifier[ReadGroupSetNameNo... | def getReadGroupSetByName(self, name):
"""
Returns a ReadGroupSet with the specified name, or raises a
ReadGroupSetNameNotFoundException if it does not exist.
"""
if name not in self._readGroupSetNameMap:
raise exceptions.ReadGroupSetNameNotFoundException(name) # depends on [con... |
def get_url(url: str) -> Union[dict, int, float, str]:
'''Perform a GET request for the url and return a dictionary parsed from
the JSON response.'''
request = Request(url, headers={"User-Agent": "pypeerassets"})
response = cast(HTTPResponse, urlopen(request))
if response.status... | def function[get_url, parameter[url]]:
constant[Perform a GET request for the url and return a dictionary parsed from
the JSON response.]
variable[request] assign[=] call[name[Request], parameter[name[url]]]
variable[response] assign[=] call[name[cast], parameter[name[HTTPResponse], call... | keyword[def] identifier[get_url] ( identifier[url] : identifier[str] )-> identifier[Union] [ identifier[dict] , identifier[int] , identifier[float] , identifier[str] ]:
literal[string]
identifier[request] = identifier[Request] ( identifier[url] , identifier[headers] ={ literal[string] : literal[st... | def get_url(url: str) -> Union[dict, int, float, str]:
"""Perform a GET request for the url and return a dictionary parsed from
the JSON response."""
request = Request(url, headers={'User-Agent': 'pypeerassets'})
response = cast(HTTPResponse, urlopen(request))
if response.status != 200:
... |
def get_project(self, resource):
"""
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well
as any parents must be identified to succeed.
Returns:
(intern.res... | def function[get_project, parameter[self, resource]]:
constant[
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well
as any parents must be identified to succeed.
Retur... | keyword[def] identifier[get_project] ( identifier[self] , identifier[resource] ):
literal[string]
identifier[self] . identifier[project_service] . identifier[set_auth] ( identifier[self] . identifier[_token_project] )
keyword[return] identifier[self] . identifier[project_service] . identi... | def get_project(self, resource):
"""
Get attributes of the data model object named by the given resource.
Args:
resource (intern.resource.boss.BossResource): resource.name as well
as any parents must be identified to succeed.
Returns:
(intern.resourc... |
def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set... | def function[os_workload_status, parameter[configs, required_interfaces, charm_func]]:
constant[
Decorator to set workload status based on complete contexts
]
def function[wrap, parameter[f]]:
def function[wrapped_f, parameter[]]:
call[name[f], parameter[<... | keyword[def] identifier[os_workload_status] ( identifier[configs] , identifier[required_interfaces] , identifier[charm_func] = keyword[None] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[f] ):
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[wrapped_f] (* ide... | def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# S... |
def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... | def function[get_regular_expressions, parameter[taxonomy_name, rebuild, no_cache]]:
constant[Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
]
<ast.Tuple object at 0x7da18eb549d0> assign[=] call[name[_get_ontology], para... | keyword[def] identifier[get_regular_expressions] ( identifier[taxonomy_name] , identifier[rebuild] = keyword[False] , identifier[no_cache] = keyword[False] ):
literal[string]
identifier[onto_name] , identifier[onto_path] , identifier[onto_url] = identifier[_get_ontology] ( identifier[taxonomy_nam... | def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... |
def get_terms(self):
''' GROUP BY is a shortcut to only getting the first in every list of group '''
if not self.terms.empty:
return self.terms
if self.from_backup:
self.terms = open_pickle(TERMS_BACKUP_PATH)
return self.terms
engine = create_engine(se... | def function[get_terms, parameter[self]]:
constant[ GROUP BY is a shortcut to only getting the first in every list of group ]
if <ast.UnaryOp object at 0x7da1b1a221a0> begin[:]
return[name[self].terms]
if name[self].from_backup begin[:]
name[self].terms assign[=] call[nam... | keyword[def] identifier[get_terms] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[terms] . identifier[empty] :
keyword[return] identifier[self] . identifier[terms]
keyword[if] identifier[self] . identifier[from_backup] :
... | def get_terms(self):
""" GROUP BY is a shortcut to only getting the first in every list of group """
if not self.terms.empty:
return self.terms # depends on [control=['if'], data=[]]
if self.from_backup:
self.terms = open_pickle(TERMS_BACKUP_PATH)
return self.terms # depends on [co... |
def coauthor_likelihoods(p1, p2):
"""returns the likelihoods of observing the actual number coauthors shared
by c{p1} and c{p2}, conditioned on whether or not p1 and p2 are a match
"""
def get_coauthors(p):
ret = set()
for m in p.mentions:
for co_m in article_to_mentions[m.a... | def function[coauthor_likelihoods, parameter[p1, p2]]:
constant[returns the likelihoods of observing the actual number coauthors shared
by c{p1} and c{p2}, conditioned on whether or not p1 and p2 are a match
]
def function[get_coauthors, parameter[p]]:
variable[ret] assign[=] ca... | keyword[def] identifier[coauthor_likelihoods] ( identifier[p1] , identifier[p2] ):
literal[string]
keyword[def] identifier[get_coauthors] ( identifier[p] ):
identifier[ret] = identifier[set] ()
keyword[for] identifier[m] keyword[in] identifier[p] . identifier[mentions] :
... | def coauthor_likelihoods(p1, p2):
"""returns the likelihoods of observing the actual number coauthors shared
by c{p1} and c{p2}, conditioned on whether or not p1 and p2 are a match
"""
def get_coauthors(p):
ret = set()
for m in p.mentions:
for co_m in article_to_mentions[m.... |
def to_wire(self, origin=None, max_size=65535):
"""Return a string containing the update in DNS compressed wire
format.
@rtype: string"""
if origin is None:
origin = self.origin
return super(Update, self).to_wire(origin, max_size) | def function[to_wire, parameter[self, origin, max_size]]:
constant[Return a string containing the update in DNS compressed wire
format.
@rtype: string]
if compare[name[origin] is constant[None]] begin[:]
variable[origin] assign[=] name[self].origin
return[call[call[na... | keyword[def] identifier[to_wire] ( identifier[self] , identifier[origin] = keyword[None] , identifier[max_size] = literal[int] ):
literal[string]
keyword[if] identifier[origin] keyword[is] keyword[None] :
identifier[origin] = identifier[self] . identifier[origin]
keyword[r... | def to_wire(self, origin=None, max_size=65535):
"""Return a string containing the update in DNS compressed wire
format.
@rtype: string"""
if origin is None:
origin = self.origin # depends on [control=['if'], data=['origin']]
return super(Update, self).to_wire(origin, max_size) |
def get_band_structure_dict(self):
"""Returns calclated band structures
Returns
-------
dict
keys: qpoints, distances, frequencies, eigenvectors, and
group_velocities
Each dict value is a list containing properties on number of paths.
... | def function[get_band_structure_dict, parameter[self]]:
constant[Returns calclated band structures
Returns
-------
dict
keys: qpoints, distances, frequencies, eigenvectors, and
group_velocities
Each dict value is a list containing properties on ... | keyword[def] identifier[get_band_structure_dict] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_band_structure] keyword[is] keyword[None] :
identifier[msg] =( literal[string] )
keyword[raise] identifier[RuntimeError] ( identifier[msg]... | def get_band_structure_dict(self):
"""Returns calclated band structures
Returns
-------
dict
keys: qpoints, distances, frequencies, eigenvectors, and
group_velocities
Each dict value is a list containing properties on number of paths.
Th... |
def _igamc(a, x):
"""Complemented incomplete Gamma integral.
SYNOPSIS:
double a, x, y, igamc();
y = igamc( a, x );
DESCRIPTION:
The function is defined by::
igamc(a,x) = 1 - igam(a,x)
inf.
-
... | def function[_igamc, parameter[a, x]]:
constant[Complemented incomplete Gamma integral.
SYNOPSIS:
double a, x, y, igamc();
y = igamc( a, x );
DESCRIPTION:
The function is defined by::
igamc(a,x) = 1 - igam(a,x)
inf.
... | keyword[def] identifier[_igamc] ( identifier[a] , identifier[x] ):
literal[string]
identifier[ax] = identifier[math] . identifier[exp] ( identifier[a] * identifier[math] . identifier[log] ( identifier[x] )- identifier[x] - identifier[math] . identifier[lgamma] ( identifier[a] ))
identifier[... | def _igamc(a, x):
"""Complemented incomplete Gamma integral.
SYNOPSIS:
double a, x, y, igamc();
y = igamc( a, x );
DESCRIPTION:
The function is defined by::
igamc(a,x) = 1 - igam(a,x)
inf.
-
... |
def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color,
thickness): # , lineType=None
'''
Extends cv2.putText with [alpha] argument
'''
x, y = cv2.getTextSize(text, fontFace,
fontScale, thickness)[0]
ox, oy = org
imgcut = img... | def function[putTextAlpha, parameter[img, text, alpha, org, fontFace, fontScale, color, thickness]]:
constant[
Extends cv2.putText with [alpha] argument
]
<ast.Tuple object at 0x7da1b1114610> assign[=] call[call[name[cv2].getTextSize, parameter[name[text], name[fontFace], name[fontScale], name[t... | keyword[def] identifier[putTextAlpha] ( identifier[img] , identifier[text] , identifier[alpha] , identifier[org] , identifier[fontFace] , identifier[fontScale] , identifier[color] ,
identifier[thickness] ):
literal[string]
identifier[x] , identifier[y] = identifier[cv2] . identifier[getTextSize] ( id... | def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color, thickness): # , lineType=None
'\n Extends cv2.putText with [alpha] argument\n '
(x, y) = cv2.getTextSize(text, fontFace, fontScale, thickness)[0]
(ox, oy) = org
imgcut = img[oy - y - 3:oy, ox:ox + x]
if img.ndim == 3:
... |
def get_partition_trees(self, p):
"""
Return the trees associated with a partition, p
"""
trees = []
for grp in p.get_membership():
try:
result = self.get_group_result(grp)
trees.append(result['ml_tree'])
except ValueError:
... | def function[get_partition_trees, parameter[self, p]]:
constant[
Return the trees associated with a partition, p
]
variable[trees] assign[=] list[[]]
for taget[name[grp]] in starred[call[name[p].get_membership, parameter[]]] begin[:]
<ast.Try object at 0x7da20c6aa3e0>
... | keyword[def] identifier[get_partition_trees] ( identifier[self] , identifier[p] ):
literal[string]
identifier[trees] =[]
keyword[for] identifier[grp] keyword[in] identifier[p] . identifier[get_membership] ():
keyword[try] :
identifier[result] = identifier[s... | def get_partition_trees(self, p):
"""
Return the trees associated with a partition, p
"""
trees = []
for grp in p.get_membership():
try:
result = self.get_group_result(grp)
trees.append(result['ml_tree']) # depends on [control=['try'], data=[]]
except... |
def section_strahler_orders(neurites, neurite_type=NeuriteType.all):
'''Inter-segment opening angles in a section'''
return map_sections(sectionfunc.strahler_order, neurites, neurite_type) | def function[section_strahler_orders, parameter[neurites, neurite_type]]:
constant[Inter-segment opening angles in a section]
return[call[name[map_sections], parameter[name[sectionfunc].strahler_order, name[neurites], name[neurite_type]]]] | keyword[def] identifier[section_strahler_orders] ( identifier[neurites] , identifier[neurite_type] = identifier[NeuriteType] . identifier[all] ):
literal[string]
keyword[return] identifier[map_sections] ( identifier[sectionfunc] . identifier[strahler_order] , identifier[neurites] , identifier[neurite_type... | def section_strahler_orders(neurites, neurite_type=NeuriteType.all):
"""Inter-segment opening angles in a section"""
return map_sections(sectionfunc.strahler_order, neurites, neurite_type) |
def _get_anchor(module_to_name, fullname):
"""Turn a full member name into an anchor.
Args:
module_to_name: Dictionary mapping modules to short names.
fullname: Fully qualified name of symbol.
Returns:
HTML anchor string. The longest module name prefix of fullname is
removed to make the anchor.... | def function[_get_anchor, parameter[module_to_name, fullname]]:
constant[Turn a full member name into an anchor.
Args:
module_to_name: Dictionary mapping modules to short names.
fullname: Fully qualified name of symbol.
Returns:
HTML anchor string. The longest module name prefix of fullname i... | keyword[def] identifier[_get_anchor] ( identifier[module_to_name] , identifier[fullname] ):
literal[string]
keyword[if] keyword[not] identifier[_anchor_re] . identifier[match] ( identifier[fullname] ):
keyword[raise] identifier[ValueError] ( literal[string] % identifier[fullname] )
identifier[anchor... | def _get_anchor(module_to_name, fullname):
"""Turn a full member name into an anchor.
Args:
module_to_name: Dictionary mapping modules to short names.
fullname: Fully qualified name of symbol.
Returns:
HTML anchor string. The longest module name prefix of fullname is
removed to make the ancho... |
def p_moduleIdentityClause(self, p):
"""moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}'"""
p[0] = ('moduleIdentityClause', p[1], # id
... | def function[p_moduleIdentityClause, parameter[self, p]]:
constant[moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}']
call[name[p]][constan... | keyword[def] identifier[p_moduleIdentityClause] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]=( literal[string] , identifier[p] [ literal[int] ],
( identifier[p] [ literal[int] ], identifier[p] [ literal[int] ]),
( identifier[... | def p_moduleIdentityClause(self, p):
"""moduleIdentityClause : LOWERCASE_IDENTIFIER MODULE_IDENTITY SubjectCategoriesPart LAST_UPDATED ExtUTCTime ORGANIZATION Text CONTACT_INFO Text DESCRIPTION Text RevisionPart COLON_COLON_EQUAL '{' objectIdentifier '}'""" # id
# p[2], # MODULE_IDENTITY
# XXX p[3], # Su... |
def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radiu... | def function[cart_to_polar, parameter[arr_c]]:
constant[Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
... | keyword[def] identifier[cart_to_polar] ( identifier[arr_c] ):
literal[string]
keyword[if] identifier[arr_c] . identifier[shape] [- literal[int] ]== literal[int] :
identifier[arr_p] = identifier[arr_c] . identifier[copy] ()
keyword[elif] identifier[arr_c] . identifier[shape] [- literal[int] ... | def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radiu... |
def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_q... | def function[_validate, parameter[self, qobj]]:
constant[Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
]
variable[n_qubits] assign[=] name[qobj].config.n_qub... | keyword[def] identifier[_validate] ( identifier[self] , identifier[qobj] ):
literal[string]
identifier[n_qubits] = identifier[qobj] . identifier[config] . identifier[n_qubits]
identifier[max_qubits] = identifier[self] . identifier[configuration] (). identifier[n_qubits]
keyword[... | def _validate(self, qobj):
"""Semantic validations of the qobj which cannot be done via schemas.
Some of these may later move to backend schemas.
1. No shots
2. No measurements in the middle
"""
n_qubits = qobj.config.n_qubits
max_qubits = self.configuration().n_qubits
if... |
def dfsmooth (window, df, ucol, k=None):
"""Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertai... | def function[dfsmooth, parameter[window, df, ucol, k]]:
constant[Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* t... | keyword[def] identifier[dfsmooth] ( identifier[window] , identifier[df] , identifier[ucol] , identifier[k] = keyword[None] ):
literal[string]
keyword[import] identifier[pandas] keyword[as] identifier[pd]
keyword[if] identifier[k] keyword[is] keyword[None] :
identifier[k] = identifier[... | def dfsmooth(window, df, ucol, k=None):
"""Smooth a :class:`pandas.DataFrame` according to a window, weighting based on
uncertainties.
Arguments are:
window
The smoothing window.
df
The :class:`pandas.DataFrame`.
ucol
The name of the column in *df* that contains the uncertain... |
def add_role_to_user(self, user, role):
""" Adds a role to user """
user.add_role(role)
self.save(user)
events.user_got_role_event.send(user, role=role) | def function[add_role_to_user, parameter[self, user, role]]:
constant[ Adds a role to user ]
call[name[user].add_role, parameter[name[role]]]
call[name[self].save, parameter[name[user]]]
call[name[events].user_got_role_event.send, parameter[name[user]]] | keyword[def] identifier[add_role_to_user] ( identifier[self] , identifier[user] , identifier[role] ):
literal[string]
identifier[user] . identifier[add_role] ( identifier[role] )
identifier[self] . identifier[save] ( identifier[user] )
identifier[events] . identifier[user_got_role... | def add_role_to_user(self, user, role):
""" Adds a role to user """
user.add_role(role)
self.save(user)
events.user_got_role_event.send(user, role=role) |
def batch_encode(self, iterator, *args, dim=0, **kwargs):
"""
Args:
iterator (iterator): Batch of labels to encode.
*args: Arguments passed to ``Encoder.batch_encode``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword ar... | def function[batch_encode, parameter[self, iterator]]:
constant[
Args:
iterator (iterator): Batch of labels to encode.
*args: Arguments passed to ``Encoder.batch_encode``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword... | keyword[def] identifier[batch_encode] ( identifier[self] , identifier[iterator] ,* identifier[args] , identifier[dim] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[torch] . identifier[stack] ( identifier[super] (). identifier[batch_encode] ( identifier[iterato... | def batch_encode(self, iterator, *args, dim=0, **kwargs):
"""
Args:
iterator (iterator): Batch of labels to encode.
*args: Arguments passed to ``Encoder.batch_encode``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword argume... |
def _pyfftw_destroys_input(flags, direction, halfcomplex, ndim):
"""Return ``True`` if FFTW destroys an input array, ``False`` otherwise."""
if any(flag in flags or _pyfftw_to_local(flag) in flags
for flag in ('FFTW_MEASURE', 'FFTW_PATIENT', 'FFTW_EXHAUSTIVE',
'FFTW_DESTROY_IN... | def function[_pyfftw_destroys_input, parameter[flags, direction, halfcomplex, ndim]]:
constant[Return ``True`` if FFTW destroys an input array, ``False`` otherwise.]
if call[name[any], parameter[<ast.GeneratorExp object at 0x7da1b1e53be0>]] begin[:]
return[constant[True]] | keyword[def] identifier[_pyfftw_destroys_input] ( identifier[flags] , identifier[direction] , identifier[halfcomplex] , identifier[ndim] ):
literal[string]
keyword[if] identifier[any] ( identifier[flag] keyword[in] identifier[flags] keyword[or] identifier[_pyfftw_to_local] ( identifier[flag] ) keyword... | def _pyfftw_destroys_input(flags, direction, halfcomplex, ndim):
"""Return ``True`` if FFTW destroys an input array, ``False`` otherwise."""
if any((flag in flags or _pyfftw_to_local(flag) in flags for flag in ('FFTW_MEASURE', 'FFTW_PATIENT', 'FFTW_EXHAUSTIVE', 'FFTW_DESTROY_INPUT'))):
return True # de... |
def prefix(self, prefix, lowercase=True):
''' Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
config_dirs /e... | def function[prefix, parameter[self, prefix, lowercase]]:
constant[ Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
... | keyword[def] identifier[prefix] ( identifier[self] , identifier[prefix] , identifier[lowercase] = keyword[True] ):
literal[string]
identifier[env_subset] ={}
keyword[for] identifier[key] keyword[in] identifier[self] . identifier[_envars] . identifier[keys] ():
keyword[if] ... | def prefix(self, prefix, lowercase=True):
""" Returns a dictionary of keys with the same prefix.
Compat with kr/env, lowercased.
> xdg = env.prefix('XDG_')
> for key, value in xdg.items():
print('%-20s' % key, value[:6], '…')
config_dirs /etc/x... |
def create_hlammagplot(plotman, h, ratio, alpha, options):
'''Plot the data of the tomodir in one overview plot.
'''
sizex, sizez = getfigsize(plotman)
# create figure
f, ax = plt.subplots(1, 3, figsize=(3 * sizex, sizez))
if options.title is not None:
plt.suptitle(options.title, fontsiz... | def function[create_hlammagplot, parameter[plotman, h, ratio, alpha, options]]:
constant[Plot the data of the tomodir in one overview plot.
]
<ast.Tuple object at 0x7da1b2248f40> assign[=] call[name[getfigsize], parameter[name[plotman]]]
<ast.Tuple object at 0x7da1b224ac20> assign[=] call[na... | keyword[def] identifier[create_hlammagplot] ( identifier[plotman] , identifier[h] , identifier[ratio] , identifier[alpha] , identifier[options] ):
literal[string]
identifier[sizex] , identifier[sizez] = identifier[getfigsize] ( identifier[plotman] )
identifier[f] , identifier[ax] = identifier[plt... | def create_hlammagplot(plotman, h, ratio, alpha, options):
"""Plot the data of the tomodir in one overview plot.
"""
(sizex, sizez) = getfigsize(plotman)
# create figure
(f, ax) = plt.subplots(1, 3, figsize=(3 * sizex, sizez))
if options.title is not None:
plt.suptitle(options.title, fon... |
def get_file_service_properties(self, timeout=None):
'''
Gets the properties of a storage account's File service, including
Azure Storage Analytics.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: The file service properties.
:rtyp... | def function[get_file_service_properties, parameter[self, timeout]]:
constant[
Gets the properties of a storage account's File service, including
Azure Storage Analytics.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: The file service pro... | keyword[def] identifier[get_file_service_properties] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[request] = identifier[HTTPRequest] ()
identifier[request] . identifier[method] = literal[string]
identifier[request] . identifier[host_locat... | def get_file_service_properties(self, timeout=None):
"""
Gets the properties of a storage account's File service, including
Azure Storage Analytics.
:param int timeout:
The timeout parameter is expressed in seconds.
:return: The file service properties.
:rtype:
... |
def write(self, chunk):
"""WSGI callable to write unbuffered data to the client.
This method is also used internally by start_response (to write
data from the iterable returned by the WSGI application).
"""
if not self.started_response:
raise AssertionError('WSGI wri... | def function[write, parameter[self, chunk]]:
constant[WSGI callable to write unbuffered data to the client.
This method is also used internally by start_response (to write
data from the iterable returned by the WSGI application).
]
if <ast.UnaryOp object at 0x7da204623760> begin... | keyword[def] identifier[write] ( identifier[self] , identifier[chunk] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[started_response] :
keyword[raise] identifier[AssertionError] ( literal[string] )
identifier[chunklen] = identifier[len] ( identi... | def write(self, chunk):
"""WSGI callable to write unbuffered data to the client.
This method is also used internally by start_response (to write
data from the iterable returned by the WSGI application).
"""
if not self.started_response:
raise AssertionError('WSGI write called be... |
def next(self):
'''Iterator next. Build up count of returned elements during iteration.'''
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__()
next = self._iterator.next()
if next is not StopIteration:
self._returned_inc(next)
return next | def function[next, parameter[self]]:
constant[Iterator next. Build up count of returned elements during iteration.]
if <ast.UnaryOp object at 0x7da18f09ce50> begin[:]
call[name[self].__iter__, parameter[]]
variable[next] assign[=] call[name[self]._iterator.next, parameter[]]
... | keyword[def] identifier[next] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_iterator] :
identifier[self] . identifier[__iter__] ()
identifier[next] = identifier[self] . identifier[_iterator] . identifier[next] ()
keyword[if] identif... | def next(self):
"""Iterator next. Build up count of returned elements during iteration."""
# if iteration has not begun, begin it.
if not self._iterator:
self.__iter__() # depends on [control=['if'], data=[]]
next = self._iterator.next()
if next is not StopIteration:
self._returned_... |
def create_release_branch(self, branch_name):
"""
Create a new release branch.
:param branch_name: The name of the release branch to create (a string).
:raises: The following exceptions can be raised:
- :exc:`~exceptions.TypeError` when :attr:`release_scheme`
... | def function[create_release_branch, parameter[self, branch_name]]:
constant[
Create a new release branch.
:param branch_name: The name of the release branch to create (a string).
:raises: The following exceptions can be raised:
- :exc:`~exceptions.TypeError` when :att... | keyword[def] identifier[create_release_branch] ( identifier[self] , identifier[branch_name] ):
literal[string]
identifier[self] . identifier[ensure_release_scheme] ( literal[string] )
keyword[if] identifier[self] . identifier[compiled_filter] . identifier[match] ( identi... | def create_release_branch(self, branch_name):
"""
Create a new release branch.
:param branch_name: The name of the release branch to create (a string).
:raises: The following exceptions can be raised:
- :exc:`~exceptions.TypeError` when :attr:`release_scheme`
... |
def decorate(self, output_tree, output_tax, unique_names):
'''
Decorate a tree with taxonomy. This code does not allow inconsistent
taxonomy within a clade. If one sequence in a clade has a different
annotation to the rest, it will split the clade. Paraphyletic group
names are di... | def function[decorate, parameter[self, output_tree, output_tax, unique_names]]:
constant[
Decorate a tree with taxonomy. This code does not allow inconsistent
taxonomy within a clade. If one sequence in a clade has a different
annotation to the rest, it will split the clade. Paraphyletic... | keyword[def] identifier[decorate] ( identifier[self] , identifier[output_tree] , identifier[output_tax] , identifier[unique_names] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] )
identifier[encountered_taxonomies] ={}
identifier[tc] = identifier[Taxon... | def decorate(self, output_tree, output_tax, unique_names):
"""
Decorate a tree with taxonomy. This code does not allow inconsistent
taxonomy within a clade. If one sequence in a clade has a different
annotation to the rest, it will split the clade. Paraphyletic group
names are distin... |
def parse_dsn(dsn):
"""Parse dsn string."""
parsed_dsn = urlparse(dsn)
parsed_path = parse_path(parsed_dsn.path)
return {
'scheme': parsed_dsn.scheme,
'sender': parsed_dsn.username,
'token': parsed_dsn.password,
'domain': parsed_dsn.hostname,
'port': parsed_dsn.po... | def function[parse_dsn, parameter[dsn]]:
constant[Parse dsn string.]
variable[parsed_dsn] assign[=] call[name[urlparse], parameter[name[dsn]]]
variable[parsed_path] assign[=] call[name[parse_path], parameter[name[parsed_dsn].path]]
return[dictionary[[<ast.Constant object at 0x7da20c991480>, ... | keyword[def] identifier[parse_dsn] ( identifier[dsn] ):
literal[string]
identifier[parsed_dsn] = identifier[urlparse] ( identifier[dsn] )
identifier[parsed_path] = identifier[parse_path] ( identifier[parsed_dsn] . identifier[path] )
keyword[return] {
literal[string] : identifier[parsed_dsn] ... | def parse_dsn(dsn):
"""Parse dsn string."""
parsed_dsn = urlparse(dsn)
parsed_path = parse_path(parsed_dsn.path)
return {'scheme': parsed_dsn.scheme, 'sender': parsed_dsn.username, 'token': parsed_dsn.password, 'domain': parsed_dsn.hostname, 'port': parsed_dsn.port or 80, 'version': parsed_path.get('ver... |
def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None):
"""Factory method for bounter implementation.
Args:
size_mb (int): Desired memory footprint of the counter.
need_iteration (Bool): With `True`, create a `HashTable` implementation which can
... | def function[bounter, parameter[size_mb, need_iteration, need_counts, log_counting]]:
constant[Factory method for bounter implementation.
Args:
size_mb (int): Desired memory footprint of the counter.
need_iteration (Bool): With `True`, create a `HashTable` implementation which can
... | keyword[def] identifier[bounter] ( identifier[size_mb] = keyword[None] , identifier[need_iteration] = keyword[True] , identifier[need_counts] = keyword[True] , identifier[log_counting] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[need_counts] :
keyword[return] identifi... | def bounter(size_mb=None, need_iteration=True, need_counts=True, log_counting=None):
"""Factory method for bounter implementation.
Args:
size_mb (int): Desired memory footprint of the counter.
need_iteration (Bool): With `True`, create a `HashTable` implementation which can
... |
def hex(x):
'''
x-->bytes | bytearray
Returns-->bytes: hex-encoded
'''
if isinstance(x, bytearray):
x = bytes(x)
return encode(x, 'hex') | def function[hex, parameter[x]]:
constant[
x-->bytes | bytearray
Returns-->bytes: hex-encoded
]
if call[name[isinstance], parameter[name[x], name[bytearray]]] begin[:]
variable[x] assign[=] call[name[bytes], parameter[name[x]]]
return[call[name[encode], parameter[name[x],... | keyword[def] identifier[hex] ( identifier[x] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[x] , identifier[bytearray] ):
identifier[x] = identifier[bytes] ( identifier[x] )
keyword[return] identifier[encode] ( identifier[x] , literal[string] ) | def hex(x):
"""
x-->bytes | bytearray
Returns-->bytes: hex-encoded
"""
if isinstance(x, bytearray):
x = bytes(x) # depends on [control=['if'], data=[]]
return encode(x, 'hex') |
def toLily(self):
'''
Method which converts the object instance and its attributes to a string of lilypond code
:return: str of lilypond code
'''
lilystring = ""
if hasattr(self, "size"):
try:
size = float(self.size)
lilystrin... | def function[toLily, parameter[self]]:
constant[
Method which converts the object instance and its attributes to a string of lilypond code
:return: str of lilypond code
]
variable[lilystring] assign[=] constant[]
if call[name[hasattr], parameter[name[self], constant[size... | keyword[def] identifier[toLily] ( identifier[self] ):
literal[string]
identifier[lilystring] = literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[try] :
identifier[size] = identifier[float] ( identifier[self] . i... | def toLily(self):
"""
Method which converts the object instance and its attributes to a string of lilypond code
:return: str of lilypond code
"""
lilystring = ''
if hasattr(self, 'size'):
try:
size = float(self.size)
lilystring += '\\abs-fontsize #' +... |
def _ir_calibrate(header, data, irchn, calib_type, mask=False):
"""IR calibration
*calib_type* in brightness_temperature, radiance, count
"""
count = data["hrpt"][:, :, irchn + 2].astype(np.float)
if calib_type == 0:
return count
# Mask unnaturally low values
mask |= count == 0.0
... | def function[_ir_calibrate, parameter[header, data, irchn, calib_type, mask]]:
constant[IR calibration
*calib_type* in brightness_temperature, radiance, count
]
variable[count] assign[=] call[call[call[name[data]][constant[hrpt]]][tuple[[<ast.Slice object at 0x7da1b22a6620>, <ast.Slice object at... | keyword[def] identifier[_ir_calibrate] ( identifier[header] , identifier[data] , identifier[irchn] , identifier[calib_type] , identifier[mask] = keyword[False] ):
literal[string]
identifier[count] = identifier[data] [ literal[string] ][:,:, identifier[irchn] + literal[int] ]. identifier[astype] ( identifi... | def _ir_calibrate(header, data, irchn, calib_type, mask=False):
"""IR calibration
*calib_type* in brightness_temperature, radiance, count
"""
count = data['hrpt'][:, :, irchn + 2].astype(np.float)
if calib_type == 0:
return count # depends on [control=['if'], data=[]]
# Mask unnaturally... |
def determine_encoding(path, default=None):
"""Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str... | def function[determine_encoding, parameter[path, default]]:
constant[Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.... | keyword[def] identifier[determine_encoding] ( identifier[path] , identifier[default] = keyword[None] ):
literal[string]
identifier[byte_order_marks] =(
( literal[string] ,( identifier[codecs] . identifier[BOM_UTF8] ,)),
( literal[string] ,( identifier[codecs] . identifier[BOM_UTF16_LE] , identifier... | def determine_encoding(path, default=None):
"""Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str... |
def convert2geojson(jsonfile, src_srs, dst_srs, src_file):
"""convert shapefile to geojson file"""
if os.path.exists(jsonfile):
os.remove(jsonfile)
if sysstr == 'Windows':
exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys.exec_prefix
else:
exepath... | def function[convert2geojson, parameter[jsonfile, src_srs, dst_srs, src_file]]:
constant[convert shapefile to geojson file]
if call[name[os].path.exists, parameter[name[jsonfile]]] begin[:]
call[name[os].remove, parameter[name[jsonfile]]]
if compare[name[sysstr] equal[==] constan... | keyword[def] identifier[convert2geojson] ( identifier[jsonfile] , identifier[src_srs] , identifier[dst_srs] , identifier[src_file] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[jsonfile] ):
identifier[os] . identifier[remove] ( iden... | def convert2geojson(jsonfile, src_srs, dst_srs, src_file):
"""convert shapefile to geojson file"""
if os.path.exists(jsonfile):
os.remove(jsonfile) # depends on [control=['if'], data=[]]
if sysstr == 'Windows':
exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys.exec_prefix # depends on... |
def get_vnetwork_portgroups_output_vnetwork_pgs_datacenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_portgroups = ET.Element("get_vnetwork_portgroups")
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgr... | def function[get_vnetwork_portgroups_output_vnetwork_pgs_datacenter, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_portgroups] assign[=] call[name[ET].Element, parameter[constant[get_v... | keyword[def] identifier[get_vnetwork_portgroups_output_vnetwork_pgs_datacenter] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_portgroups] = identifier[ET] . identifier[Eleme... | def get_vnetwork_portgroups_output_vnetwork_pgs_datacenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_portgroups = ET.Element('get_vnetwork_portgroups')
config = get_vnetwork_portgroups
output = ET.SubElement(get_vnetwork_portgroups, 'output')
... |
def box_score(game_id):
"""Gets the box score information for the game with matching id."""
# get data
data = mlbgame.data.get_box_score(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
linescore = root.find('linescore')
result = dict()
result['game_id'] = gam... | def function[box_score, parameter[game_id]]:
constant[Gets the box score information for the game with matching id.]
variable[data] assign[=] call[name[mlbgame].data.get_box_score, parameter[name[game_id]]]
variable[parsed] assign[=] call[name[etree].parse, parameter[name[data]]]
variabl... | keyword[def] identifier[box_score] ( identifier[game_id] ):
literal[string]
identifier[data] = identifier[mlbgame] . identifier[data] . identifier[get_box_score] ( identifier[game_id] )
identifier[parsed] = identifier[etree] . identifier[parse] ( identifier[data] )
identifier[root] = id... | def box_score(game_id):
"""Gets the box score information for the game with matching id."""
# get data
data = mlbgame.data.get_box_score(game_id)
# parse data
parsed = etree.parse(data)
root = parsed.getroot()
linescore = root.find('linescore')
result = dict()
result['game_id'] = gam... |
def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes']
except KeyError:
instance_data = {}
self.logger.warning('Instance at... | def function[_GetInstanceConfig, parameter[self]]:
constant[Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
]
<ast.Try object at 0x7da2044c1ae0>
<ast.Try object at 0x7da2044c0940>
return[<ast.BoolOp object at 0x7da2044c1600>] | keyword[def] identifier[_GetInstanceConfig] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[instance_data] = identifier[self] . identifier[metadata_dict] [ literal[string] ][ literal[string] ]
keyword[except] identifier[KeyError] :
identifier[instance_data] ={}
id... | def _GetInstanceConfig(self):
"""Get the instance configuration specified in metadata.
Returns:
string, the instance configuration data.
"""
try:
instance_data = self.metadata_dict['instance']['attributes'] # depends on [control=['try'], data=[]]
except KeyError:
instance_dat... |
def search_star(star):
'''
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
'''
base_url = "http://star-api.herokuapp.com/api/v1/stars/"
if not isinstance(star, str):
raise Value... | def function[search_star, parameter[star]]:
constant[
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
]
variable[base_url] assign[=] constant[http://star-api.herokuapp.com/api/v1/star... | keyword[def] identifier[search_star] ( identifier[star] ):
literal[string]
identifier[base_url] = literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[star] , identifier[str] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[else] :
... | def search_star(star):
"""
It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun.
http://star-api.herokuapp.com/api/v1/stars/Sun
"""
base_url = 'http://star-api.herokuapp.com/api/v1/stars/'
if not isinstance(star, str):
raise ValueEr... |
def Schwartzentruber(self, T, full=True, quick=True):
r'''Method to calculate `a_alpha` and its first and second
derivatives according to Schwartzentruber et al. (1990) [1]_. Returns `a_alpha`,
`da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives`
for more documentat... | def function[Schwartzentruber, parameter[self, T, full, quick]]:
constant[Method to calculate `a_alpha` and its first and second
derivatives according to Schwartzentruber et al. (1990) [1]_. Returns `a_alpha`,
`da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives`
for... | keyword[def] identifier[Schwartzentruber] ( identifier[self] , identifier[T] , identifier[full] = keyword[True] , identifier[quick] = keyword[True] ):
literal[string]
identifier[c1] , identifier[c2] , identifier[c3] = identifier[self] . identifier[alpha_function_coeffs]
identifier[T] , id... | def Schwartzentruber(self, T, full=True, quick=True):
"""Method to calculate `a_alpha` and its first and second
derivatives according to Schwartzentruber et al. (1990) [1]_. Returns `a_alpha`,
`da_alpha_dT`, and `d2a_alpha_dT2`. See `GCEOS.a_alpha_and_derivatives`
for more documentation. ... |
def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None):
"""
Update a physical interface.
Parameters:
- physicalInterfaceId (string)
- name (string)
- schemaId (string)
- description (string, optional)
Throws APIExc... | def function[updatePhysicalInterface, parameter[self, physicalInterfaceId, name, schemaId, description]]:
constant[
Update a physical interface.
Parameters:
- physicalInterfaceId (string)
- name (string)
- schemaId (string)
- description (string, optional)... | keyword[def] identifier[updatePhysicalInterface] ( identifier[self] , identifier[physicalInterfaceId] , identifier[name] , identifier[schemaId] , identifier[description] = keyword[None] ):
literal[string]
identifier[req] = identifier[ApiClient] . identifier[onePhysicalInterfacesUrl] %( identifier[s... | def updatePhysicalInterface(self, physicalInterfaceId, name, schemaId, description=None):
"""
Update a physical interface.
Parameters:
- physicalInterfaceId (string)
- name (string)
- schemaId (string)
- description (string, optional)
Throws APIExcepti... |
def rm_rf(path):
"""
Recursively (if needed) delete path.
"""
if os.path.isdir(path) and not os.path.islink(path):
shutil.rmtree(path)
elif os.path.lexists(path):
os.remove(path) | def function[rm_rf, parameter[path]]:
constant[
Recursively (if needed) delete path.
]
if <ast.BoolOp object at 0x7da1b26a48b0> begin[:]
call[name[shutil].rmtree, parameter[name[path]]] | keyword[def] identifier[rm_rf] ( identifier[path] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[isdir] ( identifier[path] ) keyword[and] keyword[not] identifier[os] . identifier[path] . identifier[islink] ( identifier[path] ):
identifier[shutil] . identifier[rmtr... | def rm_rf(path):
"""
Recursively (if needed) delete path.
"""
if os.path.isdir(path) and (not os.path.islink(path)):
shutil.rmtree(path) # depends on [control=['if'], data=[]]
elif os.path.lexists(path):
os.remove(path) # depends on [control=['if'], data=[]] |
def should_collect(self, value):
"""Decide whether a given value should be collected."""
return (
# decorated with @transition
isinstance(value, TransitionWrapper)
# Relates to a compatible transition
and value.trname in self.workflow.transitions
... | def function[should_collect, parameter[self, value]]:
constant[Decide whether a given value should be collected.]
return[<ast.BoolOp object at 0x7da18ede4730>] | keyword[def] identifier[should_collect] ( identifier[self] , identifier[value] ):
literal[string]
keyword[return] (
identifier[isinstance] ( identifier[value] , identifier[TransitionWrapper] )
keyword[and] identifier[value] . identifier[trname] keyword[in] ide... | def should_collect(self, value):
"""Decide whether a given value should be collected."""
# decorated with @transition
# Relates to a compatible transition
# Either not bound to a state field or bound to the current one
return isinstance(value, TransitionWrapper) and value.trname in self.workflow.tra... |
def asDict( self ):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(resu... | def function[asDict, parameter[self]]:
constant[
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
... | keyword[def] identifier[asDict] ( identifier[self] ):
literal[string]
keyword[if] identifier[PY_3] :
identifier[item_fn] = identifier[self] . identifier[items]
keyword[else] :
identifier[item_fn] = identifier[self] . identifier[iteritems]
keyword[def]... | def asDict(self):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), r... |
def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)... | def function[read, parameter[self, dataframe_name]]:
constant[Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
]
variable[code] assign[=] call[name[serialise_dataframe_code], parameter[name[dataframe_name], n... | keyword[def] identifier[read] ( identifier[self] , identifier[dataframe_name] : identifier[str] )-> identifier[pandas] . identifier[DataFrame] :
literal[string]
identifier[code] = identifier[serialise_dataframe_code] ( identifier[dataframe_name] , identifier[self] . identifier[kind] )
iden... | def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)
output.... |
def rl_force_redisplay() -> None: # pragma: no cover
"""
Causes readline to display the prompt and input text wherever the cursor is and start
reading input from this location. This is the proper way to restore the input line after
printing to the screen
"""
if not sys.stdout.isatty():
... | def function[rl_force_redisplay, parameter[]]:
constant[
Causes readline to display the prompt and input text wherever the cursor is and start
reading input from this location. This is the proper way to restore the input line after
printing to the screen
]
if <ast.UnaryOp object at 0x7da... | keyword[def] identifier[rl_force_redisplay] ()-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[sys] . identifier[stdout] . identifier[isatty] ():
keyword[return]
keyword[if] identifier[rl_type] == identifier[RlType] . identifier[GNU] :
identifier[readline_l... | def rl_force_redisplay() -> None: # pragma: no cover
'\n Causes readline to display the prompt and input text wherever the cursor is and start\n reading input from this location. This is the proper way to restore the input line after\n printing to the screen\n '
if not sys.stdout.isatty():
... |
def get_phone_numbers(self):
"""
: returns: dict of type and phone number list
:rtype: dict(str, list(str))
"""
phone_dict = {}
for child in self.vcard.getChildren():
if child.name == "TEL":
# phone types
type = helpers.list_to_... | def function[get_phone_numbers, parameter[self]]:
constant[
: returns: dict of type and phone number list
:rtype: dict(str, list(str))
]
variable[phone_dict] assign[=] dictionary[[], []]
for taget[name[child]] in starred[call[name[self].vcard.getChildren, parameter[]]] be... | keyword[def] identifier[get_phone_numbers] ( identifier[self] ):
literal[string]
identifier[phone_dict] ={}
keyword[for] identifier[child] keyword[in] identifier[self] . identifier[vcard] . identifier[getChildren] ():
keyword[if] identifier[child] . identifier[name] == lit... | def get_phone_numbers(self):
"""
: returns: dict of type and phone number list
:rtype: dict(str, list(str))
"""
phone_dict = {}
for child in self.vcard.getChildren():
if child.name == 'TEL':
# phone types
type = helpers.list_to_string(self._get_types_f... |
def send_command(self, data, read_delay=None):
"""Write "data" to the port and return the response form it"""
self._write(data)
if read_delay:
time.sleep(read_delay)
return self._read() | def function[send_command, parameter[self, data, read_delay]]:
constant[Write "data" to the port and return the response form it]
call[name[self]._write, parameter[name[data]]]
if name[read_delay] begin[:]
call[name[time].sleep, parameter[name[read_delay]]]
return[call[name[s... | keyword[def] identifier[send_command] ( identifier[self] , identifier[data] , identifier[read_delay] = keyword[None] ):
literal[string]
identifier[self] . identifier[_write] ( identifier[data] )
keyword[if] identifier[read_delay] :
identifier[time] . identifier[sleep] ( ident... | def send_command(self, data, read_delay=None):
"""Write "data" to the port and return the response form it"""
self._write(data)
if read_delay:
time.sleep(read_delay) # depends on [control=['if'], data=[]]
return self._read() |
def prepare_denovo_input_narrowpeak(inputfile, params, outdir):
"""Prepare a narrowPeak file for de novo motif prediction.
All regions to same size; split in test and validation set;
converted to FASTA.
Parameters
----------
inputfile : str
BED file with input regions.
params : di... | def function[prepare_denovo_input_narrowpeak, parameter[inputfile, params, outdir]]:
constant[Prepare a narrowPeak file for de novo motif prediction.
All regions to same size; split in test and validation set;
converted to FASTA.
Parameters
----------
inputfile : str
BED file with ... | keyword[def] identifier[prepare_denovo_input_narrowpeak] ( identifier[inputfile] , identifier[params] , identifier[outdir] ):
literal[string]
identifier[bedfile] = identifier[os] . identifier[path] . identifier[join] ( identifier[outdir] , literal[string] )
identifier[p] = identifier[re] . identifier... | def prepare_denovo_input_narrowpeak(inputfile, params, outdir):
"""Prepare a narrowPeak file for de novo motif prediction.
All regions to same size; split in test and validation set;
converted to FASTA.
Parameters
----------
inputfile : str
BED file with input regions.
params : di... |
def max_age(self, value):
"""
Set the MaxAge of the response.
:type value: int
:param value: the MaxAge option
"""
option = Option()
option.number = defines.OptionRegistry.MAX_AGE.number
option.value = int(value)
self.del_option_by_number(defines.... | def function[max_age, parameter[self, value]]:
constant[
Set the MaxAge of the response.
:type value: int
:param value: the MaxAge option
]
variable[option] assign[=] call[name[Option], parameter[]]
name[option].number assign[=] name[defines].OptionRegistry.MAX_A... | keyword[def] identifier[max_age] ( identifier[self] , identifier[value] ):
literal[string]
identifier[option] = identifier[Option] ()
identifier[option] . identifier[number] = identifier[defines] . identifier[OptionRegistry] . identifier[MAX_AGE] . identifier[number]
identifier[o... | def max_age(self, value):
"""
Set the MaxAge of the response.
:type value: int
:param value: the MaxAge option
"""
option = Option()
option.number = defines.OptionRegistry.MAX_AGE.number
option.value = int(value)
self.del_option_by_number(defines.OptionRegistry.MAX_A... |
def _check_obj_properties(self, pub, name="pub"):
"""
Make sure, that `pub` has the right interface.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
Raises:
InvalidType: When the `p... | def function[_check_obj_properties, parameter[self, pub, name]]:
constant[
Make sure, that `pub` has the right interface.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
Raises:
Inv... | keyword[def] identifier[_check_obj_properties] ( identifier[self] , identifier[pub] , identifier[name] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[pub] , literal[string] ):
keyword[raise] identifier[InvalidType] ( literal[string] % ... | def _check_obj_properties(self, pub, name='pub'):
"""
Make sure, that `pub` has the right interface.
Args:
pub (obj): Instance which will be checked.
name (str): Name of the instance. Used in exception. Default `pub`.
Raises:
InvalidType: When the `pub` ... |
def _compute_equations(self, x, verbose=False):
'''Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
'''
# compute the error and the normals.
normals = []
values = []
signs = []
error ... | def function[_compute_equations, parameter[self, x, verbose]]:
constant[Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
]
variable[normals] assign[=] list[[]]
variable[values] assign[=] list[[]]
var... | keyword[def] identifier[_compute_equations] ( identifier[self] , identifier[x] , identifier[verbose] = keyword[False] ):
literal[string]
identifier[normals] =[]
identifier[values] =[]
identifier[signs] =[]
identifier[error] = literal[int]
keyword[if] i... | def _compute_equations(self, x, verbose=False):
"""Compute the values and the normals (gradients) of active constraints.
Arguments:
| ``x`` -- The unknowns.
"""
# compute the error and the normals.
normals = []
values = []
signs = []
error = 0.0
if verbose:
... |
def derivatives_ctrlpts(**kwargs):
""" Computes the control points of all derivative curves up to and including the {degree}-th derivative.
Implementation of Algorithm A3.3 from The NURBS Book by Piegl & Tiller.
Output is PK[k][i], i-th control point of the k-th derivative curve where 0 <= k <... | def function[derivatives_ctrlpts, parameter[]]:
constant[ Computes the control points of all derivative curves up to and including the {degree}-th derivative.
Implementation of Algorithm A3.3 from The NURBS Book by Piegl & Tiller.
Output is PK[k][i], i-th control point of the k-th derivative c... | keyword[def] identifier[derivatives_ctrlpts] (** identifier[kwargs] ):
literal[string]
identifier[r1] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[r2] = identifier[kwargs] . identifier[get] ( literal[string] )
identifier[deriv_order] = identifier[... | def derivatives_ctrlpts(**kwargs):
""" Computes the control points of all derivative curves up to and including the {degree}-th derivative.
Implementation of Algorithm A3.3 from The NURBS Book by Piegl & Tiller.
Output is PK[k][i], i-th control point of the k-th derivative curve where 0 <= k <= de... |
def getCollectionClass(cls, name) :
"""Return the class object of a collection given its 'name'"""
try :
return cls.collectionClasses[name]
except KeyError :
raise KeyError( "There is no Collection Class of type: '%s'; currently supported values: [%s]" % (name, ', '.join(... | def function[getCollectionClass, parameter[cls, name]]:
constant[Return the class object of a collection given its 'name']
<ast.Try object at 0x7da1b0dc0940> | keyword[def] identifier[getCollectionClass] ( identifier[cls] , identifier[name] ):
literal[string]
keyword[try] :
keyword[return] identifier[cls] . identifier[collectionClasses] [ identifier[name] ]
keyword[except] identifier[KeyError] :
keyword[raise] identif... | def getCollectionClass(cls, name):
"""Return the class object of a collection given its 'name'"""
try:
return cls.collectionClasses[name] # depends on [control=['try'], data=[]]
except KeyError:
raise KeyError("There is no Collection Class of type: '%s'; currently supported values: [%s]" % ... |
def scan_for_spec(keyword):
"""
Attempt to return some sort of Spec from given keyword value.
Returns None if one could not be derived.
"""
# Both 'spec' formats are wrapped in parens, discard
keyword = keyword.lstrip('(').rstrip(')')
# First, test for intermediate '1.2+' style
matches ... | def function[scan_for_spec, parameter[keyword]]:
constant[
Attempt to return some sort of Spec from given keyword value.
Returns None if one could not be derived.
]
variable[keyword] assign[=] call[call[name[keyword].lstrip, parameter[constant[(]]].rstrip, parameter[constant[)]]]
va... | keyword[def] identifier[scan_for_spec] ( identifier[keyword] ):
literal[string]
identifier[keyword] = identifier[keyword] . identifier[lstrip] ( literal[string] ). identifier[rstrip] ( literal[string] )
identifier[matches] = identifier[release_line_re] . identifier[findall] ( identifier[keyw... | def scan_for_spec(keyword):
"""
Attempt to return some sort of Spec from given keyword value.
Returns None if one could not be derived.
"""
# Both 'spec' formats are wrapped in parens, discard
keyword = keyword.lstrip('(').rstrip(')')
# First, test for intermediate '1.2+' style
matches ... |
def clean(self):
"""Remove services without host object linked to
Note that this should not happen!
:return: None
"""
to_del = []
for serv in self:
if not serv.host:
to_del.append(serv.uuid)
for service_uuid in to_del:
del... | def function[clean, parameter[self]]:
constant[Remove services without host object linked to
Note that this should not happen!
:return: None
]
variable[to_del] assign[=] list[[]]
for taget[name[serv]] in starred[name[self]] begin[:]
if <ast.UnaryOp objec... | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
identifier[to_del] =[]
keyword[for] identifier[serv] keyword[in] identifier[self] :
keyword[if] keyword[not] identifier[serv] . identifier[host] :
identifier[to_del] . identifier[append]... | def clean(self):
"""Remove services without host object linked to
Note that this should not happen!
:return: None
"""
to_del = []
for serv in self:
if not serv.host:
to_del.append(serv.uuid) # depends on [control=['if'], data=[]] # depends on [control=['for'],... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.