code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only comments of current node
"""
super(NodeRelationViewMixin, self).initial(request, *args, **kwargs)
... | def function[initial, parameter[self, request]]:
constant[
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only comments of current node
]
call[call[name[super], parameter[name[NodeRelationViewMixin], n... | keyword[def] identifier[initial] ( identifier[self] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[super] ( identifier[NodeRelationViewMixin] , identifier[self] ). identifier[initial] ( identifier[request] ,* identifier[args] ,** identifier[kwargs] )
... | def initial(self, request, *args, **kwargs):
"""
Custom initial method:
* ensure node exists and store it in an instance attribute
* change queryset to return only comments of current node
"""
super(NodeRelationViewMixin, self).initial(request, *args, **kwargs)
self.n... |
def decode(in_bytes):
"""Decode a string using Consistent Overhead Byte Stuffing (COBS).
Input should be a byte string that has been COBS encoded. Output
is also a byte string.
A cobs.DecodeError exception will be raised if the encoded data
is invalid."""
out_bytes = []
idx = 0
... | def function[decode, parameter[in_bytes]]:
constant[Decode a string using Consistent Overhead Byte Stuffing (COBS).
Input should be a byte string that has been COBS encoded. Output
is also a byte string.
A cobs.DecodeError exception will be raised if the encoded data
is invalid.]
... | keyword[def] identifier[decode] ( identifier[in_bytes] ):
literal[string]
identifier[out_bytes] =[]
identifier[idx] = literal[int]
keyword[if] identifier[len] ( identifier[in_bytes] )> literal[int] :
keyword[while] keyword[True] :
identifier[length] = identifier[ord] ( i... | def decode(in_bytes):
"""Decode a string using Consistent Overhead Byte Stuffing (COBS).
Input should be a byte string that has been COBS encoded. Output
is also a byte string.
A cobs.DecodeError exception will be raised if the encoded data
is invalid."""
out_bytes = []
idx = 0
... |
def walk_dn(start_dir, depth=10):
'''
Walk down a directory tree. Same as os.walk but allows for a depth limit
via depth argument
'''
start_depth = len(os.path.split(start_dir))
end_depth = start_depth + depth
for root, subdirs, files in os.walk(start_dir):
yield root, subdirs, fil... | def function[walk_dn, parameter[start_dir, depth]]:
constant[
Walk down a directory tree. Same as os.walk but allows for a depth limit
via depth argument
]
variable[start_depth] assign[=] call[name[len], parameter[call[name[os].path.split, parameter[name[start_dir]]]]]
variable[end_d... | keyword[def] identifier[walk_dn] ( identifier[start_dir] , identifier[depth] = literal[int] ):
literal[string]
identifier[start_depth] = identifier[len] ( identifier[os] . identifier[path] . identifier[split] ( identifier[start_dir] ))
identifier[end_depth] = identifier[start_depth] + identifier[dept... | def walk_dn(start_dir, depth=10):
"""
Walk down a directory tree. Same as os.walk but allows for a depth limit
via depth argument
"""
start_depth = len(os.path.split(start_dir))
end_depth = start_depth + depth
for (root, subdirs, files) in os.walk(start_dir):
yield (root, subdirs, fi... |
def _validate_xor_args(self, p):
"""
Raises ValueError if 2 arguments are not passed to an XOR
"""
if len(p[1]) != 2:
raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p)) | def function[_validate_xor_args, parameter[self, p]]:
constant[
Raises ValueError if 2 arguments are not passed to an XOR
]
if compare[call[name[len], parameter[call[name[p]][constant[1]]]] not_equal[!=] constant[2]] begin[:]
<ast.Raise object at 0x7da1b246cc40> | keyword[def] identifier[_validate_xor_args] ( identifier[self] , identifier[p] ):
literal[string]
keyword[if] identifier[len] ( identifier[p] [ literal[int] ])!= literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[len] ( identifier... | def _validate_xor_args(self, p):
"""
Raises ValueError if 2 arguments are not passed to an XOR
"""
if len(p[1]) != 2:
raise ValueError('Invalid syntax: XOR only accepts 2 arguments, got {0}: {1}'.format(len(p[1]), p)) # depends on [control=['if'], data=[]] |
def process_literal_param(self, value: Optional[List[int]],
dialect: Dialect) -> str:
"""Convert things on the way from Python to the database."""
retval = self._intlist_to_dbstr(value)
return retval | def function[process_literal_param, parameter[self, value, dialect]]:
constant[Convert things on the way from Python to the database.]
variable[retval] assign[=] call[name[self]._intlist_to_dbstr, parameter[name[value]]]
return[name[retval]] | keyword[def] identifier[process_literal_param] ( identifier[self] , identifier[value] : identifier[Optional] [ identifier[List] [ identifier[int] ]],
identifier[dialect] : identifier[Dialect] )-> identifier[str] :
literal[string]
identifier[retval] = identifier[self] . identifier[_intlist_to_dbstr... | def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str:
"""Convert things on the way from Python to the database."""
retval = self._intlist_to_dbstr(value)
return retval |
def handleIncomingReply(self, observer_name, reqId, frm, result,
numReplies):
"""
Called by an external entity, like a Client, to notify of incoming
replies
:return:
"""
preparedReq = self._prepared.get((result[IDENTIFIER], reqId))
if n... | def function[handleIncomingReply, parameter[self, observer_name, reqId, frm, result, numReplies]]:
constant[
Called by an external entity, like a Client, to notify of incoming
replies
:return:
]
variable[preparedReq] assign[=] call[name[self]._prepared.get, parameter[tupl... | keyword[def] identifier[handleIncomingReply] ( identifier[self] , identifier[observer_name] , identifier[reqId] , identifier[frm] , identifier[result] ,
identifier[numReplies] ):
literal[string]
identifier[preparedReq] = identifier[self] . identifier[_prepared] . identifier[get] (( identifier[resu... | def handleIncomingReply(self, observer_name, reqId, frm, result, numReplies):
"""
Called by an external entity, like a Client, to notify of incoming
replies
:return:
"""
preparedReq = self._prepared.get((result[IDENTIFIER], reqId))
if not preparedReq:
raise RuntimeErr... |
def get_course_caches(self, usernames, course):
"""
:param username: List of username for which we want info. If usernames is None, data from all users will be returned.
:param course: A Course object
:return:
Returns data of the specified users for a specific course. users i... | def function[get_course_caches, parameter[self, usernames, course]]:
constant[
:param username: List of username for which we want info. If usernames is None, data from all users will be returned.
:param course: A Course object
:return:
Returns data of the specified users for... | keyword[def] identifier[get_course_caches] ( identifier[self] , identifier[usernames] , identifier[course] ):
literal[string]
identifier[match] ={ literal[string] : identifier[course] . identifier[get_id] ()}
keyword[if] identifier[usernames] keyword[is] keyword[not] keyword[None] :
... | def get_course_caches(self, usernames, course):
"""
:param username: List of username for which we want info. If usernames is None, data from all users will be returned.
:param course: A Course object
:return:
Returns data of the specified users for a specific course. users is a ... |
def _get_data(self, read_size):
"""Get data from the character device."""
if NIX:
return super(Keyboard, self)._get_data(read_size)
return self._pipe.recv_bytes() | def function[_get_data, parameter[self, read_size]]:
constant[Get data from the character device.]
if name[NIX] begin[:]
return[call[call[name[super], parameter[name[Keyboard], name[self]]]._get_data, parameter[name[read_size]]]]
return[call[name[self]._pipe.recv_bytes, parameter[]]] | keyword[def] identifier[_get_data] ( identifier[self] , identifier[read_size] ):
literal[string]
keyword[if] identifier[NIX] :
keyword[return] identifier[super] ( identifier[Keyboard] , identifier[self] ). identifier[_get_data] ( identifier[read_size] )
keyword[return] iden... | def _get_data(self, read_size):
"""Get data from the character device."""
if NIX:
return super(Keyboard, self)._get_data(read_size) # depends on [control=['if'], data=[]]
return self._pipe.recv_bytes() |
def set_goid2color_pval(self, goid2color):
"""Fill missing colors based on p-value of an enriched GO term."""
alpha2col = self.alpha2col
if self.pval_name is not None:
pval_name = self.pval_name
for goid, res in self.go2res.items():
pval = getattr(res, pva... | def function[set_goid2color_pval, parameter[self, goid2color]]:
constant[Fill missing colors based on p-value of an enriched GO term.]
variable[alpha2col] assign[=] name[self].alpha2col
if compare[name[self].pval_name is_not constant[None]] begin[:]
variable[pval_name] assign[=] ... | keyword[def] identifier[set_goid2color_pval] ( identifier[self] , identifier[goid2color] ):
literal[string]
identifier[alpha2col] = identifier[self] . identifier[alpha2col]
keyword[if] identifier[self] . identifier[pval_name] keyword[is] keyword[not] keyword[None] :
ident... | def set_goid2color_pval(self, goid2color):
"""Fill missing colors based on p-value of an enriched GO term."""
alpha2col = self.alpha2col
if self.pval_name is not None:
pval_name = self.pval_name
for (goid, res) in self.go2res.items():
pval = getattr(res, pval_name, None)
... |
def parse_type(parser):
# type: (Parser) -> Union[NamedType, NonNullType, ListType]
"""Handles the 'Type': TypeName, ListType, and NonNullType
parsing rules."""
start = parser.token.start
if skip(parser, TokenKind.BRACKET_L):
ast_type = parse_type(parser)
expect(parser, TokenKind.BRA... | def function[parse_type, parameter[parser]]:
constant[Handles the 'Type': TypeName, ListType, and NonNullType
parsing rules.]
variable[start] assign[=] name[parser].token.start
if call[name[skip], parameter[name[parser], name[TokenKind].BRACKET_L]] begin[:]
variable[ast_type]... | keyword[def] identifier[parse_type] ( identifier[parser] ):
literal[string]
identifier[start] = identifier[parser] . identifier[token] . identifier[start]
keyword[if] identifier[skip] ( identifier[parser] , identifier[TokenKind] . identifier[BRACKET_L] ):
identifier[ast_type] = identifier[... | def parse_type(parser):
# type: (Parser) -> Union[NamedType, NonNullType, ListType]
"Handles the 'Type': TypeName, ListType, and NonNullType\n parsing rules."
start = parser.token.start
if skip(parser, TokenKind.BRACKET_L):
ast_type = parse_type(parser)
expect(parser, TokenKind.BRACKE... |
def create(conversion_finder, parsed_att: Any, attribute_type: Type[Any], errors: Dict[Type, Exception] = None):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_at... | def function[create, parameter[conversion_finder, parsed_att, attribute_type, errors]]:
constant[
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_att:
:param a... | keyword[def] identifier[create] ( identifier[conversion_finder] , identifier[parsed_att] : identifier[Any] , identifier[attribute_type] : identifier[Type] [ identifier[Any] ], identifier[errors] : identifier[Dict] [ identifier[Type] , identifier[Exception] ]= keyword[None] ):
literal[string]
keywor... | def create(conversion_finder, parsed_att: Any, attribute_type: Type[Any], errors: Dict[Type, Exception]=None):
"""
Helper method provided because we actually can't put that in the constructor, it creates a bug in Nose tests
https://github.com/nose-devs/nose/issues/725
:param parsed_att:
... |
def parse_stats_file(self, file_name):
""" Read and parse given file_name, return config as a dictionary """
stats = {}
try:
with open(file_name, "r") as fhandle:
fbuffer = []
save_buffer = False
for line in fhandle:
... | def function[parse_stats_file, parameter[self, file_name]]:
constant[ Read and parse given file_name, return config as a dictionary ]
variable[stats] assign[=] dictionary[[], []]
<ast.Try object at 0x7da18fe93460>
return[name[stats]] | keyword[def] identifier[parse_stats_file] ( identifier[self] , identifier[file_name] ):
literal[string]
identifier[stats] ={}
keyword[try] :
keyword[with] identifier[open] ( identifier[file_name] , literal[string] ) keyword[as] identifier[fhandle] :
identifi... | def parse_stats_file(self, file_name):
""" Read and parse given file_name, return config as a dictionary """
stats = {}
try:
with open(file_name, 'r') as fhandle:
fbuffer = []
save_buffer = False
for line in fhandle:
line = line.rstrip('\n')
... |
def WriteSignedBinaryReferences(self,
binary_id,
references,
cursor=None):
"""Writes blob references for a signed binary to the DB."""
args = {
"binary_type":
binary_id.binary_type.Serialize... | def function[WriteSignedBinaryReferences, parameter[self, binary_id, references, cursor]]:
constant[Writes blob references for a signed binary to the DB.]
variable[args] assign[=] dictionary[[<ast.Constant object at 0x7da18bcc9db0>, <ast.Constant object at 0x7da18bcca290>, <ast.Constant object at 0x7da1... | keyword[def] identifier[WriteSignedBinaryReferences] ( identifier[self] ,
identifier[binary_id] ,
identifier[references] ,
identifier[cursor] = keyword[None] ):
literal[string]
identifier[args] ={
literal[string] :
identifier[binary_id] . identifier[binary_type] . identifier[SerializeToDataSto... | def WriteSignedBinaryReferences(self, binary_id, references, cursor=None):
"""Writes blob references for a signed binary to the DB."""
args = {'binary_type': binary_id.binary_type.SerializeToDataStore(), 'binary_path': binary_id.path, 'binary_path_hash': mysql_utils.Hash(binary_id.path), 'blob_references': refe... |
def create_environment(self, env_name, version_label=None,
solution_stack_name=None, cname_prefix=None, description=None,
option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
"""
Creates a new environment
""... | def function[create_environment, parameter[self, env_name, version_label, solution_stack_name, cname_prefix, description, option_settings, tier_name, tier_type, tier_version]]:
constant[
Creates a new environment
]
call[name[out], parameter[binary_operation[binary_operation[binary_operat... | keyword[def] identifier[create_environment] ( identifier[self] , identifier[env_name] , identifier[version_label] = keyword[None] ,
identifier[solution_stack_name] = keyword[None] , identifier[cname_prefix] = keyword[None] , identifier[description] = keyword[None] ,
identifier[option_settings] = keyword[None] , ide... | def create_environment(self, env_name, version_label=None, solution_stack_name=None, cname_prefix=None, description=None, option_settings=None, tier_name='WebServer', tier_type='Standard', tier_version='1.1'):
"""
Creates a new environment
"""
out('Creating environment: ' + str(env_name) + ', ti... |
def validateOneAttribute(self, ctxt, elem, attr, value):
"""Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default ] - [ VC: Entity Name ] - ... | def function[validateOneAttribute, parameter[self, ctxt, elem, attr, value]]:
constant[Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default... | keyword[def] identifier[validateOneAttribute] ( identifier[self] , identifier[ctxt] , identifier[elem] , identifier[attr] , identifier[value] ):
literal[string]
keyword[if] identifier[ctxt] keyword[is] keyword[None] : identifier[ctxt__o] = keyword[None]
keyword[else] : identifier[ctxt_... | def validateOneAttribute(self, ctxt, elem, attr, value):
"""Try to validate a single attribute for an element basically
it does the following checks as described by the XML-1.0
recommendation: - [ VC: Attribute Value Type ] - [ VC:
Fixed Attribute Default ] - [ VC: Entity Name ] - [ VC... |
def tabulate_state_transitions(x, states, pos=None):
"""Construct a dataframe where each row provides information about a state transition.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in t... | def function[tabulate_state_transitions, parameter[x, states, pos]]:
constant[Construct a dataframe where each row provides information about a state transition.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest... | keyword[def] identifier[tabulate_state_transitions] ( identifier[x] , identifier[states] , identifier[pos] = keyword[None] ):
literal[string]
identifier[x] = identifier[asarray_ndim] ( identifier[x] , literal[int] )
identifier[check_integer_dtype] ( identifier[x] )
identifier[x] = identifie... | def tabulate_state_transitions(x, states, pos=None):
"""Construct a dataframe where each row provides information about a state transition.
Parameters
----------
x : array_like, int
1-dimensional array of state values.
states : set
Set of states of interest. Any state value not in t... |
def is_injective(self):
'''Returns True if the mapping is injective (1-to-1).'''
codomain_residues = [v.to_pdb_residue_id for k, v in self.mapping.iteritems()]
return(len(codomain_residues) == len(set(codomain_residues))) | def function[is_injective, parameter[self]]:
constant[Returns True if the mapping is injective (1-to-1).]
variable[codomain_residues] assign[=] <ast.ListComp object at 0x7da1b2298100>
return[compare[call[name[len], parameter[name[codomain_residues]]] equal[==] call[name[len], parameter[call[name[set... | keyword[def] identifier[is_injective] ( identifier[self] ):
literal[string]
identifier[codomain_residues] =[ identifier[v] . identifier[to_pdb_residue_id] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[self] . identifier[mapping] . identifier[iteritems] ()]
keyword[r... | def is_injective(self):
"""Returns True if the mapping is injective (1-to-1)."""
codomain_residues = [v.to_pdb_residue_id for (k, v) in self.mapping.iteritems()]
return len(codomain_residues) == len(set(codomain_residues)) |
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
for key in JOYENT_L... | def function[avail_locations, parameter[call]]:
constant[
List all available locations
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da1b1f76a10>
variable[ret] assign[=] dictionary[[], []]
for taget[name[key]] in starred[name[JOYENT_... | keyword[def] identifier[avail_locations] ( identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
identifier[ret] ={}
keyword[f... | def avail_locations(call=None):
"""
List all available locations
"""
if call == 'action':
raise SaltCloudSystemExit('The avail_locations function must be called with -f or --function, or with the --list-locations option') # depends on [control=['if'], data=[]]
ret = {}
for key in JOYENT... |
def register_ipcluster(data):
"""
The name is a unique id that keeps this __init__ of ipyrad distinct
from interfering with other ipcontrollers. Run statements are wrapped
so that ipcluster will be killed on exit.
"""
## check if this pid already has a running cluster
data._ipcluster["cluste... | def function[register_ipcluster, parameter[data]]:
constant[
The name is a unique id that keeps this __init__ of ipyrad distinct
from interfering with other ipcontrollers. Run statements are wrapped
so that ipcluster will be killed on exit.
]
call[name[data]._ipcluster][constant[cluster_... | keyword[def] identifier[register_ipcluster] ( identifier[data] ):
literal[string]
identifier[data] . identifier[_ipcluster] [ literal[string] ]= literal[string] + identifier[str] ( identifier[os] . identifier[getpid] ())
identifier[start_ipcluster] ( identifier[data] )
keyword[return] ident... | def register_ipcluster(data):
"""
The name is a unique id that keeps this __init__ of ipyrad distinct
from interfering with other ipcontrollers. Run statements are wrapped
so that ipcluster will be killed on exit.
"""
## check if this pid already has a running cluster
data._ipcluster['cluste... |
def regularDTW(distMat, norm=True):
"""Use a local distance matrix to perform dynamic time warping.
Parameters
----------
distMat : 2D array
Local distance matrix.
Returns
-------
float
Total unweighted distance of the optimal path through the
local distance matrix.... | def function[regularDTW, parameter[distMat, norm]]:
constant[Use a local distance matrix to perform dynamic time warping.
Parameters
----------
distMat : 2D array
Local distance matrix.
Returns
-------
float
Total unweighted distance of the optimal path through the
... | keyword[def] identifier[regularDTW] ( identifier[distMat] , identifier[norm] = keyword[True] ):
literal[string]
identifier[sLen] , identifier[tLen] = identifier[distMat] . identifier[shape]
identifier[totalDistance] = identifier[zeros] (( identifier[sLen] , identifier[tLen] ))
identifier[totalDi... | def regularDTW(distMat, norm=True):
"""Use a local distance matrix to perform dynamic time warping.
Parameters
----------
distMat : 2D array
Local distance matrix.
Returns
-------
float
Total unweighted distance of the optimal path through the
local distance matrix.... |
def move_leadership(self, partition, new_leader):
"""Return a new state that is the result of changing the leadership of
a single partition.
:param partition: The partition index of the partition to change the
leadership of.
:param new_leader: The broker index of the new lea... | def function[move_leadership, parameter[self, partition, new_leader]]:
constant[Return a new state that is the result of changing the leadership of
a single partition.
:param partition: The partition index of the partition to change the
leadership of.
:param new_leader: The ... | keyword[def] identifier[move_leadership] ( identifier[self] , identifier[partition] , identifier[new_leader] ):
literal[string]
identifier[new_state] = identifier[copy] ( identifier[self] )
identifier[source] = identifier[new_state] . identifier[replicas] [ identifier[partition] ... | def move_leadership(self, partition, new_leader):
"""Return a new state that is the result of changing the leadership of
a single partition.
:param partition: The partition index of the partition to change the
leadership of.
:param new_leader: The broker index of the new leader ... |
def submit_safe_jobs(root_dir, jobs, sgeargs=None):
"""Submit the passed list of jobs to the Grid Engine server, using the
passed directory as the root for scheduler output.
- root_dir Path to output directory
- jobs Iterable of Job objects
"""
# Loop over each job, constructing S... | def function[submit_safe_jobs, parameter[root_dir, jobs, sgeargs]]:
constant[Submit the passed list of jobs to the Grid Engine server, using the
passed directory as the root for scheduler output.
- root_dir Path to output directory
- jobs Iterable of Job objects
]
for tage... | keyword[def] identifier[submit_safe_jobs] ( identifier[root_dir] , identifier[jobs] , identifier[sgeargs] = keyword[None] ):
literal[string]
keyword[for] identifier[job] keyword[in] identifier[jobs] :
identifier[job] . identifier[out] = identifier[os] . identifier[path] . identifier[join] ... | def submit_safe_jobs(root_dir, jobs, sgeargs=None):
"""Submit the passed list of jobs to the Grid Engine server, using the
passed directory as the root for scheduler output.
- root_dir Path to output directory
- jobs Iterable of Job objects
"""
# Loop over each job, constructing S... |
def calcTransitDuration(self, circular=False):
""" Estimation of the primary transit time assuming a circular orbit (see :py:func:`equations.transitDuration`)
"""
try:
if circular:
return eq.transitDurationCircular(self.P, self.star.R, self.R, self.a, self.i)
... | def function[calcTransitDuration, parameter[self, circular]]:
constant[ Estimation of the primary transit time assuming a circular orbit (see :py:func:`equations.transitDuration`)
]
<ast.Try object at 0x7da18bc70310> | keyword[def] identifier[calcTransitDuration] ( identifier[self] , identifier[circular] = keyword[False] ):
literal[string]
keyword[try] :
keyword[if] identifier[circular] :
keyword[return] identifier[eq] . identifier[transitDurationCircular] ( identifier[self] . ide... | def calcTransitDuration(self, circular=False):
""" Estimation of the primary transit time assuming a circular orbit (see :py:func:`equations.transitDuration`)
"""
try:
if circular:
return eq.transitDurationCircular(self.P, self.star.R, self.R, self.a, self.i) # depends on [control=[... |
def _aggregrate_scores(its,tss,num_sentences):
"""rerank the two vectors by
min aggregrate rank, reorder"""
final = []
for i,el in enumerate(its):
for j, le in enumerate(tss):
if el[2] == le[2]:
assert el[1] == le[1]
final.append((el[1],i+j,el[2]))
... | def function[_aggregrate_scores, parameter[its, tss, num_sentences]]:
constant[rerank the two vectors by
min aggregrate rank, reorder]
variable[final] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da2045652d0>, <ast.Name object at 0x7da2045642e0>]]] in starred[call[name[enumerat... | keyword[def] identifier[_aggregrate_scores] ( identifier[its] , identifier[tss] , identifier[num_sentences] ):
literal[string]
identifier[final] =[]
keyword[for] identifier[i] , identifier[el] keyword[in] identifier[enumerate] ( identifier[its] ):
keyword[for] identifier[j] , identifier[l... | def _aggregrate_scores(its, tss, num_sentences):
"""rerank the two vectors by
min aggregrate rank, reorder"""
final = []
for (i, el) in enumerate(its):
for (j, le) in enumerate(tss):
if el[2] == le[2]:
assert el[1] == le[1]
final.append((el[1], i + j, ... |
def print_prediction (self, ptup, precision=2):
"""Print a summary of a predicted position.
The argument *ptup* is a tuple returned by :meth:`predict`. It is
printed to :data:`sys.stdout` in a reasonable format that uses Unicode
characters.
"""
from . import ellipses
... | def function[print_prediction, parameter[self, ptup, precision]]:
constant[Print a summary of a predicted position.
The argument *ptup* is a tuple returned by :meth:`predict`. It is
printed to :data:`sys.stdout` in a reasonable format that uses Unicode
characters.
]
from re... | keyword[def] identifier[print_prediction] ( identifier[self] , identifier[ptup] , identifier[precision] = literal[int] ):
literal[string]
keyword[from] . keyword[import] identifier[ellipses]
identifier[bestra] , identifier[bestdec] , identifier[maj] , identifier[min] , identifier[pa] = i... | def print_prediction(self, ptup, precision=2):
"""Print a summary of a predicted position.
The argument *ptup* is a tuple returned by :meth:`predict`. It is
printed to :data:`sys.stdout` in a reasonable format that uses Unicode
characters.
"""
from . import ellipses
(bestra... |
def show_value(self, value):
"""
Get a specific canned value
:type value: str
:param value: Canned value to show
:rtype: dict
:return: A dictionnary containing canned value description
"""
values = self.get_values()
values = [x for x in values if... | def function[show_value, parameter[self, value]]:
constant[
Get a specific canned value
:type value: str
:param value: Canned value to show
:rtype: dict
:return: A dictionnary containing canned value description
]
variable[values] assign[=] call[name[sel... | keyword[def] identifier[show_value] ( identifier[self] , identifier[value] ):
literal[string]
identifier[values] = identifier[self] . identifier[get_values] ()
identifier[values] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[values] keyword[if] identifier[x] [ li... | def show_value(self, value):
"""
Get a specific canned value
:type value: str
:param value: Canned value to show
:rtype: dict
:return: A dictionnary containing canned value description
"""
values = self.get_values()
values = [x for x in values if x['label'] ... |
def your_tips_on_homepage(context):
"""
A template tag for the Tip of the Day on the homepage.
Note that:
* If there is an active featured_in_homepage tip it will take precedence.
* If there is no featured tip a popular tip will be displayed.
* If there is no featured tip and no popular tip,
... | def function[your_tips_on_homepage, parameter[context]]:
constant[
A template tag for the Tip of the Day on the homepage.
Note that:
* If there is an active featured_in_homepage tip it will take precedence.
* If there is no featured tip a popular tip will be displayed.
* If there is no featu... | keyword[def] identifier[your_tips_on_homepage] ( identifier[context] ):
literal[string]
identifier[context] = identifier[copy] ( identifier[context] )
identifier[site_main] = identifier[context] [ literal[string] ]. identifier[site] . identifier[root_page]
keyword[if] identifier[get_your_tip] (... | def your_tips_on_homepage(context):
"""
A template tag for the Tip of the Day on the homepage.
Note that:
* If there is an active featured_in_homepage tip it will take precedence.
* If there is no featured tip a popular tip will be displayed.
* If there is no featured tip and no popular tip,
... |
def configure(cls, impl, **kwargs):
# type: (Any, **Any) -> None
"""Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed
to the constructor. This can be used to set global defaults for
some parameters.
... | def function[configure, parameter[cls, impl]]:
constant[Sets the class to use when the base class is instantiated.
Keyword arguments will be saved and added to the arguments passed
to the constructor. This can be used to set global defaults for
some parameters.
]
variab... | keyword[def] identifier[configure] ( identifier[cls] , identifier[impl] ,** identifier[kwargs] ):
literal[string]
identifier[base] = identifier[cls] . identifier[configurable_base] ()
keyword[if] identifier[isinstance] ( identifier[impl] ,( identifier[str] , identifier[unicode_type] )):
... | def configure(cls, impl, **kwargs):
# type: (Any, **Any) -> None
'Sets the class to use when the base class is instantiated.\n\n Keyword arguments will be saved and added to the arguments passed\n to the constructor. This can be used to set global defaults for\n some parameters.\n '... |
def get_account_authToken(self, account=None, account_name=''):
""" Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
"""
if account is ... | def function[get_account_authToken, parameter[self, account, account_name]]:
constant[ Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
]
... | keyword[def] identifier[get_account_authToken] ( identifier[self] , identifier[account] = keyword[None] , identifier[account_name] = literal[string] ):
literal[string]
keyword[if] identifier[account] keyword[is] keyword[None] :
identifier[account] = identifier[self] . identifier[get... | def get_account_authToken(self, account=None, account_name=''):
""" Use the DelegateAuthRequest to provide a token and his lifetime
for the provided account.
If account is provided we use it,
else we retreive the account from the provided account_name.
"""
if account is None:
... |
def var(expr, **kw):
"""
Variance
:param expr:
:param ddof: degree of freedom
:param kw:
:return:
"""
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Var, output_type, _ddof=ddof) | def function[var, parameter[expr]]:
constant[
Variance
:param expr:
:param ddof: degree of freedom
:param kw:
:return:
]
variable[ddof] assign[=] call[name[kw].get, parameter[constant[ddof], call[name[kw].get, parameter[constant[_ddof], constant[1]]]]]
variable[output_ty... | keyword[def] identifier[var] ( identifier[expr] ,** identifier[kw] ):
literal[string]
identifier[ddof] = identifier[kw] . identifier[get] ( literal[string] , identifier[kw] . identifier[get] ( literal[string] , literal[int] ))
identifier[output_type] = identifier[_stats_type] ( identifier[expr] )
... | def var(expr, **kw):
"""
Variance
:param expr:
:param ddof: degree of freedom
:param kw:
:return:
"""
ddof = kw.get('ddof', kw.get('_ddof', 1))
output_type = _stats_type(expr)
return _reduction(expr, Var, output_type, _ddof=ddof) |
def add_component_definition(self, definition):
"""
Add a ComponentDefinition to the document
"""
# definition.identity = self._to_uri_from_namespace(definition.identity)
if definition.identity not in self._components.keys():
self._components[definition.identity] = de... | def function[add_component_definition, parameter[self, definition]]:
constant[
Add a ComponentDefinition to the document
]
if compare[name[definition].identity <ast.NotIn object at 0x7da2590d7190> call[name[self]._components.keys, parameter[]]] begin[:]
call[name[self]._c... | keyword[def] identifier[add_component_definition] ( identifier[self] , identifier[definition] ):
literal[string]
keyword[if] identifier[definition] . identifier[identity] keyword[not] keyword[in] identifier[self] . identifier[_components] . identifier[keys] ():
identifier[... | def add_component_definition(self, definition):
"""
Add a ComponentDefinition to the document
"""
# definition.identity = self._to_uri_from_namespace(definition.identity)
if definition.identity not in self._components.keys():
self._components[definition.identity] = definition # depe... |
def parse_characters(self, character_page):
"""Parses the DOM and returns anime character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL anime character page's DOM
:rtype: dict
:return: anime character attributes
:raises: :class:`.Invali... | def function[parse_characters, parameter[self, character_page]]:
constant[Parses the DOM and returns anime character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL anime character page's DOM
:rtype: dict
:return: anime character attribute... | keyword[def] identifier[parse_characters] ( identifier[self] , identifier[character_page] ):
literal[string]
identifier[anime_info] = identifier[self] . identifier[parse_sidebar] ( identifier[character_page] )
keyword[try] :
identifier[character_title] = identifier[filter] ( keyword[lambda] i... | def parse_characters(self, character_page):
"""Parses the DOM and returns anime character attributes in the sidebar.
:type character_page: :class:`bs4.BeautifulSoup`
:param character_page: MAL anime character page's DOM
:rtype: dict
:return: anime character attributes
:raises: :class:`.Invali... |
def sun_rise_set_transit_geometric(times, latitude, longitude, declination,
equation_of_time):
"""
Geometric calculation of solar sunrise, sunset, and transit.
.. warning:: The geometric calculation assumes a circular earth orbit with
the sun as a point source at ... | def function[sun_rise_set_transit_geometric, parameter[times, latitude, longitude, declination, equation_of_time]]:
constant[
Geometric calculation of solar sunrise, sunset, and transit.
.. warning:: The geometric calculation assumes a circular earth orbit with
the sun as a point source at its ... | keyword[def] identifier[sun_rise_set_transit_geometric] ( identifier[times] , identifier[latitude] , identifier[longitude] , identifier[declination] ,
identifier[equation_of_time] ):
literal[string]
identifier[latitude_rad] = identifier[np] . identifier[radians] ( identifier[latitude] )
identifier[su... | def sun_rise_set_transit_geometric(times, latitude, longitude, declination, equation_of_time):
"""
Geometric calculation of solar sunrise, sunset, and transit.
.. warning:: The geometric calculation assumes a circular earth orbit with
the sun as a point source at its center, and neglects the effect... |
def add_database_args(parser):
'''
Add a standard set of database arguments for argparse
'''
parser.add_argument(
'url',
nargs='?',
default='sqlite:///ncbi_taxonomy.db',
type=sqlite_default(),
help=('Database string URI or filename. If no database scheme '
... | def function[add_database_args, parameter[parser]]:
constant[
Add a standard set of database arguments for argparse
]
call[name[parser].add_argument, parameter[constant[url]]]
variable[db_parser] assign[=] call[name[parser].add_argument_group, parameter[]]
call[name[db_parser].ad... | keyword[def] identifier[add_database_args] ( identifier[parser] ):
literal[string]
identifier[parser] . identifier[add_argument] (
literal[string] ,
identifier[nargs] = literal[string] ,
identifier[default] = literal[string] ,
identifier[type] = identifier[sqlite_default] (),
ident... | def add_database_args(parser):
"""
Add a standard set of database arguments for argparse
"""
parser.add_argument('url', nargs='?', default='sqlite:///ncbi_taxonomy.db', type=sqlite_default(), help='Database string URI or filename. If no database scheme specified "sqlite:///" will be prepended. [%(defau... |
def forward_word_end_extend_selection(self, e): #
u"""Move forward to the end of the next word. Words are composed of
letters and digits."""
self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
self.finalize() | def function[forward_word_end_extend_selection, parameter[self, e]]:
constant[Move forward to the end of the next word. Words are composed of
letters and digits.]
call[name[self].l_buffer.forward_word_end_extend_selection, parameter[name[self].argument_reset]]
call[name[self].finalize, p... | keyword[def] identifier[forward_word_end_extend_selection] ( identifier[self] , identifier[e] ):
literal[string]
identifier[self] . identifier[l_buffer] . identifier[forward_word_end_extend_selection] ( identifier[self] . identifier[argument_reset] )
identifier[self] . identifier[finali... | def forward_word_end_extend_selection(self, e): #
u'Move forward to the end of the next word. Words are composed of\n letters and digits.'
self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
self.finalize() |
def set_observatory(self,obs):
"""
Set the IFO to retrieve data for. Since the data from both Hanford
interferometers is stored in the same frame file, this takes the first
letter of the IFO (e.g. L or H) and passes it to the --observatory option
of LSCdataFind.
@param obs: IFO to obtain data fo... | def function[set_observatory, parameter[self, obs]]:
constant[
Set the IFO to retrieve data for. Since the data from both Hanford
interferometers is stored in the same frame file, this takes the first
letter of the IFO (e.g. L or H) and passes it to the --observatory option
of LSCdataFind.
@... | keyword[def] identifier[set_observatory] ( identifier[self] , identifier[obs] ):
literal[string]
identifier[self] . identifier[add_var_opt] ( literal[string] , identifier[obs] )
identifier[self] . identifier[__observatory] = identifier[str] ( identifier[obs] )
identifier[self] . identifier[__set_... | def set_observatory(self, obs):
"""
Set the IFO to retrieve data for. Since the data from both Hanford
interferometers is stored in the same frame file, this takes the first
letter of the IFO (e.g. L or H) and passes it to the --observatory option
of LSCdataFind.
@param obs: IFO to obtain data f... |
def from_master_secret(cls, seed, network="bitcoin_testnet"):
"""Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advi... | def function[from_master_secret, parameter[cls, seed, network]]:
constant[Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure... | keyword[def] identifier[from_master_secret] ( identifier[cls] , identifier[seed] , identifier[network] = literal[string] ):
literal[string]
identifier[network] = identifier[Wallet] . identifier[get_network] ( identifier[network] )
identifier[seed] = identifier[ensure_bytes] ( identifier[se... | def from_master_secret(cls, seed, network='bitcoin_testnet'):
"""Generate a new PrivateKey from a secret key.
:param seed: The key to use to generate this wallet. It may be a long
string. Do not use a phrase from a book or song, as that will
be guessed and is not secure. My advice i... |
def activate():
"""Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
h... | def function[activate, parameter[]]:
constant[Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation... | keyword[def] identifier[activate] ():
literal[string]
identifier[parent] = identifier[lib] . identifier[parent] ()
keyword[try] :
identifier[cmd] = identifier[lib] . identifier[cmd] ( identifier[parent] )
keyword[except] identifier[SystemError] keyword[as] identifier[exc] :
... | def activate():
"""Enter into an environment with support for tab-completion
This command drops you into a subshell, similar to the one
generated via `be in ...`, except no topic is present and
instead it enables tab-completion for supported shells.
See documentation for further information.
h... |
def define_simulation_graph(batch_env, algo_cls, config):
"""Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via a... | def function[define_simulation_graph, parameter[batch_env, algo_cls, config]]:
constant[Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Obje... | keyword[def] identifier[define_simulation_graph] ( identifier[batch_env] , identifier[algo_cls] , identifier[config] ):
literal[string]
identifier[step] = identifier[tf] . identifier[Variable] ( literal[int] , keyword[False] , identifier[dtype] = identifier[tf] . identifier[int32] , identifier[name] = liter... | def define_simulation_graph(batch_env, algo_cls, config):
"""Define the algorithm and environment interaction.
Args:
batch_env: In-graph environments object.
algo_cls: Constructor of a batch algorithm.
config: Configuration object for the algorithm.
Returns:
Object providing graph elements via... |
def get_models(self, columns=None):
"""
Get the hydrated models without eager loading.
:param columns: The columns to get
:type columns: list
:return: A list of models
:rtype: orator.orm.collection.Collection
"""
results = self.apply_scopes().get_query()... | def function[get_models, parameter[self, columns]]:
constant[
Get the hydrated models without eager loading.
:param columns: The columns to get
:type columns: list
:return: A list of models
:rtype: orator.orm.collection.Collection
]
variable[results] ass... | keyword[def] identifier[get_models] ( identifier[self] , identifier[columns] = keyword[None] ):
literal[string]
identifier[results] = identifier[self] . identifier[apply_scopes] (). identifier[get_query] (). identifier[get] ( identifier[columns] ). identifier[all] ()
identifier[connection... | def get_models(self, columns=None):
"""
Get the hydrated models without eager loading.
:param columns: The columns to get
:type columns: list
:return: A list of models
:rtype: orator.orm.collection.Collection
"""
results = self.apply_scopes().get_query().get(col... |
def merge(self, other):
"""Merge other (dict or OrderedSet) into this environment.
Only works for basic types: str, list, tuple, dict and OrderedSet.
"""
for key, value in other.items():
if not key in self:
self[key] = value
elif isinstance(value,... | def function[merge, parameter[self, other]]:
constant[Merge other (dict or OrderedSet) into this environment.
Only works for basic types: str, list, tuple, dict and OrderedSet.
]
for taget[tuple[[<ast.Name object at 0x7da1b14e54e0>, <ast.Name object at 0x7da1b14e4dc0>]]] in starred[call... | keyword[def] identifier[merge] ( identifier[self] , identifier[other] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[other] . identifier[items] ():
keyword[if] keyword[not] identifier[key] keyword[in] identifier[self] :
... | def merge(self, other):
"""Merge other (dict or OrderedSet) into this environment.
Only works for basic types: str, list, tuple, dict and OrderedSet.
"""
for (key, value) in other.items():
if not key in self:
self[key] = value # depends on [control=['if'], data=[]]
... |
def _fail_if_contains_errors(response, sync_uuid=None):
"""Raise a RequestError Exception if a given response
does not denote a successful request.
"""
if response.status_code != _HTTP_OK:
raise RequestError(response)
response_json = response.json()
if sync_uuid and 'sync_status' in resp... | def function[_fail_if_contains_errors, parameter[response, sync_uuid]]:
constant[Raise a RequestError Exception if a given response
does not denote a successful request.
]
if compare[name[response].status_code not_equal[!=] name[_HTTP_OK]] begin[:]
<ast.Raise object at 0x7da1b0ff8d30>
... | keyword[def] identifier[_fail_if_contains_errors] ( identifier[response] , identifier[sync_uuid] = keyword[None] ):
literal[string]
keyword[if] identifier[response] . identifier[status_code] != identifier[_HTTP_OK] :
keyword[raise] identifier[RequestError] ( identifier[response] )
identifie... | def _fail_if_contains_errors(response, sync_uuid=None):
"""Raise a RequestError Exception if a given response
does not denote a successful request.
"""
if response.status_code != _HTTP_OK:
raise RequestError(response) # depends on [control=['if'], data=[]]
response_json = response.json()
... |
def toggle_plain_text(self, checked):
"""Toggle plain text docstring"""
if checked:
self.docstring = checked
self.switch_to_plain_text()
self.force_refresh()
self.set_option('rich_mode', not checked) | def function[toggle_plain_text, parameter[self, checked]]:
constant[Toggle plain text docstring]
if name[checked] begin[:]
name[self].docstring assign[=] name[checked]
call[name[self].switch_to_plain_text, parameter[]]
call[name[self].force_refresh, parame... | keyword[def] identifier[toggle_plain_text] ( identifier[self] , identifier[checked] ):
literal[string]
keyword[if] identifier[checked] :
identifier[self] . identifier[docstring] = identifier[checked]
identifier[self] . identifier[switch_to_plain_text] ()
... | def toggle_plain_text(self, checked):
"""Toggle plain text docstring"""
if checked:
self.docstring = checked
self.switch_to_plain_text()
self.force_refresh() # depends on [control=['if'], data=[]]
self.set_option('rich_mode', not checked) |
def parse_format_string(
format_string: str
) -> Tuple[Set[str], int, Dict[str, str], List[str]]:
"""Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
... | def function[parse_format_string, parameter[format_string]]:
constant[Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
IncompleteFormatString or Un... | keyword[def] identifier[parse_format_string] (
identifier[format_string] : identifier[str]
)-> identifier[Tuple] [ identifier[Set] [ identifier[str] ], identifier[int] , identifier[Dict] [ identifier[str] , identifier[str] ], identifier[List] [ identifier[str] ]]:
literal[string]
identifier[keys] = ident... | def parse_format_string(format_string: str) -> Tuple[Set[str], int, Dict[str, str], List[str]]:
"""Parses a format string, returning a tuple of (keys, num_args), where keys
is the set of mapping keys in the format string, and num_args is the number
of arguments required by the format string. Raises
Inc... |
def get_begin_cursor(self, project_name, logstore_name, shard_id):
""" Get begin cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
... | def function[get_begin_cursor, parameter[self, project_name, logstore_name, shard_id]]:
constant[ Get begin cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type log... | keyword[def] identifier[get_begin_cursor] ( identifier[self] , identifier[project_name] , identifier[logstore_name] , identifier[shard_id] ):
literal[string]
keyword[return] identifier[self] . identifier[get_cursor] ( identifier[project_name] , identifier[logstore_name] , identifier[shard_id] , ... | def get_begin_cursor(self, project_name, logstore_name, shard_id):
""" Get begin cursor from log service for batch pull logs
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type logstore_name: string
:par... |
def getFieldDescription(self, fieldName):
"""
Return the offset and length of a given field within the encoded output.
:param fieldName: Name of the field
:return: tuple(``offset``, ``width``) of the field within the encoded output
"""
# Find which field it's in
description = self.getDescr... | def function[getFieldDescription, parameter[self, fieldName]]:
constant[
Return the offset and length of a given field within the encoded output.
:param fieldName: Name of the field
:return: tuple(``offset``, ``width``) of the field within the encoded output
]
variable[description] assi... | keyword[def] identifier[getFieldDescription] ( identifier[self] , identifier[fieldName] ):
literal[string]
identifier[description] = identifier[self] . identifier[getDescription] ()+[( literal[string] , identifier[self] . identifier[getWidth] ())]
keyword[for] identifier[i] keyword[in] identi... | def getFieldDescription(self, fieldName):
"""
Return the offset and length of a given field within the encoded output.
:param fieldName: Name of the field
:return: tuple(``offset``, ``width``) of the field within the encoded output
"""
# Find which field it's in
description = self.getDescri... |
def readmodule(module, path=None):
'''Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.'''
res = {}
for key, value in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value
re... | def function[readmodule, parameter[module, path]]:
constant[Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary.]
variable[res] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b13571f0>, <ast.Name ob... | keyword[def] identifier[readmodule] ( identifier[module] , identifier[path] = keyword[None] ):
literal[string]
identifier[res] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[_readmodule] ( identifier[module] , identifier[path] keyword[or] []). identifier[items] ():
... | def readmodule(module, path=None):
"""Backwards compatible interface.
Call readmodule_ex() and then only keep Class objects from the
resulting dictionary."""
res = {}
for (key, value) in _readmodule(module, path or []).items():
if isinstance(value, Class):
res[key] = value # de... |
def RENEWING(self):
"""RENEWING state."""
logger.debug('In state: RENEWING')
self.current_state = STATE_RENEWING
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go()
else:
set_net(se... | def function[RENEWING, parameter[self]]:
constant[RENEWING state.]
call[name[logger].debug, parameter[constant[In state: RENEWING]]]
name[self].current_state assign[=] name[STATE_RENEWING]
if compare[name[self].script is_not constant[None]] begin[:]
call[name[self].script... | keyword[def] identifier[RENEWING] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
identifier[self] . identifier[current_state] = identifier[STATE_RENEWING]
keyword[if] identifier[self] . identifier[script] keyword[is] keyword[no... | def RENEWING(self):
"""RENEWING state."""
logger.debug('In state: RENEWING')
self.current_state = STATE_RENEWING
if self.script is not None:
self.script.script_init(self.client.lease, self.current_state)
self.script.script_go() # depends on [control=['if'], data=[]]
else:
se... |
def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
b... | def function[get, parameter[self, now]]:
constant[
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensur... | keyword[def] identifier[get] ( identifier[self] , identifier[now] ):
literal[string]
identifier[items] = identifier[self] . identifier[script] ( identifier[keys] =[ identifier[self] . identifier[key] ], identifier[args] =[ identifier[now] - identifier[self] . identifier[min_age] ])
keywor... | def get(self, now):
"""
Get a bucket key to compact. If none are available, returns
None. This uses a Lua script to ensure that the bucket key is
popped off the sorted set in an atomic fashion.
:param now: The current time, as a float. Used to ensure the
bucke... |
def fold_string(input_string, max_width):
"""
Fold a string within a maximum width.
Parameters:
input_string:
The string of data to go into the cell
max_width:
Maximum width of cell. Data is folded into multiple lines to
fit into this width.
Return:
... | def function[fold_string, parameter[input_string, max_width]]:
constant[
Fold a string within a maximum width.
Parameters:
input_string:
The string of data to go into the cell
max_width:
Maximum width of cell. Data is folded into multiple lines to
fit i... | keyword[def] identifier[fold_string] ( identifier[input_string] , identifier[max_width] ):
literal[string]
identifier[new_string] = identifier[input_string]
keyword[if] identifier[isinstance] ( identifier[input_string] , identifier[six] . identifier[string_types] ):
keyword[if] identifier[... | def fold_string(input_string, max_width):
"""
Fold a string within a maximum width.
Parameters:
input_string:
The string of data to go into the cell
max_width:
Maximum width of cell. Data is folded into multiple lines to
fit into this width.
Return:
... |
def is_nonnegative(self):
"""
Ensures :attr:`subject` is greater than or equal to 0.
"""
self._run(unittest_case.assertGreaterEqual, (self._subject, 0))
return ChainInspector(self._subject) | def function[is_nonnegative, parameter[self]]:
constant[
Ensures :attr:`subject` is greater than or equal to 0.
]
call[name[self]._run, parameter[name[unittest_case].assertGreaterEqual, tuple[[<ast.Attribute object at 0x7da18f00d570>, <ast.Constant object at 0x7da18f00f5b0>]]]]
retur... | keyword[def] identifier[is_nonnegative] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_run] ( identifier[unittest_case] . identifier[assertGreaterEqual] ,( identifier[self] . identifier[_subject] , literal[int] ))
keyword[return] identifier[ChainInspector] ( identifi... | def is_nonnegative(self):
"""
Ensures :attr:`subject` is greater than or equal to 0.
"""
self._run(unittest_case.assertGreaterEqual, (self._subject, 0))
return ChainInspector(self._subject) |
def smoothed_hazards_(self, bandwidth=1):
"""
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
"""
timeline = self._index.values
return pd.DataFrame(
np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.va... | def function[smoothed_hazards_, parameter[self, bandwidth]]:
constant[
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
]
variable[timeline] assign[=] name[self]._index.values
return[call[name[pd].DataFrame, parameter[call[name[np].dot, parameter[cal... | keyword[def] identifier[smoothed_hazards_] ( identifier[self] , identifier[bandwidth] = literal[int] ):
literal[string]
identifier[timeline] = identifier[self] . identifier[_index] . identifier[values]
keyword[return] identifier[pd] . identifier[DataFrame] (
identifier[np] . ide... | def smoothed_hazards_(self, bandwidth=1):
"""
Using the epanechnikov kernel to smooth the hazard function, with sigma/bandwidth
"""
timeline = self._index.values
return pd.DataFrame(np.dot(epanechnikov_kernel(timeline[:, None], timeline, bandwidth), self.hazards_.values), columns=self.hazar... |
def occult(target1, shape1, frame1, target2, shape2, frame2, abcorr, observer,
et):
"""
Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/c... | def function[occult, parameter[target1, shape1, frame1, target2, shape2, frame2, abcorr, observer, et]]:
constant[
Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/n... | keyword[def] identifier[occult] ( identifier[target1] , identifier[shape1] , identifier[frame1] , identifier[target2] , identifier[shape2] , identifier[frame2] , identifier[abcorr] , identifier[observer] ,
identifier[et] ):
literal[string]
identifier[target1] = identifier[stypes] . identifier[stringToChar... | def occult(target1, shape1, frame1, target2, shape2, frame2, abcorr, observer, et):
"""
Determines the occultation condition (not occulted, partially,
etc.) of one target relative to another target as seen by
an observer at a given time.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/occul... |
def _render_pages(self):
"""Render the complete document once and return the number of pages
rendered."""
self.style_log = StyleLog(self.stylesheet)
self.floats = set()
self.placed_footnotes = set()
self._start_time = time.time()
part_page_counts = {}
par... | def function[_render_pages, parameter[self]]:
constant[Render the complete document once and return the number of pages
rendered.]
name[self].style_log assign[=] call[name[StyleLog], parameter[name[self].stylesheet]]
name[self].floats assign[=] call[name[set], parameter[]]
name[s... | keyword[def] identifier[_render_pages] ( identifier[self] ):
literal[string]
identifier[self] . identifier[style_log] = identifier[StyleLog] ( identifier[self] . identifier[stylesheet] )
identifier[self] . identifier[floats] = identifier[set] ()
identifier[self] . identifier[place... | def _render_pages(self):
"""Render the complete document once and return the number of pages
rendered."""
self.style_log = StyleLog(self.stylesheet)
self.floats = set()
self.placed_footnotes = set()
self._start_time = time.time()
part_page_counts = {}
part_page_count = PartPageCount(... |
def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd... | def function[main, parameter[]]:
constant[This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
]
variable[save_settings] assign[=] constant[None]
variable[stdin_fd] assign[=] <ast.UnaryOp object at 0x7da1b16c0a60>
... | keyword[def] identifier[main] ():
literal[string]
identifier[save_settings] = keyword[None]
identifier[stdin_fd] =- literal[int]
keyword[try] :
keyword[import] identifier[termios]
identifier[stdin_fd] = identifier[sys] . identifier[stdin] . identifier[fileno] ()
ide... | def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd... |
async def delete_message(self, chat_id: typing.Union[base.Integer, base.String],
message_id: base.Integer) -> base.Boolean:
"""
Use this method to delete a message, including service messages, with the following limitations:
- A message can only be deleted if it was ... | <ast.AsyncFunctionDef object at 0x7da1b1832260> | keyword[async] keyword[def] identifier[delete_message] ( identifier[self] , identifier[chat_id] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , identifier[base] . identifier[String] ],
identifier[message_id] : identifier[base] . identifier[Integer] )-> identifier[base] . identifi... | async def delete_message(self, chat_id: typing.Union[base.Integer, base.String], message_id: base.Integer) -> base.Boolean:
"""
Use this method to delete a message, including service messages, with the following limitations:
- A message can only be deleted if it was sent less than 48 hours ago.
... |
def validate_code(self, client_id, code, client, request, *args, **kwargs):
"""Ensure the grant code is valid."""
client = client or self._clientgetter(client_id)
log.debug(
'Validate code for client %r and code %r', client.client_id, code
)
grant = self._grantgetter(... | def function[validate_code, parameter[self, client_id, code, client, request]]:
constant[Ensure the grant code is valid.]
variable[client] assign[=] <ast.BoolOp object at 0x7da1b0382530>
call[name[log].debug, parameter[constant[Validate code for client %r and code %r], name[client].client_id, na... | keyword[def] identifier[validate_code] ( identifier[self] , identifier[client_id] , identifier[code] , identifier[client] , identifier[request] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[client] = identifier[client] keyword[or] identifier[self] . identifier[_clientge... | def validate_code(self, client_id, code, client, request, *args, **kwargs):
"""Ensure the grant code is valid."""
client = client or self._clientgetter(client_id)
log.debug('Validate code for client %r and code %r', client.client_id, code)
grant = self._grantgetter(client_id=client.client_id, code=code)... |
async def post(self, public_key=None):
"""Creates new offer
Accepts:
- buyer public key
- cid
- buyer access string
Returns:
- offer parameters as dictionary
"""
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(40... | <ast.AsyncFunctionDef object at 0x7da20e957d90> | keyword[async] keyword[def] identifier[post] ( identifier[self] , identifier[public_key] = keyword[None] ):
literal[string]
keyword[if] identifier[settings] . identifier[SIGNATURE_VERIFICATION] :
identifier[super] (). identifier[verify] ()
keyword[try] :
identifier[body] = identifier[json] . iden... | async def post(self, public_key=None):
"""Creates new offer
Accepts:
- buyer public key
- cid
- buyer access string
Returns:
- offer parameters as dictionary
"""
if settings.SIGNATURE_VERIFICATION:
super().verify() # depends on [control=['if'], data=[]]
try:
body = json.l... |
def droplevel(self, level, axis=0):
"""
Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like,... | def function[droplevel, parameter[self, level, axis]]:
constant[
Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
... | keyword[def] identifier[droplevel] ( identifier[self] , identifier[level] , identifier[axis] = literal[int] ):
literal[string]
identifier[labels] = identifier[self] . identifier[_get_axis] ( identifier[axis] )
identifier[new_labels] = identifier[labels] . identifier[droplevel] ( identifier... | def droplevel(self, level, axis=0):
"""
Return DataFrame with requested index / column level(s) removed.
.. versionadded:: 0.24.0
Parameters
----------
level : int, str, or list-like
If a string is given, must be the name of a level
If list-like, ele... |
def get_plain_image_as_widget(self):
"""Used for generating thumbnails. Does not include overlaid
graphics.
"""
arr = self.getwin_array(order=self.rgb_order)
# convert numpy array to native image widget
image_w = self._get_wimage(arr)
return image_w | def function[get_plain_image_as_widget, parameter[self]]:
constant[Used for generating thumbnails. Does not include overlaid
graphics.
]
variable[arr] assign[=] call[name[self].getwin_array, parameter[]]
variable[image_w] assign[=] call[name[self]._get_wimage, parameter[name[arr... | keyword[def] identifier[get_plain_image_as_widget] ( identifier[self] ):
literal[string]
identifier[arr] = identifier[self] . identifier[getwin_array] ( identifier[order] = identifier[self] . identifier[rgb_order] )
identifier[image_w] = identifier[self] . identifier[_get_wimage]... | def get_plain_image_as_widget(self):
"""Used for generating thumbnails. Does not include overlaid
graphics.
"""
arr = self.getwin_array(order=self.rgb_order)
# convert numpy array to native image widget
image_w = self._get_wimage(arr)
return image_w |
def nvp2pl(normal, point):
"""
Make a plane from a normal vector and a point.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvp2pl_c.html
:param normal: A normal vector defining a plane.
:type normal: 3-Element Array of floats
:param point: A point defining a plane.
:type point: ... | def function[nvp2pl, parameter[normal, point]]:
constant[
Make a plane from a normal vector and a point.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvp2pl_c.html
:param normal: A normal vector defining a plane.
:type normal: 3-Element Array of floats
:param point: A point defi... | keyword[def] identifier[nvp2pl] ( identifier[normal] , identifier[point] ):
literal[string]
identifier[normal] = identifier[stypes] . identifier[toDoubleVector] ( identifier[normal] )
identifier[point] = identifier[stypes] . identifier[toDoubleVector] ( identifier[point] )
identifier[plane] = ide... | def nvp2pl(normal, point):
"""
Make a plane from a normal vector and a point.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/nvp2pl_c.html
:param normal: A normal vector defining a plane.
:type normal: 3-Element Array of floats
:param point: A point defining a plane.
:type point: ... |
def format_value(self, value, padding):
"""Get padding adjusting for negative values."""
# padding = padding - 1 if value < 0 and padding > 0 else padding
# prefix = '-' if value < 0 else ''
if padding:
return "{:0{pad}d}".format(value, pad=padding)
else:
... | def function[format_value, parameter[self, value, padding]]:
constant[Get padding adjusting for negative values.]
if name[padding] begin[:]
return[call[constant[{:0{pad}d}].format, parameter[name[value]]]] | keyword[def] identifier[format_value] ( identifier[self] , identifier[value] , identifier[padding] ):
literal[string]
keyword[if] identifier[padding] :
keyword[return] literal[string] . identifier[format] ( identifier[value] , identifier[pad] = identifier[padding]... | def format_value(self, value, padding):
"""Get padding adjusting for negative values."""
# padding = padding - 1 if value < 0 and padding > 0 else padding
# prefix = '-' if value < 0 else ''
if padding:
return '{:0{pad}d}'.format(value, pad=padding) # depends on [control=['if'], data=[]]
el... |
def set_logger(self, logger):
"""
Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module.
"""
self.__logger = logger... | def function[set_logger, parameter[self, logger]]:
constant[
Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module.
]
... | keyword[def] identifier[set_logger] ( identifier[self] , identifier[logger] ):
literal[string]
identifier[self] . identifier[__logger] = identifier[logger]
identifier[self] . identifier[session] . identifier[set_logger] ( identifier[self] . identifier[__logger] ) | def set_logger(self, logger):
"""
Set a logger to send debug messages to
Parameters
----------
logger : `Logger <http://docs.python.org/2/library/logging.html>`_
A python logger used to get debugging output from this module.
"""
self.__logger = logger
sel... |
def _get_object_as_soft(self):
"""Return object as SOFT formatted string."""
soft = []
if self.database is not None:
soft.append(self.database._get_object_as_soft())
soft += ["^%s = %s" % (self.geotype, self.name),
self._get_metadata_as_string()]
for ... | def function[_get_object_as_soft, parameter[self]]:
constant[Return object as SOFT formatted string.]
variable[soft] assign[=] list[[]]
if compare[name[self].database is_not constant[None]] begin[:]
call[name[soft].append, parameter[call[name[self].database._get_object_as_soft, p... | keyword[def] identifier[_get_object_as_soft] ( identifier[self] ):
literal[string]
identifier[soft] =[]
keyword[if] identifier[self] . identifier[database] keyword[is] keyword[not] keyword[None] :
identifier[soft] . identifier[append] ( identifier[self] . identifier[databa... | def _get_object_as_soft(self):
"""Return object as SOFT formatted string."""
soft = []
if self.database is not None:
soft.append(self.database._get_object_as_soft()) # depends on [control=['if'], data=[]]
soft += ['^%s = %s' % (self.geotype, self.name), self._get_metadata_as_string()]
for s... |
def execute(self, time_interval):
"""
Execute the factor over the given time interval. Note that this is normally done by the workflow,
but can also be done on the factor directly
:param time_interval: The time interval
:return: self (for chaining)
"""
logging.in... | def function[execute, parameter[self, time_interval]]:
constant[
Execute the factor over the given time interval. Note that this is normally done by the workflow,
but can also be done on the factor directly
:param time_interval: The time interval
:return: self (for chaining)
... | keyword[def] identifier[execute] ( identifier[self] , identifier[time_interval] ):
literal[string]
identifier[logging] . identifier[info] ( literal[string] . identifier[format] (
identifier[self] . identifier[tool] . identifier[__class__] . identifier[__name__] , identifier[time_interval] ... | def execute(self, time_interval):
"""
Execute the factor over the given time interval. Note that this is normally done by the workflow,
but can also be done on the factor directly
:param time_interval: The time interval
:return: self (for chaining)
"""
logging.info('{} r... |
def to_labeled_point(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: bool... | def function[to_labeled_point, parameter[sc, features, labels, categorical]]:
constant[Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
... | keyword[def] identifier[to_labeled_point] ( identifier[sc] , identifier[features] , identifier[labels] , identifier[categorical] = keyword[False] ):
literal[string]
identifier[labeled_points] =[]
keyword[for] identifier[x] , identifier[y] keyword[in] identifier[zip] ( identifier[features] , identif... | def to_labeled_point(sc, features, labels, categorical=False):
"""Convert numpy arrays of features and labels into
a LabeledPoint RDD for MLlib and ML integration.
:param sc: Spark context
:param features: numpy array with features
:param labels: numpy array with labels
:param categorical: bool... |
def format(self, vertices):
"""Format instance to dump
vertices is dict of name to Vertex
"""
index = ' '.join(str(vertices[vn].index) for vn in self.vnames)
com = ' '.join(self.vnames) # for comment
return '({0:s}) // {1:s} ({2:s})'.format(index, self.name, com) | def function[format, parameter[self, vertices]]:
constant[Format instance to dump
vertices is dict of name to Vertex
]
variable[index] assign[=] call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da18fe92f20>]]
variable[com] assign[=] call[constant[ ].join, parameter... | keyword[def] identifier[format] ( identifier[self] , identifier[vertices] ):
literal[string]
identifier[index] = literal[string] . identifier[join] ( identifier[str] ( identifier[vertices] [ identifier[vn] ]. identifier[index] ) keyword[for] identifier[vn] keyword[in] identifier[self] . identifi... | def format(self, vertices):
"""Format instance to dump
vertices is dict of name to Vertex
"""
index = ' '.join((str(vertices[vn].index) for vn in self.vnames))
com = ' '.join(self.vnames) # for comment
return '({0:s}) // {1:s} ({2:s})'.format(index, self.name, com) |
def begin(self, total: int, name=None, message=None):
"""Call before starting work on a monitor, specifying name and amount of work"""
self.total = total
message = message or name or "Working..."
self.name = name or "ProgressMonitor"
self.update(0, message) | def function[begin, parameter[self, total, name, message]]:
constant[Call before starting work on a monitor, specifying name and amount of work]
name[self].total assign[=] name[total]
variable[message] assign[=] <ast.BoolOp object at 0x7da1b23478b0>
name[self].name assign[=] <ast.BoolOp ... | keyword[def] identifier[begin] ( identifier[self] , identifier[total] : identifier[int] , identifier[name] = keyword[None] , identifier[message] = keyword[None] ):
literal[string]
identifier[self] . identifier[total] = identifier[total]
identifier[message] = identifier[message] keyword[o... | def begin(self, total: int, name=None, message=None):
"""Call before starting work on a monitor, specifying name and amount of work"""
self.total = total
message = message or name or 'Working...'
self.name = name or 'ProgressMonitor'
self.update(0, message) |
def update(self, ogpgs):
"""
Method to update object group permissions general
:param ogpgs: List containing object group permissions general desired to updated
:return: None
"""
data = {'ogpgs': ogpgs}
ogpgs_ids = [str(ogpg.get('id')) for ogpg in ogpgs]
... | def function[update, parameter[self, ogpgs]]:
constant[
Method to update object group permissions general
:param ogpgs: List containing object group permissions general desired to updated
:return: None
]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da1... | keyword[def] identifier[update] ( identifier[self] , identifier[ogpgs] ):
literal[string]
identifier[data] ={ literal[string] : identifier[ogpgs] }
identifier[ogpgs_ids] =[ identifier[str] ( identifier[ogpg] . identifier[get] ( literal[string] )) keyword[for] identifier[ogpg] keyword[in... | def update(self, ogpgs):
"""
Method to update object group permissions general
:param ogpgs: List containing object group permissions general desired to updated
:return: None
"""
data = {'ogpgs': ogpgs}
ogpgs_ids = [str(ogpg.get('id')) for ogpg in ogpgs]
return super(Api... |
def tmppath(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
Returns a path directly under root that is guaranteed to be unique by
using the uuid module.
'''
return os.path.join(root, prefix + uuid.uuid4().hex + suffix) | def function[tmppath, parameter[root, prefix, suffix]]:
constant[
Returns a path directly under root that is guaranteed to be unique by
using the uuid module.
]
return[call[name[os].path.join, parameter[name[root], binary_operation[binary_operation[name[prefix] + call[name[uuid].uuid4, parameter... | keyword[def] identifier[tmppath] ( identifier[root] = identifier[TEMPS_DIR] , identifier[prefix] = identifier[TEMPS_PREFIX] , identifier[suffix] = identifier[TEMPS_SUFFIX] ):
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[root] , identifier[prefix] + iden... | def tmppath(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
"""
Returns a path directly under root that is guaranteed to be unique by
using the uuid module.
"""
return os.path.join(root, prefix + uuid.uuid4().hex + suffix) |
def register_trading_control(self, control):
"""
Register a new TradingControl to be checked prior to order calls.
"""
if self.initialized:
raise RegisterTradingControlPostInit()
self.trading_controls.append(control) | def function[register_trading_control, parameter[self, control]]:
constant[
Register a new TradingControl to be checked prior to order calls.
]
if name[self].initialized begin[:]
<ast.Raise object at 0x7da1b2005840>
call[name[self].trading_controls.append, parameter[name[... | keyword[def] identifier[register_trading_control] ( identifier[self] , identifier[control] ):
literal[string]
keyword[if] identifier[self] . identifier[initialized] :
keyword[raise] identifier[RegisterTradingControlPostInit] ()
identifier[self] . identifier[trading_controls]... | def register_trading_control(self, control):
"""
Register a new TradingControl to be checked prior to order calls.
"""
if self.initialized:
raise RegisterTradingControlPostInit() # depends on [control=['if'], data=[]]
self.trading_controls.append(control) |
def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist.
"""
if fname is not None:
return (self / fname).rm()
try:
self.remove()
except OSError:
pass | def function[rm, parameter[self, fname]]:
constant[Remove a file, don't raise exception if file does not exist.
]
if compare[name[fname] is_not constant[None]] begin[:]
return[call[binary_operation[name[self] / name[fname]].rm, parameter[]]]
<ast.Try object at 0x7da207f02110> | keyword[def] identifier[rm] ( identifier[self] , identifier[fname] = keyword[None] ):
literal[string]
keyword[if] identifier[fname] keyword[is] keyword[not] keyword[None] :
keyword[return] ( identifier[self] / identifier[fname] ). identifier[rm] ()
keyword[try] :
... | def rm(self, fname=None):
"""Remove a file, don't raise exception if file does not exist.
"""
if fname is not None:
return (self / fname).rm() # depends on [control=['if'], data=['fname']]
try:
self.remove() # depends on [control=['try'], data=[]]
except OSError:
pass ... |
def setup_env(app):
"""
Setup enviroment
Creates required directory and storage objects (on the
global enviroment) used by this extension.
"""
env = app.env
GalleryEntryExtractor.env = env
out_imgdir = os.path.join(app.outdir, '_images')
if not os.path.isdir(RST_PATH):
os.m... | def function[setup_env, parameter[app]]:
constant[
Setup enviroment
Creates required directory and storage objects (on the
global enviroment) used by this extension.
]
variable[env] assign[=] name[app].env
name[GalleryEntryExtractor].env assign[=] name[env]
variable[out_... | keyword[def] identifier[setup_env] ( identifier[app] ):
literal[string]
identifier[env] = identifier[app] . identifier[env]
identifier[GalleryEntryExtractor] . identifier[env] = identifier[env]
identifier[out_imgdir] = identifier[os] . identifier[path] . identifier[join] ( identifier[app] . ide... | def setup_env(app):
"""
Setup enviroment
Creates required directory and storage objects (on the
global enviroment) used by this extension.
"""
env = app.env
GalleryEntryExtractor.env = env
out_imgdir = os.path.join(app.outdir, '_images')
if not os.path.isdir(RST_PATH):
os.ma... |
def normaliseWV(wV, normFac=1.0):
"""
make char probs divisible by one
"""
f = sum(wV) / normFac
return [ i/f for i in wV ] | def function[normaliseWV, parameter[wV, normFac]]:
constant[
make char probs divisible by one
]
variable[f] assign[=] binary_operation[call[name[sum], parameter[name[wV]]] / name[normFac]]
return[<ast.ListComp object at 0x7da20e9572e0>] | keyword[def] identifier[normaliseWV] ( identifier[wV] , identifier[normFac] = literal[int] ):
literal[string]
identifier[f] = identifier[sum] ( identifier[wV] )/ identifier[normFac]
keyword[return] [ identifier[i] / identifier[f] keyword[for] identifier[i] keyword[in] identifier[wV] ] | def normaliseWV(wV, normFac=1.0):
"""
make char probs divisible by one
"""
f = sum(wV) / normFac
return [i / f for i in wV] |
def unwatch(connection, volume_id):
""" Remove watching of a volume
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume_id: str
:param volume_id: VolumeID to add to the watchlist
:returns: bool - True if the watch was successful
"""
... | def function[unwatch, parameter[connection, volume_id]]:
constant[ Remove watching of a volume
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume_id: str
:param volume_id: VolumeID to add to the watchlist
:returns: bool - True if the wa... | keyword[def] identifier[unwatch] ( identifier[connection] , identifier[volume_id] ):
literal[string]
keyword[try] :
identifier[volume] = identifier[connection] . identifier[get_all_volumes] ( identifier[volume_ids] =[ identifier[volume_id] ])[ literal[int] ]
identifier[volume] . identifie... | def unwatch(connection, volume_id):
""" Remove watching of a volume
:type connection: boto.ec2.connection.EC2Connection
:param connection: EC2 connection object
:type volume_id: str
:param volume_id: VolumeID to add to the watchlist
:returns: bool - True if the watch was successful
"""
... |
def _solidAngleMMD(self):
"""
Compute solid angle within the mask annulus (deg^2) as a
function of mag_1 and mag_2
"""
# Take upper corner of the magnitude bin
mag_2,mag_1 = np.meshgrid(self.roi.bins_mag[1:],self.roi.bins_mag[1:])
# Havent tested since adding fra... | def function[_solidAngleMMD, parameter[self]]:
constant[
Compute solid angle within the mask annulus (deg^2) as a
function of mag_1 and mag_2
]
<ast.Tuple object at 0x7da2047e93f0> assign[=] call[name[np].meshgrid, parameter[call[name[self].roi.bins_mag][<ast.Slice object at 0x7d... | keyword[def] identifier[_solidAngleMMD] ( identifier[self] ):
literal[string]
identifier[mag_2] , identifier[mag_1] = identifier[np] . identifier[meshgrid] ( identifier[self] . identifier[roi] . identifier[bins_mag] [ literal[int] :], identifier[self] . identifier[roi] . identifier[bins_ma... | def _solidAngleMMD(self):
"""
Compute solid angle within the mask annulus (deg^2) as a
function of mag_1 and mag_2
"""
# Take upper corner of the magnitude bin
(mag_2, mag_1) = np.meshgrid(self.roi.bins_mag[1:], self.roi.bins_mag[1:])
# Havent tested since adding fracdet
unma... |
def comment(self, id_num):
"""Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int id_num: (required), comment ... | def function[comment, parameter[self, id_num]]:
constant[Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int i... | keyword[def] identifier[comment] ( identifier[self] , identifier[id_num] ):
literal[string]
identifier[json] = keyword[None]
keyword[if] identifier[int] ( identifier[id_num] )> literal[int] :
identifier[owner] , identifier[repo] = identifier[self] . identifier[repository]
... | def comment(self, id_num):
"""Get a single comment by its id.
The catch here is that id is NOT a simple number to obtain. If
you were to look at the comments on issue #15 in
sigmavirus24/Todo.txt-python, the first comment's id is 4150787.
:param int id_num: (required), comment id, ... |
def get_epoll_events(self):
"""
Create a bit mask using ``EPOLL*`` family of constants.
"""
epoll_events = 0
if self & EVENT_READ:
epoll_events |= select.EPOLLIN
if self & EVENT_WRITE:
epoll_events |= select.EPOLLOUT
return epoll_events | def function[get_epoll_events, parameter[self]]:
constant[
Create a bit mask using ``EPOLL*`` family of constants.
]
variable[epoll_events] assign[=] constant[0]
if binary_operation[name[self] <ast.BitAnd object at 0x7da2590d6b60> name[EVENT_READ]] begin[:]
<ast.AugAssign... | keyword[def] identifier[get_epoll_events] ( identifier[self] ):
literal[string]
identifier[epoll_events] = literal[int]
keyword[if] identifier[self] & identifier[EVENT_READ] :
identifier[epoll_events] |= identifier[select] . identifier[EPOLLIN]
keyword[if] identif... | def get_epoll_events(self):
"""
Create a bit mask using ``EPOLL*`` family of constants.
"""
epoll_events = 0
if self & EVENT_READ:
epoll_events |= select.EPOLLIN # depends on [control=['if'], data=[]]
if self & EVENT_WRITE:
epoll_events |= select.EPOLLOUT # depends on [... |
def template(tpl, template_adapter=SimpleTemplate, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
'''
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.get('template_settings',{})
lookup = kwargs.... | def function[template, parameter[tpl, template_adapter]]:
constant[
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
]
if <ast.BoolOp object at 0x7da1b04708e0> begin[:]
variable[settings] assign[=] call[name... | keyword[def] identifier[template] ( identifier[tpl] , identifier[template_adapter] = identifier[SimpleTemplate] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[tpl] keyword[not] keyword[in] identifier[TEMPLATES] keyword[or] identifier[DEBUG] :
identifier[settings] = identifi... | def template(tpl, template_adapter=SimpleTemplate, **kwargs):
"""
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
"""
if tpl not in TEMPLATES or DEBUG:
settings = kwargs.get('template_settings', {})
lookup = kwargs... |
def close_debt_position(self, symbol, account=None):
""" Close a debt position and reclaim the collateral
:param str symbol: Symbol to close debt position for
:raises ValueError: if symbol has no open call position
"""
if not account:
if "default_account" in ... | def function[close_debt_position, parameter[self, symbol, account]]:
constant[ Close a debt position and reclaim the collateral
:param str symbol: Symbol to close debt position for
:raises ValueError: if symbol has no open call position
]
if <ast.UnaryOp object at 0x7da1... | keyword[def] identifier[close_debt_position] ( identifier[self] , identifier[symbol] , identifier[account] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[account] :
keyword[if] literal[string] keyword[in] identifier[self] . identifier[blockchain] . identifi... | def close_debt_position(self, symbol, account=None):
""" Close a debt position and reclaim the collateral
:param str symbol: Symbol to close debt position for
:raises ValueError: if symbol has no open call position
"""
if not account:
if 'default_account' in self.blockch... |
def get(self, lengths: Union[mx.nd.NDArray, int, float]) -> Union[mx.nd.NDArray, float]:
"""
Calculate the length penalty for the given vector of lengths.
:param lengths: A scalar or a matrix of sentence lengths of dimensionality (batch_size, 1).
:return: The length penalty. A scalar or... | def function[get, parameter[self, lengths]]:
constant[
Calculate the length penalty for the given vector of lengths.
:param lengths: A scalar or a matrix of sentence lengths of dimensionality (batch_size, 1).
:return: The length penalty. A scalar or a matrix (batch_size, 1) depending on... | keyword[def] identifier[get] ( identifier[self] , identifier[lengths] : identifier[Union] [ identifier[mx] . identifier[nd] . identifier[NDArray] , identifier[int] , identifier[float] ])-> identifier[Union] [ identifier[mx] . identifier[nd] . identifier[NDArray] , identifier[float] ]:
literal[string]
... | def get(self, lengths: Union[mx.nd.NDArray, int, float]) -> Union[mx.nd.NDArray, float]:
"""
Calculate the length penalty for the given vector of lengths.
:param lengths: A scalar or a matrix of sentence lengths of dimensionality (batch_size, 1).
:return: The length penalty. A scalar or a m... |
def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs):
"""
Update an existing dataset
"""
if dataset_id is None:
raise HydraError("Dataset must have an ID to be updated.")
user_id = kwargs.get('user_id')
dataset = db.DBSession.query(Datas... | def function[update_dataset, parameter[dataset_id, name, data_type, val, unit_id, metadata, flush]]:
constant[
Update an existing dataset
]
if compare[name[dataset_id] is constant[None]] begin[:]
<ast.Raise object at 0x7da18c4cccd0>
variable[user_id] assign[=] call[name[kwarg... | keyword[def] identifier[update_dataset] ( identifier[dataset_id] , identifier[name] , identifier[data_type] , identifier[val] , identifier[unit_id] , identifier[metadata] ={}, identifier[flush] = keyword[True] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[dataset_id] keyword[is] keyw... | def update_dataset(dataset_id, name, data_type, val, unit_id, metadata={}, flush=True, **kwargs):
"""
Update an existing dataset
"""
if dataset_id is None:
raise HydraError('Dataset must have an ID to be updated.') # depends on [control=['if'], data=[]]
user_id = kwargs.get('user_id')
... |
def _get_on_name(self, func):
"""Return `eventname` when the function name is `on_<eventname>()`."""
r = re.match("^on_(.+)$", func.__name__)
if r:
event = r.group(1)
else:
raise ValueError("The function name should be "
"`on_<eventnam... | def function[_get_on_name, parameter[self, func]]:
constant[Return `eventname` when the function name is `on_<eventname>()`.]
variable[r] assign[=] call[name[re].match, parameter[constant[^on_(.+)$], name[func].__name__]]
if name[r] begin[:]
variable[event] assign[=] call[name[r]... | keyword[def] identifier[_get_on_name] ( identifier[self] , identifier[func] ):
literal[string]
identifier[r] = identifier[re] . identifier[match] ( literal[string] , identifier[func] . identifier[__name__] )
keyword[if] identifier[r] :
identifier[event] = identifier[r] . iden... | def _get_on_name(self, func):
"""Return `eventname` when the function name is `on_<eventname>()`."""
r = re.match('^on_(.+)$', func.__name__)
if r:
event = r.group(1) # depends on [control=['if'], data=[]]
else:
raise ValueError('The function name should be `on_<eventname>`().')
ret... |
async def read_loop(self):
"""
Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate callback on the
... | <ast.AsyncFunctionDef object at 0x7da20cabfd00> | keyword[async] keyword[def] identifier[read_loop] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[closing] :
keyword[try] :
identifier[xid] , identifier[zxid] , identifier[response] = keyword[await] identifier[self] .... | async def read_loop(self):
"""
Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate callback on the
... |
def _backspaced_single_line_animation(animation_, *args, **kwargs):
"""Turn an animation into an automatically backspaced animation.
Args:
animation: A function that returns a generator that yields
strings for animation frames.
args: Arguments for the animation function.
kwargs:... | def function[_backspaced_single_line_animation, parameter[animation_]]:
constant[Turn an animation into an automatically backspaced animation.
Args:
animation: A function that returns a generator that yields
strings for animation frames.
args: Arguments for the animation function.
... | keyword[def] identifier[_backspaced_single_line_animation] ( identifier[animation_] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[animation_gen] = identifier[animation_] (* identifier[args] ,** identifier[kwargs] )
keyword[yield] identifier[next] ( identifier[animation_gen]... | def _backspaced_single_line_animation(animation_, *args, **kwargs):
"""Turn an animation into an automatically backspaced animation.
Args:
animation: A function that returns a generator that yields
strings for animation frames.
args: Arguments for the animation function.
kwargs:... |
def start_instance(self,
# these are common to any
# CloudProvider.start_instance() call
key_name, public_key_path, private_key_path,
security_group, flavor, image_id, image_userdata,
username=None,
... | def function[start_instance, parameter[self, key_name, public_key_path, private_key_path, security_group, flavor, image_id, image_userdata, username, node_name, boot_disk_type, boot_disk_size, tags, scheduling, accelerator_count, accelerator_type, allow_project_ssh_keys, local_ssd_count, local_ssd_interface, min_cpu_pl... | keyword[def] identifier[start_instance] ( identifier[self] ,
identifier[key_name] , identifier[public_key_path] , identifier[private_key_path] ,
identifier[security_group] , identifier[flavor] , identifier[image_id] , identifier[image_userdata] ,
identifier[username] = keyword[None] ,
identifier[node_name] = ... | def start_instance(self, key_name, public_key_path, private_key_path, security_group, flavor, image_id, image_userdata, username=None, node_name=None, boot_disk_type='pd-standard', boot_disk_size=10, tags=None, scheduling=None, accelerator_count=0, accelerator_type='default', allow_project_ssh_keys=True, local_ssd_coun... |
def _token_to_subwords(self, token):
"""Greedily split token into subwords."""
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(
min(len(token), start + self._max_subword_len), start, -1):
candidate = token[start:end]
if (candidate ... | def function[_token_to_subwords, parameter[self, token]]:
constant[Greedily split token into subwords.]
variable[subwords] assign[=] list[[]]
variable[start] assign[=] constant[0]
while compare[name[start] less[<] call[name[len], parameter[name[token]]]] begin[:]
variable... | keyword[def] identifier[_token_to_subwords] ( identifier[self] , identifier[token] ):
literal[string]
identifier[subwords] =[]
identifier[start] = literal[int]
keyword[while] identifier[start] < identifier[len] ( identifier[token] ):
identifier[subword] = keyword[None]
keyword[f... | def _token_to_subwords(self, token):
"""Greedily split token into subwords."""
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(min(len(token), start + self._max_subword_len), start, -1):
candidate = token[start:end]
if candidate i... |
def from_maybe_starargs(cls, args, use_comma=True):
"""If `args` has one element which appears to be a list, return it.
Otherwise, return a list as normal.
Mainly used by Sass function implementations that predate `...`
support, so they can accept both a list of arguments and a single l... | def function[from_maybe_starargs, parameter[cls, args, use_comma]]:
constant[If `args` has one element which appears to be a list, return it.
Otherwise, return a list as normal.
Mainly used by Sass function implementations that predate `...`
support, so they can accept both a list of ar... | keyword[def] identifier[from_maybe_starargs] ( identifier[cls] , identifier[args] , identifier[use_comma] = keyword[True] ):
literal[string]
keyword[if] identifier[len] ( identifier[args] )== literal[int] :
keyword[if] identifier[isinstance] ( identifier[args] [ literal[int] ], ident... | def from_maybe_starargs(cls, args, use_comma=True):
"""If `args` has one element which appears to be a list, return it.
Otherwise, return a list as normal.
Mainly used by Sass function implementations that predate `...`
support, so they can accept both a list of arguments and a single list
... |
def delete_servers(*servers, **options):
'''
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param com... | def function[delete_servers, parameter[]]:
constant[
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
... | keyword[def] identifier[delete_servers] (* identifier[servers] ,** identifier[options] ):
literal[string]
identifier[test] = identifier[options] . identifier[pop] ( literal[string] , keyword[False] )
identifier[commit] = identifier[options] . identifier[pop] ( literal[string] , keyword[True] )
... | def delete_servers(*servers, **options):
"""
Removes NTP servers configured on the device.
:param servers: list of IP Addresses/Domain Names to be removed as NTP
servers
:param test (bool): discard loaded config. By default ``test`` is False
(will not dicard the changes)
:param comm... |
def delete(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to DELETE"""
if urls is not None:
overrides['urls'] = urls
return self.where(accept='DELETE', **overrides) | def function[delete, parameter[self, urls]]:
constant[Sets the acceptable HTTP method to DELETE]
if compare[name[urls] is_not constant[None]] begin[:]
call[name[overrides]][constant[urls]] assign[=] name[urls]
return[call[name[self].where, parameter[]]] | keyword[def] identifier[delete] ( identifier[self] , identifier[urls] = keyword[None] ,** identifier[overrides] ):
literal[string]
keyword[if] identifier[urls] keyword[is] keyword[not] keyword[None] :
identifier[overrides] [ literal[string] ]= identifier[urls]
keyword[ret... | def delete(self, urls=None, **overrides):
"""Sets the acceptable HTTP method to DELETE"""
if urls is not None:
overrides['urls'] = urls # depends on [control=['if'], data=['urls']]
return self.where(accept='DELETE', **overrides) |
def configure(self):
"""Configure the Python stdlib logger"""
if self.debug is not None and not self.debug:
self._remove_debug_handlers()
self._remove_debug_only()
logging.config.dictConfig(self.config)
try:
logging.captureWarnings(True)
except Att... | def function[configure, parameter[self]]:
constant[Configure the Python stdlib logger]
if <ast.BoolOp object at 0x7da207f03d90> begin[:]
call[name[self]._remove_debug_handlers, parameter[]]
call[name[self]._remove_debug_only, parameter[]]
call[name[logging].config.dictCon... | keyword[def] identifier[configure] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[debug] keyword[is] keyword[not] keyword[None] keyword[and] keyword[not] identifier[self] . identifier[debug] :
identifier[self] . identifier[_remove_debug_handlers]... | def configure(self):
"""Configure the Python stdlib logger"""
if self.debug is not None and (not self.debug):
self._remove_debug_handlers() # depends on [control=['if'], data=[]]
self._remove_debug_only()
logging.config.dictConfig(self.config)
try:
logging.captureWarnings(True) # d... |
def parent(self, parent_object, limit_parent_language=True):
"""
Return all content items which are associated with a given parent object.
"""
return self.all().parent(parent_object, limit_parent_language) | def function[parent, parameter[self, parent_object, limit_parent_language]]:
constant[
Return all content items which are associated with a given parent object.
]
return[call[call[name[self].all, parameter[]].parent, parameter[name[parent_object], name[limit_parent_language]]]] | keyword[def] identifier[parent] ( identifier[self] , identifier[parent_object] , identifier[limit_parent_language] = keyword[True] ):
literal[string]
keyword[return] identifier[self] . identifier[all] (). identifier[parent] ( identifier[parent_object] , identifier[limit_parent_language] ) | def parent(self, parent_object, limit_parent_language=True):
"""
Return all content items which are associated with a given parent object.
"""
return self.all().parent(parent_object, limit_parent_language) |
def find_by_ast(line, version_token="__version__"): # type: (str,str) -> Optional[str]
"""
Safer way to 'execute' python code to get a simple value
:param line:
:param version_token:
:return:
"""
if not line:
return ""
# clean up line.
simplified_line = simplify_line(line)
... | def function[find_by_ast, parameter[line, version_token]]:
constant[
Safer way to 'execute' python code to get a simple value
:param line:
:param version_token:
:return:
]
if <ast.UnaryOp object at 0x7da1b15c0e50> begin[:]
return[constant[]]
variable[simplified_line] ... | keyword[def] identifier[find_by_ast] ( identifier[line] , identifier[version_token] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[line] :
keyword[return] literal[string]
identifier[simplified_line] = identifier[simplify_line] ( identifier[line] )
... | def find_by_ast(line, version_token='__version__'): # type: (str,str) -> Optional[str]
"\n Safer way to 'execute' python code to get a simple value\n :param line:\n :param version_token:\n :return:\n "
if not line:
return '' # depends on [control=['if'], data=[]]
# clean up line.
... |
def cross_entropy_neighbors_in_rep(adata, use_rep, n_points=3):
"""Compare neighborhood graph of representation based on cross entropy.
`n_points` denotes the number of points to add as highlight annotation.
Returns
-------
The cross entropy and the geodesic-distance-weighted cross entropy as
... | def function[cross_entropy_neighbors_in_rep, parameter[adata, use_rep, n_points]]:
constant[Compare neighborhood graph of representation based on cross entropy.
`n_points` denotes the number of points to add as highlight annotation.
Returns
-------
The cross entropy and the geodesic-distance-w... | keyword[def] identifier[cross_entropy_neighbors_in_rep] ( identifier[adata] , identifier[use_rep] , identifier[n_points] = literal[int] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[adata] . identifier[obsm] . identifier[keys] ():
keyword[raise] ident... | def cross_entropy_neighbors_in_rep(adata, use_rep, n_points=3):
"""Compare neighborhood graph of representation based on cross entropy.
`n_points` denotes the number of points to add as highlight annotation.
Returns
-------
The cross entropy and the geodesic-distance-weighted cross entropy as
... |
def get_box_files(self, box_key):
'''Gets to file infos in a single box.
Args:
box_key key for the file
return (status code, list of file info dicts)
'''
uri = '/'.join([self.api_uri,
self.boxes_suffix,
box_key,
self.files_suffix
])
return self._req('get', uri) | def function[get_box_files, parameter[self, box_key]]:
constant[Gets to file infos in a single box.
Args:
box_key key for the file
return (status code, list of file info dicts)
]
variable[uri] assign[=] call[constant[/].join, parameter[list[[<ast.Attribute object at 0x7da1b26acf10>, <ast.At... | keyword[def] identifier[get_box_files] ( identifier[self] , identifier[box_key] ):
literal[string]
identifier[uri] = literal[string] . identifier[join] ([ identifier[self] . identifier[api_uri] ,
identifier[self] . identifier[boxes_suffix] ,
identifier[box_key] ,
identifier[self] . identifier[files_su... | def get_box_files(self, box_key):
"""Gets to file infos in a single box.
Args:
box_key key for the file
return (status code, list of file info dicts)
"""
uri = '/'.join([self.api_uri, self.boxes_suffix, box_key, self.files_suffix])
return self._req('get', uri) |
def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.ab... | def function[set_src_filepath, parameter[self, src_dir_path]]:
constant[
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
]
call[name[log].debug, parameter[constant[set_sr... | keyword[def] identifier[set_src_filepath] ( identifier[self] , identifier[src_dir_path] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[src_dir_path] )
identifier[self] . identifier[abs_src_filepath] = identifier[src_dir_path] . identifier[resolved_pat... | def set_src_filepath(self, src_dir_path):
"""
Set one filepath to backup this file.
Called for every file in the source directory.
:argument src_dir_path: filesystem_walk.DirEntryPath() instance
"""
log.debug("set_src_filepath() with: '%s'", src_dir_path)
self.abs_src_filepa... |
def pad_position_w(self, i):
"""
Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return:
"""
if i >= self.n_pads_w:
raise ModelError("pad index out... | def function[pad_position_w, parameter[self, i]]:
constant[
Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return:
]
if compare[name[i] greater_or_equal[>=] n... | keyword[def] identifier[pad_position_w] ( identifier[self] , identifier[i] ):
literal[string]
keyword[if] identifier[i] >= identifier[self] . identifier[n_pads_w] :
keyword[raise] identifier[ModelError] ( literal[string] )
keyword[return] ( identifier[self] . identifier[widt... | def pad_position_w(self, i):
"""
Determines the position of the ith pad in the width direction.
Assumes equally spaced pads.
:param i: ith number of pad in width direction (0-indexed)
:return:
"""
if i >= self.n_pads_w:
raise ModelError('pad index out-of-bounds')... |
def course_or_program_exist(self, course_id, program_uuid):
"""
Return whether the input course or program exist.
"""
course_exists = course_id and CourseApiClient().get_course_details(course_id)
program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(pro... | def function[course_or_program_exist, parameter[self, course_id, program_uuid]]:
constant[
Return whether the input course or program exist.
]
variable[course_exists] assign[=] <ast.BoolOp object at 0x7da1b0127fd0>
variable[program_exists] assign[=] <ast.BoolOp object at 0x7da1b0... | keyword[def] identifier[course_or_program_exist] ( identifier[self] , identifier[course_id] , identifier[program_uuid] ):
literal[string]
identifier[course_exists] = identifier[course_id] keyword[and] identifier[CourseApiClient] (). identifier[get_course_details] ( identifier[course_id] )
... | def course_or_program_exist(self, course_id, program_uuid):
"""
Return whether the input course or program exist.
"""
course_exists = course_id and CourseApiClient().get_course_details(course_id)
program_exists = program_uuid and CourseCatalogApiServiceClient().program_exists(program_uuid)
... |
def inspect(self):
"""Retreive dictionary of 'Field: Value' attributes"""
results = {}
for fname in dir(self):
if not fname.startswith('_'):
value = getattr(self, fname)
if isinstance(value, collections.Callable):
continue
... | def function[inspect, parameter[self]]:
constant[Retreive dictionary of 'Field: Value' attributes]
variable[results] assign[=] dictionary[[], []]
for taget[name[fname]] in starred[call[name[dir], parameter[name[self]]]] begin[:]
if <ast.UnaryOp object at 0x7da1b06cc970> begin[:]
... | keyword[def] identifier[inspect] ( identifier[self] ):
literal[string]
identifier[results] ={}
keyword[for] identifier[fname] keyword[in] identifier[dir] ( identifier[self] ):
keyword[if] keyword[not] identifier[fname] . identifier[startswith] ( literal[string] ):
... | def inspect(self):
"""Retreive dictionary of 'Field: Value' attributes"""
results = {}
for fname in dir(self):
if not fname.startswith('_'):
value = getattr(self, fname)
if isinstance(value, collections.Callable):
continue # depends on [control=['if'], data=[... |
def nvmlDeviceGetViolationStatus(device, perfPolicyType):
r"""
/**
* Gets the duration of time during which the device was throttled (lower than requested clocks) due to power
* or thermal constraints.
*
* The method is important to users who are tying to understand if their GPUs throttle at... | def function[nvmlDeviceGetViolationStatus, parameter[device, perfPolicyType]]:
constant[
/**
* Gets the duration of time during which the device was throttled (lower than requested clocks) due to power
* or thermal constraints.
*
* The method is important to users who are tying to unders... | keyword[def] identifier[nvmlDeviceGetViolationStatus] ( identifier[device] , identifier[perfPolicyType] ):
literal[string]
identifier[c_perfPolicy_type] = identifier[_nvmlPerfPolicyType_t] ( identifier[perfPolicyType] )
identifier[c_violTime] = identifier[c_nvmlViolationTime_t] ()
identifier[fn] ... | def nvmlDeviceGetViolationStatus(device, perfPolicyType):
"""
/**
* Gets the duration of time during which the device was throttled (lower than requested clocks) due to power
* or thermal constraints.
*
* The method is important to users who are tying to understand if their GPUs throttle at ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.