code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def name_for_number(numobj, lang, script=None, region=None):
"""Returns a carrier name for the given PhoneNumber object, in the
language provided.
The carrier name is the one the number was originally allocated to,
however if the country supports mobile number portability the number might
not belon... | def function[name_for_number, parameter[numobj, lang, script, region]]:
constant[Returns a carrier name for the given PhoneNumber object, in the
language provided.
The carrier name is the one the number was originally allocated to,
however if the country supports mobile number portability the numbe... | keyword[def] identifier[name_for_number] ( identifier[numobj] , identifier[lang] , identifier[script] = keyword[None] , identifier[region] = keyword[None] ):
literal[string]
identifier[ntype] = identifier[number_type] ( identifier[numobj] )
keyword[if] identifier[_is_mobile] ( identifier[ntype] ):
... | def name_for_number(numobj, lang, script=None, region=None):
"""Returns a carrier name for the given PhoneNumber object, in the
language provided.
The carrier name is the one the number was originally allocated to,
however if the country supports mobile number portability the number might
not belon... |
def handleResponseEnd(self):
"""
Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes.
"""
try:
if not self._finished:
... | def function[handleResponseEnd, parameter[self]]:
constant[
Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes.
]
<ast.Try object at 0x7... | keyword[def] identifier[handleResponseEnd] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[if] keyword[not] identifier[self] . identifier[_finished] :
identifier[reactor] . identifier[callInThread] (
identifier[self] . identifier[resourc... | def handleResponseEnd(self):
"""
Extends handleResponseEnd to not care about the user closing/refreshing
their browser before the response is finished. Also calls cacheContent
in a thread that we don't care when it finishes.
"""
try:
if not self._finished:
rea... |
def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
jsn = {}
jsn["txid"] = self.Hash.To0xString()
jsn["size"] = self.Size()
jsn["type"] = TransactionType.ToName(self.Type)
jsn["v... | def function[ToJson, parameter[self]]:
constant[
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
]
variable[jsn] assign[=] dictionary[[], []]
call[name[jsn]][constant[txid]] assign[=] call[name[self].Hash.To0xString, paramet... | keyword[def] identifier[ToJson] ( identifier[self] ):
literal[string]
identifier[jsn] ={}
identifier[jsn] [ literal[string] ]= identifier[self] . identifier[Hash] . identifier[To0xString] ()
identifier[jsn] [ literal[string] ]= identifier[self] . identifier[Size] ()
ident... | def ToJson(self):
"""
Convert object members to a dictionary that can be parsed as JSON.
Returns:
dict:
"""
jsn = {}
jsn['txid'] = self.Hash.To0xString()
jsn['size'] = self.Size()
jsn['type'] = TransactionType.ToName(self.Type)
jsn['version'] = self.Version
... |
def parse(self, data):
# type: (bytes) -> None
'''
Parse the passed in data into a UDF Entity ID.
Parameters:
data - The data to parse.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Enti... | def function[parse, parameter[self, data]]:
constant[
Parse the passed in data into a UDF Entity ID.
Parameters:
data - The data to parse.
Returns:
Nothing.
]
if name[self]._initialized begin[:]
<ast.Raise object at 0x7da20c6c4a90>
<ast.... | keyword[def] identifier[parse] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] )
( identifier[self] . identifi... | def parse(self, data):
# type: (bytes) -> None
'\n Parse the passed in data into a UDF Entity ID.\n\n Parameters:\n data - The data to parse.\n Returns:\n Nothing.\n '
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Entity ID already... |
def open(self):
"""
Called on new websocket connection.
"""
sess_id = self._get_sess_id()
if sess_id:
self.application.pc.websockets[self._get_sess_id()] = self
self.write_message(json.dumps({"cmd": "status", "status": "open"}))
else:
s... | def function[open, parameter[self]]:
constant[
Called on new websocket connection.
]
variable[sess_id] assign[=] call[name[self]._get_sess_id, parameter[]]
if name[sess_id] begin[:]
call[name[self].application.pc.websockets][call[name[self]._get_sess_id, parameter... | keyword[def] identifier[open] ( identifier[self] ):
literal[string]
identifier[sess_id] = identifier[self] . identifier[_get_sess_id] ()
keyword[if] identifier[sess_id] :
identifier[self] . identifier[application] . identifier[pc] . identifier[websockets] [ identifier[self] .... | def open(self):
"""
Called on new websocket connection.
"""
sess_id = self._get_sess_id()
if sess_id:
self.application.pc.websockets[self._get_sess_id()] = self
self.write_message(json.dumps({'cmd': 'status', 'status': 'open'})) # depends on [control=['if'], data=[]]
els... |
def evaluate(self):
"""Evaluate functional value of previous iteration."""
if self.opt['AccurateDFid']:
DX = self.reconstruct()
W = self.dstep.W
S = self.dstep.S
else:
W = mp_W
S = mp_S
Xf = mp_Zf
Df = mp_Df
... | def function[evaluate, parameter[self]]:
constant[Evaluate functional value of previous iteration.]
if call[name[self].opt][constant[AccurateDFid]] begin[:]
variable[DX] assign[=] call[name[self].reconstruct, parameter[]]
variable[W] assign[=] name[self].dstep.W
... | keyword[def] identifier[evaluate] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[opt] [ literal[string] ]:
identifier[DX] = identifier[self] . identifier[reconstruct] ()
identifier[W] = identifier[self] . identifier[dstep] . identifier[W]... | def evaluate(self):
"""Evaluate functional value of previous iteration."""
if self.opt['AccurateDFid']:
DX = self.reconstruct()
W = self.dstep.W
S = self.dstep.S # depends on [control=['if'], data=[]]
else:
W = mp_W
S = mp_S
Xf = mp_Zf
Df = mp_Df
... |
def get_closest_point_to_line(A, B, P):
'''
Find the closest point on a line. This point will be reproducible by a Hue
lamp.
'''
AP = XYPoint(P.x - A.x, P.y - A.y)
AB = XYPoint(B.x - A.x, B.y - A.y)
ab2 = AB.x * AB.x + AB.y * AB.y
ap_ab = AP.x * AB.x + AP.y * AB.y
t = ap_ab / ab2
... | def function[get_closest_point_to_line, parameter[A, B, P]]:
constant[
Find the closest point on a line. This point will be reproducible by a Hue
lamp.
]
variable[AP] assign[=] call[name[XYPoint], parameter[binary_operation[name[P].x - name[A].x], binary_operation[name[P].y - name[A].y]]]
... | keyword[def] identifier[get_closest_point_to_line] ( identifier[A] , identifier[B] , identifier[P] ):
literal[string]
identifier[AP] = identifier[XYPoint] ( identifier[P] . identifier[x] - identifier[A] . identifier[x] , identifier[P] . identifier[y] - identifier[A] . identifier[y] )
identifier[AB] = ... | def get_closest_point_to_line(A, B, P):
"""
Find the closest point on a line. This point will be reproducible by a Hue
lamp.
"""
AP = XYPoint(P.x - A.x, P.y - A.y)
AB = XYPoint(B.x - A.x, B.y - A.y)
ab2 = AB.x * AB.x + AB.y * AB.y
ap_ab = AP.x * AB.x + AP.y * AB.y
t = ap_ab / ab2
... |
def get_type_size(self, type):
"""
Get the size of this type for converting a hex string to the
type. Return 0 if the size is not known.
"""
typeobj = self.get_type(type)
if hasattr(typeobj, 'size'):
return typeobj.size()
return 0 | def function[get_type_size, parameter[self, type]]:
constant[
Get the size of this type for converting a hex string to the
type. Return 0 if the size is not known.
]
variable[typeobj] assign[=] call[name[self].get_type, parameter[name[type]]]
if call[name[hasattr], parame... | keyword[def] identifier[get_type_size] ( identifier[self] , identifier[type] ):
literal[string]
identifier[typeobj] = identifier[self] . identifier[get_type] ( identifier[type] )
keyword[if] identifier[hasattr] ( identifier[typeobj] , literal[string] ):
keyword[return] ide... | def get_type_size(self, type):
"""
Get the size of this type for converting a hex string to the
type. Return 0 if the size is not known.
"""
typeobj = self.get_type(type)
if hasattr(typeobj, 'size'):
return typeobj.size() # depends on [control=['if'], data=[]]
return 0 |
def add_permissions(self, grp_name, resource, permissions):
""" Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
... | def function[add_permissions, parameter[self, grp_name, resource, permissions]]:
constant[ Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data mod... | keyword[def] identifier[add_permissions] ( identifier[self] , identifier[grp_name] , identifier[resource] , identifier[permissions] ):
literal[string]
identifier[self] . identifier[service] . identifier[add_permissions] (
identifier[grp_name] , identifier[resource] , identifier[permissions... | def add_permissions(self, grp_name, resource, permissions):
""" Add additional permissions for the group associated with the given resource.
Args:
grp_name (string): Name of group.
resource (intern.resource.boss.BossResource): Identifies which data model object to operate on.
... |
def find_container_traits(cls_or_string):
"""
Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits
"""
if utils.is_str(cls_or_string):
if not templat... | def function[find_container_traits, parameter[cls_or_string]]:
constant[
Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits
]
if call[name[utils].is... | keyword[def] identifier[find_container_traits] ( identifier[cls_or_string] ):
literal[string]
keyword[if] identifier[utils] . identifier[is_str] ( identifier[cls_or_string] ):
keyword[if] keyword[not] identifier[templates] . identifier[is_instantiation] ( identifier[cls_or_string] ):
... | def find_container_traits(cls_or_string):
"""
Find the container traits type of a declaration.
Args:
cls_or_string (str | declarations.declaration_t): a string
Returns:
declarations.container_traits: a container traits
"""
if utils.is_str(cls_or_string):
if not template... |
def get_query_result(self, query_object):
"""Returns a pandas dataframe based on the query object"""
# Here, we assume that all the queries will use the same datasource, which is
# is a valid assumption for current setting. In a long term, we may or maynot
# support multiple queries fro... | def function[get_query_result, parameter[self, query_object]]:
constant[Returns a pandas dataframe based on the query object]
variable[timestamp_format] assign[=] constant[None]
if compare[name[self].datasource.type equal[==] constant[table]] begin[:]
variable[dttm_col] assign[=]... | keyword[def] identifier[get_query_result] ( identifier[self] , identifier[query_object] ):
literal[string]
identifier[timestamp_format] = keyword[None]
keyword[if] identifier[self] . identifier[datasource] . identifier[type] == literal[string] :
... | def get_query_result(self, query_object):
"""Returns a pandas dataframe based on the query object"""
# Here, we assume that all the queries will use the same datasource, which is
# is a valid assumption for current setting. In a long term, we may or maynot
# support multiple queries from different data ... |
def get_country_by_id(self, country_id) -> 'Country':
"""
Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country
"""
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in s... | def function[get_country_by_id, parameter[self, country_id]]:
constant[
Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country
]
call[name[VALID_POSITIVE_INT].validate, parameter[name[country_id], constant[get_country_by_id]... | keyword[def] identifier[get_country_by_id] ( identifier[self] , identifier[country_id] )-> literal[string] :
literal[string]
identifier[VALID_POSITIVE_INT] . identifier[validate] ( identifier[country_id] , literal[string] , identifier[exc] = identifier[ValueError] )
keyword[if] identifier... | def get_country_by_id(self, country_id) -> 'Country':
"""
Gets a country in this coalition by its ID
Args:
country_id: country Id
Returns: Country
"""
VALID_POSITIVE_INT.validate(country_id, 'get_country_by_id', exc=ValueError)
if country_id not in self._countri... |
def dict(self, name, key_caps=False, value_caps=False):
'''
Returns a JSON dict
@key_caps: Converts all dictionary keys to uppercase
@value_caps: Converts all dictionary values to uppercase
@return: JSON item (may be a variable, list or dictionary)
'''
# Invalid... | def function[dict, parameter[self, name, key_caps, value_caps]]:
constant[
Returns a JSON dict
@key_caps: Converts all dictionary keys to uppercase
@value_caps: Converts all dictionary values to uppercase
@return: JSON item (may be a variable, list or dictionary)
]
... | keyword[def] identifier[dict] ( identifier[self] , identifier[name] , identifier[key_caps] = keyword[False] , identifier[value_caps] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[json_data] [ identifier[name] ], identi... | def dict(self, name, key_caps=False, value_caps=False):
"""
Returns a JSON dict
@key_caps: Converts all dictionary keys to uppercase
@value_caps: Converts all dictionary values to uppercase
@return: JSON item (may be a variable, list or dictionary)
"""
# Invalid Diction... |
def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
"""
next_start = task_source.next_start()
if next_start is not None:
if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:
raise ValueError('Inval... | def function[__update, parameter[self, task_source]]:
constant[ Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
]
variable[next_start] assign[=] call[name[task_source].next_start, parameter[]]
if compare[name[next_start] is_not consta... | keyword[def] identifier[__update] ( identifier[self] , identifier[task_source] ):
literal[string]
identifier[next_start] = identifier[task_source] . identifier[next_start] ()
keyword[if] identifier[next_start] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[next_start] . identifier... | def __update(self, task_source):
""" Recheck next start of tasks from the given one only
:param task_source: source to check
:return: None
"""
next_start = task_source.next_start()
if next_start is not None:
if next_start.tzinfo is None or next_start.tzinfo != timezone.utc:
raise... |
def readlink(path):
'''
Equivalent to os.readlink()
'''
if six.PY3 or not salt.utils.platform.is_windows():
return os.readlink(path)
if not HAS_WIN32FILE:
log.error('Cannot read %s, missing required modules', path)
reparse_data = _get_reparse_data(path)
if not reparse_data... | def function[readlink, parameter[path]]:
constant[
Equivalent to os.readlink()
]
if <ast.BoolOp object at 0x7da18dc9bc40> begin[:]
return[call[name[os].readlink, parameter[name[path]]]]
if <ast.UnaryOp object at 0x7da18dc98cd0> begin[:]
call[name[log].error, param... | keyword[def] identifier[readlink] ( identifier[path] ):
literal[string]
keyword[if] identifier[six] . identifier[PY3] keyword[or] keyword[not] identifier[salt] . identifier[utils] . identifier[platform] . identifier[is_windows] ():
keyword[return] identifier[os] . identifier[readlink] ( ident... | def readlink(path):
"""
Equivalent to os.readlink()
"""
if six.PY3 or not salt.utils.platform.is_windows():
return os.readlink(path) # depends on [control=['if'], data=[]]
if not HAS_WIN32FILE:
log.error('Cannot read %s, missing required modules', path) # depends on [control=['if']... |
def clear(self):
""" Clear any existing values from this queue. """
logger.debug('Clearing queue: "%s"', self.name)
return self.redis.delete(self.name) | def function[clear, parameter[self]]:
constant[ Clear any existing values from this queue. ]
call[name[logger].debug, parameter[constant[Clearing queue: "%s"], name[self].name]]
return[call[name[self].redis.delete, parameter[name[self].name]]] | keyword[def] identifier[clear] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[self] . identifier[name] )
keyword[return] identifier[self] . identifier[redis] . identifier[delete] ( identifier[self] . identifier[name] ) | def clear(self):
""" Clear any existing values from this queue. """
logger.debug('Clearing queue: "%s"', self.name)
return self.redis.delete(self.name) |
def validate_token_request(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
# REQUIRED. Value MUST be set to "refresh_token".
if request.grant_type != 'refresh_token':
raise errors.UnsupportedGrantTypeError(reque... | def function[validate_token_request, parameter[self, request]]:
constant[
:param request: OAuthlib request.
:type request: oauthlib.common.Request
]
if compare[name[request].grant_type not_equal[!=] constant[refresh_token]] begin[:]
<ast.Raise object at 0x7da1b18e4eb0>
... | keyword[def] identifier[validate_token_request] ( identifier[self] , identifier[request] ):
literal[string]
keyword[if] identifier[request] . identifier[grant_type] != literal[string] :
keyword[raise] identifier[errors] . identifier[UnsupportedGrantTypeError] ( identifier[re... | def validate_token_request(self, request):
"""
:param request: OAuthlib request.
:type request: oauthlib.common.Request
"""
# REQUIRED. Value MUST be set to "refresh_token".
if request.grant_type != 'refresh_token':
raise errors.UnsupportedGrantTypeError(request=request) # d... |
def afx_small():
"""Small transformer model with small batch size for fast step times."""
hparams = transformer.transformer_tpu()
hparams.filter_size = 1024
hparams.num_heads = 4
hparams.num_hidden_layers = 3
hparams.batch_size = 512
return hparams | def function[afx_small, parameter[]]:
constant[Small transformer model with small batch size for fast step times.]
variable[hparams] assign[=] call[name[transformer].transformer_tpu, parameter[]]
name[hparams].filter_size assign[=] constant[1024]
name[hparams].num_heads assign[=] constan... | keyword[def] identifier[afx_small] ():
literal[string]
identifier[hparams] = identifier[transformer] . identifier[transformer_tpu] ()
identifier[hparams] . identifier[filter_size] = literal[int]
identifier[hparams] . identifier[num_heads] = literal[int]
identifier[hparams] . identifier[num_hidden_la... | def afx_small():
"""Small transformer model with small batch size for fast step times."""
hparams = transformer.transformer_tpu()
hparams.filter_size = 1024
hparams.num_heads = 4
hparams.num_hidden_layers = 3
hparams.batch_size = 512
return hparams |
def configure(cfgpath=None):
"""
Configure lexibank.
:return: a pair (config, logger)
"""
cfgpath = Path(cfgpath) \
if cfgpath else Path(user_config_dir(pylexibank.__name__)) / 'config.ini'
if not cfgpath.exists():
print("""
{0}
You seem to be running lexibank for the first tim... | def function[configure, parameter[cfgpath]]:
constant[
Configure lexibank.
:return: a pair (config, logger)
]
variable[cfgpath] assign[=] <ast.IfExp object at 0x7da1b26ac790>
if <ast.UnaryOp object at 0x7da20c6c4490> begin[:]
call[name[print], parameter[call[constant... | keyword[def] identifier[configure] ( identifier[cfgpath] = keyword[None] ):
literal[string]
identifier[cfgpath] = identifier[Path] ( identifier[cfgpath] ) keyword[if] identifier[cfgpath] keyword[else] identifier[Path] ( identifier[user_config_dir] ( identifier[pylexibank] . identifier[__name__] ))/ lite... | def configure(cfgpath=None):
"""
Configure lexibank.
:return: a pair (config, logger)
"""
cfgpath = Path(cfgpath) if cfgpath else Path(user_config_dir(pylexibank.__name__)) / 'config.ini'
if not cfgpath.exists():
print('\n{0}\n\nYou seem to be running lexibank for the first time.\nYour ... |
def _sunos_memdata():
'''
Return the memory information for SunOS-like systems
'''
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].s... | def function[_sunos_memdata, parameter[]]:
constant[
Return the memory information for SunOS-like systems
]
variable[grains] assign[=] dictionary[[<ast.Constant object at 0x7da1b2054430>, <ast.Constant object at 0x7da1b2054040>], [<ast.Constant object at 0x7da1b2054070>, <ast.Constant object at ... | keyword[def] identifier[_sunos_memdata] ():
literal[string]
identifier[grains] ={ literal[string] : literal[int] , literal[string] : literal[int] }
identifier[prtconf] = literal[string]
keyword[for] identifier[line] keyword[in] identifier[__salt__] [ literal[string] ]( identifier[prtconf] , ... | def _sunos_memdata():
"""
Return the memory information for SunOS-like systems
"""
grains = {'mem_total': 0, 'swap_total': 0}
prtconf = '/usr/sbin/prtconf 2>/dev/null'
for line in __salt__['cmd.run'](prtconf, python_shell=True).splitlines():
comps = line.split(' ')
if comps[0].st... |
def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data.
"""
matrix = np.matrix([row[:response_index] + row[response_index+1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.uint8)
return matrix, outcomes | def function[list_to_tf_input, parameter[data, response_index, num_outcomes]]:
constant[
Separates the outcome feature from the data.
]
variable[matrix] assign[=] call[name[np].matrix, parameter[<ast.ListComp object at 0x7da1b0353160>]]
variable[outcomes] assign[=] call[name[np].asarray, par... | keyword[def] identifier[list_to_tf_input] ( identifier[data] , identifier[response_index] , identifier[num_outcomes] ):
literal[string]
identifier[matrix] = identifier[np] . identifier[matrix] ([ identifier[row] [: identifier[response_index] ]+ identifier[row] [ identifier[response_index] + literal[int] :] key... | def list_to_tf_input(data, response_index, num_outcomes):
"""
Separates the outcome feature from the data.
"""
matrix = np.matrix([row[:response_index] + row[response_index + 1:] for row in data])
outcomes = np.asarray([row[response_index] for row in data], dtype=np.uint8)
return (matrix, outcomes) |
def edges_unique_length(self):
"""
How long is each unique edge.
Returns
----------
length : (len(self.edges_unique), ) float
Length of each unique edge
"""
vector = np.subtract(*self.vertices[self.edges_unique.T])
length = np.linalg.norm(vector... | def function[edges_unique_length, parameter[self]]:
constant[
How long is each unique edge.
Returns
----------
length : (len(self.edges_unique), ) float
Length of each unique edge
]
variable[vector] assign[=] call[name[np].subtract, parameter[<ast.Starr... | keyword[def] identifier[edges_unique_length] ( identifier[self] ):
literal[string]
identifier[vector] = identifier[np] . identifier[subtract] (* identifier[self] . identifier[vertices] [ identifier[self] . identifier[edges_unique] . identifier[T] ])
identifier[length] = identifier[np] . id... | def edges_unique_length(self):
"""
How long is each unique edge.
Returns
----------
length : (len(self.edges_unique), ) float
Length of each unique edge
"""
vector = np.subtract(*self.vertices[self.edges_unique.T])
length = np.linalg.norm(vector, axis=1)
... |
def do_i_raise_dependency(self, status, inherit_parents, hosts, services, timeperiods):
# pylint: disable=too-many-locals
"""Check if this object or one of its dependency state (chk dependencies) match the status
:param status: state list where dependency matters (notification failure criteria)... | def function[do_i_raise_dependency, parameter[self, status, inherit_parents, hosts, services, timeperiods]]:
constant[Check if this object or one of its dependency state (chk dependencies) match the status
:param status: state list where dependency matters (notification failure criteria)
:type ... | keyword[def] identifier[do_i_raise_dependency] ( identifier[self] , identifier[status] , identifier[inherit_parents] , identifier[hosts] , identifier[services] , identifier[timeperiods] ):
literal[string]
keyword[for] identifier[stat] keyword[in] identifier[status] :
keywo... | def do_i_raise_dependency(self, status, inherit_parents, hosts, services, timeperiods):
# pylint: disable=too-many-locals
'Check if this object or one of its dependency state (chk dependencies) match the status\n\n :param status: state list where dependency matters (notification failure criteria)\n ... |
def default(self, meth):
"""
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
"""
if self._default is not NOTHING:
raise Def... | def function[default, parameter[self, meth]]:
constant[
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
]
if compare[name[self]._defaul... | keyword[def] identifier[default] ( identifier[self] , identifier[meth] ):
literal[string]
keyword[if] identifier[self] . identifier[_default] keyword[is] keyword[not] identifier[NOTHING] :
keyword[raise] identifier[DefaultAlreadySetError] ()
identifier[self] . identifier... | def default(self, meth):
"""
Decorator that allows to set the default for an attribute.
Returns *meth* unchanged.
:raises DefaultAlreadySetError: If default has been set before.
.. versionadded:: 17.1.0
"""
if self._default is not NOTHING:
raise DefaultAlreadyS... |
def legacy_write(self, request_id, msg, max_doc_size, with_last_error):
"""Send OP_INSERT, etc., optionally returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DEL... | def function[legacy_write, parameter[self, request_id, msg, max_doc_size, with_last_error]]:
constant[Send OP_INSERT, etc., optionally returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, an OP_I... | keyword[def] identifier[legacy_write] ( identifier[self] , identifier[request_id] , identifier[msg] , identifier[max_doc_size] , identifier[with_last_error] ):
literal[string]
keyword[if] keyword[not] identifier[with_last_error] keyword[and] keyword[not] identifier[self] . identifier[is_writab... | def legacy_write(self, request_id, msg, max_doc_size, with_last_error):
"""Send OP_INSERT, etc., optionally returning response as a dict.
Can raise ConnectionFailure or OperationFailure.
:Parameters:
- `request_id`: an int.
- `msg`: bytes, an OP_INSERT, OP_UPDATE, or OP_DELETE ... |
def list_nodes_select(nodes, selection, call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_select function must be called '
'with -f or --function.'
)
if 'e... | def function[list_nodes_select, parameter[nodes, selection, call]]:
constant[
Return a list of the VMs that are on the provider, with select fields
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da1b1ff0d30>
if compare[constant[error] in name... | keyword[def] identifier[list_nodes_select] ( identifier[nodes] , identifier[selection] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
... | def list_nodes_select(nodes, selection, call=None):
"""
Return a list of the VMs that are on the provider, with select fields
"""
if call == 'action':
raise SaltCloudSystemExit('The list_nodes_select function must be called with -f or --function.') # depends on [control=['if'], data=[]]
if ... |
def loadAnns(self, ids=[]):
"""
Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
if type(ids) == list:
return [self.anns[id] for id in ids]
elif type(ids)... | def function[loadAnns, parameter[self, ids]]:
constant[
Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
]
if compare[call[name[type], parameter[name[ids]]] equal[==] name[list]]... | keyword[def] identifier[loadAnns] ( identifier[self] , identifier[ids] =[]):
literal[string]
keyword[if] identifier[type] ( identifier[ids] )== identifier[list] :
keyword[return] [ identifier[self] . identifier[anns] [ identifier[id] ] keyword[for] identifier[id] keyword[in] identi... | def loadAnns(self, ids=[]):
"""
Load anns with the specified ids.
:param ids (int array) : integer ids specifying anns
:return: anns (object array) : loaded ann objects
"""
if type(ids) == list:
return [self.anns[id] for id in ids] # depends on [control=['if'], dat... |
def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables... | def function[build, parameter[self, context, variant, build_path, install_path, install, build_type]]:
constant[Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
... | keyword[def] identifier[build] ( identifier[self] , identifier[context] , identifier[variant] , identifier[build_path] , identifier[install_path] , identifier[install] = keyword[False] ,
identifier[build_type] = identifier[BuildType] . identifier[local] ):
literal[string]
identifier[ret] ={}
... | def build(self, context, variant, build_path, install_path, install=False, build_type=BuildType.local):
"""Perform the build.
Note that most of the func args aren't used here - that's because this
info is already passed to the custom build command via environment
variables.
"""
... |
def NewPathSpec(cls, type_indicator, **kwargs):
"""Creates a new path specification for the specific type indicator.
Args:
type_indicator (str): type indicator.
kwargs (dict): keyword arguments depending on the path specification.
Returns:
PathSpec: path specification.
Raises:
... | def function[NewPathSpec, parameter[cls, type_indicator]]:
constant[Creates a new path specification for the specific type indicator.
Args:
type_indicator (str): type indicator.
kwargs (dict): keyword arguments depending on the path specification.
Returns:
PathSpec: path specificatio... | keyword[def] identifier[NewPathSpec] ( identifier[cls] , identifier[type_indicator] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[type_indicator] keyword[not] keyword[in] identifier[cls] . identifier[_path_spec_types] :
keyword[raise] identifier[KeyError] (
literal[str... | def NewPathSpec(cls, type_indicator, **kwargs):
"""Creates a new path specification for the specific type indicator.
Args:
type_indicator (str): type indicator.
kwargs (dict): keyword arguments depending on the path specification.
Returns:
PathSpec: path specification.
Raises:
... |
def update(self,iiter,H,Y,eta,loss):
"""Update the trace_var in new iteration"""
if iiter <= self.niter_trace+1:
self.H[iiter] = H
self.Y[iiter] = Y
elif iiter >self.niter - self.niter_trace + 1:
self.H[self.ltrace+iiter-self.niter-1] = H
self.Y[se... | def function[update, parameter[self, iiter, H, Y, eta, loss]]:
constant[Update the trace_var in new iteration]
if compare[name[iiter] less_or_equal[<=] binary_operation[name[self].niter_trace + constant[1]]] begin[:]
call[name[self].H][name[iiter]] assign[=] name[H]
call[... | keyword[def] identifier[update] ( identifier[self] , identifier[iiter] , identifier[H] , identifier[Y] , identifier[eta] , identifier[loss] ):
literal[string]
keyword[if] identifier[iiter] <= identifier[self] . identifier[niter_trace] + literal[int] :
identifier[self] . identifier[H] ... | def update(self, iiter, H, Y, eta, loss):
"""Update the trace_var in new iteration"""
if iiter <= self.niter_trace + 1:
self.H[iiter] = H
self.Y[iiter] = Y # depends on [control=['if'], data=['iiter']]
elif iiter > self.niter - self.niter_trace + 1:
self.H[self.ltrace + iiter - self... |
def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
for fld in ("doses", "ns", "means", "stdevs"):
arr = getattr(self, fld)[:-1]
setattr(self, fld, arr)
self._validate() | def function[drop_dose, parameter[self]]:
constant[
Drop the maximum dose and related response values.
]
for taget[name[fld]] in starred[tuple[[<ast.Constant object at 0x7da204345750>, <ast.Constant object at 0x7da204345090>, <ast.Constant object at 0x7da204346080>, <ast.Constant object ... | keyword[def] identifier[drop_dose] ( identifier[self] ):
literal[string]
keyword[for] identifier[fld] keyword[in] ( literal[string] , literal[string] , literal[string] , literal[string] ):
identifier[arr] = identifier[getattr] ( identifier[self] , identifier[fld] )[:- literal[int] ]
... | def drop_dose(self):
"""
Drop the maximum dose and related response values.
"""
for fld in ('doses', 'ns', 'means', 'stdevs'):
arr = getattr(self, fld)[:-1]
setattr(self, fld, arr) # depends on [control=['for'], data=['fld']]
self._validate() |
def handle_events(self):
"""
An event handler that processes events from stdin and calls the on_click
function of the respective object. This function is run in another
thread, so as to not stall the main thread.
"""
for event in sys.stdin:
if event.startswith... | def function[handle_events, parameter[self]]:
constant[
An event handler that processes events from stdin and calls the on_click
function of the respective object. This function is run in another
thread, so as to not stall the main thread.
]
for taget[name[event]] in star... | keyword[def] identifier[handle_events] ( identifier[self] ):
literal[string]
keyword[for] identifier[event] keyword[in] identifier[sys] . identifier[stdin] :
keyword[if] identifier[event] . identifier[startswith] ( literal[string] ):
keyword[continue]
... | def handle_events(self):
"""
An event handler that processes events from stdin and calls the on_click
function of the respective object. This function is run in another
thread, so as to not stall the main thread.
"""
for event in sys.stdin:
if event.startswith('['):
... |
def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False,
inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@t... | def function[ru_strftime, parameter[format, date, inflected, inflected_day, preposition]]:
constant[
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{datetime... | keyword[def] identifier[ru_strftime] ( identifier[format] = literal[string] , identifier[date] = keyword[None] , identifier[inflected] = keyword[False] ,
identifier[inflected_day] = keyword[False] , identifier[preposition] = keyword[False] ):
literal[string]
keyword[if] identifier[date] keyword[is] key... | def ru_strftime(format=u'%d.%m.%Y', date=None, inflected=False, inflected_day=False, preposition=False):
"""
Russian strftime without locale
@param format: strftime format, default=u'%d.%m.%Y'
@type format: C{unicode}
@param date: date value, default=None translates to today
@type date: C{date... |
def explore(layer=None):
"""Function used to discover the Scapy layers and protocols.
It helps to see which packets exists in contrib or layer files.
params:
- layer: If specified, the function will explore the layer. If not,
the GUI mode will be activated, to browse the available layers... | def function[explore, parameter[layer]]:
constant[Function used to discover the Scapy layers and protocols.
It helps to see which packets exists in contrib or layer files.
params:
- layer: If specified, the function will explore the layer. If not,
the GUI mode will be activated, to b... | keyword[def] identifier[explore] ( identifier[layer] = keyword[None] ):
literal[string]
keyword[if] identifier[layer] keyword[is] keyword[None] :
keyword[if] keyword[not] identifier[conf] . identifier[interactive] :
keyword[raise] identifier[Scapy_Exception] ( literal[string]
... | def explore(layer=None):
"""Function used to discover the Scapy layers and protocols.
It helps to see which packets exists in contrib or layer files.
params:
- layer: If specified, the function will explore the layer. If not,
the GUI mode will be activated, to browse the available layers... |
def phase_bin_magseries(phases, mags,
binsize=0.005,
minbinelems=7):
'''Bins a phased magnitude/flux time-series using the bin size provided.
Parameters
----------
phases,mags : np.array
The phased magnitude/flux time-series to bin in phase. Non-... | def function[phase_bin_magseries, parameter[phases, mags, binsize, minbinelems]]:
constant[Bins a phased magnitude/flux time-series using the bin size provided.
Parameters
----------
phases,mags : np.array
The phased magnitude/flux time-series to bin in phase. Non-finite
elements w... | keyword[def] identifier[phase_bin_magseries] ( identifier[phases] , identifier[mags] ,
identifier[binsize] = literal[int] ,
identifier[minbinelems] = literal[int] ):
literal[string]
keyword[if] keyword[not] ( identifier[phases] . identifier[shape] keyword[and] identifier[mags] . identifier[shape... | def phase_bin_magseries(phases, mags, binsize=0.005, minbinelems=7):
"""Bins a phased magnitude/flux time-series using the bin size provided.
Parameters
----------
phases,mags : np.array
The phased magnitude/flux time-series to bin in phase. Non-finite
elements will be removed from the... |
def slow_augment(n, ii, jj, idx, count, x, y, u, v, c):
'''Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - th... | def function[slow_augment, parameter[n, ii, jj, idx, count, x, y, u, v, c]]:
constant[Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the fi... | keyword[def] identifier[slow_augment] ( identifier[n] , identifier[ii] , identifier[jj] , identifier[idx] , identifier[count] , identifier[x] , identifier[y] , identifier[u] , identifier[v] , identifier[c] ):
literal[string]
... | def slow_augment(n, ii, jj, idx, count, x, y, u, v, c):
"""Perform the augmentation step to assign unassigned i and j
n - the # of i and j, also the marker of unassigned x and y
ii - the unassigned i
jj - the ragged arrays of j for each i
idx - the index of the first j for each i
count - th... |
def make_html_tag(tag, text=None, **params):
"""Create an HTML tag string.
tag
The HTML tag to use (e.g. 'a', 'span' or 'div')
text
The text to enclose between opening and closing tag. If no text is specified then only
the opening tag is returned.
Example::
make_html_t... | def function[make_html_tag, parameter[tag, text]]:
constant[Create an HTML tag string.
tag
The HTML tag to use (e.g. 'a', 'span' or 'div')
text
The text to enclose between opening and closing tag. If no text is specified then only
the opening tag is returned.
Example::
... | keyword[def] identifier[make_html_tag] ( identifier[tag] , identifier[text] = keyword[None] ,** identifier[params] ):
literal[string]
identifier[params_string] = literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[sorted] ( identifier[params] . identifier[... | def make_html_tag(tag, text=None, **params):
"""Create an HTML tag string.
tag
The HTML tag to use (e.g. 'a', 'span' or 'div')
text
The text to enclose between opening and closing tag. If no text is specified then only
the opening tag is returned.
Example::
make_html_t... |
def tas2eas(Vtas, H):
"""True Airspeed to Equivalent Airspeed"""
rho = density(H)
Veas = Vtas * np.sqrt(rho/rho0)
return Veas | def function[tas2eas, parameter[Vtas, H]]:
constant[True Airspeed to Equivalent Airspeed]
variable[rho] assign[=] call[name[density], parameter[name[H]]]
variable[Veas] assign[=] binary_operation[name[Vtas] * call[name[np].sqrt, parameter[binary_operation[name[rho] / name[rho0]]]]]
return[na... | keyword[def] identifier[tas2eas] ( identifier[Vtas] , identifier[H] ):
literal[string]
identifier[rho] = identifier[density] ( identifier[H] )
identifier[Veas] = identifier[Vtas] * identifier[np] . identifier[sqrt] ( identifier[rho] / identifier[rho0] )
keyword[return] identifier[Veas] | def tas2eas(Vtas, H):
"""True Airspeed to Equivalent Airspeed"""
rho = density(H)
Veas = Vtas * np.sqrt(rho / rho0)
return Veas |
def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
servers = yield self.getClusterServers()
d = {
'workers': {},
'crons': {},
'queues': {}
}
now = time.time()
reverse_map = {... | def function[clusterStatus, parameter[self]]:
constant[
Returns a dict of cluster nodes and their status information
]
variable[servers] assign[=] <ast.Yield object at 0x7da1b189fac0>
variable[d] assign[=] dictionary[[<ast.Constant object at 0x7da1b189f640>, <ast.Constant object ... | keyword[def] identifier[clusterStatus] ( identifier[self] ):
literal[string]
identifier[servers] = keyword[yield] identifier[self] . identifier[getClusterServers] ()
identifier[d] ={
literal[string] :{},
literal[string] :{},
literal[string] :{}
}
... | def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
servers = (yield self.getClusterServers())
d = {'workers': {}, 'crons': {}, 'queues': {}}
now = time.time()
reverse_map = {}
for sname in servers:
last = (yield self._get_key('/s... |
def create_config(config_path="scriptworker.yaml"):
"""Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tuple: (config ... | def function[create_config, parameter[config_path]]:
constant[Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tupl... | keyword[def] identifier[create_config] ( identifier[config_path] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[config_path] ):
identifier[print] ( literal[string] . identifier[format] ( identifier[config_path] ),... | def create_config(config_path='scriptworker.yaml'):
"""Create a config from DEFAULT_CONFIG, arguments, and config file.
Then validate it and freeze it.
Args:
config_path (str, optional): the path to the config file. Defaults to
"scriptworker.yaml"
Returns:
tuple: (config ... |
def get_region():
"""Use the environment to get the current region"""
global _REGION
if _REGION is None:
region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1"
region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")}
if region_name not in region_dict:
r... | def function[get_region, parameter[]]:
constant[Use the environment to get the current region]
<ast.Global object at 0x7da20cabf430>
if compare[name[_REGION] is constant[None]] begin[:]
variable[region_name] assign[=] <ast.BoolOp object at 0x7da20cabd6c0>
variable[reg... | keyword[def] identifier[get_region] ():
literal[string]
keyword[global] identifier[_REGION]
keyword[if] identifier[_REGION] keyword[is] keyword[None] :
identifier[region_name] = identifier[os] . identifier[getenv] ( literal[string] ) keyword[or] literal[string]
identifier[regi... | def get_region():
"""Use the environment to get the current region"""
global _REGION
if _REGION is None:
region_name = os.getenv('AWS_DEFAULT_REGION') or 'us-east-1'
region_dict = {r.name: r for r in boto.regioninfo.get_regions('ec2')}
if region_name not in region_dict:
r... |
def update(self, use_template=False, **metadata_defaults):
""" OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property """
self.validate()
tree_to_update = self._xml_tree if not use_template else self._get_template(**metadata_defaults)
supported_props = self._metadata... | def function[update, parameter[self, use_template]]:
constant[ OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property ]
call[name[self].validate, parameter[]]
variable[tree_to_update] assign[=] <ast.IfExp object at 0x7da1b25d45e0>
variable[supported_props] assign[=] na... | keyword[def] identifier[update] ( identifier[self] , identifier[use_template] = keyword[False] ,** identifier[metadata_defaults] ):
literal[string]
identifier[self] . identifier[validate] ()
identifier[tree_to_update] = identifier[self] . identifier[_xml_tree] keyword[if] keyword[not] ... | def update(self, use_template=False, **metadata_defaults):
""" OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property """
self.validate()
tree_to_update = self._xml_tree if not use_template else self._get_template(**metadata_defaults)
supported_props = self._metadata_props
# Itera... |
def fields2jsonschema(self, fields, ordered=False, partial=None):
"""Return the JSON Schema Object given a mapping between field names and
:class:`Field <marshmallow.Field>` objects.
:param dict fields: A dictionary of field name field object pairs
:param bool ordered: Whether to preser... | def function[fields2jsonschema, parameter[self, fields, ordered, partial]]:
constant[Return the JSON Schema Object given a mapping between field names and
:class:`Field <marshmallow.Field>` objects.
:param dict fields: A dictionary of field name field object pairs
:param bool ordered: W... | keyword[def] identifier[fields2jsonschema] ( identifier[self] , identifier[fields] , identifier[ordered] = keyword[False] , identifier[partial] = keyword[None] ):
literal[string]
identifier[jsonschema] ={ literal[string] : literal[string] , literal[string] : identifier[OrderedDict] () keyword[if] ... | def fields2jsonschema(self, fields, ordered=False, partial=None):
"""Return the JSON Schema Object given a mapping between field names and
:class:`Field <marshmallow.Field>` objects.
:param dict fields: A dictionary of field name field object pairs
:param bool ordered: Whether to preserve t... |
def _stop_instance(self):
"""
Stop the instance.
"""
try:
vm_stop = self.compute.virtual_machines.power_off(
self.running_instance_id, self.running_instance_id
)
except Exception as error:
raise AzureCloudException(
... | def function[_stop_instance, parameter[self]]:
constant[
Stop the instance.
]
<ast.Try object at 0x7da1b1a229b0>
call[name[vm_stop].wait, parameter[]] | keyword[def] identifier[_stop_instance] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[vm_stop] = identifier[self] . identifier[compute] . identifier[virtual_machines] . identifier[power_off] (
identifier[self] . identifier[running_instance_id] , identifie... | def _stop_instance(self):
"""
Stop the instance.
"""
try:
vm_stop = self.compute.virtual_machines.power_off(self.running_instance_id, self.running_instance_id) # depends on [control=['try'], data=[]]
except Exception as error:
raise AzureCloudException('Unable to stop instan... |
def formdata_post(url, fields):
"""Send an HTTP request with a multipart/form-data body for the
given URL and return the data returned by the server.
"""
content_type, data = formdata_encode(fields)
req = urllib2.Request(url, data)
req.add_header('Content-Type', content_type)
return urllib2.... | def function[formdata_post, parameter[url, fields]]:
constant[Send an HTTP request with a multipart/form-data body for the
given URL and return the data returned by the server.
]
<ast.Tuple object at 0x7da1b0b0de10> assign[=] call[name[formdata_encode], parameter[name[fields]]]
variable[... | keyword[def] identifier[formdata_post] ( identifier[url] , identifier[fields] ):
literal[string]
identifier[content_type] , identifier[data] = identifier[formdata_encode] ( identifier[fields] )
identifier[req] = identifier[urllib2] . identifier[Request] ( identifier[url] , identifier[data] )
iden... | def formdata_post(url, fields):
"""Send an HTTP request with a multipart/form-data body for the
given URL and return the data returned by the server.
"""
(content_type, data) = formdata_encode(fields)
req = urllib2.Request(url, data)
req.add_header('Content-Type', content_type)
return urllib... |
def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') | def function[_filehandler, parameter[configurable]]:
constant[Default logging file handler.]
variable[filename] assign[=] call[name[configurable].log_name.replace, parameter[constant[.], name[sep]]]
variable[path] assign[=] call[name[join], parameter[name[configurable].log_path, call[constant[{0... | keyword[def] identifier[_filehandler] ( identifier[configurable] ):
literal[string]
identifier[filename] = identifier[configurable] . identifier[log_name] . identifier[replace] ( literal[string] , identifier[sep] )
identifier[path] = identifier[join] ( identifier[configurable] . identifier[log_path] ... | def _filehandler(configurable):
"""Default logging file handler."""
filename = configurable.log_name.replace('.', sep)
path = join(configurable.log_path, '{0}.log'.format(filename))
return FileHandler(path, mode='a+') |
def hide(self):
"""Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``)"""
self._hidden = True
for artist in self.annotations.values():
artist.set_visible(False)
for fig in self.figures:
... | def function[hide, parameter[self]]:
constant[Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``)]
name[self]._hidden assign[=] constant[True]
for taget[name[artist]] in starred[call[name[self].annotations.... | keyword[def] identifier[hide] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_hidden] = keyword[True]
keyword[for] identifier[artist] keyword[in] identifier[self] . identifier[annotations] . identifier[values] ():
identifier[artist] . identifier[set_vi... | def hide(self):
"""Hides all annotation artists associated with the DataCursor. Returns
self to allow "chaining". (e.g. ``datacursor.hide().disable()``)"""
self._hidden = True
for artist in self.annotations.values():
artist.set_visible(False) # depends on [control=['for'], data=['artist']]
... |
def set_options(self, options):
"""
Configure all the many options we'll need to make this happen.
"""
self.verbosity = int(options.get('verbosity'))
# Will we be gzipping?
self.gzip = getattr(settings, 'BAKERY_GZIP', False)
# And if so what content types will w... | def function[set_options, parameter[self, options]]:
constant[
Configure all the many options we'll need to make this happen.
]
name[self].verbosity assign[=] call[name[int], parameter[call[name[options].get, parameter[constant[verbosity]]]]]
name[self].gzip assign[=] call[name[g... | keyword[def] identifier[set_options] ( identifier[self] , identifier[options] ):
literal[string]
identifier[self] . identifier[verbosity] = identifier[int] ( identifier[options] . identifier[get] ( literal[string] ))
identifier[self] . identifier[gzip] = identifier[getattr] ( ide... | def set_options(self, options):
"""
Configure all the many options we'll need to make this happen.
"""
self.verbosity = int(options.get('verbosity'))
# Will we be gzipping?
self.gzip = getattr(settings, 'BAKERY_GZIP', False)
# And if so what content types will we be gzipping?
sel... |
def load_from_dict(self, conf_dict=None):
""" Load the configuration from a dictionary.
Args:
conf_dict (dict): Dictionary with the configuration.
"""
self.set_to_default()
self._update_dict(self._config, conf_dict)
self._update_python_paths() | def function[load_from_dict, parameter[self, conf_dict]]:
constant[ Load the configuration from a dictionary.
Args:
conf_dict (dict): Dictionary with the configuration.
]
call[name[self].set_to_default, parameter[]]
call[name[self]._update_dict, parameter[name[self].... | keyword[def] identifier[load_from_dict] ( identifier[self] , identifier[conf_dict] = keyword[None] ):
literal[string]
identifier[self] . identifier[set_to_default] ()
identifier[self] . identifier[_update_dict] ( identifier[self] . identifier[_config] , identifier[conf_dict] )
ide... | def load_from_dict(self, conf_dict=None):
""" Load the configuration from a dictionary.
Args:
conf_dict (dict): Dictionary with the configuration.
"""
self.set_to_default()
self._update_dict(self._config, conf_dict)
self._update_python_paths() |
def create_parser(self, prog_name, subcommand):
"""
Customize the parser to include option groups.
"""
parser = optparse.OptionParser(
prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.get_o... | def function[create_parser, parameter[self, prog_name, subcommand]]:
constant[
Customize the parser to include option groups.
]
variable[parser] assign[=] call[name[optparse].OptionParser, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da1b14d02e0>, <ast.Name objec... | keyword[def] identifier[create_parser] ( identifier[self] , identifier[prog_name] , identifier[subcommand] ):
literal[string]
identifier[parser] = identifier[optparse] . identifier[OptionParser] (
identifier[prog] = identifier[prog_name] ,
identifier[usage] = identifier[self] . id... | def create_parser(self, prog_name, subcommand):
"""
Customize the parser to include option groups.
"""
parser = optparse.OptionParser(prog=prog_name, usage=self.usage(subcommand), version=self.get_version(), option_list=self.get_option_list())
for (name, description, option_list) in... |
def _check_transition_validity(self, check_transition):
""" Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState.
Start transitions are forbidden in the ConcurrencyState
:param check_transition: the transition to check for validity
:return:
... | def function[_check_transition_validity, parameter[self, check_transition]]:
constant[ Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState.
Start transitions are forbidden in the ConcurrencyState
:param check_transition: the transition to check for validi... | keyword[def] identifier[_check_transition_validity] ( identifier[self] , identifier[check_transition] ):
literal[string]
identifier[valid] , identifier[message] = identifier[super] ( identifier[PreemptiveConcurrencyState] , identifier[self] ). identifier[_check_transition_validity] ( identifier[che... | def _check_transition_validity(self, check_transition):
""" Transition of BarrierConcurrencyStates must least fulfill the condition of a ContainerState.
Start transitions are forbidden in the ConcurrencyState
:param check_transition: the transition to check for validity
:return:
"""... |
def resolve(self, current_file, rel_path):
"""Search the filesystem."""
search_path = [path.dirname(current_file)] + self.search_path
target_path = None
for search in search_path:
if self.exists(path.join(search, rel_path)):
target_path = path.normpath(path.join(search, rel_path))
... | def function[resolve, parameter[self, current_file, rel_path]]:
constant[Search the filesystem.]
variable[search_path] assign[=] binary_operation[list[[<ast.Call object at 0x7da20c76e890>]] + name[self].search_path]
variable[target_path] assign[=] constant[None]
for taget[name[search]] i... | keyword[def] identifier[resolve] ( identifier[self] , identifier[current_file] , identifier[rel_path] ):
literal[string]
identifier[search_path] =[ identifier[path] . identifier[dirname] ( identifier[current_file] )]+ identifier[self] . identifier[search_path]
identifier[target_path] = keyword[None]... | def resolve(self, current_file, rel_path):
"""Search the filesystem."""
search_path = [path.dirname(current_file)] + self.search_path
target_path = None
for search in search_path:
if self.exists(path.join(search, rel_path)):
target_path = path.normpath(path.join(search, rel_path))
... |
def parse(src):
"""Note: src should be ascii string"""
rt = libparser.parse(byref(post), src)
return (
rt,
string_at(post.title, post.tsz),
string_at(post.tpic, post.tpsz),
post.body
) | def function[parse, parameter[src]]:
constant[Note: src should be ascii string]
variable[rt] assign[=] call[name[libparser].parse, parameter[call[name[byref], parameter[name[post]]], name[src]]]
return[tuple[[<ast.Name object at 0x7da18bcc9330>, <ast.Call object at 0x7da18bcc9db0>, <ast.Call object ... | keyword[def] identifier[parse] ( identifier[src] ):
literal[string]
identifier[rt] = identifier[libparser] . identifier[parse] ( identifier[byref] ( identifier[post] ), identifier[src] )
keyword[return] (
identifier[rt] ,
identifier[string_at] ( identifier[post] . identifier[title] , identif... | def parse(src):
"""Note: src should be ascii string"""
rt = libparser.parse(byref(post), src)
return (rt, string_at(post.title, post.tsz), string_at(post.tpic, post.tpsz), post.body) |
def Match(self, file_entry):
"""Determines if a file entry matches the filter.
Args:
file_entry (dfvfs.FileEntry): a file entry.
Returns:
bool: True if the file entry matches the filter.
"""
if not file_entry:
return False
filename = file_entry.name.lower()
return filena... | def function[Match, parameter[self, file_entry]]:
constant[Determines if a file entry matches the filter.
Args:
file_entry (dfvfs.FileEntry): a file entry.
Returns:
bool: True if the file entry matches the filter.
]
if <ast.UnaryOp object at 0x7da207f9be80> begin[:]
ret... | keyword[def] identifier[Match] ( identifier[self] , identifier[file_entry] ):
literal[string]
keyword[if] keyword[not] identifier[file_entry] :
keyword[return] keyword[False]
identifier[filename] = identifier[file_entry] . identifier[name] . identifier[lower] ()
keyword[return] ident... | def Match(self, file_entry):
"""Determines if a file entry matches the filter.
Args:
file_entry (dfvfs.FileEntry): a file entry.
Returns:
bool: True if the file entry matches the filter.
"""
if not file_entry:
return False # depends on [control=['if'], data=[]]
filename = ... |
def FromTimedelta(self, td):
"""Convertd timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY,
td.microseconds * _NANOS_PER_MICROSECOND) | def function[FromTimedelta, parameter[self, td]]:
constant[Convertd timedelta to Duration.]
call[name[self]._NormalizeDuration, parameter[binary_operation[name[td].seconds + binary_operation[name[td].days * name[_SECONDS_PER_DAY]]], binary_operation[name[td].microseconds * name[_NANOS_PER_MICROSECOND]]]... | keyword[def] identifier[FromTimedelta] ( identifier[self] , identifier[td] ):
literal[string]
identifier[self] . identifier[_NormalizeDuration] ( identifier[td] . identifier[seconds] + identifier[td] . identifier[days] * identifier[_SECONDS_PER_DAY] ,
identifier[td] . identifier[microseconds] * identi... | def FromTimedelta(self, td):
"""Convertd timedelta to Duration."""
self._NormalizeDuration(td.seconds + td.days * _SECONDS_PER_DAY, td.microseconds * _NANOS_PER_MICROSECOND) |
def _check_inputs(self, operators, weights):
""" Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
weights :... | def function[_check_inputs, parameter[self, operators, weights]]:
constant[ Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class ... | keyword[def] identifier[_check_inputs] ( identifier[self] , identifier[operators] , identifier[weights] ):
literal[string]
identifier[operators] = identifier[self] . identifier[_check_type] ( identifier[operators] )
keyword[for] identifier[operator] keyword[in] identifier[operators] :... | def _check_inputs(self, operators, weights):
""" Check Inputs
This method cheks that the input operators and weights are correctly
formatted
Parameters
----------
operators : list, tuple or np.ndarray
List of linear operator class instances
weights : lis... |
def check_jobs(jobs):
"""Validate number of jobs."""
if jobs == 0:
raise click.UsageError("Jobs must be >= 1 or == -1")
elif jobs < 0:
import multiprocessing
jobs = multiprocessing.cpu_count()
return jobs | def function[check_jobs, parameter[jobs]]:
constant[Validate number of jobs.]
if compare[name[jobs] equal[==] constant[0]] begin[:]
<ast.Raise object at 0x7da18eb56da0>
return[name[jobs]] | keyword[def] identifier[check_jobs] ( identifier[jobs] ):
literal[string]
keyword[if] identifier[jobs] == literal[int] :
keyword[raise] identifier[click] . identifier[UsageError] ( literal[string] )
keyword[elif] identifier[jobs] < literal[int] :
keyword[import] identifier[multip... | def check_jobs(jobs):
"""Validate number of jobs."""
if jobs == 0:
raise click.UsageError('Jobs must be >= 1 or == -1') # depends on [control=['if'], data=[]]
elif jobs < 0:
import multiprocessing
jobs = multiprocessing.cpu_count() # depends on [control=['if'], data=['jobs']]
r... |
def get_distance_function(distance):
"""
Returns the distance function from the string name provided
:param distance: The string name of the distributions
:return:
"""
# If we provided distance function ourselves, use it
if callable(distance):
return distance
try:
return... | def function[get_distance_function, parameter[distance]]:
constant[
Returns the distance function from the string name provided
:param distance: The string name of the distributions
:return:
]
if call[name[callable], parameter[name[distance]]] begin[:]
return[name[distance]]
... | keyword[def] identifier[get_distance_function] ( identifier[distance] ):
literal[string]
keyword[if] identifier[callable] ( identifier[distance] ):
keyword[return] identifier[distance]
keyword[try] :
keyword[return] identifier[_supported_distances_lookup] ()[ identifier[dist... | def get_distance_function(distance):
"""
Returns the distance function from the string name provided
:param distance: The string name of the distributions
:return:
"""
# If we provided distance function ourselves, use it
if callable(distance):
return distance # depends on [control=... |
def check_privatenet(self):
"""
Check if privatenet is running, and if container is same as the current Chains/privnet database.
Raises:
PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match
"""
rpc_settings.setup(self.RPC_LIST)
... | def function[check_privatenet, parameter[self]]:
constant[
Check if privatenet is running, and if container is same as the current Chains/privnet database.
Raises:
PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match
]
call[name[... | keyword[def] identifier[check_privatenet] ( identifier[self] ):
literal[string]
identifier[rpc_settings] . identifier[setup] ( identifier[self] . identifier[RPC_LIST] )
identifier[client] = identifier[RPCClient] ()
keyword[try] :
identifier[version] = identifier[clie... | def check_privatenet(self):
"""
Check if privatenet is running, and if container is same as the current Chains/privnet database.
Raises:
PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match
"""
rpc_settings.setup(self.RPC_LIST)
clien... |
def receive(self):
"""I receive data+hash, check for a match, confirm or not
confirm to the sender, and return the data payload.
"""
def _receive(input_message):
self.data = input_message[:-64]
_hash = input_message[-64:]
if h.sha256(self.data).hexdige... | def function[receive, parameter[self]]:
constant[I receive data+hash, check for a match, confirm or not
confirm to the sender, and return the data payload.
]
def function[_receive, parameter[input_message]]:
name[self].data assign[=] call[name[input_message]][<ast.Slice o... | keyword[def] identifier[receive] ( identifier[self] ):
literal[string]
keyword[def] identifier[_receive] ( identifier[input_message] ):
identifier[self] . identifier[data] = identifier[input_message] [:- literal[int] ]
identifier[_hash] = identifier[input_message] [- lite... | def receive(self):
"""I receive data+hash, check for a match, confirm or not
confirm to the sender, and return the data payload.
"""
def _receive(input_message):
self.data = input_message[:-64]
_hash = input_message[-64:]
if h.sha256(self.data).hexdigest() == _hash:
... |
def fullvars(obj):
'''
like `vars()` but support `__slots__`.
'''
try:
return vars(obj)
except TypeError:
pass
# __slots__
slotsnames = set()
for cls in type(obj).__mro__:
__slots__ = getattr(cls, '__slots__', None)
if __slots__:
if isinstanc... | def function[fullvars, parameter[obj]]:
constant[
like `vars()` but support `__slots__`.
]
<ast.Try object at 0x7da1b002caf0>
variable[slotsnames] assign[=] call[name[set], parameter[]]
for taget[name[cls]] in starred[call[name[type], parameter[name[obj]]].__mro__] begin[:]
... | keyword[def] identifier[fullvars] ( identifier[obj] ):
literal[string]
keyword[try] :
keyword[return] identifier[vars] ( identifier[obj] )
keyword[except] identifier[TypeError] :
keyword[pass]
identifier[slotsnames] = identifier[set] ()
keyword[for] identifie... | def fullvars(obj):
"""
like `vars()` but support `__slots__`.
"""
try:
return vars(obj) # depends on [control=['try'], data=[]]
except TypeError:
pass # depends on [control=['except'], data=[]]
# __slots__
slotsnames = set()
for cls in type(obj).__mro__:
__slots... |
def activateCells(self,
activeColumns,
basalReinforceCandidates,
apicalReinforceCandidates,
basalGrowthCandidates,
apicalGrowthCandidates,
learn=True):
"""
Activate cells in the specified colu... | def function[activateCells, parameter[self, activeColumns, basalReinforceCandidates, apicalReinforceCandidates, basalGrowthCandidates, apicalGrowthCandidates, learn]]:
constant[
Activate cells in the specified columns, using the result of the previous
'depolarizeCells' as predictions. Then learn.
@... | keyword[def] identifier[activateCells] ( identifier[self] ,
identifier[activeColumns] ,
identifier[basalReinforceCandidates] ,
identifier[apicalReinforceCandidates] ,
identifier[basalGrowthCandidates] ,
identifier[apicalGrowthCandidates] ,
identifier[learn] = keyword[True] ):
literal[string]
( i... | def activateCells(self, activeColumns, basalReinforceCandidates, apicalReinforceCandidates, basalGrowthCandidates, apicalGrowthCandidates, learn=True):
"""
Activate cells in the specified columns, using the result of the previous
'depolarizeCells' as predictions. Then learn.
@param activeColumns (numpy... |
def finish_response(self):
"""
Completes the response and performs the following tasks:
- Remove the `'ws4py.socket'` and `'ws4py.websocket'`
environ keys.
- Attach the returned websocket, if any, to the WSGI server
using its ``link_websocket_to_server`` method.
... | def function[finish_response, parameter[self]]:
constant[
Completes the response and performs the following tasks:
- Remove the `'ws4py.socket'` and `'ws4py.websocket'`
environ keys.
- Attach the returned websocket, if any, to the WSGI server
using its ``link_websock... | keyword[def] identifier[finish_response] ( identifier[self] ):
literal[string]
identifier[rest] = identifier[iter] ( identifier[self] . identifier[result] )
identifier[first] = identifier[list] ( identifier[itertools] . identifier[islice] ( identifier[rest] , literal[int] ))
... | def finish_response(self):
"""
Completes the response and performs the following tasks:
- Remove the `'ws4py.socket'` and `'ws4py.websocket'`
environ keys.
- Attach the returned websocket, if any, to the WSGI server
using its ``link_websocket_to_server`` method.
... |
def voronoi(script, region_num=10, overlap=False):
"""Voronoi Atlas parameterization
"""
filter_xml = ''.join([
' <filter name="Parametrization: Voronoi Atlas">\n',
' <Param name="regionNum"',
'value="%d"' % region_num,
'description="Approx. Region Num"',
'type="... | def function[voronoi, parameter[script, region_num, overlap]]:
constant[Voronoi Atlas parameterization
]
variable[filter_xml] assign[=] call[constant[].join, parameter[list[[<ast.Constant object at 0x7da1b0295270>, <ast.Constant object at 0x7da1b0297790>, <ast.BinOp object at 0x7da1b0297a00>, <ast.... | keyword[def] identifier[voronoi] ( identifier[script] , identifier[region_num] = literal[int] , identifier[overlap] = keyword[False] ):
literal[string]
identifier[filter_xml] = literal[string] . identifier[join] ([
literal[string] ,
literal[string] ,
literal[string] % identifier[region_num] ... | def voronoi(script, region_num=10, overlap=False):
"""Voronoi Atlas parameterization
"""
filter_xml = ''.join([' <filter name="Parametrization: Voronoi Atlas">\n', ' <Param name="regionNum"', 'value="%d"' % region_num, 'description="Approx. Region Num"', 'type="RichInt"', 'tooltip="An estimation of the... |
def dump_nodes(self):
"""Dump current screen UI to list
Returns:
List of UINode object, For
example:
[UINode(
bounds=Bounds(left=0, top=0, right=480, bottom=168),
checkable=False,
class_name='android.view.View',
... | def function[dump_nodes, parameter[self]]:
constant[Dump current screen UI to list
Returns:
List of UINode object, For
example:
[UINode(
bounds=Bounds(left=0, top=0, right=480, bottom=168),
checkable=False,
class_name='... | keyword[def] identifier[dump_nodes] ( identifier[self] ):
literal[string]
identifier[xmldata] = identifier[self] . identifier[_uiauto] . identifier[dump] ()
identifier[dom] = identifier[xml] . identifier[dom] . identifier[minidom] . identifier[parseString] ( identifier[xmldata] . identifie... | def dump_nodes(self):
"""Dump current screen UI to list
Returns:
List of UINode object, For
example:
[UINode(
bounds=Bounds(left=0, top=0, right=480, bottom=168),
checkable=False,
class_name='android.view.View',
... |
def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None):
'''
Deletes a certificate from Amazon.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_server_cert mycert_name
'''
conn = _get_conn(region=region, key=ke... | def function[delete_server_cert, parameter[cert_name, region, key, keyid, profile]]:
constant[
Deletes a certificate from Amazon.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_server_cert mycert_name
]
variable[conn] assign[=] ... | keyword[def] identifier[delete_server_cert] ( identifier[cert_name] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
identifier[conn] = identifier[_get_conn] ( identifier[region] = identifier[... | def delete_server_cert(cert_name, region=None, key=None, keyid=None, profile=None):
"""
Deletes a certificate from Amazon.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt myminion boto_iam.delete_server_cert mycert_name
"""
conn = _get_conn(region=region, key=ke... |
def show_lbaas_l7rule(self, l7rule, l7policy, **_params):
"""Fetches information of a certain L7 policy's rule."""
return self.get(self.lbaas_l7rule_path % (l7policy, l7rule),
params=_params) | def function[show_lbaas_l7rule, parameter[self, l7rule, l7policy]]:
constant[Fetches information of a certain L7 policy's rule.]
return[call[name[self].get, parameter[binary_operation[name[self].lbaas_l7rule_path <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18f00e710>, <ast.Name object... | keyword[def] identifier[show_lbaas_l7rule] ( identifier[self] , identifier[l7rule] , identifier[l7policy] ,** identifier[_params] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[self] . identifier[lbaas_l7rule_path] %( identifier[l7policy] , identifier[l7rule] ),... | def show_lbaas_l7rule(self, l7rule, l7policy, **_params):
"""Fetches information of a certain L7 policy's rule."""
return self.get(self.lbaas_l7rule_path % (l7policy, l7rule), params=_params) |
def shift(txt, indent = ' ', prepend = ''):
"""Return a list corresponding to the lines of text in the `txt` list
indented by `indent`. Prepend instead the string given in `prepend` to the
beginning of the first line. Note that if len(prepend) > len(indent), then
`prepend` will be truncated (doing be... | def function[shift, parameter[txt, indent, prepend]]:
constant[Return a list corresponding to the lines of text in the `txt` list
indented by `indent`. Prepend instead the string given in `prepend` to the
beginning of the first line. Note that if len(prepend) > len(indent), then
`prepend` will be tr... | keyword[def] identifier[shift] ( identifier[txt] , identifier[indent] = literal[string] , identifier[prepend] = literal[string] ):
literal[string]
keyword[if] identifier[type] ( identifier[indent] ) keyword[is] identifier[int] :
identifier[indent] = identifier[indent] * literal[string]
ide... | def shift(txt, indent=' ', prepend=''):
"""Return a list corresponding to the lines of text in the `txt` list
indented by `indent`. Prepend instead the string given in `prepend` to the
beginning of the first line. Note that if len(prepend) > len(indent), then
`prepend` will be truncated (doing better... |
def get_idxs(exprs):
"""
Finds sympy.tensor.indexed.Idx instances and returns them.
"""
idxs = set()
for expr in (exprs):
for i in expr.find(sympy.Idx):
idxs.add(i)
return sorted(idxs, key=str) | def function[get_idxs, parameter[exprs]]:
constant[
Finds sympy.tensor.indexed.Idx instances and returns them.
]
variable[idxs] assign[=] call[name[set], parameter[]]
for taget[name[expr]] in starred[name[exprs]] begin[:]
for taget[name[i]] in starred[call[name[expr].find... | keyword[def] identifier[get_idxs] ( identifier[exprs] ):
literal[string]
identifier[idxs] = identifier[set] ()
keyword[for] identifier[expr] keyword[in] ( identifier[exprs] ):
keyword[for] identifier[i] keyword[in] identifier[expr] . identifier[find] ( identifier[sympy] . identifier[Idx]... | def get_idxs(exprs):
"""
Finds sympy.tensor.indexed.Idx instances and returns them.
"""
idxs = set()
for expr in exprs:
for i in expr.find(sympy.Idx):
idxs.add(i) # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=['expr']]
return sorted(idxs, ke... |
def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for i, e in enumerate(L) if L.index(e) == i] | def function[uniquify_list, parameter[L]]:
constant[Same order unique list using only a list compression.]
return[<ast.ListComp object at 0x7da20c6aba00>] | keyword[def] identifier[uniquify_list] ( identifier[L] ):
literal[string]
keyword[return] [ identifier[e] keyword[for] identifier[i] , identifier[e] keyword[in] identifier[enumerate] ( identifier[L] ) keyword[if] identifier[L] . identifier[index] ( identifier[e] )== identifier[i] ] | def uniquify_list(L):
"""Same order unique list using only a list compression."""
return [e for (i, e) in enumerate(L) if L.index(e) == i] |
def redistribute_threads(blockdimx, blockdimy, blockdimz,
dimx, dimy, dimz):
"""
Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary
"""
# Shift threads from the z dimension
# into the y dimension
... | def function[redistribute_threads, parameter[blockdimx, blockdimy, blockdimz, dimx, dimy, dimz]]:
constant[
Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary
]
while compare[name[blockdimz] greater[... | keyword[def] identifier[redistribute_threads] ( identifier[blockdimx] , identifier[blockdimy] , identifier[blockdimz] ,
identifier[dimx] , identifier[dimy] , identifier[dimz] ):
literal[string]
keyword[while] identifier[blockdimz] > identifier[dimz] :
identifier[tmp] = identifier[bloc... | def redistribute_threads(blockdimx, blockdimy, blockdimz, dimx, dimy, dimz):
"""
Redistribute threads from the Z dimension towards the X dimension.
Also clamp number of threads to the problem dimension size,
if necessary
"""
# Shift threads from the z dimension
# into the y dimension
whi... |
def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines()
else:
users = []
return [u... | def function[GetConfiguredUsers, parameter[self]]:
constant[Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
]
if call[name[os].path.exists, parameter[name[self].google_users_file]] begin[:]
variable[... | keyword[def] identifier[GetConfiguredUsers] ( identifier[self] ):
literal[string]
keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[google_users_file] ):
identifier[users] = identifier[open] ( identifier[self] . identifier[google_users_file] ). ident... | def GetConfiguredUsers(self):
"""Retrieve the list of configured Google user accounts.
Returns:
list, the username strings of users congfigured by Google.
"""
if os.path.exists(self.google_users_file):
users = open(self.google_users_file).readlines() # depends on [control=['if'], data=[]... |
def to_python(obj,
in_dict,
str_keys=None,
date_keys=None,
int_keys=None,
object_map=None,
bool_keys=None,
dict_keys=None,
**kwargs):
"""Extends a given object for API Consumption.
:param obj: Object to extend.
:param in_dict: Dict to extract data from.
:param string_key... | def function[to_python, parameter[obj, in_dict, str_keys, date_keys, int_keys, object_map, bool_keys, dict_keys]]:
constant[Extends a given object for API Consumption.
:param obj: Object to extend.
:param in_dict: Dict to extract data from.
:param string_keys: List of in_dict keys that will be extr... | keyword[def] identifier[to_python] ( identifier[obj] ,
identifier[in_dict] ,
identifier[str_keys] = keyword[None] ,
identifier[date_keys] = keyword[None] ,
identifier[int_keys] = keyword[None] ,
identifier[object_map] = keyword[None] ,
identifier[bool_keys] = keyword[None] ,
identifier[dict_keys] = keyword[Non... | def to_python(obj, in_dict, str_keys=None, date_keys=None, int_keys=None, object_map=None, bool_keys=None, dict_keys=None, **kwargs):
"""Extends a given object for API Consumption.
:param obj: Object to extend.
:param in_dict: Dict to extract data from.
:param string_keys: List of in_dict keys that wil... |
def close(self):
""" closes render window """
# must close out axes marker
if hasattr(self, 'axes_widget'):
del self.axes_widget
# reset scalar bar stuff
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
self._sca... | def function[close, parameter[self]]:
constant[ closes render window ]
if call[name[hasattr], parameter[name[self], constant[axes_widget]]] begin[:]
<ast.Delete object at 0x7da20e961f60>
name[self]._scalar_bar_slots assign[=] call[name[set], parameter[call[name[range], parameter[name[MAX... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
keyword[del] identifier[self] . identifier[axes_widget]
identifier[self] . identifier[_scalar_bar_slots] = ide... | def close(self):
""" closes render window """
# must close out axes marker
if hasattr(self, 'axes_widget'):
del self.axes_widget # depends on [control=['if'], data=[]]
# reset scalar bar stuff
self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS))
self._scalar_bar_slot_lookup = {}
se... |
def trace(self, s, active=None, verbose=False):
"""
Rewrite string *s* like `apply()`, but yield each rewrite step.
Args:
s (str): the input string to process
active (optional): a collection of external module names
that may be applied if called
... | def function[trace, parameter[self, s, active, verbose]]:
constant[
Rewrite string *s* like `apply()`, but yield each rewrite step.
Args:
s (str): the input string to process
active (optional): a collection of external module names
that may be applied if ... | keyword[def] identifier[trace] ( identifier[self] , identifier[s] , identifier[active] = keyword[None] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] identifier[active] keyword[is] keyword[None] :
identifier[active] = identifier[self] . identifier[active]
... | def trace(self, s, active=None, verbose=False):
"""
Rewrite string *s* like `apply()`, but yield each rewrite step.
Args:
s (str): the input string to process
active (optional): a collection of external module names
that may be applied if called
v... |
def visit_augassign(self, node, parent):
"""visit a AugAssign node by returning a fresh instance of it"""
newnode = nodes.AugAssign(
self._bin_op_classes[type(node.op)] + "=",
node.lineno,
node.col_offset,
parent,
)
newnode.postinit(
... | def function[visit_augassign, parameter[self, node, parent]]:
constant[visit a AugAssign node by returning a fresh instance of it]
variable[newnode] assign[=] call[name[nodes].AugAssign, parameter[binary_operation[call[name[self]._bin_op_classes][call[name[type], parameter[name[node].op]]] + constant[=]... | keyword[def] identifier[visit_augassign] ( identifier[self] , identifier[node] , identifier[parent] ):
literal[string]
identifier[newnode] = identifier[nodes] . identifier[AugAssign] (
identifier[self] . identifier[_bin_op_classes] [ identifier[type] ( identifier[node] . identifier[op] )]+... | def visit_augassign(self, node, parent):
"""visit a AugAssign node by returning a fresh instance of it"""
newnode = nodes.AugAssign(self._bin_op_classes[type(node.op)] + '=', node.lineno, node.col_offset, parent)
newnode.postinit(self.visit(node.target, newnode), self.visit(node.value, newnode))
return ... |
def buttons(self, master):
"""Adds 'OK' and 'Cancel' buttons to standard button frame.
Override if need for different configuration.
"""
subframe = tk.Frame(master)
subframe.pack(side=tk.RIGHT)
ttk.Button(
subframe,
text="OK",
width=... | def function[buttons, parameter[self, master]]:
constant[Adds 'OK' and 'Cancel' buttons to standard button frame.
Override if need for different configuration.
]
variable[subframe] assign[=] call[name[tk].Frame, parameter[name[master]]]
call[name[subframe].pack, parameter[]]
... | keyword[def] identifier[buttons] ( identifier[self] , identifier[master] ):
literal[string]
identifier[subframe] = identifier[tk] . identifier[Frame] ( identifier[master] )
identifier[subframe] . identifier[pack] ( identifier[side] = identifier[tk] . identifier[RIGHT] )
identifi... | def buttons(self, master):
"""Adds 'OK' and 'Cancel' buttons to standard button frame.
Override if need for different configuration.
"""
subframe = tk.Frame(master)
subframe.pack(side=tk.RIGHT)
ttk.Button(subframe, text='OK', width=10, command=self.ok, default=tk.ACTIVE).pack(side=tk.LE... |
def on_canvas_slave__electrode_selected(self, slave, data):
'''
.. versionchanged:: 0.11
Clear any temporary routes (drawn while mouse is down) from routes
list.
.. versionchanged:: 0.11.3
Clear temporary routes by setting ``df_routes`` property of
... | def function[on_canvas_slave__electrode_selected, parameter[self, slave, data]]:
constant[
.. versionchanged:: 0.11
Clear any temporary routes (drawn while mouse is down) from routes
list.
.. versionchanged:: 0.11.3
Clear temporary routes by setting ``df_rout... | keyword[def] identifier[on_canvas_slave__electrode_selected] ( identifier[self] , identifier[slave] , identifier[data] ):
literal[string]
keyword[if] identifier[self] . identifier[plugin] keyword[is] keyword[None] :
keyword[return]
... | def on_canvas_slave__electrode_selected(self, slave, data):
"""
.. versionchanged:: 0.11
Clear any temporary routes (drawn while mouse is down) from routes
list.
.. versionchanged:: 0.11.3
Clear temporary routes by setting ``df_routes`` property of
:a... |
def _array_2d_repr(self):
"""creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns
and provides a representation for the coefficients that makes
plotting easier"""
sc_array = np.zeros((self.nmax + 1, 2 * self.mmax + 1),
dtype=np.complex128)
... | def function[_array_2d_repr, parameter[self]]:
constant[creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns
and provides a representation for the coefficients that makes
plotting easier]
variable[sc_array] assign[=] call[name[np].zeros, parameter[tuple[[<ast.BinOp object at... | keyword[def] identifier[_array_2d_repr] ( identifier[self] ):
literal[string]
identifier[sc_array] = identifier[np] . identifier[zeros] (( identifier[self] . identifier[nmax] + literal[int] , literal[int] * identifier[self] . identifier[mmax] + literal[int] ),
identifier[dtype] = iden... | def _array_2d_repr(self):
"""creates a 2D array that has nmax + 1 rows and 2*mmax + 1 columns
and provides a representation for the coefficients that makes
plotting easier"""
sc_array = np.zeros((self.nmax + 1, 2 * self.mmax + 1), dtype=np.complex128)
lst = self._reshape_n_vecs()
sc_arr... |
def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
"""
return ctx.tag[
ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))] | def function[render_rootURL, parameter[self, ctx, data]]:
constant[
Add the WebSite's root URL as a child of the given tag.
]
return[call[name[ctx].tag][call[call[name[ixmantissa].ISiteURLGenerator, parameter[name[self].store]].rootURL, parameter[call[name[IRequest], parameter[name[ctx]]]]]]... | keyword[def] identifier[render_rootURL] ( identifier[self] , identifier[ctx] , identifier[data] ):
literal[string]
keyword[return] identifier[ctx] . identifier[tag] [
identifier[ixmantissa] . identifier[ISiteURLGenerator] ( identifier[self] . identifier[store] ). identifier[rootURL] ( ide... | def render_rootURL(self, ctx, data):
"""
Add the WebSite's root URL as a child of the given tag.
"""
return ctx.tag[ixmantissa.ISiteURLGenerator(self.store).rootURL(IRequest(ctx))] |
def parse(self, limit=None):
"""
:param limit:
:return:
"""
if limit is not None:
LOG.info("Only parsing first %s rows fo each file", str(limit))
LOG.info("Parsing files...")
if self.test_only:
self.test_mode = True
self._proces... | def function[parse, parameter[self, limit]]:
constant[
:param limit:
:return:
]
if compare[name[limit] is_not constant[None]] begin[:]
call[name[LOG].info, parameter[constant[Only parsing first %s rows fo each file], call[name[str], parameter[name[limit]]]]]
... | keyword[def] identifier[parse] ( identifier[self] , identifier[limit] = keyword[None] ):
literal[string]
keyword[if] identifier[limit] keyword[is] keyword[not] keyword[None] :
identifier[LOG] . identifier[info] ( literal[string] , identifier[str] ( identifier[limit] ))
id... | def parse(self, limit=None):
"""
:param limit:
:return:
"""
if limit is not None:
LOG.info('Only parsing first %s rows fo each file', str(limit)) # depends on [control=['if'], data=['limit']]
LOG.info('Parsing files...')
if self.test_only:
self.test_mode = True ... |
def set_volume(self, volume):
""" Allows to set volume. Should be value between 0..1.
Returns the new volume.
"""
volume = min(max(0, volume), 1)
self.logger.info("Receiver:setting volume to %.1f", volume)
self.send_message({MESSAGE_TYPE: 'SET_VOLUME',
... | def function[set_volume, parameter[self, volume]]:
constant[ Allows to set volume. Should be value between 0..1.
Returns the new volume.
]
variable[volume] assign[=] call[name[min], parameter[call[name[max], parameter[constant[0], name[volume]]], constant[1]]]
call[name[self].lo... | keyword[def] identifier[set_volume] ( identifier[self] , identifier[volume] ):
literal[string]
identifier[volume] = identifier[min] ( identifier[max] ( literal[int] , identifier[volume] ), literal[int] )
identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifie... | def set_volume(self, volume):
""" Allows to set volume. Should be value between 0..1.
Returns the new volume.
"""
volume = min(max(0, volume), 1)
self.logger.info('Receiver:setting volume to %.1f', volume)
self.send_message({MESSAGE_TYPE: 'SET_VOLUME', 'volume': {'level': volume}})
... |
def attach(self, gui):
"""Attach the view to the GUI."""
super(CorrelogramView, self).attach(gui)
self.actions.add(self.toggle_normalization, shortcut='n')
self.actions.separator()
self.actions.add(self.set_bin, alias='cb')
self.actions.add(self.set_window, alias='cw') | def function[attach, parameter[self, gui]]:
constant[Attach the view to the GUI.]
call[call[name[super], parameter[name[CorrelogramView], name[self]]].attach, parameter[name[gui]]]
call[name[self].actions.add, parameter[name[self].toggle_normalization]]
call[name[self].actions.separator,... | keyword[def] identifier[attach] ( identifier[self] , identifier[gui] ):
literal[string]
identifier[super] ( identifier[CorrelogramView] , identifier[self] ). identifier[attach] ( identifier[gui] )
identifier[self] . identifier[actions] . identifier[add] ( identifier[self] . identifier[togg... | def attach(self, gui):
"""Attach the view to the GUI."""
super(CorrelogramView, self).attach(gui)
self.actions.add(self.toggle_normalization, shortcut='n')
self.actions.separator()
self.actions.add(self.set_bin, alias='cb')
self.actions.add(self.set_window, alias='cw') |
def create_request(self, reset_wfs_iterator=False):
"""Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param reset_wfs_iterator: When re-running the method this flag is used to reset/... | def function[create_request, parameter[self, reset_wfs_iterator]]:
constant[Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param reset_wfs_iterator: When re-running the method this f... | keyword[def] identifier[create_request] ( identifier[self] , identifier[reset_wfs_iterator] = keyword[False] ):
literal[string]
keyword[if] identifier[reset_wfs_iterator] :
identifier[self] . identifier[wfs_iterator] = keyword[None]
identifier[ogc_service] = identifier[OgcI... | def create_request(self, reset_wfs_iterator=False):
"""Set download requests
Create a list of DownloadRequests for all Sentinel-2 acquisitions within request's time interval and
acceptable cloud coverage.
:param reset_wfs_iterator: When re-running the method this flag is used to reset/keep... |
def validate_aggregation(agg):
"""Validate an aggregation for use in Vega-Lite.
Translate agg to one of the following supported named aggregations:
['mean', 'sum', 'median', 'min', 'max', 'count']
Parameters
----------
agg : string or callable
A string
Supported reductions are ['m... | def function[validate_aggregation, parameter[agg]]:
constant[Validate an aggregation for use in Vega-Lite.
Translate agg to one of the following supported named aggregations:
['mean', 'sum', 'median', 'min', 'max', 'count']
Parameters
----------
agg : string or callable
A string
... | keyword[def] identifier[validate_aggregation] ( identifier[agg] ):
literal[string]
keyword[if] identifier[agg] keyword[is] keyword[None] :
keyword[return] identifier[agg]
identifier[supported_aggs] =[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string]... | def validate_aggregation(agg):
"""Validate an aggregation for use in Vega-Lite.
Translate agg to one of the following supported named aggregations:
['mean', 'sum', 'median', 'min', 'max', 'count']
Parameters
----------
agg : string or callable
A string
Supported reductions are ['m... |
def generate_hashes(peaks, fan_value: int = DEFAULT_FAN_VALUE):
"""
Hash list structure:
sha1_hash[0:20] time_offset
[(e05b341a9b77a51fd26, 32), ... ]
"""
if PEAK_SORT:
peaks = sorted(peaks, key=lambda x: x[1])
# peaks.sort(key=itemgetter(1))
for i in range(len(peaks))... | def function[generate_hashes, parameter[peaks, fan_value]]:
constant[
Hash list structure:
sha1_hash[0:20] time_offset
[(e05b341a9b77a51fd26, 32), ... ]
]
if name[PEAK_SORT] begin[:]
variable[peaks] assign[=] call[name[sorted], parameter[name[peaks]]]
for ta... | keyword[def] identifier[generate_hashes] ( identifier[peaks] , identifier[fan_value] : identifier[int] = identifier[DEFAULT_FAN_VALUE] ):
literal[string]
keyword[if] identifier[PEAK_SORT] :
identifier[peaks] = identifier[sorted] ( identifier[peaks] , identifier[key] = keyword[lambda] identifier[... | def generate_hashes(peaks, fan_value: int=DEFAULT_FAN_VALUE):
"""
Hash list structure:
sha1_hash[0:20] time_offset
[(e05b341a9b77a51fd26, 32), ... ]
"""
if PEAK_SORT:
peaks = sorted(peaks, key=lambda x: x[1]) # depends on [control=['if'], data=[]]
# peaks.sort(key=itemgetter(1... |
def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f"{short_time}:{second:02}" | def function[to_iso_time_string, parameter[self]]:
constant[ Return the iso time string only ]
variable[short_time] assign[=] call[name[self].to_short_time_string, parameter[]]
variable[second] assign[=] name[self].time.second
return[<ast.JoinedStr object at 0x7da1b27e3730>] | keyword[def] identifier[to_iso_time_string] ( identifier[self] )-> identifier[str] :
literal[string]
identifier[short_time] = identifier[self] . identifier[to_short_time_string] ()
identifier[second] = identifier[self] . identifier[time] . identifier[second]
keyword[return] lite... | def to_iso_time_string(self) -> str:
""" Return the iso time string only """
short_time = self.to_short_time_string()
second = self.time.second
return f'{short_time}:{second:02}' |
def to_unicode(sorb, allow_eval=False):
r"""Ensure that strings are unicode (UTF-8 encoded).
Evaluate bytes literals that are sometimes accidentally created by str(b'whatever')
>>> to_unicode(b'whatever')
'whatever'
>>> to_unicode(b'b"whatever"')
'whatever'
>>> to_unicode(repr(b'b"whatever... | def function[to_unicode, parameter[sorb, allow_eval]]:
constant[Ensure that strings are unicode (UTF-8 encoded).
Evaluate bytes literals that are sometimes accidentally created by str(b'whatever')
>>> to_unicode(b'whatever')
'whatever'
>>> to_unicode(b'b"whatever"')
'whatever'
>>> to_u... | keyword[def] identifier[to_unicode] ( identifier[sorb] , identifier[allow_eval] = keyword[False] ):
literal[string]
keyword[if] identifier[sorb] keyword[is] keyword[None] :
keyword[return] identifier[sorb]
keyword[if] identifier[isinstance] ( identifier[sorb] , identifier[bytes] ):
... | def to_unicode(sorb, allow_eval=False):
"""Ensure that strings are unicode (UTF-8 encoded).
Evaluate bytes literals that are sometimes accidentally created by str(b'whatever')
>>> to_unicode(b'whatever')
'whatever'
>>> to_unicode(b'b"whatever"')
'whatever'
>>> to_unicode(repr(b'b"whatever"... |
def get_string(self, recalculate_width=True):
"""Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wasn't set
e... | def function[get_string, parameter[self, recalculate_width]]:
constant[Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wa... | keyword[def] identifier[get_string] ( identifier[self] , identifier[recalculate_width] = keyword[True] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[_table] )== literal[int] :
keyword[return] literal[string]
keyword[if] identifier... | def get_string(self, recalculate_width=True):
"""Get the table as a String.
Parameters
----------
recalculate_width : bool, optional
If width for each column should be recalculated(default True).
Note that width is always calculated if it wasn't set
expli... |
def read_and_decode(filename, is_train=None):
"""Return tensor to read from TFRecord."""
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example, featur... | def function[read_and_decode, parameter[filename, is_train]]:
constant[Return tensor to read from TFRecord.]
variable[filename_queue] assign[=] call[name[tf].train.string_input_producer, parameter[list[[<ast.Name object at 0x7da18bc71ba0>]]]]
variable[reader] assign[=] call[name[tf].TFRecordRead... | keyword[def] identifier[read_and_decode] ( identifier[filename] , identifier[is_train] = keyword[None] ):
literal[string]
identifier[filename_queue] = identifier[tf] . identifier[train] . identifier[string_input_producer] ([ identifier[filename] ])
identifier[reader] = identifier[tf] . identifier[TFRe... | def read_and_decode(filename, is_train=None):
"""Return tensor to read from TFRecord."""
filename_queue = tf.train.string_input_producer([filename])
reader = tf.TFRecordReader()
(_, serialized_example) = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example, features={'la... |
def register_from_fields(self, *args):
"""
Register config name from field widgets
Arguments:
*args: Fields that contains widget
:class:`djangocodemirror.widget.CodeMirrorWidget`.
Returns:
list: List of registered config names from fields.
... | def function[register_from_fields, parameter[self]]:
constant[
Register config name from field widgets
Arguments:
*args: Fields that contains widget
:class:`djangocodemirror.widget.CodeMirrorWidget`.
Returns:
list: List of registered config names... | keyword[def] identifier[register_from_fields] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[names] =[]
keyword[for] identifier[field] keyword[in] identifier[args] :
identifier[widget] = identifier[self] . identifier[resolve_widget] ( identifier[field]... | def register_from_fields(self, *args):
"""
Register config name from field widgets
Arguments:
*args: Fields that contains widget
:class:`djangocodemirror.widget.CodeMirrorWidget`.
Returns:
list: List of registered config names from fields.
""... |
def attach(domain, filename):
'''
Attach existing datasets to their harvest remote id
Mapping between identifiers should be in FILENAME CSV file.
'''
log.info('Attaching datasets for domain %s', domain)
result = actions.attach(domain, filename)
log.info('Attached %s datasets to %s', result.... | def function[attach, parameter[domain, filename]]:
constant[
Attach existing datasets to their harvest remote id
Mapping between identifiers should be in FILENAME CSV file.
]
call[name[log].info, parameter[constant[Attaching datasets for domain %s], name[domain]]]
variable[result] a... | keyword[def] identifier[attach] ( identifier[domain] , identifier[filename] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] , identifier[domain] )
identifier[result] = identifier[actions] . identifier[attach] ( identifier[domain] , identifier[filename] )
identifier[log] . ... | def attach(domain, filename):
"""
Attach existing datasets to their harvest remote id
Mapping between identifiers should be in FILENAME CSV file.
"""
log.info('Attaching datasets for domain %s', domain)
result = actions.attach(domain, filename)
log.info('Attached %s datasets to %s', result.... |
def spawn_batch_jobs(job, shared_ids, input_args):
"""
Spawns an alignment job for every sample in the input configuration file
"""
samples = []
config = input_args['config']
with open(config, 'r') as f_in:
for line in f_in:
line = line.strip().split(',')
uuid = l... | def function[spawn_batch_jobs, parameter[job, shared_ids, input_args]]:
constant[
Spawns an alignment job for every sample in the input configuration file
]
variable[samples] assign[=] list[[]]
variable[config] assign[=] call[name[input_args]][constant[config]]
with call[name[ope... | keyword[def] identifier[spawn_batch_jobs] ( identifier[job] , identifier[shared_ids] , identifier[input_args] ):
literal[string]
identifier[samples] =[]
identifier[config] = identifier[input_args] [ literal[string] ]
keyword[with] identifier[open] ( identifier[config] , literal[string] ) keyword... | def spawn_batch_jobs(job, shared_ids, input_args):
"""
Spawns an alignment job for every sample in the input configuration file
"""
samples = []
config = input_args['config']
with open(config, 'r') as f_in:
for line in f_in:
line = line.strip().split(',')
uuid = l... |
def idle_task(self):
'''handle missing parameters'''
self.pstate.vehicle_name = self.vehicle_name
self.pstate.fetch_check(self.master) | def function[idle_task, parameter[self]]:
constant[handle missing parameters]
name[self].pstate.vehicle_name assign[=] name[self].vehicle_name
call[name[self].pstate.fetch_check, parameter[name[self].master]] | keyword[def] identifier[idle_task] ( identifier[self] ):
literal[string]
identifier[self] . identifier[pstate] . identifier[vehicle_name] = identifier[self] . identifier[vehicle_name]
identifier[self] . identifier[pstate] . identifier[fetch_check] ( identifier[self] . identifier[master] ) | def idle_task(self):
"""handle missing parameters"""
self.pstate.vehicle_name = self.vehicle_name
self.pstate.fetch_check(self.master) |
def STRUCT_DECL(self, cursor, num=None):
"""
Handles Structure declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Structure, num) | def function[STRUCT_DECL, parameter[self, cursor, num]]:
constant[
Handles Structure declaration.
Its a wrapper to _record_decl.
]
return[call[name[self]._record_decl, parameter[name[cursor], name[typedesc].Structure, name[num]]]] | keyword[def] identifier[STRUCT_DECL] ( identifier[self] , identifier[cursor] , identifier[num] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_record_decl] ( identifier[cursor] , identifier[typedesc] . identifier[Structure] , identifier[num] ) | def STRUCT_DECL(self, cursor, num=None):
"""
Handles Structure declaration.
Its a wrapper to _record_decl.
"""
return self._record_decl(cursor, typedesc.Structure, num) |
def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
"""
client = self.client
# We get an exception like this when ... | def function[_assemble_and_send_request, parameter[self]]:
constant[
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
]
variable[client] assign[=] name[self].clien... | keyword[def] identifier[_assemble_and_send_request] ( identifier[self] ):
literal[string]
identifier[client] = identifier[self] . identifier[client]
keyword[del] identifier[self] . identifier[ClientDetail] . identifier[IntegratorId]
ident... | def _assemble_and_send_request(self):
"""
Fires off the Fedex request.
@warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES
ON FedexBaseService AND IS INHERITED.
"""
client = self.client
# We get an exception like this when specifying an ... |
def evaluate(self, x):
r"""Evaluate the kernels at given frequencies.
Parameters
----------
x : array_like
Graph frequencies at which to evaluate the filter.
Returns
-------
y : ndarray
Frequency response of the filters. Shape ``(g.Nf, le... | def function[evaluate, parameter[self, x]]:
constant[Evaluate the kernels at given frequencies.
Parameters
----------
x : array_like
Graph frequencies at which to evaluate the filter.
Returns
-------
y : ndarray
Frequency response of the ... | keyword[def] identifier[evaluate] ( identifier[self] , identifier[x] ):
literal[string]
identifier[x] = identifier[np] . identifier[asanyarray] ( identifier[x] )
identifier[y] = identifier[np] . identifier[empty] ([ identifier[self] . identifier[Nf] ]+ identifier[list] ( identifie... | def evaluate(self, x):
"""Evaluate the kernels at given frequencies.
Parameters
----------
x : array_like
Graph frequencies at which to evaluate the filter.
Returns
-------
y : ndarray
Frequency response of the filters. Shape ``(g.Nf, len(x))... |
def filter_query(s):
"""
Filters given query with the below regex
and returns lists of quoted and unquoted strings
"""
matches = re.findall(r'(?:"([^"]*)")|([^"]*)', s)
result_quoted = [t[0].strip() for t in matches if t[0]]
result_unquoted = [t[1].strip() for t in matches if t[1]]
retur... | def function[filter_query, parameter[s]]:
constant[
Filters given query with the below regex
and returns lists of quoted and unquoted strings
]
variable[matches] assign[=] call[name[re].findall, parameter[constant[(?:"([^"]*)")|([^"]*)], name[s]]]
variable[result_quoted] assign[=] <a... | keyword[def] identifier[filter_query] ( identifier[s] ):
literal[string]
identifier[matches] = identifier[re] . identifier[findall] ( literal[string] , identifier[s] )
identifier[result_quoted] =[ identifier[t] [ literal[int] ]. identifier[strip] () keyword[for] identifier[t] keyword[in] identifier... | def filter_query(s):
"""
Filters given query with the below regex
and returns lists of quoted and unquoted strings
"""
matches = re.findall('(?:"([^"]*)")|([^"]*)', s)
result_quoted = [t[0].strip() for t in matches if t[0]]
result_unquoted = [t[1].strip() for t in matches if t[1]]
return... |
def _compute_missing_rates(self, currency):
"""Fill missing rates of a currency.
This is done by linear interpolation of the two closest available rates.
:param str currency: The currency to fill missing rates for.
"""
rates = self._rates[currency]
# tmp will store the... | def function[_compute_missing_rates, parameter[self, currency]]:
constant[Fill missing rates of a currency.
This is done by linear interpolation of the two closest available rates.
:param str currency: The currency to fill missing rates for.
]
variable[rates] assign[=] call[nam... | keyword[def] identifier[_compute_missing_rates] ( identifier[self] , identifier[currency] ):
literal[string]
identifier[rates] = identifier[self] . identifier[_rates] [ identifier[currency] ]
identifier[tmp] = identifier[defaultdict] ( keyword[lambda] :[ keyword[None] , keyword[N... | def _compute_missing_rates(self, currency):
"""Fill missing rates of a currency.
This is done by linear interpolation of the two closest available rates.
:param str currency: The currency to fill missing rates for.
"""
rates = self._rates[currency]
# tmp will store the closest rate... |
def _FormatTypeCheck(type_):
"""Pretty format of type check."""
if isinstance(type_, tuple):
items = [_FormatTypeCheck(t) for t in type_]
return "(%s)" % ", ".join(items)
elif hasattr(type_, "__name__"):
return type_.__name__
else:
return repr(type_) | def function[_FormatTypeCheck, parameter[type_]]:
constant[Pretty format of type check.]
if call[name[isinstance], parameter[name[type_], name[tuple]]] begin[:]
variable[items] assign[=] <ast.ListComp object at 0x7da18f00d000>
return[binary_operation[constant[(%s)] <ast.Mod objec... | keyword[def] identifier[_FormatTypeCheck] ( identifier[type_] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[type_] , identifier[tuple] ):
identifier[items] =[ identifier[_FormatTypeCheck] ( identifier[t] ) keyword[for] identifier[t] keyword[in] identifier[type_] ]
keyword[ret... | def _FormatTypeCheck(type_):
"""Pretty format of type check."""
if isinstance(type_, tuple):
items = [_FormatTypeCheck(t) for t in type_]
return '(%s)' % ', '.join(items) # depends on [control=['if'], data=[]]
elif hasattr(type_, '__name__'):
return type_.__name__ # depends on [con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.