code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def expMenu(groups,folder):
"""read experiment.txt and return a dict with [firstOfNewExp, color, star, comments]."""
### GENERATE THE MENU DATA BASED ON EXPERIMENT FILE
orphans = sorted(list(groups.keys()))
menu=[]
if os.path.exists(folder+'/experiment.txt'):
with open(folder+'/experiment.tx... | def function[expMenu, parameter[groups, folder]]:
constant[read experiment.txt and return a dict with [firstOfNewExp, color, star, comments].]
variable[orphans] assign[=] call[name[sorted], parameter[call[name[list], parameter[call[name[groups].keys, parameter[]]]]]]
variable[menu] assign[=] lis... | keyword[def] identifier[expMenu] ( identifier[groups] , identifier[folder] ):
literal[string]
identifier[orphans] = identifier[sorted] ( identifier[list] ( identifier[groups] . identifier[keys] ()))
identifier[menu] =[]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( id... | def expMenu(groups, folder):
"""read experiment.txt and return a dict with [firstOfNewExp, color, star, comments]."""
### GENERATE THE MENU DATA BASED ON EXPERIMENT FILE
orphans = sorted(list(groups.keys()))
menu = []
if os.path.exists(folder + '/experiment.txt'):
with open(folder + '/experi... |
def __Logout(si):
"""
Disconnect (logout) service instance
@param si: Service instance (returned from Connect)
"""
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout()
except Exception as e:
pass | def function[__Logout, parameter[si]]:
constant[
Disconnect (logout) service instance
@param si: Service instance (returned from Connect)
]
<ast.Try object at 0x7da18ede53c0> | keyword[def] identifier[__Logout] ( identifier[si] ):
literal[string]
keyword[try] :
keyword[if] identifier[si] :
identifier[content] = identifier[si] . identifier[RetrieveContent] ()
identifier[content] . identifier[sessionManager] . identifier[Logout] ()
keyword[except] ide... | def __Logout(si):
"""
Disconnect (logout) service instance
@param si: Service instance (returned from Connect)
"""
try:
if si:
content = si.RetrieveContent()
content.sessionManager.Logout() # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
... |
def clausius_clapeyron(T):
"""Compute saturation vapor pressure as function of temperature T.
Input: T is temperature in Kelvin
Output: saturation vapor pressure in mb or hPa
Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16
claimed to be accurate to within 0.1... | def function[clausius_clapeyron, parameter[T]]:
constant[Compute saturation vapor pressure as function of temperature T.
Input: T is temperature in Kelvin
Output: saturation vapor pressure in mb or hPa
Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16
claim... | keyword[def] identifier[clausius_clapeyron] ( identifier[T] ):
literal[string]
identifier[Tcel] = identifier[T] - identifier[tempCtoK]
identifier[es] = literal[int] * identifier[exp] ( literal[int] * identifier[Tcel] /( identifier[Tcel] + literal[int] ))
keyword[return] identifier[es] | def clausius_clapeyron(T):
"""Compute saturation vapor pressure as function of temperature T.
Input: T is temperature in Kelvin
Output: saturation vapor pressure in mb or hPa
Formula from Rogers and Yau "A Short Course in Cloud Physics" (Pergammon Press), p. 16
claimed to be accurate to within 0.1... |
def get_top_drawdowns(returns, top=10):
"""
Finds top drawdowns, sorted by drawdown amount.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, optional
The amount of ... | def function[get_top_drawdowns, parameter[returns, top]]:
constant[
Finds top drawdowns, sorted by drawdown amount.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, opt... | keyword[def] identifier[get_top_drawdowns] ( identifier[returns] , identifier[top] = literal[int] ):
literal[string]
identifier[returns] = identifier[returns] . identifier[copy] ()
identifier[df_cum] = identifier[ep] . identifier[cum_returns] ( identifier[returns] , literal[int] )
identifier[run... | def get_top_drawdowns(returns, top=10):
"""
Finds top drawdowns, sorted by drawdown amount.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
top : int, optional
The amount of ... |
def get_domain_config(self, domain):
"""Makes a discovery of domain name and resolves configuration of DNS provider
:param domain: str
domain name
:return: DomainConnectConfig
domain connect config
:raises: NoDomainConnectRecordException
when no _doma... | def function[get_domain_config, parameter[self, domain]]:
constant[Makes a discovery of domain name and resolves configuration of DNS provider
:param domain: str
domain name
:return: DomainConnectConfig
domain connect config
:raises: NoDomainConnectRecordExceptio... | keyword[def] identifier[get_domain_config] ( identifier[self] , identifier[domain] ):
literal[string]
identifier[domain_root] = identifier[self] . identifier[identify_domain_root] ( identifier[domain] )
identifier[host] = literal[string]
keyword[if] identifier[len] ( identifier... | def get_domain_config(self, domain):
"""Makes a discovery of domain name and resolves configuration of DNS provider
:param domain: str
domain name
:return: DomainConnectConfig
domain connect config
:raises: NoDomainConnectRecordException
when no _domainco... |
def value(self):
'''Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
'''
if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False:
r... | def function[value, parameter[self]]:
constant[Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
]
if <ast.BoolOp object at 0x7da2045646d0> begin[:]
return[call[call[name[self].__dic... | keyword[def] identifier[value] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[__dict__] [ literal[string] ])== literal[int] keyword[and] identifier[current_app] . identifier[config] [ literal[string] ] keyword[is] keyword[False] :
... | def value(self):
"""Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
"""
if len(self.__dict__['values']) == 1 and current_app.config['FORCE_ATTRIBUTE_VALUE_AS_LIST'] is False:
return self._... |
def AddGroupTags(r, group, tags, dry_run=False):
"""
Adds tags to a node group.
@type group: str
@param group: group to add tags to
@type tags: list of string
@param tags: tags to add to the group
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: string
@... | def function[AddGroupTags, parameter[r, group, tags, dry_run]]:
constant[
Adds tags to a node group.
@type group: str
@param group: group to add tags to
@type tags: list of string
@param tags: tags to add to the group
@type dry_run: bool
@param dry_run: whether to perform a dry run
... | keyword[def] identifier[AddGroupTags] ( identifier[r] , identifier[group] , identifier[tags] , identifier[dry_run] = keyword[False] ):
literal[string]
identifier[query] ={
literal[string] : identifier[dry_run] ,
literal[string] : identifier[tags] ,
}
keyword[return] identifier[r] . id... | def AddGroupTags(r, group, tags, dry_run=False):
"""
Adds tags to a node group.
@type group: str
@param group: group to add tags to
@type tags: list of string
@param tags: tags to add to the group
@type dry_run: bool
@param dry_run: whether to perform a dry run
@rtype: string
@... |
def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
i... | def function[_nuke_set_zero_margins, parameter[widget_object]]:
constant[Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
]
variable[parentApp] assign[=] call[name[QtWidgets].QApplication.allWidgets, parameter[]]
variable[parentWidgetList]... | keyword[def] identifier[_nuke_set_zero_margins] ( identifier[widget_object] ):
literal[string]
identifier[parentApp] = identifier[QtWidgets] . identifier[QApplication] . identifier[allWidgets] ()
identifier[parentWidgetList] =[]
keyword[for] identifier[parent] keyword[in] identifier[parentApp]... | def _nuke_set_zero_margins(widget_object):
"""Remove Nuke margins when docked UI
.. _More info:
https://gist.github.com/maty974/4739917
"""
parentApp = QtWidgets.QApplication.allWidgets()
parentWidgetList = []
for parent in parentApp:
for child in parent.children():
i... |
def _set_logging_rate_memory(self, v, load=False):
"""
Setter method for logging_rate_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/logging_rate_memory (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_logging_rate_memory is considered as a... | def function[_set_logging_rate_memory, parameter[self, v, load]]:
constant[
Setter method for logging_rate_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/logging_rate_memory (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_logging_rate_... | keyword[def] identifier[_set_logging_rate_memory] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_logging_rate_memory(self, v, load=False):
"""
Setter method for logging_rate_memory, mapped from YANG variable /rbridge_id/resource_monitor/memory/logging_rate_memory (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_logging_rate_memory is considered as a... |
def fisher_mean(dec=None, inc=None, di_block=None):
"""
Calculates the Fisher mean and associated parameters from either a list of
declination values and a separate list of inclination values or from a
di_block (a nested list a nested list of [dec,inc,1.0]). Returns a
dictionary with the Fisher mean... | def function[fisher_mean, parameter[dec, inc, di_block]]:
constant[
Calculates the Fisher mean and associated parameters from either a list of
declination values and a separate list of inclination values or from a
di_block (a nested list a nested list of [dec,inc,1.0]). Returns a
dictionary with... | keyword[def] identifier[fisher_mean] ( identifier[dec] = keyword[None] , identifier[inc] = keyword[None] , identifier[di_block] = keyword[None] ):
literal[string]
keyword[if] identifier[di_block] keyword[is] keyword[None] :
identifier[di_block] = identifier[make_di_block] ( identifier[dec] , id... | def fisher_mean(dec=None, inc=None, di_block=None):
"""
Calculates the Fisher mean and associated parameters from either a list of
declination values and a separate list of inclination values or from a
di_block (a nested list a nested list of [dec,inc,1.0]). Returns a
dictionary with the Fisher mean... |
def _get_enterprise_customer_users_batch(self, start, end):
"""
Returns a batched queryset of EnterpriseCustomerUser objects.
"""
LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end)
return User.objects.filter(pk__in=self._get_enterpri... | def function[_get_enterprise_customer_users_batch, parameter[self, start, end]]:
constant[
Returns a batched queryset of EnterpriseCustomerUser objects.
]
call[name[LOGGER].info, parameter[constant[Fetching new batch of enterprise customer users from indexes: %s to %s], name[start], name... | keyword[def] identifier[_get_enterprise_customer_users_batch] ( identifier[self] , identifier[start] , identifier[end] ):
literal[string]
identifier[LOGGER] . identifier[info] ( literal[string] , identifier[start] , identifier[end] )
keyword[return] identifier[User] . identifier[objects] ... | def _get_enterprise_customer_users_batch(self, start, end):
"""
Returns a batched queryset of EnterpriseCustomerUser objects.
"""
LOGGER.info('Fetching new batch of enterprise customer users from indexes: %s to %s', start, end)
return User.objects.filter(pk__in=self._get_enterprise_customer_... |
def format_survival_rate():
"""cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session.
"""
arguments = docopt.docopt(
format_survival_rate.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
rate = survival_r... | def function[format_survival_rate, parameter[]]:
constant[cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session.
]
variable[arguments] assign[=] call[name[docopt].docopt, parameter[name[format_survival_rate].__doc__]]
with call[name[use_db], parameter[call[... | keyword[def] identifier[format_survival_rate] ():
literal[string]
identifier[arguments] = identifier[docopt] . identifier[docopt] (
identifier[format_survival_rate] . identifier[__doc__] , identifier[version] = literal[string] )
keyword[with] identifier[use_db] ( identifier[arguments] [ literal[... | def format_survival_rate():
"""cr-rate
Usage: cr-rate <session-file>
Calculate the survival rate of a session.
"""
arguments = docopt.docopt(format_survival_rate.__doc__, version='cr-rate 1.0')
with use_db(arguments['<session-file>'], WorkDB.Mode.open) as db:
rate = survival_rate(db) ... |
def hdate(self, date):
"""Set the dates of the HDate object based on a given Hebrew date."""
# Sanity checks
if date is None and isinstance(self.gdate, datetime.date):
# Calculate the value since gdate has been set
date = self.hdate
if not isinstance(date, Hebrew... | def function[hdate, parameter[self, date]]:
constant[Set the dates of the HDate object based on a given Hebrew date.]
if <ast.BoolOp object at 0x7da1b0aa4eb0> begin[:]
variable[date] assign[=] name[self].hdate
if <ast.UnaryOp object at 0x7da1b092f9d0> begin[:]
<ast.Raise ... | keyword[def] identifier[hdate] ( identifier[self] , identifier[date] ):
literal[string]
keyword[if] identifier[date] keyword[is] keyword[None] keyword[and] identifier[isinstance] ( identifier[self] . identifier[gdate] , identifier[datetime] . identifier[date] ):
... | def hdate(self, date):
"""Set the dates of the HDate object based on a given Hebrew date."""
# Sanity checks
if date is None and isinstance(self.gdate, datetime.date):
# Calculate the value since gdate has been set
date = self.hdate # depends on [control=['if'], data=[]]
if not isinstan... |
def draw_normal_initial(self):
"""
Draw parameters from a mean-field normal family
"""
means, scale = self.get_means_and_scales_from_q()
return np.random.normal(means,scale,size=[self.sims,means.shape[0]]).T | def function[draw_normal_initial, parameter[self]]:
constant[
Draw parameters from a mean-field normal family
]
<ast.Tuple object at 0x7da18f00f520> assign[=] call[name[self].get_means_and_scales_from_q, parameter[]]
return[call[name[np].random.normal, parameter[name[means], name[sca... | keyword[def] identifier[draw_normal_initial] ( identifier[self] ):
literal[string]
identifier[means] , identifier[scale] = identifier[self] . identifier[get_means_and_scales_from_q] ()
keyword[return] identifier[np] . identifier[random] . identifier[normal] ( identifier[means] , identifie... | def draw_normal_initial(self):
"""
Draw parameters from a mean-field normal family
"""
(means, scale) = self.get_means_and_scales_from_q()
return np.random.normal(means, scale, size=[self.sims, means.shape[0]]).T |
def vlan_classifier_group_groupid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vlan = ET.SubElement(config, "vlan", xmlns="urn:brocade.com:mgmt:brocade-vlan")
classifier = ET.SubElement(vlan, "classifier")
group = ET.SubElement(classifier, "gr... | def function[vlan_classifier_group_groupid, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[vlan] assign[=] call[name[ET].SubElement, parameter[name[config], constant[vlan]]]
variable[classif... | keyword[def] identifier[vlan_classifier_group_groupid] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[vlan] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string... | def vlan_classifier_group_groupid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
vlan = ET.SubElement(config, 'vlan', xmlns='urn:brocade.com:mgmt:brocade-vlan')
classifier = ET.SubElement(vlan, 'classifier')
group = ET.SubElement(classifier, 'group')
oper_key =... |
def timeout_callback(self):
"""过期回调函数.
如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调
"""
# Check if elapsed time since last response exceeds our configured
# maximum keep alive timeout value
now = time()
time_elapsed = now - self._last_response_time
if ti... | def function[timeout_callback, parameter[self]]:
constant[过期回调函数.
如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调
]
variable[now] assign[=] call[name[time], parameter[]]
variable[time_elapsed] assign[=] binary_operation[name[now] - name[self]._last_response_time]
if compar... | keyword[def] identifier[timeout_callback] ( identifier[self] ):
literal[string]
identifier[now] = identifier[time] ()
identifier[time_elapsed] = identifier[now] - identifier[self] . identifier[_last_response_time]
keyword[if] identifier[time_elapsed] < identifi... | def timeout_callback(self):
"""过期回调函数.
如果设置了timeout则会启动一个协程按当前时间和最近的响应时间只差递归的执行这个回调
"""
# Check if elapsed time since last response exceeds our configured
# maximum keep alive timeout value
now = time()
time_elapsed = now - self._last_response_time
if time_elapsed < self.timeou... |
def populations_slices(particles, num_pop_list):
"""2-tuple of slices for selection of two populations.
"""
slices = []
i_prev = 0
for num_pop in num_pop_list:
slices.append(slice(i_prev, i_prev + num_pop))
i_prev += num_pop
return slices | def function[populations_slices, parameter[particles, num_pop_list]]:
constant[2-tuple of slices for selection of two populations.
]
variable[slices] assign[=] list[[]]
variable[i_prev] assign[=] constant[0]
for taget[name[num_pop]] in starred[name[num_pop_list]] begin[:]
... | keyword[def] identifier[populations_slices] ( identifier[particles] , identifier[num_pop_list] ):
literal[string]
identifier[slices] =[]
identifier[i_prev] = literal[int]
keyword[for] identifier[num_pop] keyword[in] identifier[num_pop_list] :
identifier[slices] . identifier[append] (... | def populations_slices(particles, num_pop_list):
"""2-tuple of slices for selection of two populations.
"""
slices = []
i_prev = 0
for num_pop in num_pop_list:
slices.append(slice(i_prev, i_prev + num_pop))
i_prev += num_pop # depends on [control=['for'], data=['num_pop']]
retur... |
def validate(self, value):
"""Validate field value."""
if value is not None:
if not isinstance(value, list):
raise ValidationError("field must be a list")
for index, element in enumerate(value):
try:
self.inner.validate(element... | def function[validate, parameter[self, value]]:
constant[Validate field value.]
if compare[name[value] is_not constant[None]] begin[:]
if <ast.UnaryOp object at 0x7da1b1990640> begin[:]
<ast.Raise object at 0x7da1b1990dc0>
for taget[tuple[[<ast.Name object at ... | keyword[def] identifier[validate] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[list] ):
keyword[ra... | def validate(self, value):
"""Validate field value."""
if value is not None:
if not isinstance(value, list):
raise ValidationError('field must be a list') # depends on [control=['if'], data=[]]
for (index, element) in enumerate(value):
try:
self.inner.val... |
def machine(self):
"""Return the flavour attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FLAVOUR) | def function[machine, parameter[self]]:
constant[Return the flavour attribute of the BFD file being processed.]
if <ast.UnaryOp object at 0x7da20c6e6fb0> begin[:]
<ast.Raise object at 0x7da20c6e5b70>
return[call[name[_bfd].get_bfd_attribute, parameter[name[self]._ptr, name[BfdAttributes].FLA... | keyword[def] identifier[machine] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_ptr] :
keyword[raise] identifier[BfdException] ( literal[string] )
keyword[return] identifier[_bfd] . identifier[get_bfd_attribute] ( identifier[... | def machine(self):
"""Return the flavour attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException('BFD not initialized') # depends on [control=['if'], data=[]]
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.FLAVOUR) |
def json(self, answer):
"""
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
"""
self.content_type = "application/json"
if hasattr(answer, '__json__'):
answer = answer.__json__... | def function[json, parameter[self, answer]]:
constant[
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
]
name[self].content_type assign[=] constant[application/json]
if call[name[hasattr],... | keyword[def] identifier[json] ( identifier[self] , identifier[answer] ):
literal[string]
identifier[self] . identifier[content_type] = literal[string]
keyword[if] identifier[hasattr] ( identifier[answer] , literal[string] ):
identifier[answer] = identifier[answer] . identif... | def json(self, answer):
"""
Set the response content type to application/json and serialize
the content.
:param anwser The response as a Python object
"""
self.content_type = 'application/json'
if hasattr(answer, '__json__'):
answer = answer.__json__() # depends on ... |
def _choose_base_case(is_accepted,
accepted,
rejected,
name=None):
"""Helper to `choose` which expand_dims `is_accepted` and applies tf.where."""
def _expand_is_accepted_like(x):
"""Helper to expand `is_accepted` like the shape of some input arg.... | def function[_choose_base_case, parameter[is_accepted, accepted, rejected, name]]:
constant[Helper to `choose` which expand_dims `is_accepted` and applies tf.where.]
def function[_expand_is_accepted_like, parameter[x]]:
constant[Helper to expand `is_accepted` like the shape of some input... | keyword[def] identifier[_choose_base_case] ( identifier[is_accepted] ,
identifier[accepted] ,
identifier[rejected] ,
identifier[name] = keyword[None] ):
literal[string]
keyword[def] identifier[_expand_is_accepted_like] ( identifier[x] ):
literal[string]
keyword[with] identifier[tf] . identifier... | def _choose_base_case(is_accepted, accepted, rejected, name=None):
"""Helper to `choose` which expand_dims `is_accepted` and applies tf.where."""
def _expand_is_accepted_like(x):
"""Helper to expand `is_accepted` like the shape of some input arg."""
with tf.compat.v1.name_scope('expand_is_accep... |
def benchmark_hash_data():
"""
CommandLine:
python ~/code/ubelt/dev/bench_hash.py --convert=True --show
python ~/code/ubelt/dev/bench_hash.py --convert=False --show
"""
import ubelt as ub
#ITEM = 'JUST A STRING' * 100
ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4]
HASHERS = [... | def function[benchmark_hash_data, parameter[]]:
constant[
CommandLine:
python ~/code/ubelt/dev/bench_hash.py --convert=True --show
python ~/code/ubelt/dev/bench_hash.py --convert=False --show
]
import module[ubelt] as alias[ub]
variable[ITEM] assign[=] list[[<ast.Constant obj... | keyword[def] identifier[benchmark_hash_data] ():
literal[string]
keyword[import] identifier[ubelt] keyword[as] identifier[ub]
identifier[ITEM] =[ literal[int] , literal[int] , literal[string] , literal[string] ,[ literal[string] ]* literal[int] ]
identifier[HASHERS] =[ literal[string] , ... | def benchmark_hash_data():
"""
CommandLine:
python ~/code/ubelt/dev/bench_hash.py --convert=True --show
python ~/code/ubelt/dev/bench_hash.py --convert=False --show
"""
import ubelt as ub
#ITEM = 'JUST A STRING' * 100
ITEM = [0, 1, 'a', 'b', ['JUST A STRING'] * 4]
HASHERS = [... |
def _show_or_dump(self, dump=False, indent=3,
lvl="", label_lvl="", first_call=True):
""" Reproduced from packet.py """
ct = AnsiColorTheme() if dump else conf.color_theme
s = "%s%s %s %s \n" % (label_lvl, ct.punct("###["),
ct.layer_name(self.... | def function[_show_or_dump, parameter[self, dump, indent, lvl, label_lvl, first_call]]:
constant[ Reproduced from packet.py ]
variable[ct] assign[=] <ast.IfExp object at 0x7da1b21a19c0>
variable[s] assign[=] binary_operation[constant[%s%s %s %s
] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.N... | keyword[def] identifier[_show_or_dump] ( identifier[self] , identifier[dump] = keyword[False] , identifier[indent] = literal[int] ,
identifier[lvl] = literal[string] , identifier[label_lvl] = literal[string] , identifier[first_call] = keyword[True] ):
literal[string]
identifier[ct] = identifier[An... | def _show_or_dump(self, dump=False, indent=3, lvl='', label_lvl='', first_call=True):
""" Reproduced from packet.py """
ct = AnsiColorTheme() if dump else conf.color_theme
s = '%s%s %s %s \n' % (label_lvl, ct.punct('###['), ct.layer_name(self.name), ct.punct(']###'))
for f in self.fields_desc[:-1]:
... |
def _get_batch_requests(self, timeout=None):
"""try to get request as fast as possible, once empty and stop falg or time-out, just return Empty"""
reqs = []
s = time()
while len(reqs) < self.batch_size and (time() - s) < timeout:
try:
req = self.queue.get(bloc... | def function[_get_batch_requests, parameter[self, timeout]]:
constant[try to get request as fast as possible, once empty and stop falg or time-out, just return Empty]
variable[reqs] assign[=] list[[]]
variable[s] assign[=] call[name[time], parameter[]]
while <ast.BoolOp object at 0x7da20... | keyword[def] identifier[_get_batch_requests] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[reqs] =[]
identifier[s] = identifier[time] ()
keyword[while] identifier[len] ( identifier[reqs] )< identifier[self] . identifier[batch_size] keywor... | def _get_batch_requests(self, timeout=None):
"""try to get request as fast as possible, once empty and stop falg or time-out, just return Empty"""
reqs = []
s = time()
while len(reqs) < self.batch_size and time() - s < timeout:
try:
req = self.queue.get(block=False)
self.... |
def convert_from_latlon_to_utm(points=None,
latitudes=None,
longitudes=None,
false_easting=None,
false_northing=None):
"""Convert latitude and longitude data to UTM as a list of coordinates.
... | def function[convert_from_latlon_to_utm, parameter[points, latitudes, longitudes, false_easting, false_northing]]:
constant[Convert latitude and longitude data to UTM as a list of coordinates.
Input
points: list of points given in decimal degrees (latitude, longitude) or
latitudes: list of latitu... | keyword[def] identifier[convert_from_latlon_to_utm] ( identifier[points] = keyword[None] ,
identifier[latitudes] = keyword[None] ,
identifier[longitudes] = keyword[None] ,
identifier[false_easting] = keyword[None] ,
identifier[false_northing] = keyword[None] ):
literal[string]
identifier[old_geo] = id... | def convert_from_latlon_to_utm(points=None, latitudes=None, longitudes=None, false_easting=None, false_northing=None):
"""Convert latitude and longitude data to UTM as a list of coordinates.
Input
points: list of points given in decimal degrees (latitude, longitude) or
latitudes: list of latitudes ... |
def _parse_term(_rawterms):
"""Parse a term line.
The term is organized as a succesion of ``key:value`` pairs
that are extracted into the same dictionnary until a new
header is encountered
Arguments:
line (str): the line containing a term statement
"""
... | def function[_parse_term, parameter[_rawterms]]:
constant[Parse a term line.
The term is organized as a succesion of ``key:value`` pairs
that are extracted into the same dictionnary until a new
header is encountered
Arguments:
line (str): the line containing a term ... | keyword[def] identifier[_parse_term] ( identifier[_rawterms] ):
literal[string]
identifier[line] = keyword[yield]
identifier[_rawterms] . identifier[append] ( identifier[collections] . identifier[defaultdict] ( identifier[list] ))
keyword[while] keyword[True] :
iden... | def _parse_term(_rawterms):
"""Parse a term line.
The term is organized as a succesion of ``key:value`` pairs
that are extracted into the same dictionnary until a new
header is encountered
Arguments:
line (str): the line containing a term statement
"""
line ... |
def get_model_custom_fields(self):
""" Return a list of custom fields for this model, directly callable
without an instance. Use like Foo.get_model_custom_fields(Foo)
"""
return CustomField.objects.filter(
content_type=ContentType.objects.get_for_model(self)) | def function[get_model_custom_fields, parameter[self]]:
constant[ Return a list of custom fields for this model, directly callable
without an instance. Use like Foo.get_model_custom_fields(Foo)
]
return[call[name[CustomField].objects.filter, parameter[]]] | keyword[def] identifier[get_model_custom_fields] ( identifier[self] ):
literal[string]
keyword[return] identifier[CustomField] . identifier[objects] . identifier[filter] (
identifier[content_type] = identifier[ContentType] . identifier[objects] . identifier[get_for_model] ( identifier[sel... | def get_model_custom_fields(self):
""" Return a list of custom fields for this model, directly callable
without an instance. Use like Foo.get_model_custom_fields(Foo)
"""
return CustomField.objects.filter(content_type=ContentType.objects.get_for_model(self)) |
def parse_headers(self, req, name, field):
"""Pull a header value from the request."""
# Use req.get_headers rather than req.headers for performance
return req.get_header(name, required=False) or core.missing | def function[parse_headers, parameter[self, req, name, field]]:
constant[Pull a header value from the request.]
return[<ast.BoolOp object at 0x7da1b22ea020>] | keyword[def] identifier[parse_headers] ( identifier[self] , identifier[req] , identifier[name] , identifier[field] ):
literal[string]
keyword[return] identifier[req] . identifier[get_header] ( identifier[name] , identifier[required] = keyword[False] ) keyword[or] identifier[core] . ident... | def parse_headers(self, req, name, field):
"""Pull a header value from the request."""
# Use req.get_headers rather than req.headers for performance
return req.get_header(name, required=False) or core.missing |
async def run_task(self, container, task, newthread = False):
"Run task() in task pool. Raise an exception or return the return value"
e = TaskEvent(self, task=task, newthread = newthread)
await container.wait_for_send(e)
ev = await TaskDoneEvent.createMatcher(e)
if hasattr(ev, '... | <ast.AsyncFunctionDef object at 0x7da18dc99f90> | keyword[async] keyword[def] identifier[run_task] ( identifier[self] , identifier[container] , identifier[task] , identifier[newthread] = keyword[False] ):
literal[string]
identifier[e] = identifier[TaskEvent] ( identifier[self] , identifier[task] = identifier[task] , identifier[newthread] = identi... | async def run_task(self, container, task, newthread=False):
"""Run task() in task pool. Raise an exception or return the return value"""
e = TaskEvent(self, task=task, newthread=newthread)
await container.wait_for_send(e)
ev = await TaskDoneEvent.createMatcher(e)
if hasattr(ev, 'exception'):
... |
def all(cls):
"""
Get all consts
:return: list
"""
result = []
for name in dir(cls):
if not name.isupper():
continue
value = getattr(cls, name)
if isinstance(value, ItemsList):
result.append(value[0])
... | def function[all, parameter[cls]]:
constant[
Get all consts
:return: list
]
variable[result] assign[=] list[[]]
for taget[name[name]] in starred[call[name[dir], parameter[name[cls]]]] begin[:]
if <ast.UnaryOp object at 0x7da1b18322c0> begin[:]
... | keyword[def] identifier[all] ( identifier[cls] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[name] keyword[in] identifier[dir] ( identifier[cls] ):
keyword[if] keyword[not] identifier[name] . identifier[isupper] ():
keyword[continue]
... | def all(cls):
"""
Get all consts
:return: list
"""
result = []
for name in dir(cls):
if not name.isupper():
continue # depends on [control=['if'], data=[]]
value = getattr(cls, name)
if isinstance(value, ItemsList):
result.append(value... |
def get_set(self, project, articleset, **filters):
"""List the articlesets in a project"""
url = URL.articleset.format(**locals())
return self.request(url, **filters) | def function[get_set, parameter[self, project, articleset]]:
constant[List the articlesets in a project]
variable[url] assign[=] call[name[URL].articleset.format, parameter[]]
return[call[name[self].request, parameter[name[url]]]] | keyword[def] identifier[get_set] ( identifier[self] , identifier[project] , identifier[articleset] ,** identifier[filters] ):
literal[string]
identifier[url] = identifier[URL] . identifier[articleset] . identifier[format] (** identifier[locals] ())
keyword[return] identifier[self] . ident... | def get_set(self, project, articleset, **filters):
"""List the articlesets in a project"""
url = URL.articleset.format(**locals())
return self.request(url, **filters) |
def parse_bcftools_stats(self):
"""
Find bcftools stats logs and parse their data
Bcftools stats reports contain 'sets' of data, which can
have multiple vcf files each (but usually don't). Here,
we treat each 'set' as a MultiQC sample, taking the first
input filen... | def function[parse_bcftools_stats, parameter[self]]:
constant[
Find bcftools stats logs and parse their data
Bcftools stats reports contain 'sets' of data, which can
have multiple vcf files each (but usually don't). Here,
we treat each 'set' as a MultiQC sample, taking the ... | keyword[def] identifier[parse_bcftools_stats] ( identifier[self] ):
literal[string]
identifier[collapse_complementary] = identifier[getattr] ( identifier[config] , literal[string] ,{}). identifier[get] ( literal[string] , keyword[False] )
keyword[if] identifier[collapse_complementary] :
... | def parse_bcftools_stats(self):
"""
Find bcftools stats logs and parse their data
Bcftools stats reports contain 'sets' of data, which can
have multiple vcf files each (but usually don't). Here,
we treat each 'set' as a MultiQC sample, taking the first
input filename ... |
def to_mono(y):
'''Force an audio signal down to mono.
Parameters
----------
y : np.ndarray [shape=(2,n) or shape=(n,)]
audio time series, either stereo or mono
Returns
-------
y_mono : np.ndarray [shape=(n,)]
`y` as a monophonic time-series
Notes
-----
This fu... | def function[to_mono, parameter[y]]:
constant[Force an audio signal down to mono.
Parameters
----------
y : np.ndarray [shape=(2,n) or shape=(n,)]
audio time series, either stereo or mono
Returns
-------
y_mono : np.ndarray [shape=(n,)]
`y` as a monophonic time-series
... | keyword[def] identifier[to_mono] ( identifier[y] ):
literal[string]
identifier[util] . identifier[valid_audio] ( identifier[y] , identifier[mono] = keyword[False] )
keyword[if] identifier[y] . identifier[ndim] > literal[int] :
identifier[y] = identifier[np] . identifier[mean] ( identi... | def to_mono(y):
"""Force an audio signal down to mono.
Parameters
----------
y : np.ndarray [shape=(2,n) or shape=(n,)]
audio time series, either stereo or mono
Returns
-------
y_mono : np.ndarray [shape=(n,)]
`y` as a monophonic time-series
Notes
-----
This fu... |
def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s | def function[_create_socket, parameter[self]]:
constant[Creates ssl socket, connects to stream api and
sets timeout.
]
variable[s] assign[=] call[name[socket].socket, parameter[name[socket].AF_INET, name[socket].SOCK_STREAM]]
variable[s] assign[=] call[name[ssl].wrap_socket, para... | keyword[def] identifier[_create_socket] ( identifier[self] ):
literal[string]
identifier[s] = identifier[socket] . identifier[socket] ( identifier[socket] . identifier[AF_INET] , identifier[socket] . identifier[SOCK_STREAM] )
identifier[s] = identifier[ssl] . identifier[wrap_socket] ( iden... | def _create_socket(self):
"""Creates ssl socket, connects to stream api and
sets timeout.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s = ssl.wrap_socket(s)
s.connect((self.host, self.__port))
s.settimeout(self.timeout)
return s |
def user_info(self, username):
"""
Get info of a specific user.
:param username: the username of the user to get info about
:return:
"""
request_url = "{}/api/0/user/{}".format(self.instance, username)
return_value = self._call_api(request_url)
return re... | def function[user_info, parameter[self, username]]:
constant[
Get info of a specific user.
:param username: the username of the user to get info about
:return:
]
variable[request_url] assign[=] call[constant[{}/api/0/user/{}].format, parameter[name[self].instance, name[us... | keyword[def] identifier[user_info] ( identifier[self] , identifier[username] ):
literal[string]
identifier[request_url] = literal[string] . identifier[format] ( identifier[self] . identifier[instance] , identifier[username] )
identifier[return_value] = identifier[self] . identifier[_call_... | def user_info(self, username):
"""
Get info of a specific user.
:param username: the username of the user to get info about
:return:
"""
request_url = '{}/api/0/user/{}'.format(self.instance, username)
return_value = self._call_api(request_url)
return return_value |
def article(request, slug):
"""
The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article.
"""
# Get current CMS Page as article tree
tree = request.current_page.get_public_object()
# Check whether it really is a tree.
# It could also be one of its sub-pa... | def function[article, parameter[request, slug]]:
constant[
The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article.
]
variable[tree] assign[=] call[name[request].current_page.get_public_object, parameter[]]
if compare[name[tree].application_urls not_... | keyword[def] identifier[article] ( identifier[request] , identifier[slug] ):
literal[string]
identifier[tree] = identifier[request] . identifier[current_page] . identifier[get_public_object] ()
keyword[if] identifier[tree] . identifier[application_urls] != literal[string] :
... | def article(request, slug):
"""
The main view of the Django-CMS Articles! Takes a request and a slug,
renders the article.
"""
# Get current CMS Page as article tree
tree = request.current_page.get_public_object()
# Check whether it really is a tree.
# It could also be one of its sub-pag... |
def make_step_lcont (transition):
"""Return a ufunc-like step function that is left-continuous. Returns 1 if
x > transition, 0 otherwise.
"""
if not np.isfinite (transition):
raise ValueError ('"transition" argument must be finite number; got %r' % transition)
def step_lcont (x):
x... | def function[make_step_lcont, parameter[transition]]:
constant[Return a ufunc-like step function that is left-continuous. Returns 1 if
x > transition, 0 otherwise.
]
if <ast.UnaryOp object at 0x7da2047e9c90> begin[:]
<ast.Raise object at 0x7da1b26b7be0>
def function[step_lcont, ... | keyword[def] identifier[make_step_lcont] ( identifier[transition] ):
literal[string]
keyword[if] keyword[not] identifier[np] . identifier[isfinite] ( identifier[transition] ):
keyword[raise] identifier[ValueError] ( literal[string] % identifier[transition] )
keyword[def] identifier[step_... | def make_step_lcont(transition):
"""Return a ufunc-like step function that is left-continuous. Returns 1 if
x > transition, 0 otherwise.
"""
if not np.isfinite(transition):
raise ValueError('"transition" argument must be finite number; got %r' % transition) # depends on [control=['if'], data=[... |
def set_edge_label(self, edge, label):
"""
Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label.
"""
self.set_edge_properties(edge, label=label )
if not self.DIRECTED:
self.s... | def function[set_edge_label, parameter[self, edge, label]]:
constant[
Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label.
]
call[name[self].set_edge_properties, parameter[name[edge]]]
... | keyword[def] identifier[set_edge_label] ( identifier[self] , identifier[edge] , identifier[label] ):
literal[string]
identifier[self] . identifier[set_edge_properties] ( identifier[edge] , identifier[label] = identifier[label] )
keyword[if] keyword[not] identifier[self] . identifier[DIRE... | def set_edge_label(self, edge, label):
"""
Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label.
"""
self.set_edge_properties(edge, label=label)
if not self.DIRECTED:
self.set_edge_propertie... |
async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None):
"""|coro|
Changes the client's presence.
The activity parameter is a :class:`Activity` object (not a string) that represents
the activity being done currently. This could also be the slimmed down ... | <ast.AsyncFunctionDef object at 0x7da1b1f25f60> | keyword[async] keyword[def] identifier[change_presence] ( identifier[self] ,*, identifier[activity] = keyword[None] , identifier[status] = keyword[None] , identifier[afk] = keyword[False] , identifier[shard_id] = keyword[None] ):
literal[string]
keyword[if] identifier[status] keyword[is] keywo... | async def change_presence(self, *, activity=None, status=None, afk=False, shard_id=None):
"""|coro|
Changes the client's presence.
The activity parameter is a :class:`Activity` object (not a string) that represents
the activity being done currently. This could also be the slimmed down vers... |
def create(self):
""" Override method for creating FormBaseNew form """
self.add_handlers({'^T': self.quit, '^Q': self.quit,
'^V': self.toggle_view})
self.add(npyscreen.TitleFixedText, name=self.action['title'], value='')
response = self.action['api_action'].in... | def function[create, parameter[self]]:
constant[ Override method for creating FormBaseNew form ]
call[name[self].add_handlers, parameter[dictionary[[<ast.Constant object at 0x7da2047eb400>, <ast.Constant object at 0x7da2047e85e0>, <ast.Constant object at 0x7da2047ea1a0>], [<ast.Attribute object at 0x7da... | keyword[def] identifier[create] ( identifier[self] ):
literal[string]
identifier[self] . identifier[add_handlers] ({ literal[string] : identifier[self] . identifier[quit] , literal[string] : identifier[self] . identifier[quit] ,
literal[string] : identifier[self] . identifier[toggle_view] ... | def create(self):
""" Override method for creating FormBaseNew form """
self.add_handlers({'^T': self.quit, '^Q': self.quit, '^V': self.toggle_view})
self.add(npyscreen.TitleFixedText, name=self.action['title'], value='')
response = self.action['api_action'].inventory(choices=['repos', 'tools', 'images'... |
def _parse_match(self, match):
"""
If there is a group dict, return the dict;
even if there's only one value in the dict, return a dictionary;
If there is a group in match, return the group;
if there is only one value in the group, return the value;
if there has n... | def function[_parse_match, parameter[self, match]]:
constant[
If there is a group dict, return the dict;
even if there's only one value in the dict, return a dictionary;
If there is a group in match, return the group;
if there is only one value in the group, return the va... | keyword[def] identifier[_parse_match] ( identifier[self] , identifier[match] ):
literal[string]
keyword[if] keyword[not] identifier[match] :
keyword[if] identifier[self] . identifier[default] :
keyword[return] identifier[self] . identifier[default]
ke... | def _parse_match(self, match):
"""
If there is a group dict, return the dict;
even if there's only one value in the dict, return a dictionary;
If there is a group in match, return the group;
if there is only one value in the group, return the value;
if there has no gr... |
def has_hints(self):
"""
True if self provides hints on the cutoff energy.
"""
for acc in ["low", "normal", "high"]:
try:
if self.hint_for_accuracy(acc) is None:
return False
except KeyError:
return False
... | def function[has_hints, parameter[self]]:
constant[
True if self provides hints on the cutoff energy.
]
for taget[name[acc]] in starred[list[[<ast.Constant object at 0x7da2047eac50>, <ast.Constant object at 0x7da2047e92a0>, <ast.Constant object at 0x7da2047e9600>]]] begin[:]
<ast... | keyword[def] identifier[has_hints] ( identifier[self] ):
literal[string]
keyword[for] identifier[acc] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
keyword[try] :
keyword[if] identifier[self] . identifier[hint_for_accuracy] ( identifier[acc] )... | def has_hints(self):
"""
True if self provides hints on the cutoff energy.
"""
for acc in ['low', 'normal', 'high']:
try:
if self.hint_for_accuracy(acc) is None:
return False # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]]
... |
def create_parser(self, subparsers):
"""
Creates the subparser for this particular command
"""
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents)
self.add_arguments()
self.parser.set_defaults(func=self.handle)
return self.parser | def function[create_parser, parameter[self, subparsers]]:
constant[
Creates the subparser for this particular command
]
name[self].parser assign[=] call[name[subparsers].add_parser, parameter[name[self].name]]
call[name[self].add_arguments, parameter[]]
call[name[self].pa... | keyword[def] identifier[create_parser] ( identifier[self] , identifier[subparsers] ):
literal[string]
identifier[self] . identifier[parser] = identifier[subparsers] . identifier[add_parser] ( identifier[self] . identifier[name] , identifier[help] = identifier[self] . identifier[help] , identifier[p... | def create_parser(self, subparsers):
"""
Creates the subparser for this particular command
"""
self.parser = subparsers.add_parser(self.name, help=self.help, parents=self.parents)
self.add_arguments()
self.parser.set_defaults(func=self.handle)
return self.parser |
def connect(cls, pipeline_method, name=None):
"""
Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None
"""
new_pool = pip... | def function[connect, parameter[cls, pipeline_method, name]]:
constant[
Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None
]
... | keyword[def] identifier[connect] ( identifier[cls] , identifier[pipeline_method] , identifier[name] = keyword[None] ):
literal[string]
identifier[new_pool] = identifier[pipeline_method] (). identifier[connection_pool]
keyword[try] :
keyword[if] identifier[cls] . identifier[g... | def connect(cls, pipeline_method, name=None):
"""
Low level logic to bind a callable method to a name.
Don't call this directly unless you know what you are doing.
:param pipeline_method: callable
:param name: str optional
:return: None
"""
new_pool = pipeline_me... |
def decorate_obj(parent, n, o, otype, recurse=True, redecorate=False):
"""Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (type): instance of the ... | def function[decorate_obj, parameter[parent, n, o, otype, recurse, redecorate]]:
constant[Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (typ... | keyword[def] identifier[decorate_obj] ( identifier[parent] , identifier[n] , identifier[o] , identifier[otype] , identifier[recurse] = keyword[True] , identifier[redecorate] = keyword[False] ):
literal[string]
keyword[global] identifier[_decor_count] , identifier[_decorated_o]
keyword[from] identif... | def decorate_obj(parent, n, o, otype, recurse=True, redecorate=False):
"""Adds the decoration for automated logging to the specified object, if it
hasn't already been done.
Args:
parent: object that `o` belongs to.
n (str): name in the parent's dictionary.
o (type): instance of the ... |
def event_estimation(self, event, logliks, logsumexps, renamed=''):
"""Show the values underlying bayesian modality estimations of an event
Parameters
----------
Returns
-------
Raises
------
"""
plotter = _ModelLoglikPlotter()
plotter... | def function[event_estimation, parameter[self, event, logliks, logsumexps, renamed]]:
constant[Show the values underlying bayesian modality estimations of an event
Parameters
----------
Returns
-------
Raises
------
]
variable[plotter] assign[... | keyword[def] identifier[event_estimation] ( identifier[self] , identifier[event] , identifier[logliks] , identifier[logsumexps] , identifier[renamed] = literal[string] ):
literal[string]
identifier[plotter] = identifier[_ModelLoglikPlotter] ()
identifier[plotter] . identifier[plot] ( ident... | def event_estimation(self, event, logliks, logsumexps, renamed=''):
"""Show the values underlying bayesian modality estimations of an event
Parameters
----------
Returns
-------
Raises
------
"""
plotter = _ModelLoglikPlotter()
plotter.plot(event,... |
def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks, w_dim, w_dim.size)... | def function[local_1d_halo_exchange, parameter[k, v, num_w_blocks, w_dim, mask_right]]:
constant[Halo exchange for keys and values for Local 1D attention.]
if compare[name[num_w_blocks] is_not constant[None]] begin[:]
if name[mask_right] begin[:]
variable[k] assig... | keyword[def] identifier[local_1d_halo_exchange] ( identifier[k] , identifier[v] , identifier[num_w_blocks] , identifier[w_dim] , identifier[mask_right] ):
literal[string]
keyword[if] identifier[num_w_blocks] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[mask_right] :
identifi... | def local_1d_halo_exchange(k, v, num_w_blocks, w_dim, mask_right):
"""Halo exchange for keys and values for Local 1D attention."""
if num_w_blocks is not None:
if mask_right:
k = mtf.left_halo_exchange(k, num_w_blocks, w_dim, w_dim.size)
v = mtf.left_halo_exchange(v, num_w_blocks... |
def ulocalized_time(self, time, context, request):
"""Returns the localized time in string format
"""
value = ut(time, long_format=self.show_time, time_only=False,
context=context, request=request)
return value or "" | def function[ulocalized_time, parameter[self, time, context, request]]:
constant[Returns the localized time in string format
]
variable[value] assign[=] call[name[ut], parameter[name[time]]]
return[<ast.BoolOp object at 0x7da18f09d300>] | keyword[def] identifier[ulocalized_time] ( identifier[self] , identifier[time] , identifier[context] , identifier[request] ):
literal[string]
identifier[value] = identifier[ut] ( identifier[time] , identifier[long_format] = identifier[self] . identifier[show_time] , identifier[time_only] = keyword[... | def ulocalized_time(self, time, context, request):
"""Returns the localized time in string format
"""
value = ut(time, long_format=self.show_time, time_only=False, context=context, request=request)
return value or '' |
def get_content_type(self, msg, content_type="HTML"):
"""
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type -... | def function[get_content_type, parameter[self, msg, content_type]]:
constant[
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
... | keyword[def] identifier[get_content_type] ( identifier[self] , identifier[msg] , identifier[content_type] = literal[string] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[content_type] . identifier[upper] ():
identifier[content_type] = identifier[self] . ident... | def get_content_type(self, msg, content_type='HTML'):
"""
Given an Email.Message object, gets the content-type payload
as specified by @content_type. This is the actual body of the
email.
@Params
msg - Email.Message object to get message content for
content_type - Typ... |
def get_name_for_model(cls, model):
""" Get a name for given class or model:
-- it's a service type for a service
-- it's a <service_type>.<resource_model_name> for a resource
"""
key = cls.get_model_key(model)
model_str = cls._get_model_str(model)
service... | def function[get_name_for_model, parameter[cls, model]]:
constant[ Get a name for given class or model:
-- it's a service type for a service
-- it's a <service_type>.<resource_model_name> for a resource
]
variable[key] assign[=] call[name[cls].get_model_key, parameter[nam... | keyword[def] identifier[get_name_for_model] ( identifier[cls] , identifier[model] ):
literal[string]
identifier[key] = identifier[cls] . identifier[get_model_key] ( identifier[model] )
identifier[model_str] = identifier[cls] . identifier[_get_model_str] ( identifier[model] )
ident... | def get_name_for_model(cls, model):
""" Get a name for given class or model:
-- it's a service type for a service
-- it's a <service_type>.<resource_model_name> for a resource
"""
key = cls.get_model_key(model)
model_str = cls._get_model_str(model)
service = cls._registry... |
def plot_isoratios(self,xiso,yiso,fign=1,spec=None,deltax=True,deltay=True,logx=False,logy=False,
title=None,legend=None,legloc='lower right',errbar=True,dcycle=500,addiso=None,
co_toggle='c',cust_toggle=None,shift=0,weighting=None,zoneselect=None,iniabufile='iniab2.0E-02... | def function[plot_isoratios, parameter[self, xiso, yiso, fign, spec, deltax, deltay, logx, logy, title, legend, legloc, errbar, dcycle, addiso, co_toggle, cust_toggle, shift, weighting, zoneselect, iniabufile, plt_sparse, plt_symb, plt_col, plt_lt, plt_lw, alpha_dum, plt_massrange, plt_show, figsave]]:
constant... | keyword[def] identifier[plot_isoratios] ( identifier[self] , identifier[xiso] , identifier[yiso] , identifier[fign] = literal[int] , identifier[spec] = keyword[None] , identifier[deltax] = keyword[True] , identifier[deltay] = keyword[True] , identifier[logx] = keyword[False] , identifier[logy] = keyword[False] ,
ide... | def plot_isoratios(self, xiso, yiso, fign=1, spec=None, deltax=True, deltay=True, logx=False, logy=False, title=None, legend=None, legloc='lower right', errbar=True, dcycle=500, addiso=None, co_toggle='c', cust_toggle=None, shift=0, weighting=None, zoneselect=None, iniabufile='iniab2.0E-02GN93.ppn', plt_sparse=1, plt_s... |
def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
""" dayofweek == 0 means Sunday, whichweek 5 means last instance """
first = datetime.datetime(year, month, 1, hour, minute)
# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),
# Because 7 % 7 = 0
weekdayo... | def function[picknthweekday, parameter[year, month, dayofweek, hour, minute, whichweek]]:
constant[ dayofweek == 0 means Sunday, whichweek 5 means last instance ]
variable[first] assign[=] call[name[datetime].datetime, parameter[name[year], name[month], constant[1], name[hour], name[minute]]]
va... | keyword[def] identifier[picknthweekday] ( identifier[year] , identifier[month] , identifier[dayofweek] , identifier[hour] , identifier[minute] , identifier[whichweek] ):
literal[string]
identifier[first] = identifier[datetime] . identifier[datetime] ( identifier[year] , identifier[month] , literal[int] , i... | def picknthweekday(year, month, dayofweek, hour, minute, whichweek):
""" dayofweek == 0 means Sunday, whichweek 5 means last instance """
first = datetime.datetime(year, month, 1, hour, minute)
# This will work if dayofweek is ISO weekday (1-7) or Microsoft-style (0-6),
# Because 7 % 7 = 0
weekdayon... |
def status():
'''Show the manager's current status.'''
with Session() as session:
resp = session.Manager.status()
print(tabulate([('Status', 'Active Sessions'),
(resp['status'], resp['active_sessions'])],
headers='firstrow')) | def function[status, parameter[]]:
constant[Show the manager's current status.]
with call[name[Session], parameter[]] begin[:]
variable[resp] assign[=] call[name[session].Manager.status, parameter[]]
call[name[print], parameter[call[name[tabulate], parameter[list[[<ast.Tu... | keyword[def] identifier[status] ():
literal[string]
keyword[with] identifier[Session] () keyword[as] identifier[session] :
identifier[resp] = identifier[session] . identifier[Manager] . identifier[status] ()
identifier[print] ( identifier[tabulate] ([( literal[string] , literal[string] ... | def status():
"""Show the manager's current status."""
with Session() as session:
resp = session.Manager.status()
print(tabulate([('Status', 'Active Sessions'), (resp['status'], resp['active_sessions'])], headers='firstrow')) # depends on [control=['with'], data=['session']] |
def findFile(input):
"""Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE)
if not input:
return no
# We use 'osfn' here to insure that any IRAF variables are
# expanded out before splitting out the path...
_fdir,... | def function[findFile, parameter[input]]:
constant[Search a directory for full filename with optional path.]
if <ast.UnaryOp object at 0x7da1b0ef7790> begin[:]
return[name[no]]
<ast.Tuple object at 0x7da1b0ef6080> assign[=] call[name[os].path.split, parameter[call[name[osfn], parameter[n... | keyword[def] identifier[findFile] ( identifier[input] ):
literal[string]
keyword[if] keyword[not] identifier[input] :
keyword[return] identifier[no]
identifier[_fdir] , identifier[_fname] = identifier[os] . identifier[path] . identifier[split] ( identifier[osfn] (... | def findFile(input):
"""Search a directory for full filename with optional path."""
# If no input name is provided, default to returning 'no'(FALSE)
if not input:
return no # depends on [control=['if'], data=[]]
# We use 'osfn' here to insure that any IRAF variables are
# expanded out befor... |
def iter_lines(self, warn_only=False):
"""yields stdout text, line by line."""
remain = ""
for data in self.iter_content(LINE_CHUNK_SIZE, warn_only=True):
line_break_found = data[-1] in (b"\n", b"\r")
lines = data.decode(self.codec).splitlines()
lines[0] = rem... | def function[iter_lines, parameter[self, warn_only]]:
constant[yields stdout text, line by line.]
variable[remain] assign[=] constant[]
for taget[name[data]] in starred[call[name[self].iter_content, parameter[name[LINE_CHUNK_SIZE]]]] begin[:]
variable[line_break_found] assign[=] ... | keyword[def] identifier[iter_lines] ( identifier[self] , identifier[warn_only] = keyword[False] ):
literal[string]
identifier[remain] = literal[string]
keyword[for] identifier[data] keyword[in] identifier[self] . identifier[iter_content] ( identifier[LINE_CHUNK_SIZE] , identifier[warn_... | def iter_lines(self, warn_only=False):
"""yields stdout text, line by line."""
remain = ''
for data in self.iter_content(LINE_CHUNK_SIZE, warn_only=True):
line_break_found = data[-1] in (b'\n', b'\r')
lines = data.decode(self.codec).splitlines()
lines[0] = remain + lines[0]
i... |
def closest_point_naive(mesh, points):
"""
Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimesh
Takes mesh to have same... | def function[closest_point_naive, parameter[mesh, points]]:
constant[
Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimes... | keyword[def] identifier[closest_point_naive] ( identifier[mesh] , identifier[points] ):
literal[string]
identifier[triangles] = identifier[mesh] . identifier[triangles] . identifier[view] ( identifier[np] . identifier[ndarray] )
identifier[points] = identifier[np] . identifier[asanyarray] ( ... | def closest_point_naive(mesh, points):
"""
Given a mesh and a list of points find the closest point
on any triangle.
Does this by constructing a very large intermediate array and
comparing every point to every triangle.
Parameters
----------
mesh : Trimesh
Takes mesh to have same... |
def select_newest_project(dx_project_ids):
"""
Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date.
Args:
dx_project_ids: `list` of DNAnexus project IDs.
Returns:
`str`.
"""
if len(dx_project_ids) == 1:
return dx_proj... | def function[select_newest_project, parameter[dx_project_ids]]:
constant[
Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date.
Args:
dx_project_ids: `list` of DNAnexus project IDs.
Returns:
`str`.
]
if compare[call[na... | keyword[def] identifier[select_newest_project] ( identifier[dx_project_ids] ):
literal[string]
keyword[if] identifier[len] ( identifier[dx_project_ids] )== literal[int] :
keyword[return] identifier[dx_project_ids] [ literal[int] ]
identifier[projects] =[ identifier[dxpy] . identifier[DXPro... | def select_newest_project(dx_project_ids):
"""
Given a list of DNAnexus project IDs, returns the one that is newest as determined by creation date.
Args:
dx_project_ids: `list` of DNAnexus project IDs.
Returns:
`str`.
"""
if len(dx_project_ids) == 1:
return dx_proj... |
def _evaluate3(nodes, x_val, y_val):
"""Helper for :func:`evaluate` when ``nodes`` is degree 3.
Args:
nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve.
x_val (float): ``x``-coordinate for evaluation.
y_val (float): ``y``-coordinate for evaluation.
Returns:
float: ... | def function[_evaluate3, parameter[nodes, x_val, y_val]]:
constant[Helper for :func:`evaluate` when ``nodes`` is degree 3.
Args:
nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve.
x_val (float): ``x``-coordinate for evaluation.
y_val (float): ``y``-coordinate for evaluation... | keyword[def] identifier[_evaluate3] ( identifier[nodes] , identifier[x_val] , identifier[y_val] ):
literal[string]
identifier[sylvester_mat] = identifier[np] . identifier[zeros] (( literal[int] , literal[int] ), identifier[order] = literal[string] )
identifier[delta] = identifier[nodes] - id... | def _evaluate3(nodes, x_val, y_val):
"""Helper for :func:`evaluate` when ``nodes`` is degree 3.
Args:
nodes (numpy.ndarray): ``2 x 4`` array of nodes in a curve.
x_val (float): ``x``-coordinate for evaluation.
y_val (float): ``y``-coordinate for evaluation.
Returns:
float: ... |
def get_settings_from_profile(profile, profile_dir=None):
# type: (str, Any)->str
""""Returns the configuration file path for the given profile.
:param profile: Profile name to be used.
:param profile_dir: The directory where the profile configuration file should reside. It
may... | def function[get_settings_from_profile, parameter[profile, profile_dir]]:
constant["Returns the configuration file path for the given profile.
:param profile: Profile name to be used.
:param profile_dir: The directory where the profile configuration file should reside. It
may b... | keyword[def] identifier[get_settings_from_profile] ( identifier[profile] , identifier[profile_dir] = keyword[None] ):
literal[string]
keyword[if] identifier[profile_dir] keyword[is] keyword[None] :
keyword[import] identifier[settings]
identifier[profile_dir] = identifier[settings]
... | def get_settings_from_profile(profile, profile_dir=None):
# type: (str, Any)->str
'"Returns the configuration file path for the given profile.\n\n :param profile: Profile name to be used.\n :param profile_dir: The directory where the profile configuration file should reside. It\n m... |
def run(self):
"""Starts the algo
Connects to the Blotter, processes market data and passes
tick data to the ``on_tick`` function and bar data to the
``on_bar`` methods.
"""
history = pd.DataFrame()
# get history from csv dir
if self.backtest and self.b... | def function[run, parameter[self]]:
constant[Starts the algo
Connects to the Blotter, processes market data and passes
tick data to the ``on_tick`` function and bar data to the
``on_bar`` methods.
]
variable[history] assign[=] call[name[pd].DataFrame, parameter[]]
... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[history] = identifier[pd] . identifier[DataFrame] ()
keyword[if] identifier[self] . identifier[backtest] keyword[and] identifier[self] . identifier[backtest_csv] :
identifier[kind] = li... | def run(self):
"""Starts the algo
Connects to the Blotter, processes market data and passes
tick data to the ``on_tick`` function and bar data to the
``on_bar`` methods.
"""
history = pd.DataFrame()
# get history from csv dir
if self.backtest and self.backtest_csv:
... |
def generate_nonce():
""" Generate nonce number """
nonce = ''.join([str(randint(0, 9)) for i in range(8)])
return HMAC(
nonce.encode(),
"secret".encode(),
sha1
).hexdigest() | def function[generate_nonce, parameter[]]:
constant[ Generate nonce number ]
variable[nonce] assign[=] call[constant[].join, parameter[<ast.ListComp object at 0x7da20c6abd00>]]
return[call[call[name[HMAC], parameter[call[name[nonce].encode, parameter[]], call[constant[secret].encode, parameter[]], n... | keyword[def] identifier[generate_nonce] ():
literal[string]
identifier[nonce] = literal[string] . identifier[join] ([ identifier[str] ( identifier[randint] ( literal[int] , literal[int] )) keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] )])
keyword[return] ident... | def generate_nonce():
""" Generate nonce number """
nonce = ''.join([str(randint(0, 9)) for i in range(8)])
return HMAC(nonce.encode(), 'secret'.encode(), sha1).hexdigest() |
def _parse_get_snapshot_schedule(cls, args):
"""
Parse command line arguments for updating hbase snapshot schedule or to get details.
"""
argparser = ArgumentParser(prog="cluster snapshot_schedule")
group = argparser.add_mutually_exclusive_group(required=True)
group.add_... | def function[_parse_get_snapshot_schedule, parameter[cls, args]]:
constant[
Parse command line arguments for updating hbase snapshot schedule or to get details.
]
variable[argparser] assign[=] call[name[ArgumentParser], parameter[]]
variable[group] assign[=] call[name[argparser].... | keyword[def] identifier[_parse_get_snapshot_schedule] ( identifier[cls] , identifier[args] ):
literal[string]
identifier[argparser] = identifier[ArgumentParser] ( identifier[prog] = literal[string] )
identifier[group] = identifier[argparser] . identifier[add_mutually_exclusive_group] ( id... | def _parse_get_snapshot_schedule(cls, args):
"""
Parse command line arguments for updating hbase snapshot schedule or to get details.
"""
argparser = ArgumentParser(prog='cluster snapshot_schedule')
group = argparser.add_mutually_exclusive_group(required=True)
group.add_argument('--id', ... |
def get_for_org(self, org_id, ids, skip_cache=False):
'''
Returns objects for the given identifiers
If called with a list returns a list, else returns a single entity
'''
t = type(ids)
if t != list:
ids = [ids]
objs = []
... | def function[get_for_org, parameter[self, org_id, ids, skip_cache]]:
constant[
Returns objects for the given identifiers
If called with a list returns a list, else returns a single entity
]
variable[t] assign[=] call[name[type], parameter[name[ids]]]
if compare[name[t] no... | keyword[def] identifier[get_for_org] ( identifier[self] , identifier[org_id] , identifier[ids] , identifier[skip_cache] = keyword[False] ):
literal[string]
identifier[t] = identifier[type] ( identifier[ids] )
keyword[if] identifier[t] != identifier[list] :
identifier[ids] =[ ... | def get_for_org(self, org_id, ids, skip_cache=False):
"""
Returns objects for the given identifiers
If called with a list returns a list, else returns a single entity
"""
t = type(ids)
if t != list:
ids = [ids] # depends on [control=['if'], data=[]]
objs = []
for id ... |
def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
'''
remove and purge do identical things but with different pacman commands,
this function performs the common logic.
'''
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0]
except MinionError as exc:
... | def function[_uninstall, parameter[action, name, pkgs]]:
constant[
remove and purge do identical things but with different pacman commands,
this function performs the common logic.
]
<ast.Try object at 0x7da1b2135330>
variable[old] assign[=] call[name[list_pkgs], parameter[]]
var... | keyword[def] identifier[_uninstall] ( identifier[action] = literal[string] , identifier[name] = keyword[None] , identifier[pkgs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[pkg_params] = identifier[__salt__] [ literal[string] ]( identifier[name] , identifier... | def _uninstall(action='remove', name=None, pkgs=None, **kwargs):
"""
remove and purge do identical things but with different pacman commands,
this function performs the common logic.
"""
try:
pkg_params = __salt__['pkg_resource.parse_targets'](name, pkgs)[0] # depends on [control=['try'], d... |
def jsonify(py_data, default=None, indent=4, sort_keys=True):
"""
Converts the inputted Python data to JSON format.
:param py_data | <variant>
"""
return json.dumps(py_data, default=py2json, indent=indent, sort_keys=sort_keys) | def function[jsonify, parameter[py_data, default, indent, sort_keys]]:
constant[
Converts the inputted Python data to JSON format.
:param py_data | <variant>
]
return[call[name[json].dumps, parameter[name[py_data]]]] | keyword[def] identifier[jsonify] ( identifier[py_data] , identifier[default] = keyword[None] , identifier[indent] = literal[int] , identifier[sort_keys] = keyword[True] ):
literal[string]
keyword[return] identifier[json] . identifier[dumps] ( identifier[py_data] , identifier[default] = identifier[py2json]... | def jsonify(py_data, default=None, indent=4, sort_keys=True):
"""
Converts the inputted Python data to JSON format.
:param py_data | <variant>
"""
return json.dumps(py_data, default=py2json, indent=indent, sort_keys=sort_keys) |
def set_application_language(params):
"""Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
:type params: object
""... | def function[set_application_language, parameter[params]]:
constant[Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
... | keyword[def] identifier[set_application_language] ( identifier[params] ):
literal[string]
identifier[lang] = identifier[params] . identifier[get] ( literal[string] , literal[string] , keyword[None] )
keyword[if] identifier[lang] :
identifier[set_locale] ( identifier[lang] )
identifi... | def set_application_language(params):
"""Set the locale and translation for a pywws program.
This function reads the language from the configuration file, then
calls :func:`set_locale` and :func:`set_translation`.
:param params: a :class:`pywws.storage.params` object.
:type params: object
""... |
def update_default_rules(self):
"""Concatinate application and global security group rules."""
app_ingress = self.properties['security_group']['ingress']
ingress = conservative_merger.merge(DEFAULT_SECURITYGROUP_RULES, app_ingress)
resolved_ingress = self.resolve_self_references(ingress)... | def function[update_default_rules, parameter[self]]:
constant[Concatinate application and global security group rules.]
variable[app_ingress] assign[=] call[call[name[self].properties][constant[security_group]]][constant[ingress]]
variable[ingress] assign[=] call[name[conservative_merger].merge,... | keyword[def] identifier[update_default_rules] ( identifier[self] ):
literal[string]
identifier[app_ingress] = identifier[self] . identifier[properties] [ literal[string] ][ literal[string] ]
identifier[ingress] = identifier[conservative_merger] . identifier[merge] ( identifier[DEFAULT_SECU... | def update_default_rules(self):
"""Concatinate application and global security group rules."""
app_ingress = self.properties['security_group']['ingress']
ingress = conservative_merger.merge(DEFAULT_SECURITYGROUP_RULES, app_ingress)
resolved_ingress = self.resolve_self_references(ingress)
self.log.in... |
def generate_sample_cfn_module(env_root, module_dir=None):
"""Generate skeleton CloudFormation sample module."""
if module_dir is None:
module_dir = os.path.join(env_root, 'sampleapp.cfn')
generate_sample_module(module_dir)
for i in ['stacks.yaml', 'dev-us-east-1.env']:
shutil.copyfile(
... | def function[generate_sample_cfn_module, parameter[env_root, module_dir]]:
constant[Generate skeleton CloudFormation sample module.]
if compare[name[module_dir] is constant[None]] begin[:]
variable[module_dir] assign[=] call[name[os].path.join, parameter[name[env_root], constant[sampleap... | keyword[def] identifier[generate_sample_cfn_module] ( identifier[env_root] , identifier[module_dir] = keyword[None] ):
literal[string]
keyword[if] identifier[module_dir] keyword[is] keyword[None] :
identifier[module_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[env_ro... | def generate_sample_cfn_module(env_root, module_dir=None):
"""Generate skeleton CloudFormation sample module."""
if module_dir is None:
module_dir = os.path.join(env_root, 'sampleapp.cfn') # depends on [control=['if'], data=['module_dir']]
generate_sample_module(module_dir)
for i in ['stacks.ya... |
def set_bounds(self, lb, ub):
"""
Change the lower and upper bounds of a variable.
"""
if lb is not None and ub is not None and lb > ub:
raise ValueError(
"The provided lower bound {} is larger than the provided upper bound {}".format(lb, ub)
)
... | def function[set_bounds, parameter[self, lb, ub]]:
constant[
Change the lower and upper bounds of a variable.
]
if <ast.BoolOp object at 0x7da1b0b7f310> begin[:]
<ast.Raise object at 0x7da1b0b7fd00>
name[self]._lb assign[=] name[lb]
name[self]._ub assign[=] name[u... | keyword[def] identifier[set_bounds] ( identifier[self] , identifier[lb] , identifier[ub] ):
literal[string]
keyword[if] identifier[lb] keyword[is] keyword[not] keyword[None] keyword[and] identifier[ub] keyword[is] keyword[not] keyword[None] keyword[and] identifier[lb] > identifier[ub] :
... | def set_bounds(self, lb, ub):
"""
Change the lower and upper bounds of a variable.
"""
if lb is not None and ub is not None and (lb > ub):
raise ValueError('The provided lower bound {} is larger than the provided upper bound {}'.format(lb, ub)) # depends on [control=['if'], data=[]]
... |
def raise_402(instance, msg=None):
"""Abort the current request with a 402 (Payment Required) response code.
If the message is given it's output as an error message in the response
body (correctly converted to the requested MIME type).
:param instance: Resource instance (used to access the response)
... | def function[raise_402, parameter[instance, msg]]:
constant[Abort the current request with a 402 (Payment Required) response code.
If the message is given it's output as an error message in the response
body (correctly converted to the requested MIME type).
:param instance: Resource instance (used ... | keyword[def] identifier[raise_402] ( identifier[instance] , identifier[msg] = keyword[None] ):
literal[string]
identifier[instance] . identifier[response] . identifier[status] = literal[int]
keyword[if] identifier[msg] :
identifier[instance] . identifier[response] . identifier[body_raw] ={ ... | def raise_402(instance, msg=None):
"""Abort the current request with a 402 (Payment Required) response code.
If the message is given it's output as an error message in the response
body (correctly converted to the requested MIME type).
:param instance: Resource instance (used to access the response)
... |
def filter_counter(self, counter, min=2, max=100000000):
"""
Filter the counted records.
Returns: List with record numbers.
"""
records_filterd = {}
counter_all_records = 0
for item in counter:
counter_all_records += 1
if max > counter[ite... | def function[filter_counter, parameter[self, counter, min, max]]:
constant[
Filter the counted records.
Returns: List with record numbers.
]
variable[records_filterd] assign[=] dictionary[[], []]
variable[counter_all_records] assign[=] constant[0]
for taget[name[... | keyword[def] identifier[filter_counter] ( identifier[self] , identifier[counter] , identifier[min] = literal[int] , identifier[max] = literal[int] ):
literal[string]
identifier[records_filterd] ={}
identifier[counter_all_records] = literal[int]
keyword[for] identifier[item] key... | def filter_counter(self, counter, min=2, max=100000000):
"""
Filter the counted records.
Returns: List with record numbers.
"""
records_filterd = {}
counter_all_records = 0
for item in counter:
counter_all_records += 1
if max > counter[item] >= min:
r... |
def from_file(cls, fmt, filename=None,
structure_file=None, are_coops=False):
"""
Creates a CompleteCohp object from an output file of a COHP
calculation. Valid formats are either LMTO (for the Stuttgart
LMTO-ASA code) or LOBSTER (for the LOBSTER code).
Args:
... | def function[from_file, parameter[cls, fmt, filename, structure_file, are_coops]]:
constant[
Creates a CompleteCohp object from an output file of a COHP
calculation. Valid formats are either LMTO (for the Stuttgart
LMTO-ASA code) or LOBSTER (for the LOBSTER code).
Args:
... | keyword[def] identifier[from_file] ( identifier[cls] , identifier[fmt] , identifier[filename] = keyword[None] ,
identifier[structure_file] = keyword[None] , identifier[are_coops] = keyword[False] ):
literal[string]
identifier[fmt] = identifier[fmt] . identifier[upper] ()
keyword[if] iden... | def from_file(cls, fmt, filename=None, structure_file=None, are_coops=False):
"""
Creates a CompleteCohp object from an output file of a COHP
calculation. Valid formats are either LMTO (for the Stuttgart
LMTO-ASA code) or LOBSTER (for the LOBSTER code).
Args:
cohp_file: ... |
def accept(self, f, *args):
"""Like 'match', but consume the token (tokenizer advances.)"""
match = self.match(f, *args)
if match is None:
return
self.tokenizer.skip(len(match.tokens))
return match | def function[accept, parameter[self, f]]:
constant[Like 'match', but consume the token (tokenizer advances.)]
variable[match] assign[=] call[name[self].match, parameter[name[f], <ast.Starred object at 0x7da1b0fd17b0>]]
if compare[name[match] is constant[None]] begin[:]
return[None]
... | keyword[def] identifier[accept] ( identifier[self] , identifier[f] ,* identifier[args] ):
literal[string]
identifier[match] = identifier[self] . identifier[match] ( identifier[f] ,* identifier[args] )
keyword[if] identifier[match] keyword[is] keyword[None] :
keyword[return]... | def accept(self, f, *args):
"""Like 'match', but consume the token (tokenizer advances.)"""
match = self.match(f, *args)
if match is None:
return # depends on [control=['if'], data=[]]
self.tokenizer.skip(len(match.tokens))
return match |
def display_leader_imbalance(cluster_topologies):
"""Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
... | def function[display_leader_imbalance, parameter[cluster_topologies]]:
constant[Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
]
variable[broker_ids] assign[=] call[name[list], parameter[ca... | keyword[def] identifier[display_leader_imbalance] ( identifier[cluster_topologies] ):
literal[string]
identifier[broker_ids] = identifier[list] ( identifier[next] ( identifier[six] . identifier[itervalues] ( identifier[cluster_topologies] )). identifier[brokers] . identifier[keys] ())
keyword[assert] ... | def display_leader_imbalance(cluster_topologies):
"""Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object.
"""
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all((se... |
def output_cleaned(self, process_data):
"""
Return verified and cleaned output.
Parameters
----------
process_data : raw process output
Returns
-------
NumPy array or list of features.
"""
if self.METADATA["data_type"] == "raster":
... | def function[output_cleaned, parameter[self, process_data]]:
constant[
Return verified and cleaned output.
Parameters
----------
process_data : raw process output
Returns
-------
NumPy array or list of features.
]
if compare[call[name[sel... | keyword[def] identifier[output_cleaned] ( identifier[self] , identifier[process_data] ):
literal[string]
keyword[if] identifier[self] . identifier[METADATA] [ literal[string] ]== literal[string] :
keyword[if] identifier[is_numpy_or_masked_array] ( identifier[process_data] ):
... | def output_cleaned(self, process_data):
"""
Return verified and cleaned output.
Parameters
----------
process_data : raw process output
Returns
-------
NumPy array or list of features.
"""
if self.METADATA['data_type'] == 'raster':
if is_... |
def set_total_deposit(
self,
given_block_identifier: BlockSpecification,
channel_identifier: ChannelID,
total_deposit: TokenAmount,
partner: Address,
):
""" Set channel's total deposit.
`total_deposit` has to be monotonically increasing, t... | def function[set_total_deposit, parameter[self, given_block_identifier, channel_identifier, total_deposit, partner]]:
constant[ Set channel's total deposit.
`total_deposit` has to be monotonically increasing, this is enforced by
the `TokenNetwork` smart contract. This is done for the same reaso... | keyword[def] identifier[set_total_deposit] (
identifier[self] ,
identifier[given_block_identifier] : identifier[BlockSpecification] ,
identifier[channel_identifier] : identifier[ChannelID] ,
identifier[total_deposit] : identifier[TokenAmount] ,
identifier[partner] : identifier[Address] ,
):
literal[stri... | def set_total_deposit(self, given_block_identifier: BlockSpecification, channel_identifier: ChannelID, total_deposit: TokenAmount, partner: Address):
""" Set channel's total deposit.
`total_deposit` has to be monotonically increasing, this is enforced by
the `TokenNetwork` smart contract. This is d... |
def get_win_launcher(type):
"""
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
"""
launcher_fn = '%s.exe' % type
if is_64bit():
launcher_fn = launcher_fn.replace(".", "-64.")
... | def function[get_win_launcher, parameter[type]]:
constant[
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
]
variable[launcher_fn] assign[=] binary_operation[constant[%s.exe] <ast.Mo... | keyword[def] identifier[get_win_launcher] ( identifier[type] ):
literal[string]
identifier[launcher_fn] = literal[string] % identifier[type]
keyword[if] identifier[is_64bit] ():
identifier[launcher_fn] = identifier[launcher_fn] . identifier[replace] ( literal[string] , literal[string] )
... | def get_win_launcher(type):
"""
Load the Windows launcher (executable) suitable for launching a script.
`type` should be either 'cli' or 'gui'
Returns the executable as a byte string.
"""
launcher_fn = '%s.exe' % type
if is_64bit():
launcher_fn = launcher_fn.replace('.', '-64.') #... |
def image_files_download(self, image_id):
"""Get data file for image with given identifier.
Parameters
----------
image_id : string
Unique image identifier
Returns
-------
FileInfo
Information about image file on disk or None if identifie... | def function[image_files_download, parameter[self, image_id]]:
constant[Get data file for image with given identifier.
Parameters
----------
image_id : string
Unique image identifier
Returns
-------
FileInfo
Information about image file o... | keyword[def] identifier[image_files_download] ( identifier[self] , identifier[image_id] ):
literal[string]
identifier[img] = identifier[self] . identifier[image_files_get] ( identifier[image_id] )
keyword[if] identifier[img] keyword[is] keyword[None] :
key... | def image_files_download(self, image_id):
"""Get data file for image with given identifier.
Parameters
----------
image_id : string
Unique image identifier
Returns
-------
FileInfo
Information about image file on disk or None if identifier
... |
def get_parchg(self, poscar, kpoint, band, spin=None, phase=False,
scale=2):
"""
Generates a Chgcar object, which is the charge density of the specified
wavefunction.
This function generates a Chgcar object with the charge density of the
wavefunction specified... | def function[get_parchg, parameter[self, poscar, kpoint, band, spin, phase, scale]]:
constant[
Generates a Chgcar object, which is the charge density of the specified
wavefunction.
This function generates a Chgcar object with the charge density of the
wavefunction specified by b... | keyword[def] identifier[get_parchg] ( identifier[self] , identifier[poscar] , identifier[kpoint] , identifier[band] , identifier[spin] = keyword[None] , identifier[phase] = keyword[False] ,
identifier[scale] = literal[int] ):
literal[string]
keyword[if] identifier[phase] keyword[and] keyword[n... | def get_parchg(self, poscar, kpoint, band, spin=None, phase=False, scale=2):
"""
Generates a Chgcar object, which is the charge density of the specified
wavefunction.
This function generates a Chgcar object with the charge density of the
wavefunction specified by band and kpoint (an... |
def get_current_hgnc_id(hgnc_name):
"""Return the HGNC ID(s) corresponding to a current or outdate HGNC symbol.
Parameters
----------
hgnc_name : str
The HGNC symbol to be converted, possibly an outdated symbol.
Returns
-------
str or list of str or None
If there is a singl... | def function[get_current_hgnc_id, parameter[hgnc_name]]:
constant[Return the HGNC ID(s) corresponding to a current or outdate HGNC symbol.
Parameters
----------
hgnc_name : str
The HGNC symbol to be converted, possibly an outdated symbol.
Returns
-------
str or list of str or N... | keyword[def] identifier[get_current_hgnc_id] ( identifier[hgnc_name] ):
literal[string]
identifier[hgnc_id] = identifier[get_hgnc_id] ( identifier[hgnc_name] )
keyword[if] identifier[hgnc_id] :
keyword[return] identifier[hgnc_id]
identifier[hgnc_id] = identifier[prev_sym_map] . identi... | def get_current_hgnc_id(hgnc_name):
"""Return the HGNC ID(s) corresponding to a current or outdate HGNC symbol.
Parameters
----------
hgnc_name : str
The HGNC symbol to be converted, possibly an outdated symbol.
Returns
-------
str or list of str or None
If there is a singl... |
def next_token(self):
"""Lexical analyser of the raw input."""
while self.char is not None:
if self.char.isspace():
# The current character is a whitespace
self.whitespace()
continue
elif self.char == '#':
# The cu... | def function[next_token, parameter[self]]:
constant[Lexical analyser of the raw input.]
while compare[name[self].char is_not constant[None]] begin[:]
if call[name[self].char.isspace, parameter[]] begin[:]
call[name[self].whitespace, parameter[]]
contin... | keyword[def] identifier[next_token] ( identifier[self] ):
literal[string]
keyword[while] identifier[self] . identifier[char] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[char] . identifier[isspace] ():
identifier... | def next_token(self):
"""Lexical analyser of the raw input."""
while self.char is not None:
if self.char.isspace():
# The current character is a whitespace
self.whitespace()
continue # depends on [control=['if'], data=[]]
elif self.char == '#':
# ... |
def _parse_header_id(line):
"""
Pull the transcript or protein identifier from the header line
which starts with '>'
"""
if type(line) is not binary_type:
raise TypeError("Expected header line to be of type %s but got %s" % (
binary_type, type(line)))
if len(line) <= 1:
... | def function[_parse_header_id, parameter[line]]:
constant[
Pull the transcript or protein identifier from the header line
which starts with '>'
]
if compare[call[name[type], parameter[name[line]]] is_not name[binary_type]] begin[:]
<ast.Raise object at 0x7da1b08d4a30>
if comp... | keyword[def] identifier[_parse_header_id] ( identifier[line] ):
literal[string]
keyword[if] identifier[type] ( identifier[line] ) keyword[is] keyword[not] identifier[binary_type] :
keyword[raise] identifier[TypeError] ( literal[string] %(
identifier[binary_type] , identifier[type] ( i... | def _parse_header_id(line):
"""
Pull the transcript or protein identifier from the header line
which starts with '>'
"""
if type(line) is not binary_type:
raise TypeError('Expected header line to be of type %s but got %s' % (binary_type, type(line))) # depends on [control=['if'], data=['bin... |
def getTextFromNode(node):
"""
Scans through all children of node and gathers the
text. If node has non-text child-nodes then
NotTextNodeError is raised.
"""
t = ""
for n in node.childNodes:
if n.nodeType == n.TEXT_NODE:
t += n.nodeValue
else:
raise No... | def function[getTextFromNode, parameter[node]]:
constant[
Scans through all children of node and gathers the
text. If node has non-text child-nodes then
NotTextNodeError is raised.
]
variable[t] assign[=] constant[]
for taget[name[n]] in starred[name[node].childNodes] begin[:]
... | keyword[def] identifier[getTextFromNode] ( identifier[node] ):
literal[string]
identifier[t] = literal[string]
keyword[for] identifier[n] keyword[in] identifier[node] . identifier[childNodes] :
keyword[if] identifier[n] . identifier[nodeType] == identifier[n] . identifier[TEXT_NODE] :
... | def getTextFromNode(node):
"""
Scans through all children of node and gathers the
text. If node has non-text child-nodes then
NotTextNodeError is raised.
"""
t = ''
for n in node.childNodes:
if n.nodeType == n.TEXT_NODE:
t += n.nodeValue # depends on [control=['if'], dat... |
def create_session_entity_type(
self,
parent,
session_entity_type,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates a session entity type.
Example:
... | def function[create_session_entity_type, parameter[self, parent, session_entity_type, retry, timeout, metadata]]:
constant[
Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.SessionEntityTypesClient()
... | keyword[def] identifier[create_session_entity_type] (
identifier[self] ,
identifier[parent] ,
identifier[session_entity_type] ,
identifier[retry] = identifier[google] . identifier[api_core] . identifier[gapic_v1] . identifier[method] . identifier[DEFAULT] ,
identifier[timeout] = identifier[google] . identifier[a... | def create_session_entity_type(self, parent, session_entity_type, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None):
"""
Creates a session entity type.
Example:
>>> import dialogflow_v2
>>>
>>> client =... |
def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs):
""" Detect infinite recursion and prevent it.
This is an implementation detail of readNamelist.
Raises NamelistRecursionError if namFilename is in the process of being included
"""
# normalize
filename = os.path.abspath(os.path.norm... | def function[_readNamelist, parameter[currentlyIncluding, cache, namFilename, unique_glyphs]]:
constant[ Detect infinite recursion and prevent it.
This is an implementation detail of readNamelist.
Raises NamelistRecursionError if namFilename is in the process of being included
]
variable[filenam... | keyword[def] identifier[_readNamelist] ( identifier[currentlyIncluding] , identifier[cache] , identifier[namFilename] , identifier[unique_glyphs] ):
literal[string]
identifier[filename] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[normcase] ( ide... | def _readNamelist(currentlyIncluding, cache, namFilename, unique_glyphs):
""" Detect infinite recursion and prevent it.
This is an implementation detail of readNamelist.
Raises NamelistRecursionError if namFilename is in the process of being included
"""
# normalize
filename = os.path.abspath(os.pat... |
def record(self, tags=None):
"""records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context.
"""
if tags is None:
tags = TagContext.get()
if self._invalid:
... | def function[record, parameter[self, tags]]:
constant[records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context.
]
if compare[name[tags] is constant[None]] begin[:]
... | keyword[def] identifier[record] ( identifier[self] , identifier[tags] = keyword[None] ):
literal[string]
keyword[if] identifier[tags] keyword[is] keyword[None] :
identifier[tags] = identifier[TagContext] . identifier[get] ()
keyword[if] identifier[self] . identifier[_inval... | def record(self, tags=None):
"""records all the measures at the same time with a tag_map.
tag_map could either be explicitly passed to the method, or implicitly
read from current runtime context.
"""
if tags is None:
tags = TagContext.get() # depends on [control=['if'], data=['t... |
def add_live_points(self):
"""Add the remaining set of live points to the current set of dead
points. Instantiates a generator that will be called by
the user. Returns the same outputs as :meth:`sample`."""
# Check if the remaining live points have already been added
# to the ou... | def function[add_live_points, parameter[self]]:
constant[Add the remaining set of live points to the current set of dead
points. Instantiates a generator that will be called by
the user. Returns the same outputs as :meth:`sample`.]
if name[self].added_live begin[:]
<ast.Raise obj... | keyword[def] identifier[add_live_points] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[added_live] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
keyword[else] :
iden... | def add_live_points(self):
"""Add the remaining set of live points to the current set of dead
points. Instantiates a generator that will be called by
the user. Returns the same outputs as :meth:`sample`."""
# Check if the remaining live points have already been added
# to the output set of s... |
def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return
logger.log(5, "Evaluate Javascript: `%s`.", expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _to_py(out) | def function[eval_js, parameter[self, expr]]:
constant[Evaluate a Javascript expression.]
if <ast.UnaryOp object at 0x7da1b120a410> begin[:]
call[name[self]._pending_js_eval.append, parameter[name[expr]]]
return[None]
call[name[logger].log, parameter[constant[5], constant... | keyword[def] identifier[eval_js] ( identifier[self] , identifier[expr] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_built] ():
identifier[self] . identifier[_pending_js_eval] . identifier[append] ( identifier[expr] )
keyword[return]
... | def eval_js(self, expr):
"""Evaluate a Javascript expression."""
if not self.is_built():
self._pending_js_eval.append(expr)
return # depends on [control=['if'], data=[]]
logger.log(5, 'Evaluate Javascript: `%s`.', expr)
out = self.page().mainFrame().evaluateJavaScript(expr)
return _... |
def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... | def function[applet_list_projects, parameter[object_id, input_params, always_retry]]:
constant[
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
]
return[call[name[DXHTTPRe... | keyword[def] identifier[applet_list_projects] ( identifier[object_id] , identifier[input_params] ={}, identifier[always_retry] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[DXHTTPRequest] ( literal[string] % identifier[object_id] , identifier[input_params] , identifi... | def applet_list_projects(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/listProjects API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2FlistProjects
"""
return DXHTTPRequest('/%s/listProjec... |
def overhang(self, tile):
"""
Get the left and right absolute overflow -- the amount of box
overhanging `tile`, can be viewed as self \\ tile (set theory relative
complement, but in a bounding sense)
"""
ll = np.abs(amin(self.l - tile.l, aN(0, dim=self.dim)))
rr =... | def function[overhang, parameter[self, tile]]:
constant[
Get the left and right absolute overflow -- the amount of box
overhanging `tile`, can be viewed as self \ tile (set theory relative
complement, but in a bounding sense)
]
variable[ll] assign[=] call[name[np].abs, pa... | keyword[def] identifier[overhang] ( identifier[self] , identifier[tile] ):
literal[string]
identifier[ll] = identifier[np] . identifier[abs] ( identifier[amin] ( identifier[self] . identifier[l] - identifier[tile] . identifier[l] , identifier[aN] ( literal[int] , identifier[dim] = identifier[self] ... | def overhang(self, tile):
"""
Get the left and right absolute overflow -- the amount of box
overhanging `tile`, can be viewed as self \\ tile (set theory relative
complement, but in a bounding sense)
"""
ll = np.abs(amin(self.l - tile.l, aN(0, dim=self.dim)))
rr = np.abs(amax... |
def _mkpda(self, nonterms, productions, productions_struct, terminals, splitstring=1):
"""
This function generates a PDA from a CNF grammar as described in:
- http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf
- http://www.eng.utah.edu/~cs3100/lectures/l18/pda-notes.p... | def function[_mkpda, parameter[self, nonterms, productions, productions_struct, terminals, splitstring]]:
constant[
This function generates a PDA from a CNF grammar as described in:
- http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf
- http://www.eng.utah.edu/~cs3100... | keyword[def] identifier[_mkpda] ( identifier[self] , identifier[nonterms] , identifier[productions] , identifier[productions_struct] , identifier[terminals] , identifier[splitstring] = literal[int] ):
literal[string]
identifier[pda] = identifier[PDA] ( identifier[self] . identifier[alphabet] )
... | def _mkpda(self, nonterms, productions, productions_struct, terminals, splitstring=1):
"""
This function generates a PDA from a CNF grammar as described in:
- http://www.oit.edu/faculty/sherry.yang/CST229/Lectures/7_pda.pdf
- http://www.eng.utah.edu/~cs3100/lectures/l18/pda-notes.pdf
... |
def insult(rest):
"Generate a random insult from datahamster"
# not supplying any style will automatically redirect to a random
url = 'http://autoinsult.datahamster.com/'
ins_type = random.randrange(4)
ins_url = url + "?style={ins_type}".format(**locals())
insre = re.compile('<div class="insult" id="insult">(.*?)... | def function[insult, parameter[rest]]:
constant[Generate a random insult from datahamster]
variable[url] assign[=] constant[http://autoinsult.datahamster.com/]
variable[ins_type] assign[=] call[name[random].randrange, parameter[constant[4]]]
variable[ins_url] assign[=] binary_operation[n... | keyword[def] identifier[insult] ( identifier[rest] ):
literal[string]
identifier[url] = literal[string]
identifier[ins_type] = identifier[random] . identifier[randrange] ( literal[int] )
identifier[ins_url] = identifier[url] + literal[string] . identifier[format] (** identifier[locals] ())
identifier[in... | def insult(rest):
"""Generate a random insult from datahamster""" # not supplying any style will automatically redirect to a random
url = 'http://autoinsult.datahamster.com/'
ins_type = random.randrange(4)
ins_url = url + '?style={ins_type}'.format(**locals())
insre = re.compile('<div class="insult... |
def receive_nak_rebinding(self, pkt):
"""Receive NAK in REBINDING state."""
logger.debug("C3.1. Received NAK?, in RENEWING state.")
if self.process_received_nak(pkt):
logger.debug("C3.1: T. Received NAK, in RENEWING state, "
"raise INIT.")
raise s... | def function[receive_nak_rebinding, parameter[self, pkt]]:
constant[Receive NAK in REBINDING state.]
call[name[logger].debug, parameter[constant[C3.1. Received NAK?, in RENEWING state.]]]
if call[name[self].process_received_nak, parameter[name[pkt]]] begin[:]
call[name[logger].de... | keyword[def] identifier[receive_nak_rebinding] ( identifier[self] , identifier[pkt] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[self] . identifier[process_received_nak] ( identifier[pkt] ):
identifier[logger] . identifi... | def receive_nak_rebinding(self, pkt):
"""Receive NAK in REBINDING state."""
logger.debug('C3.1. Received NAK?, in RENEWING state.')
if self.process_received_nak(pkt):
logger.debug('C3.1: T. Received NAK, in RENEWING state, raise INIT.')
raise self.INIT() # depends on [control=['if'], data=[... |
def do_shell(self, arg):
"""
! - spawn a system shell
shell - spawn a system shell
! <command> [arguments...] - execute a single shell command
shell <command> [arguments...] - execute a single shell command
"""
if self.cmdprefix:
raise CmdError("prefix... | def function[do_shell, parameter[self, arg]]:
constant[
! - spawn a system shell
shell - spawn a system shell
! <command> [arguments...] - execute a single shell command
shell <command> [arguments...] - execute a single shell command
]
if name[self].cmdprefix begi... | keyword[def] identifier[do_shell] ( identifier[self] , identifier[arg] ):
literal[string]
keyword[if] identifier[self] . identifier[cmdprefix] :
keyword[raise] identifier[CmdError] ( literal[string] )
identifier[shell] = i... | def do_shell(self, arg):
"""
! - spawn a system shell
shell - spawn a system shell
! <command> [arguments...] - execute a single shell command
shell <command> [arguments...] - execute a single shell command
"""
if self.cmdprefix:
raise CmdError('prefix not allowed... |
def add_template_network_events(self, columns, vectors):
""" Add a vector indexed """
# initialize with zeros - since vectors can be None, look for the
# longest one that isn't
new_events = None
new_events = numpy.zeros(
max([len(v) for v in vectors if v is not None])... | def function[add_template_network_events, parameter[self, columns, vectors]]:
constant[ Add a vector indexed ]
variable[new_events] assign[=] constant[None]
variable[new_events] assign[=] call[name[numpy].zeros, parameter[call[name[max], parameter[<ast.ListComp object at 0x7da2054a74c0>]]]]
... | keyword[def] identifier[add_template_network_events] ( identifier[self] , identifier[columns] , identifier[vectors] ):
literal[string]
identifier[new_events] = keyword[None]
identifier[new_events] = identifier[numpy] . identifier[zeros] (
identifier[max] ([ iden... | def add_template_network_events(self, columns, vectors):
""" Add a vector indexed """
# initialize with zeros - since vectors can be None, look for the
# longest one that isn't
new_events = None
new_events = numpy.zeros(max([len(v) for v in vectors if v is not None]), dtype=self.network_event_dtype)... |
def _timestamp_handler(c, ctx):
"""Handles timestamp values. Entered after the year component has been completed; tokenizes the remaining
components.
"""
assert c in _TIMESTAMP_YEAR_DELIMITERS
ctx.set_ion_type(IonType.TIMESTAMP)
if len(ctx.value) != 4:
_illegal_character(c, ctx, 'Timesta... | def function[_timestamp_handler, parameter[c, ctx]]:
constant[Handles timestamp values. Entered after the year component has been completed; tokenizes the remaining
components.
]
assert[compare[name[c] in name[_TIMESTAMP_YEAR_DELIMITERS]]]
call[name[ctx].set_ion_type, parameter[name[IonType]... | keyword[def] identifier[_timestamp_handler] ( identifier[c] , identifier[ctx] ):
literal[string]
keyword[assert] identifier[c] keyword[in] identifier[_TIMESTAMP_YEAR_DELIMITERS]
identifier[ctx] . identifier[set_ion_type] ( identifier[IonType] . identifier[TIMESTAMP] )
keyword[if] identifier[... | def _timestamp_handler(c, ctx):
"""Handles timestamp values. Entered after the year component has been completed; tokenizes the remaining
components.
"""
assert c in _TIMESTAMP_YEAR_DELIMITERS
ctx.set_ion_type(IonType.TIMESTAMP)
if len(ctx.value) != 4:
_illegal_character(c, ctx, 'Timesta... |
def _run_funnel(args):
"""Run funnel TES server with rabix bunny for CWL.
"""
host = "localhost"
port = "8088"
main_file, json_file, project_name = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), "funnel_work"))
log_file = os.path.join(work_dir, "%s... | def function[_run_funnel, parameter[args]]:
constant[Run funnel TES server with rabix bunny for CWL.
]
variable[host] assign[=] constant[localhost]
variable[port] assign[=] constant[8088]
<ast.Tuple object at 0x7da1b17a5840> assign[=] call[name[_get_main_and_json], parameter[name[arg... | keyword[def] identifier[_run_funnel] ( identifier[args] ):
literal[string]
identifier[host] = literal[string]
identifier[port] = literal[string]
identifier[main_file] , identifier[json_file] , identifier[project_name] = identifier[_get_main_and_json] ( identifier[args] . identifier[directory] )... | def _run_funnel(args):
"""Run funnel TES server with rabix bunny for CWL.
"""
host = 'localhost'
port = '8088'
(main_file, json_file, project_name) = _get_main_and_json(args.directory)
work_dir = utils.safe_makedir(os.path.join(os.getcwd(), 'funnel_work'))
log_file = os.path.join(work_dir, '... |
def handle_change(self, change):
""" Handle changes from atom ContainerLists """
op = change['operation']
if op in 'append':
self.add(len(change['value']), LatLng(*change['item']))
elif op == 'insert':
self.add(change['index'], LatLng(*change['item']))
eli... | def function[handle_change, parameter[self, change]]:
constant[ Handle changes from atom ContainerLists ]
variable[op] assign[=] call[name[change]][constant[operation]]
if compare[name[op] in constant[append]] begin[:]
call[name[self].add, parameter[call[name[len], parameter[call... | keyword[def] identifier[handle_change] ( identifier[self] , identifier[change] ):
literal[string]
identifier[op] = identifier[change] [ literal[string] ]
keyword[if] identifier[op] keyword[in] literal[string] :
identifier[self] . identifier[add] ( identifier[len] ( identifi... | def handle_change(self, change):
""" Handle changes from atom ContainerLists """
op = change['operation']
if op in 'append':
self.add(len(change['value']), LatLng(*change['item'])) # depends on [control=['if'], data=[]]
elif op == 'insert':
self.add(change['index'], LatLng(*change['item... |
def get_audio_metadata(fname):
""" collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
"""
from mutagenx.easyid3 import ... | def function[get_audio_metadata, parameter[fname]]:
constant[ collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
]
... | keyword[def] identifier[get_audio_metadata] ( identifier[fname] ):
literal[string]
keyword[from] identifier[mutagenx] . identifier[easyid3] keyword[import] identifier[EasyID3]
identifier[audio] = identifier[EasyID3] ( identifier[fname] )
identifier[audio_dict] ={}
keyword[try] :
... | def get_audio_metadata(fname):
""" collects basic MP3 metadata
Works, once you use mutagenx (buried deep in issues page)
['Angels']
['Red Back Fever']
['Red Back Fever']
{'album': ['Red Back Fever'], 'title': ['Red Back Fever'], 'artist': ['Angels']}
"""
from mutagenx.easyid3 import ... |
def trailing_stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response ... | def function[trailing_stop_loss, parameter[self, accountID]]:
constant[
Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.r... | keyword[def] identifier[trailing_stop_loss] ( identifier[self] , identifier[accountID] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[create] (
identifier[accountID] ,
identifier[order] = identifier[TrailingStopLossOrderRequest] (** identi... | def trailing_stop_loss(self, accountID, **kwargs):
"""
Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response cont... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.