code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def generate_action(args):
"""Generate action."""
controller = args.get('<controller>')
action = args.get('<action>')
with_template = args.get('-t')
current_path = os.getcwd()
logger.info('Start generating action.')
controller_file_path = os.path.join(current_path, 'application/controllers... | def function[generate_action, parameter[args]]:
constant[Generate action.]
variable[controller] assign[=] call[name[args].get, parameter[constant[<controller>]]]
variable[action] assign[=] call[name[args].get, parameter[constant[<action>]]]
variable[with_template] assign[=] call[name[arg... | keyword[def] identifier[generate_action] ( identifier[args] ):
literal[string]
identifier[controller] = identifier[args] . identifier[get] ( literal[string] )
identifier[action] = identifier[args] . identifier[get] ( literal[string] )
identifier[with_template] = identifier[args] . identifier[get]... | def generate_action(args):
"""Generate action."""
controller = args.get('<controller>')
action = args.get('<action>')
with_template = args.get('-t')
current_path = os.getcwd()
logger.info('Start generating action.')
controller_file_path = os.path.join(current_path, 'application/controllers',... |
def hexdump( source, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, address_base=None ):
"""Print the contents of a byte string in tabular hexadecimal/ASCII format.
source
The byte string to print.
start
Start offset to read from (default: start)
end
... | def function[hexdump, parameter[source, start, end, length, major_len, minor_len, colour, address_base]]:
constant[Print the contents of a byte string in tabular hexadecimal/ASCII format.
source
The byte string to print.
start
Start offset to read from (default: start)
end
... | keyword[def] identifier[hexdump] ( identifier[source] , identifier[start] = keyword[None] , identifier[end] = keyword[None] , identifier[length] = keyword[None] , identifier[major_len] = literal[int] , identifier[minor_len] = literal[int] , identifier[colour] = keyword[True] , identifier[address_base] = keyword[None]... | def hexdump(source, start=None, end=None, length=None, major_len=8, minor_len=4, colour=True, address_base=None):
"""Print the contents of a byte string in tabular hexadecimal/ASCII format.
source
The byte string to print.
start
Start offset to read from (default: start)
end
... |
def p_align(p):
""" asm : ALIGN expr
| ALIGN pexpr
"""
align = p[2].eval()
if align < 2:
error(p.lineno(1), "ALIGN value must be greater than 1")
return
MEMORY.set_org(MEMORY.org + (align - MEMORY.org % align) % align, p.lineno(1)) | def function[p_align, parameter[p]]:
constant[ asm : ALIGN expr
| ALIGN pexpr
]
variable[align] assign[=] call[call[name[p]][constant[2]].eval, parameter[]]
if compare[name[align] less[<] constant[2]] begin[:]
call[name[error], parameter[call[name[p].lineno, param... | keyword[def] identifier[p_align] ( identifier[p] ):
literal[string]
identifier[align] = identifier[p] [ literal[int] ]. identifier[eval] ()
keyword[if] identifier[align] < literal[int] :
identifier[error] ( identifier[p] . identifier[lineno] ( literal[int] ), literal[string] )
keywo... | def p_align(p):
""" asm : ALIGN expr
| ALIGN pexpr
"""
align = p[2].eval()
if align < 2:
error(p.lineno(1), 'ALIGN value must be greater than 1')
return # depends on [control=['if'], data=[]]
MEMORY.set_org(MEMORY.org + (align - MEMORY.org % align) % align, p.lineno(1)) |
def allhexlify(data):
"""Hexlify given data into a string representation with hex values for all chars
Input like
'ab\x04ce'
becomes
'\x61\x62\x04\x63\x65'
"""
hx = binascii.hexlify(data)
return b''.join([b'\\x' + o for o in re.findall(b'..', hx)]) | def function[allhexlify, parameter[data]]:
constant[Hexlify given data into a string representation with hex values for all chars
Input like
'abce'
becomes
'abce'
]
variable[hx] assign[=] call[name[binascii].hexlify, parameter[name[data]]]
return[call[constant[b''].join... | keyword[def] identifier[allhexlify] ( identifier[data] ):
literal[string]
identifier[hx] = identifier[binascii] . identifier[hexlify] ( identifier[data] )
keyword[return] literal[string] . identifier[join] ([ literal[string] + identifier[o] keyword[for] identifier[o] keyword[in] identifier[re] . ... | def allhexlify(data):
"""Hexlify given data into a string representation with hex values for all chars
Input like
'ab\x04ce'
becomes
'ab\x04ce'
"""
hx = binascii.hexlify(data)
return b''.join([b'\\x' + o for o in re.findall(b'..', hx)]) |
def replace_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with renamed keys including keys only found in key_map."""
return {key_map[k]: v for k, v in record.items() if k in key_map} | def function[replace_keys, parameter[record, key_map]]:
constant[New record with renamed keys including keys only found in key_map.]
return[<ast.DictComp object at 0x7da1b184ac20>] | keyword[def] identifier[replace_keys] ( identifier[record] : identifier[Mapping] , identifier[key_map] : identifier[Mapping] )-> identifier[dict] :
literal[string]
keyword[return] { identifier[key_map] [ identifier[k] ]: identifier[v] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[r... | def replace_keys(record: Mapping, key_map: Mapping) -> dict:
"""New record with renamed keys including keys only found in key_map."""
return {key_map[k]: v for (k, v) in record.items() if k in key_map} |
def delete_repository_method(namespace, name, snapshot_id):
"""Redacts a method and all of its associated configurations.
The method should exist in the methods repository.
Args:
namespace (str): Methods namespace
method (str): method name
snapshot_id (int): snapshot_id of the meth... | def function[delete_repository_method, parameter[namespace, name, snapshot_id]]:
constant[Redacts a method and all of its associated configurations.
The method should exist in the methods repository.
Args:
namespace (str): Methods namespace
method (str): method name
snapshot_id... | keyword[def] identifier[delete_repository_method] ( identifier[namespace] , identifier[name] , identifier[snapshot_id] ):
literal[string]
identifier[uri] = literal[string] . identifier[format] ( identifier[namespace] , identifier[name] , identifier[snapshot_id] )
keyword[return] identifier[__delete] ... | def delete_repository_method(namespace, name, snapshot_id):
"""Redacts a method and all of its associated configurations.
The method should exist in the methods repository.
Args:
namespace (str): Methods namespace
method (str): method name
snapshot_id (int): snapshot_id of the meth... |
def Input_setIgnoreInputEvents(self, ignore):
"""
Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return value.
Description: Ignore... | def function[Input_setIgnoreInputEvents, parameter[self, ignore]]:
constant[
Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return... | keyword[def] identifier[Input_setIgnoreInputEvents] ( identifier[self] , identifier[ignore] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[ignore] ,( identifier[bool] ,)
), literal[string] % identifier[type] (
identifier[ignore] )
identifier[subdom_funcs] = identifier[self] . i... | def Input_setIgnoreInputEvents(self, ignore):
"""
Function path: Input.setIgnoreInputEvents
Domain: Input
Method name: setIgnoreInputEvents
Parameters:
Required arguments:
'ignore' (type: boolean) -> Ignores input events processing when set to true.
No return value.
Description: Igno... |
def split_fasta(f, id2f):
"""
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file
"""
opened = {}
for seq in parse_fasta(f):
id = seq[0].split('>')[1].split()[0]
if id not in id2f:
continue
fasta = id2f[id]
... | def function[split_fasta, parameter[f, id2f]]:
constant[
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file
]
variable[opened] assign[=] dictionary[[], []]
for taget[name[seq]] in starred[call[name[parse_fasta], parameter[name[f]]]... | keyword[def] identifier[split_fasta] ( identifier[f] , identifier[id2f] ):
literal[string]
identifier[opened] ={}
keyword[for] identifier[seq] keyword[in] identifier[parse_fasta] ( identifier[f] ):
identifier[id] = identifier[seq] [ literal[int] ]. identifier[split] ( literal[string] )[ li... | def split_fasta(f, id2f):
"""
split fasta file into separate fasta files based on list of scaffolds
that belong to each separate file
"""
opened = {}
for seq in parse_fasta(f):
id = seq[0].split('>')[1].split()[0]
if id not in id2f:
continue # depends on [control=['i... |
def set_detail_level(self, detail_levels):
"""
Sets the detail levels from the input dictionary in detail_levels.
"""
if detail_levels is None:
return
self.detail_levels = detail_levels
if 'api' in detail_levels:
self.api_detail_level = detail_lev... | def function[set_detail_level, parameter[self, detail_levels]]:
constant[
Sets the detail levels from the input dictionary in detail_levels.
]
if compare[name[detail_levels] is constant[None]] begin[:]
return[None]
name[self].detail_levels assign[=] name[detail_levels]
... | keyword[def] identifier[set_detail_level] ( identifier[self] , identifier[detail_levels] ):
literal[string]
keyword[if] identifier[detail_levels] keyword[is] keyword[None] :
keyword[return]
identifier[self] . identifier[detail_levels] = identifier[detail_levels]
... | def set_detail_level(self, detail_levels):
"""
Sets the detail levels from the input dictionary in detail_levels.
"""
if detail_levels is None:
return # depends on [control=['if'], data=[]]
self.detail_levels = detail_levels
if 'api' in detail_levels:
self.api_detail_lev... |
def p_notminus_assignment(self, t):
'''notminus_assignment : IDENT EQ NOTMINUS'''
self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","notMinus"])) | def function[p_notminus_assignment, parameter[self, t]]:
constant[notminus_assignment : IDENT EQ NOTMINUS]
call[name[self].accu.add, parameter[call[name[Term], parameter[constant[obs_vlabel], list[[<ast.Attribute object at 0x7da1b28ae710>, <ast.BinOp object at 0x7da1b28acc10>, <ast.Constant object at 0x... | keyword[def] identifier[p_notminus_assignment] ( identifier[self] , identifier[t] ):
literal[string]
identifier[self] . identifier[accu] . identifier[add] ( identifier[Term] ( literal[string] ,[ identifier[self] . identifier[name] , literal[string] + identifier[t] [ literal[int] ]+ literal[string] , litera... | def p_notminus_assignment(self, t):
"""notminus_assignment : IDENT EQ NOTMINUS"""
self.accu.add(Term('obs_vlabel', [self.name, 'gen("' + t[1] + '")', 'notMinus'])) |
def imbox(xy, w, h, angle=0.0, **kwargs):
"""
draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return:
"""
from matplotlib.patches import Rectangle
return imbound(Rectangle, xy, w, h, angle, **kwargs) | def function[imbox, parameter[xy, w, h, angle]]:
constant[
draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return:
]
from relative_module[matplotlib.patches] import module[Rectangle]
return[call[name[imbound]... | keyword[def] identifier[imbox] ( identifier[xy] , identifier[w] , identifier[h] , identifier[angle] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[matplotlib] . identifier[patches] keyword[import] identifier[Rectangle]
keyword[return] identifier[imbound] ( ident... | def imbox(xy, w, h, angle=0.0, **kwargs):
"""
draw boundary box
:param xy: start index xy (ji)
:param w: width
:param h: height
:param angle:
:param kwargs:
:return:
"""
from matplotlib.patches import Rectangle
return imbound(Rectangle, xy, w, h, angle, **kwargs) |
def twoline2rv(longstr1, longstr2, whichconst, afspc_mode=False):
"""Return a Satellite imported from two lines of TLE data.
Provide the two TLE lines as strings `longstr1` and `longstr2`,
and select which standard set of gravitational constants you want
by providing `gravity_constants`:
`sgp4.ear... | def function[twoline2rv, parameter[longstr1, longstr2, whichconst, afspc_mode]]:
constant[Return a Satellite imported from two lines of TLE data.
Provide the two TLE lines as strings `longstr1` and `longstr2`,
and select which standard set of gravitational constants you want
by providing `gravity_c... | keyword[def] identifier[twoline2rv] ( identifier[longstr1] , identifier[longstr2] , identifier[whichconst] , identifier[afspc_mode] = keyword[False] ):
literal[string]
identifier[deg2rad] = identifier[pi] / literal[int] ;
identifier[xpdotp] = literal[int] /( literal[int] * identifier[pi] );
ide... | def twoline2rv(longstr1, longstr2, whichconst, afspc_mode=False):
"""Return a Satellite imported from two lines of TLE data.
Provide the two TLE lines as strings `longstr1` and `longstr2`,
and select which standard set of gravitational constants you want
by providing `gravity_constants`:
`sgp4.ear... |
def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(":")+1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline()
... | def function[_read_section, parameter[self]]:
constant[Read and return an entire section]
variable[lines] assign[=] list[[<ast.Subscript object at 0x7da20c6aa110>]]
name[self]._last assign[=] call[name[self]._f.readline, parameter[]]
while <ast.BoolOp object at 0x7da20c6ab430> begin[:]
... | keyword[def] identifier[_read_section] ( identifier[self] ):
literal[string]
identifier[lines] =[ identifier[self] . identifier[_last] [ identifier[self] . identifier[_last] . identifier[find] ( literal[string] )+ literal[int] :]]
identifier[self] . identifier[_last] = identifier[self] . i... | def _read_section(self):
"""Read and return an entire section"""
lines = [self._last[self._last.find(':') + 1:]]
self._last = self._f.readline()
while len(self._last) > 0 and len(self._last[0].strip()) == 0:
lines.append(self._last)
self._last = self._f.readline() # depends on [control=... |
def update(self, _values=None, **values):
"""
Update a record in the database
:param values: The values of the update
:type values: dict
:return: The number of records affected
:rtype: int
"""
if _values is not None:
values.update(_values)
... | def function[update, parameter[self, _values]]:
constant[
Update a record in the database
:param values: The values of the update
:type values: dict
:return: The number of records affected
:rtype: int
]
if compare[name[_values] is_not constant[None]] beg... | keyword[def] identifier[update] ( identifier[self] , identifier[_values] = keyword[None] ,** identifier[values] ):
literal[string]
keyword[if] identifier[_values] keyword[is] keyword[not] keyword[None] :
identifier[values] . identifier[update] ( identifier[_values] )
iden... | def update(self, _values=None, **values):
"""
Update a record in the database
:param values: The values of the update
:type values: dict
:return: The number of records affected
:rtype: int
"""
if _values is not None:
values.update(_values) # depends on ... |
def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for domain, attrs in self.header_domains.items():
header_element = document.createElement(
'allow-http-request-headers-from'
)
... | def function[_add_header_domains_xml, parameter[self, document]]:
constant[
Generates the XML elements for allowed header domains.
]
for taget[tuple[[<ast.Name object at 0x7da1b176ab00>, <ast.Name object at 0x7da1b17698a0>]]] in starred[call[name[self].header_domains.items, parameter[]]... | keyword[def] identifier[_add_header_domains_xml] ( identifier[self] , identifier[document] ):
literal[string]
keyword[for] identifier[domain] , identifier[attrs] keyword[in] identifier[self] . identifier[header_domains] . identifier[items] ():
identifier[header_element] = identifier... | def _add_header_domains_xml(self, document):
"""
Generates the XML elements for allowed header domains.
"""
for (domain, attrs) in self.header_domains.items():
header_element = document.createElement('allow-http-request-headers-from')
header_element.setAttribute('domain', domain... |
def __build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T],
logger: Logger = None) -> Parser:
"""
Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_ty... | def function[__build_parser_for_fileobject_and_desiredtype, parameter[self, obj_on_filesystem, object_typ, logger]]:
constant[
Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_type.
To do that, it iterates through all registered parsers in the lis... | keyword[def] identifier[__build_parser_for_fileobject_and_desiredtype] ( identifier[self] , identifier[obj_on_filesystem] : identifier[PersistedObject] , identifier[object_typ] : identifier[Type] [ identifier[T] ],
identifier[logger] : identifier[Logger] = keyword[None] )-> identifier[Parser] :
literal[stri... | def __build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T], logger: Logger=None) -> Parser:
"""
Builds from the registry, a parser to parse object obj_on_filesystem as an object of type object_type.
To do that, it iterates through all registered ... |
def from_file(filename, use_cores=True, thresh=1.e-4):
"""
Reads an xr-formatted file to create an Xr object.
Args:
filename (str): name of file to read from.
use_cores (bool): use core positions and discard shell
positions if set to True (default). ... | def function[from_file, parameter[filename, use_cores, thresh]]:
constant[
Reads an xr-formatted file to create an Xr object.
Args:
filename (str): name of file to read from.
use_cores (bool): use core positions and discard shell
positions if set to T... | keyword[def] identifier[from_file] ( identifier[filename] , identifier[use_cores] = keyword[True] , identifier[thresh] = literal[int] ):
literal[string]
keyword[with] identifier[zopen] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
keyword[return] identifier[... | def from_file(filename, use_cores=True, thresh=0.0001):
"""
Reads an xr-formatted file to create an Xr object.
Args:
filename (str): name of file to read from.
use_cores (bool): use core positions and discard shell
positions if set to True (default). Oth... |
def _exec_info(self):
"""
Caching wrapper around client.exec_inspect
"""
if self._info is None:
self._info = self.client.exec_inspect(self.exec_id)
return self._info | def function[_exec_info, parameter[self]]:
constant[
Caching wrapper around client.exec_inspect
]
if compare[name[self]._info is constant[None]] begin[:]
name[self]._info assign[=] call[name[self].client.exec_inspect, parameter[name[self].exec_id]]
return[name[self]._... | keyword[def] identifier[_exec_info] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_info] keyword[is] keyword[None] :
identifier[self] . identifier[_info] = identifier[self] . identifier[client] . identifier[exec_inspect] ( identifier[self] . identif... | def _exec_info(self):
"""
Caching wrapper around client.exec_inspect
"""
if self._info is None:
self._info = self.client.exec_inspect(self.exec_id) # depends on [control=['if'], data=[]]
return self._info |
def calculate_size(name, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size | def function[calculate_size, parameter[name, thread_id]]:
constant[ Calculates the request payload size]
variable[data_size] assign[=] constant[0]
<ast.AugAssign object at 0x7da1b26ad960>
<ast.AugAssign object at 0x7da1b26ac310>
return[name[data_size]] | keyword[def] identifier[calculate_size] ( identifier[name] , identifier[thread_id] ):
literal[string]
identifier[data_size] = literal[int]
identifier[data_size] += identifier[calculate_size_str] ( identifier[name] )
identifier[data_size] += identifier[LONG_SIZE_IN_BYTES]
keyword[return] i... | def calculate_size(name, thread_id):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size |
def GetTypeManager(self):
""" Get dynamic type manager """
dynTypeMgr = None
if self.hostSystem:
try:
dynTypeMgr = self.hostSystem.RetrieveDynamicTypeManager()
except vmodl.fault.MethodNotFound as err:
pass
if not dynTypeMgr:
# Older host not s... | def function[GetTypeManager, parameter[self]]:
constant[ Get dynamic type manager ]
variable[dynTypeMgr] assign[=] constant[None]
if name[self].hostSystem begin[:]
<ast.Try object at 0x7da18ede7880>
if <ast.UnaryOp object at 0x7da18ede7cd0> begin[:]
variable[cmdli... | keyword[def] identifier[GetTypeManager] ( identifier[self] ):
literal[string]
identifier[dynTypeMgr] = keyword[None]
keyword[if] identifier[self] . identifier[hostSystem] :
keyword[try] :
identifier[dynTypeMgr] = identifier[self] . identifier[hostSystem] . identifier[Ret... | def GetTypeManager(self):
""" Get dynamic type manager """
dynTypeMgr = None
if self.hostSystem:
try:
dynTypeMgr = self.hostSystem.RetrieveDynamicTypeManager() # depends on [control=['try'], data=[]]
except vmodl.fault.MethodNotFound as err:
pass # depends on [contr... |
def can_user_approve_this_page(self, user):
"""Check if a user can approve this page."""
self.ensure_one()
# if it's not required, anyone can approve
if not self.is_approval_required:
return True
# if user belongs to 'Knowledge / Manager', he can approve anything
... | def function[can_user_approve_this_page, parameter[self, user]]:
constant[Check if a user can approve this page.]
call[name[self].ensure_one, parameter[]]
if <ast.UnaryOp object at 0x7da18f58e980> begin[:]
return[constant[True]]
if call[name[user].has_group, parameter[constant[do... | keyword[def] identifier[can_user_approve_this_page] ( identifier[self] , identifier[user] ):
literal[string]
identifier[self] . identifier[ensure_one] ()
keyword[if] keyword[not] identifier[self] . identifier[is_approval_required] :
keyword[return] keyword[True]
... | def can_user_approve_this_page(self, user):
"""Check if a user can approve this page."""
self.ensure_one()
# if it's not required, anyone can approve
if not self.is_approval_required:
return True # depends on [control=['if'], data=[]]
# if user belongs to 'Knowledge / Manager', he can appro... |
def ensure_str(s):
r""" Ensure that s is a str and not a bytes (.decode() if necessary)
>>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
"I'm 2. When I grow up I want to be a str!"
>>> ensure_str(42)
'42'
"""
try:
return s.decode()
except AttributeError:
if i... | def function[ensure_str, parameter[s]]:
constant[ Ensure that s is a str and not a bytes (.decode() if necessary)
>>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
"I'm 2. When I grow up I want to be a str!"
>>> ensure_str(42)
'42'
]
<ast.Try object at 0x7da2054a69e0>
ret... | keyword[def] identifier[ensure_str] ( identifier[s] ):
literal[string]
keyword[try] :
keyword[return] identifier[s] . identifier[decode] ()
keyword[except] identifier[AttributeError] :
keyword[if] identifier[isinstance] ( identifier[s] , identifier[str] ):
keyword[ret... | def ensure_str(s):
""" Ensure that s is a str and not a bytes (.decode() if necessary)
>>> ensure_str(b"I'm 2. When I grow up I want to be a str!")
"I'm 2. When I grow up I want to be a str!"
>>> ensure_str(42)
'42'
"""
try:
return s.decode() # depends on [control=['try'], data=[]]... |
def pid(self):
"""
The integer PID of the subprocess or None.
"""
pf = self.path('cmd.pid')
if not os.path.exists(pf):
return None
with open(pf, 'r') as f:
return int(f.read()) | def function[pid, parameter[self]]:
constant[
The integer PID of the subprocess or None.
]
variable[pf] assign[=] call[name[self].path, parameter[constant[cmd.pid]]]
if <ast.UnaryOp object at 0x7da204565450> begin[:]
return[constant[None]]
with call[name[open], pa... | keyword[def] identifier[pid] ( identifier[self] ):
literal[string]
identifier[pf] = identifier[self] . identifier[path] ( literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[pf] ):
keyword[return] keyword[None]
... | def pid(self):
"""
The integer PID of the subprocess or None.
"""
pf = self.path('cmd.pid')
if not os.path.exists(pf):
return None # depends on [control=['if'], data=[]]
with open(pf, 'r') as f:
return int(f.read()) # depends on [control=['with'], data=['f']] |
def _bool_encode(self, d):
"""
Converts bool values to lowercase strings
"""
for k, v in d.items():
if isinstance(v, bool):
d[k] = str(v).lower()
return d | def function[_bool_encode, parameter[self, d]]:
constant[
Converts bool values to lowercase strings
]
for taget[tuple[[<ast.Name object at 0x7da1b0e0ee00>, <ast.Name object at 0x7da1b0e0e980>]]] in starred[call[name[d].items, parameter[]]] begin[:]
if call[name[i... | keyword[def] identifier[_bool_encode] ( identifier[self] , identifier[d] ):
literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d] . identifier[items] ():
keyword[if] identifier[isinstance] ( identifier[v] , identifier[bool] ):
identif... | def _bool_encode(self, d):
"""
Converts bool values to lowercase strings
"""
for (k, v) in d.items():
if isinstance(v, bool):
d[k] = str(v).lower() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]]
return d |
def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False):
"""Upload the results of training (as automatically recorded by your
env's monitor) to OpenAI Gym.
Args:
training_dir (Optional[str]): A directory containing the results of a training run.
a... | def function[upload, parameter[training_dir, algorithm_id, writeup, api_key, ignore_open_monitors]]:
constant[Upload the results of training (as automatically recorded by your
env's monitor) to OpenAI Gym.
Args:
training_dir (Optional[str]): A directory containing the results of a training run.... | keyword[def] identifier[upload] ( identifier[training_dir] , identifier[algorithm_id] = keyword[None] , identifier[writeup] = keyword[None] , identifier[api_key] = keyword[None] , identifier[ignore_open_monitors] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[ignore_open_monitor... | def upload(training_dir, algorithm_id=None, writeup=None, api_key=None, ignore_open_monitors=False):
"""Upload the results of training (as automatically recorded by your
env's monitor) to OpenAI Gym.
Args:
training_dir (Optional[str]): A directory containing the results of a training run.
a... |
def VRRPNewMaster_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
VRRPNewMaster = ET.SubElement(config, "VRRPNewMaster", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info = ET.SubEl... | def function[VRRPNewMaster_originator_switch_info_switchIpV4Address, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[VRRPNewMaster] assign[=] call[name[ET].SubElement, parameter[name[config], constan... | keyword[def] identifier[VRRPNewMaster_originator_switch_info_switchIpV4Address] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[VRRPNewMaster] = identifier[ET] . identifier[SubElement] ( i... | def VRRPNewMaster_originator_switch_info_switchIpV4Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
VRRPNewMaster = ET.SubElement(config, 'VRRPNewMaster', xmlns='http://brocade.com/ns/brocade-notification-stream')
originator_switch_info = ET.SubElement(VRRPNewMas... |
def fetch_list_members(list_url):
""" Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education """
match = re.match(r'.+twitter\.com\/(.+)\/lists\/(.+)', list_url)
if not match:
print('cannot parse list url %s' % list_url)
return ... | def function[fetch_list_members, parameter[list_url]]:
constant[ Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education ]
variable[match] assign[=] call[name[re].match, parameter[constant[.+twitter\.com\/(.+)\/lists\/(.+)], name[list_url]]]... | keyword[def] identifier[fetch_list_members] ( identifier[list_url] ):
literal[string]
identifier[match] = identifier[re] . identifier[match] ( literal[string] , identifier[list_url] )
keyword[if] keyword[not] identifier[match] :
identifier[print] ( literal[string] % identifier[list_url] )
... | def fetch_list_members(list_url):
""" Get all members of the list specified by the given url. E.g., https://twitter.com/lore77/lists/libri-cultura-education """
match = re.match('.+twitter\\.com\\/(.+)\\/lists\\/(.+)', list_url)
if not match:
print('cannot parse list url %s' % list_url)
retu... |
def _to_output_code(self):
"""Return a unicode object with the Gremlin/MATCH representation of this Literal."""
# All supported Literal objects serialize to identical strings both in Gremlin and MATCH.
self.validate()
if self.value is None:
return u'null'
elif self.va... | def function[_to_output_code, parameter[self]]:
constant[Return a unicode object with the Gremlin/MATCH representation of this Literal.]
call[name[self].validate, parameter[]]
if compare[name[self].value is constant[None]] begin[:]
return[constant[null]]
<ast.Raise object at 0x7da1b1... | keyword[def] identifier[_to_output_code] ( identifier[self] ):
literal[string]
identifier[self] . identifier[validate] ()
keyword[if] identifier[self] . identifier[value] keyword[is] keyword[None] :
keyword[return] literal[string]
keyword[elif] identifi... | def _to_output_code(self):
"""Return a unicode object with the Gremlin/MATCH representation of this Literal."""
# All supported Literal objects serialize to identical strings both in Gremlin and MATCH.
self.validate()
if self.value is None:
return u'null' # depends on [control=['if'], data=[]]
... |
def get_instance_of(self, model_cls):
"""
Search the data to find a instance
of a model specified in the template
"""
for obj in self.data.values():
if isinstance(obj, model_cls):
return obj
LOGGER.error('Context Not Found')
raise Excep... | def function[get_instance_of, parameter[self, model_cls]]:
constant[
Search the data to find a instance
of a model specified in the template
]
for taget[name[obj]] in starred[call[name[self].data.values, parameter[]]] begin[:]
if call[name[isinstance], parameter[n... | keyword[def] identifier[get_instance_of] ( identifier[self] , identifier[model_cls] ):
literal[string]
keyword[for] identifier[obj] keyword[in] identifier[self] . identifier[data] . identifier[values] ():
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[model_cls] ... | def get_instance_of(self, model_cls):
"""
Search the data to find a instance
of a model specified in the template
"""
for obj in self.data.values():
if isinstance(obj, model_cls):
return obj # depends on [control=['if'], data=[]] # depends on [control=['for'], data=... |
def _try_recover(self, trial, error_msg):
"""Tries to recover trial.
Notifies SearchAlgorithm and Scheduler if failure to recover.
Args:
trial (Trial): Trial to recover.
error_msg (str): Error message from prior to invoking this method.
"""
try:
... | def function[_try_recover, parameter[self, trial, error_msg]]:
constant[Tries to recover trial.
Notifies SearchAlgorithm and Scheduler if failure to recover.
Args:
trial (Trial): Trial to recover.
error_msg (str): Error message from prior to invoking this method.
... | keyword[def] identifier[_try_recover] ( identifier[self] , identifier[trial] , identifier[error_msg] ):
literal[string]
keyword[try] :
identifier[self] . identifier[trial_executor] . identifier[stop_trial] (
identifier[trial] ,
identifier[error] = identifier[e... | def _try_recover(self, trial, error_msg):
"""Tries to recover trial.
Notifies SearchAlgorithm and Scheduler if failure to recover.
Args:
trial (Trial): Trial to recover.
error_msg (str): Error message from prior to invoking this method.
"""
try:
self.tri... |
def unassign_item_from_bank(self, item_id, bank_id):
"""Removes an ``Item`` from a ``Bank``.
arg: item_id (osid.id.Id): the ``Id`` of the ``Item``
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
raise: NotFound - ``item_id`` or ``bank_id`` not found or
``ite... | def function[unassign_item_from_bank, parameter[self, item_id, bank_id]]:
constant[Removes an ``Item`` from a ``Bank``.
arg: item_id (osid.id.Id): the ``Id`` of the ``Item``
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
raise: NotFound - ``item_id`` or ``bank_id`` not fou... | keyword[def] identifier[unassign_item_from_bank] ( identifier[self] , identifier[item_id] , identifier[bank_id] ):
literal[string]
identifier[mgr] = identifier[self] . identifier[_get_provider_manager] ( literal[string] , identifier[local] = keyword[True] )
identifier[loo... | def unassign_item_from_bank(self, item_id, bank_id):
"""Removes an ``Item`` from a ``Bank``.
arg: item_id (osid.id.Id): the ``Id`` of the ``Item``
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
raise: NotFound - ``item_id`` or ``bank_id`` not found or
``item_id... |
def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1,
**kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at orig... | def function[calculate_pore_shape, parameter[elements, coordinates, adjust, increment]]:
constant[Return average diameter for a molecule.]
variable[coordinates] assign[=] call[name[deepcopy], parameter[name[coordinates]]]
variable[origin] assign[=] call[name[np].array, parameter[list[[<ast.Const... | keyword[def] identifier[calculate_pore_shape] ( identifier[elements] , identifier[coordinates] , identifier[adjust] = literal[int] , identifier[increment] = literal[int] ,
** identifier[kwargs] ):
literal[string]
identifier[coordinates] = identifier[deepcopy] ( identifier[coordinates] )
iden... | def calculate_pore_shape(elements, coordinates, adjust=1, increment=0.1, **kwargs):
"""Return average diameter for a molecule."""
# Copy the coordinates as will perform many opertaions on them
coordinates = deepcopy(coordinates)
# Center of our cartesian system is always at origin
origin = np.array(... |
def _get_stmt_by_group(self, stmt_type, stmts_this_type, eh):
"""Group Statements of `stmt_type` by their hierarchical relations."""
# Dict of stmt group key tuples, indexed by their first Agent
stmt_by_first = collections.defaultdict(lambda: [])
# Dict of stmt group key tuples, indexed ... | def function[_get_stmt_by_group, parameter[self, stmt_type, stmts_this_type, eh]]:
constant[Group Statements of `stmt_type` by their hierarchical relations.]
variable[stmt_by_first] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b2347550>]]
variable[stmt_by_s... | keyword[def] identifier[_get_stmt_by_group] ( identifier[self] , identifier[stmt_type] , identifier[stmts_this_type] , identifier[eh] ):
literal[string]
identifier[stmt_by_first] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[])
identifier[stmt_by... | def _get_stmt_by_group(self, stmt_type, stmts_this_type, eh):
"""Group Statements of `stmt_type` by their hierarchical relations."""
# Dict of stmt group key tuples, indexed by their first Agent
stmt_by_first = collections.defaultdict(lambda : [])
# Dict of stmt group key tuples, indexed by their second... |
def iter_instances(self):
"""Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object
"""
for wrkey in set(self.keys()):
obj = self.get(wrkey)
if obj is None:
... | def function[iter_instances, parameter[self]]:
constant[Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object
]
for taget[name[wrkey]] in starred[call[name[set], parameter[call[name[self].ke... | keyword[def] identifier[iter_instances] ( identifier[self] ):
literal[string]
keyword[for] identifier[wrkey] keyword[in] identifier[set] ( identifier[self] . identifier[keys] ()):
identifier[obj] = identifier[self] . identifier[get] ( identifier[wrkey] )
keyword[if] id... | def iter_instances(self):
"""Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object
"""
for wrkey in set(self.keys()):
obj = self.get(wrkey)
if obj is None:
continue # de... |
def colorlogs(format="short"):
"""Append a rainbow logging handler and a formatter to the root logger"""
try:
from rainbow_logging_handler import RainbowLoggingHandler
import sys
# setup `RainbowLoggingHandler`
logger = logging.root
# same as default
if format == ... | def function[colorlogs, parameter[format]]:
constant[Append a rainbow logging handler and a formatter to the root logger]
<ast.Try object at 0x7da1b26a2ad0> | keyword[def] identifier[colorlogs] ( identifier[format] = literal[string] ):
literal[string]
keyword[try] :
keyword[from] identifier[rainbow_logging_handler] keyword[import] identifier[RainbowLoggingHandler]
keyword[import] identifier[sys]
identifier[logger] = iden... | def colorlogs(format='short'):
"""Append a rainbow logging handler and a formatter to the root logger"""
try:
from rainbow_logging_handler import RainbowLoggingHandler
import sys
# setup `RainbowLoggingHandler`
logger = logging.root
# same as default
if format == ... |
def query(self, q, data=None, union=True, limit=None):
"""
Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
... | def function[query, parameter[self, q, data, union, limit]]:
constant[
Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to th... | keyword[def] identifier[query] ( identifier[self] , identifier[q] , identifier[data] = keyword[None] , identifier[union] = keyword[True] , identifier[limit] = keyword[None] ):
literal[string]
keyword[if] identifier[data] :
identifier[q] = identifier[self] . identifier[_apply_handlebar... | def query(self, q, data=None, union=True, limit=None):
"""
Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
te... |
def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
return Client(
server=server[0],
authport=server[1],
secret=server[2],
dict=sel... | def function[_get_client, parameter[self, server]]:
constant[
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
]
return[call[name[Client], parameter[]]] | keyword[def] identifier[_get_client] ( identifier[self] , identifier[server] ):
literal[string]
keyword[return] identifier[Client] (
identifier[server] = identifier[server] [ literal[int] ],
identifier[authport] = identifier[server] [ literal[int] ],
identifier[secret] =... | def _get_client(self, server):
"""
Get the pyrad client for a given server. RADIUS server is described by
a 3-tuple: (<hostname>, <port>, <secret>).
"""
return Client(server=server[0], authport=server[1], secret=server[2], dict=self._get_dictionary()) |
def _transform_abstract(plpy, module_ident):
"""Transform abstract, bi-directionally.
Transforms an abstract using one of content columns
('abstract' or 'html') to determine which direction the transform
will go (cnxml->html or html->cnxml).
A transform is done on either one of them to make
the... | def function[_transform_abstract, parameter[plpy, module_ident]]:
constant[Transform abstract, bi-directionally.
Transforms an abstract using one of content columns
('abstract' or 'html') to determine which direction the transform
will go (cnxml->html or html->cnxml).
A transform is done on eit... | keyword[def] identifier[_transform_abstract] ( identifier[plpy] , identifier[module_ident] ):
literal[string]
identifier[plan] = identifier[plpy] . identifier[prepare] ( literal[string] ,( literal[string] ,))
identifier[result] = identifier[plpy] . identifier[execute] ( identifier[plan] ,( identifier[... | def _transform_abstract(plpy, module_ident):
"""Transform abstract, bi-directionally.
Transforms an abstract using one of content columns
('abstract' or 'html') to determine which direction the transform
will go (cnxml->html or html->cnxml).
A transform is done on either one of them to make
the... |
def add(name, gid=None, **kwargs):
'''
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
'''
### NOTE: **kwargs isn't used here but needs to be included in this
### function for compatibility with the group.present state
if info(name):
... | def function[add, parameter[name, gid]]:
constant[
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
]
if call[name[info], parameter[name[name]]] begin[:]
<ast.Raise object at 0x7da18ede47c0>
if call[name[salt].utils.stringut... | keyword[def] identifier[add] ( identifier[name] , identifier[gid] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[info] ( identifier[name] ):
keyword[raise] identifier[CommandExecutionError] (
literal[string] . identifier[format] ( identifier[n... | def add(name, gid=None, **kwargs):
"""
Add the specified group
CLI Example:
.. code-block:: bash
salt '*' group.add foo 3456
"""
### NOTE: **kwargs isn't used here but needs to be included in this
### function for compatibility with the group.present state
if info(name):
... |
def asynchronous(self, fun, low, user='UNKNOWN', pub=None):
'''
Execute the function in a multiprocess and return the event tag to use
to watch for the return
'''
async_pub = pub if pub is not None else self._gen_async_pub()
proc = salt.utils.process.SignalHandlingMultip... | def function[asynchronous, parameter[self, fun, low, user, pub]]:
constant[
Execute the function in a multiprocess and return the event tag to use
to watch for the return
]
variable[async_pub] assign[=] <ast.IfExp object at 0x7da18bccb8e0>
variable[proc] assign[=] call[na... | keyword[def] identifier[asynchronous] ( identifier[self] , identifier[fun] , identifier[low] , identifier[user] = literal[string] , identifier[pub] = keyword[None] ):
literal[string]
identifier[async_pub] = identifier[pub] keyword[if] identifier[pub] keyword[is] keyword[not] keyword[None] key... | def asynchronous(self, fun, low, user='UNKNOWN', pub=None):
"""
Execute the function in a multiprocess and return the event tag to use
to watch for the return
"""
async_pub = pub if pub is not None else self._gen_async_pub()
proc = salt.utils.process.SignalHandlingMultiprocessingProc... |
def _add_group(self, group, attrs):
"""
:param group: group_name
:param attrs:
:return:
"""
self.handle.create_group(group)
if attrs is not None:
self._add_attributes(group, attrs) | def function[_add_group, parameter[self, group, attrs]]:
constant[
:param group: group_name
:param attrs:
:return:
]
call[name[self].handle.create_group, parameter[name[group]]]
if compare[name[attrs] is_not constant[None]] begin[:]
call[name[self]... | keyword[def] identifier[_add_group] ( identifier[self] , identifier[group] , identifier[attrs] ):
literal[string]
identifier[self] . identifier[handle] . identifier[create_group] ( identifier[group] )
keyword[if] identifier[attrs] keyword[is] keyword[not] keyword[None] :
i... | def _add_group(self, group, attrs):
"""
:param group: group_name
:param attrs:
:return:
"""
self.handle.create_group(group)
if attrs is not None:
self._add_attributes(group, attrs) # depends on [control=['if'], data=['attrs']] |
def get_type_string(item):
"""Return type string of an object."""
if isinstance(item, DataFrame):
return "DataFrame"
if isinstance(item, Index):
return type(item).__name__
if isinstance(item, Series):
return "Series"
found = re.findall(r"<(?:type|class) '(\S*)'>",
... | def function[get_type_string, parameter[item]]:
constant[Return type string of an object.]
if call[name[isinstance], parameter[name[item], name[DataFrame]]] begin[:]
return[constant[DataFrame]]
if call[name[isinstance], parameter[name[item], name[Index]]] begin[:]
return[call[nam... | keyword[def] identifier[get_type_string] ( identifier[item] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[item] , identifier[DataFrame] ):
keyword[return] literal[string]
keyword[if] identifier[isinstance] ( identifier[item] , identifier[Index] ):
keyword[ret... | def get_type_string(item):
"""Return type string of an object."""
if isinstance(item, DataFrame):
return 'DataFrame' # depends on [control=['if'], data=[]]
if isinstance(item, Index):
return type(item).__name__ # depends on [control=['if'], data=[]]
if isinstance(item, Series):
... |
def getResourceValue(self,ep,res,cbfn="",noResp=False,cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optional - s... | def function[getResourceValue, parameter[self, ep, res, cbfn, noResp, cacheOnly]]:
constant[
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bo... | keyword[def] identifier[getResourceValue] ( identifier[self] , identifier[ep] , identifier[res] , identifier[cbfn] = literal[string] , identifier[noResp] = keyword[False] , identifier[cacheOnly] = keyword[False] ):
literal[string]
identifier[q] ={}
identifier[result] = identifier[asyncResult] ( identifier[c... | def getResourceValue(self, ep, res, cbfn='', noResp=False, cacheOnly=False):
"""
Get value of a specific resource on a specific endpoint.
:param str ep: name of endpoint
:param str res: name of resource
:param fnptr cbfn: Optional - callback function to be called on completion
:param bool noResp: Optio... |
def single_side_pathway_enrichment(pathway_definitions,
gene_signature,
n_genes):
"""Identify overrepresented pathways using the Fisher's exact test for
significance on a given pathway definition and gene signature.
(FDR correction for mu... | def function[single_side_pathway_enrichment, parameter[pathway_definitions, gene_signature, n_genes]]:
constant[Identify overrepresented pathways using the Fisher's exact test for
significance on a given pathway definition and gene signature.
(FDR correction for multiple testing is applied in
`_sign... | keyword[def] identifier[single_side_pathway_enrichment] ( identifier[pathway_definitions] ,
identifier[gene_signature] ,
identifier[n_genes] ):
literal[string]
keyword[if] keyword[not] identifier[gene_signature] :
keyword[return] identifier[pd] . identifier[Series] ( identifier[name] = litera... | def single_side_pathway_enrichment(pathway_definitions, gene_signature, n_genes):
"""Identify overrepresented pathways using the Fisher's exact test for
significance on a given pathway definition and gene signature.
(FDR correction for multiple testing is applied in
`_significant_pathways_dataframe`).
... |
def cluster_node_present(name, node, extra_args=None):
'''
Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
node... | def function[cluster_node_present, parameter[name, node, extra_args]]:
constant[
Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__n... | keyword[def] identifier[cluster_node_present] ( identifier[name] , identifier[node] , identifier[extra_args] = keyword[None] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] , literal[string] : keyword[True] , literal[string] : literal[string] , literal[string] :{}}
identifier... | def cluster_node_present(name, node, extra_args=None):
"""
Add a node to the Pacemaker cluster via PCS
Should be run on one cluster node only
(there may be races)
Can only be run on a already setup/added node
name
Irrelevant, not used (recommended: pcs_setup__node_add_{{node}})
node... |
def scan_list(self, start_time=None, end_time=None, **kwargs):
"""List scans stored in Security Center in a given time range.
Time is given in UNIX timestamps, assumed to be UTC. If a `datetime` is
passed it is converted. If `end_time` is not specified it is NOW. If
`start_time` is not ... | def function[scan_list, parameter[self, start_time, end_time]]:
constant[List scans stored in Security Center in a given time range.
Time is given in UNIX timestamps, assumed to be UTC. If a `datetime` is
passed it is converted. If `end_time` is not specified it is NOW. If
`start_time` ... | keyword[def] identifier[scan_list] ( identifier[self] , identifier[start_time] = keyword[None] , identifier[end_time] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
identifier[end_time] = identifier[datetime] . identifier[utcfromtimestamp] ( identifier[int] (... | def scan_list(self, start_time=None, end_time=None, **kwargs):
"""List scans stored in Security Center in a given time range.
Time is given in UNIX timestamps, assumed to be UTC. If a `datetime` is
passed it is converted. If `end_time` is not specified it is NOW. If
`start_time` is not spec... |
def Vm(self):
r'''Molar volume of the chemical at its current phase and
temperature and pressure, in units of [m^3/mol].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`thermo.volume.VolumeGas` to per... | def function[Vm, parameter[self]]:
constant[Molar volume of the chemical at its current phase and
temperature and pressure, in units of [m^3/mol].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`therm... | keyword[def] identifier[Vm] ( identifier[self] ):
literal[string]
keyword[return] identifier[phase_select_property] ( identifier[phase] = identifier[self] . identifier[phase] , identifier[s] = identifier[self] . identifier[Vms] , identifier[l] = identifier[self] . identifier[Vml] , identifier[g] =... | def Vm(self):
"""Molar volume of the chemical at its current phase and
temperature and pressure, in units of [m^3/mol].
Utilizes the object oriented interfaces
:obj:`thermo.volume.VolumeSolid`,
:obj:`thermo.volume.VolumeLiquid`,
and :obj:`thermo.volume.VolumeGas` to perform ... |
def read(self, size=None):
"""
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or None, read until EOF is reached.
Return an empty string at EOF.
"""
if size is None or size < 0:
return "".join(list(self))
... | def function[read, parameter[self, size]]:
constant[
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or None, read until EOF is reached.
Return an empty string at EOF.
]
if <ast.BoolOp object at 0x7da1b1190cd0> begin[:]
... | keyword[def] identifier[read] ( identifier[self] , identifier[size] = keyword[None] ):
literal[string]
keyword[if] identifier[size] keyword[is] keyword[None] keyword[or] identifier[size] < literal[int] :
keyword[return] literal[string] . identifier[join] ( identifier[list] ( iden... | def read(self, size=None):
"""
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or None, read until EOF is reached.
Return an empty string at EOF.
"""
if size is None or size < 0:
return ''.join(list(self)) # depends on [co... |
def send(self, picture, *args):
"""
Send a 'picture' message to the socket (or actor). The picture is a
string that defines the type of each frame. This makes it easy to send
a complex multiframe message in one call. The picture can contain any
of these characters, each corresponding to one or two argum... | def function[send, parameter[self, picture]]:
constant[
Send a 'picture' message to the socket (or actor). The picture is a
string that defines the type of each frame. This makes it easy to send
a complex multiframe message in one call. The picture can contain any
of these characters, each corresponding... | keyword[def] identifier[send] ( identifier[self] , identifier[picture] ,* identifier[args] ):
literal[string]
keyword[return] identifier[lib] . identifier[zsock_send] ( identifier[self] . identifier[_as_parameter_] , identifier[picture] ,* identifier[args] ) | def send(self, picture, *args):
"""
Send a 'picture' message to the socket (or actor). The picture is a
string that defines the type of each frame. This makes it easy to send
a complex multiframe message in one call. The picture can contain any
of these characters, each corresponding to one or two arguments... |
def get_transform(offset, scale):
'''
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix re... | def function[get_transform, parameter[offset, scale]]:
constant[
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
... | keyword[def] identifier[get_transform] ( identifier[offset] , identifier[scale] ):
literal[string]
keyword[return] identifier[pd] . identifier[DataFrame] ([[ identifier[scale] , literal[int] , identifier[offset] . identifier[x] ],[ literal[int] , identifier[scale] , identifier[offset] . identifier[y] ],
... | def get_transform(offset, scale):
"""
Parameters
----------
offset : pandas.Series
Cartesian ``(x, y)`` coordinate of offset origin.
scale : pandas.Series
Scaling factor for ``x`` and ``y`` dimensions.
Returns
-------
pandas.DataFrame
3x3 transformation matrix re... |
def list_subadressen_by_huisnummer(self, huisnummer):
'''
List all `subadressen` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the \
`subadressen` are wanted. OR A huisnummer id.
:rtype: A :class:`list` of :class:`Gebouw`
'''
... | def function[list_subadressen_by_huisnummer, parameter[self, huisnummer]]:
constant[
List all `subadressen` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the `subadressen` are wanted. OR A huisnummer id.
:rtype: A :class:`list` of :class:`Ge... | keyword[def] identifier[list_subadressen_by_huisnummer] ( identifier[self] , identifier[huisnummer] ):
literal[string]
keyword[try] :
identifier[id] = identifier[huisnummer] . identifier[id]
keyword[except] identifier[AttributeError] :
identifier[id] = identifie... | def list_subadressen_by_huisnummer(self, huisnummer):
"""
List all `subadressen` for a :class:`Huisnummer`.
:param huisnummer: The :class:`Huisnummer` for which the `subadressen` are wanted. OR A huisnummer id.
:rtype: A :class:`list` of :class:`Gebouw`
"""
try:
... |
def find_connection(self):
'''find an antenna tracker connection if possible'''
if self.connection is not None:
return self.connection
for m in self.mpstate.mav_master:
if 'HEARTBEAT' in m.messages:
if m.messages['HEARTBEAT'].type == mavutil.mavlink.MAV_TY... | def function[find_connection, parameter[self]]:
constant[find an antenna tracker connection if possible]
if compare[name[self].connection is_not constant[None]] begin[:]
return[name[self].connection]
for taget[name[m]] in starred[name[self].mpstate.mav_master] begin[:]
if... | keyword[def] identifier[find_connection] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[connection] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[connection]
keyword[for] identifier[m] keyword[in... | def find_connection(self):
"""find an antenna tracker connection if possible"""
if self.connection is not None:
return self.connection # depends on [control=['if'], data=[]]
for m in self.mpstate.mav_master:
if 'HEARTBEAT' in m.messages:
if m.messages['HEARTBEAT'].type == mavuti... |
def _get_os_properties():
"""Retrieve distribution properties.
**Note that platform.linux_distribution and platform.dist are deprecated
and will be removed in Python 3.7. By that time, distro will become
mandatory.
"""
if IS_DISTRO_INSTALLED:
return distro.linux_distribution(full_distri... | def function[_get_os_properties, parameter[]]:
constant[Retrieve distribution properties.
**Note that platform.linux_distribution and platform.dist are deprecated
and will be removed in Python 3.7. By that time, distro will become
mandatory.
]
if name[IS_DISTRO_INSTALLED] begin[:]
... | keyword[def] identifier[_get_os_properties] ():
literal[string]
keyword[if] identifier[IS_DISTRO_INSTALLED] :
keyword[return] identifier[distro] . identifier[linux_distribution] ( identifier[full_distribution_name] = keyword[False] )
keyword[return] identifier[platform] . identifier[linux_... | def _get_os_properties():
"""Retrieve distribution properties.
**Note that platform.linux_distribution and platform.dist are deprecated
and will be removed in Python 3.7. By that time, distro will become
mandatory.
"""
if IS_DISTRO_INSTALLED:
return distro.linux_distribution(full_distri... |
def get_security_group_id(self, name):
"""
Take name string, give back security group ID.
To get around VPC's API being stupid.
"""
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in s... | def function[get_security_group_id, parameter[self, name]]:
constant[
Take name string, give back security group ID.
To get around VPC's API being stupid.
]
if <ast.UnaryOp object at 0x7da18bc729b0> begin[:]
name[self]._security_groups assign[=] dictionary[[], []... | keyword[def] identifier[get_security_group_id] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[_security_groups] ={}
keyword[for] identif... | def get_security_group_id(self, name):
"""
Take name string, give back security group ID.
To get around VPC's API being stupid.
"""
# Memoize entire list of groups
if not hasattr(self, '_security_groups'):
self._security_groups = {}
for group in self.get_all_security... |
def _save_group_field(self, field_type, group):
"""This method packs a group field"""
if field_type == 0x0000:
# Ignored (commentar block)
pass
elif field_type == 0x0001:
if group.id_ is not None:
return (4, struct.pack('<I', group.id_... | def function[_save_group_field, parameter[self, field_type, group]]:
constant[This method packs a group field]
if compare[name[field_type] equal[==] constant[0]] begin[:]
pass
return[constant[False]] | keyword[def] identifier[_save_group_field] ( identifier[self] , identifier[field_type] , identifier[group] ):
literal[string]
keyword[if] identifier[field_type] == literal[int] :
keyword[pass]
keyword[elif] identifier[field_type] == literal[int] :
key... | def _save_group_field(self, field_type, group):
"""This method packs a group field"""
if field_type == 0:
# Ignored (commentar block)
pass # depends on [control=['if'], data=[]]
elif field_type == 1:
if group.id_ is not None:
return (4, struct.pack('<I', group.id_)) # d... |
def get_consumers(self, consumer_cls, channel):
""" Kombu callback to set up consumers.
Called after any (re)connection to the broker.
"""
_log.debug('setting up consumers %s', self)
for provider in self._providers:
callbacks = [partial(self.handle_message, provider... | def function[get_consumers, parameter[self, consumer_cls, channel]]:
constant[ Kombu callback to set up consumers.
Called after any (re)connection to the broker.
]
call[name[_log].debug, parameter[constant[setting up consumers %s], name[self]]]
for taget[name[provider]] in starr... | keyword[def] identifier[get_consumers] ( identifier[self] , identifier[consumer_cls] , identifier[channel] ):
literal[string]
identifier[_log] . identifier[debug] ( literal[string] , identifier[self] )
keyword[for] identifier[provider] keyword[in] identifier[self] . identifier[_provide... | def get_consumers(self, consumer_cls, channel):
""" Kombu callback to set up consumers.
Called after any (re)connection to the broker.
"""
_log.debug('setting up consumers %s', self)
for provider in self._providers:
callbacks = [partial(self.handle_message, provider)]
consum... |
def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
... | def function[get_tty_size, parameter[self]]:
constant[
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. ... | keyword[def] identifier[get_tty_size] ( identifier[self] ):
literal[string]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[ret] = identifier[self] . identifier[_tty_size_windows] (- literal[int] )
identifier[ret] = identifier[r... | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
... |
def frange(x, y, jump=1):
"""
range for floats
"""
precision = get_sig_digits(jump)
while x < y:
yield round(x, precision)
x += jump | def function[frange, parameter[x, y, jump]]:
constant[
range for floats
]
variable[precision] assign[=] call[name[get_sig_digits], parameter[name[jump]]]
while compare[name[x] less[<] name[y]] begin[:]
<ast.Yield object at 0x7da207f9ab30>
<ast.AugAssign object at ... | keyword[def] identifier[frange] ( identifier[x] , identifier[y] , identifier[jump] = literal[int] ):
literal[string]
identifier[precision] = identifier[get_sig_digits] ( identifier[jump] )
keyword[while] identifier[x] < identifier[y] :
keyword[yield] identifier[round] ( identifier[x] , iden... | def frange(x, y, jump=1):
"""
range for floats
"""
precision = get_sig_digits(jump)
while x < y:
yield round(x, precision)
x += jump # depends on [control=['while'], data=['x']] |
def scan_file(pym, filename, sentinel, installed):
'''Entry point scan that creates a PyModule instance if needed.
'''
if not utils.is_python_script(filename):
return
if not pym:
# This is for finding a previously created instance, not finding an
# installed module with the same... | def function[scan_file, parameter[pym, filename, sentinel, installed]]:
constant[Entry point scan that creates a PyModule instance if needed.
]
if <ast.UnaryOp object at 0x7da204344280> begin[:]
return[None]
if <ast.UnaryOp object at 0x7da18f09c430> begin[:]
variable[... | keyword[def] identifier[scan_file] ( identifier[pym] , identifier[filename] , identifier[sentinel] , identifier[installed] ):
literal[string]
keyword[if] keyword[not] identifier[utils] . identifier[is_python_script] ( identifier[filename] ):
keyword[return]
keyword[if] keyword[not] iden... | def scan_file(pym, filename, sentinel, installed):
"""Entry point scan that creates a PyModule instance if needed.
"""
if not utils.is_python_script(filename):
return # depends on [control=['if'], data=[]]
if not pym:
# This is for finding a previously created instance, not finding an
... |
def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for root, dirs, files in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path):
os.rmdir(dir_path) | def function[remove_empty_dirs, parameter[path]]:
constant[ removes empty dirs under a given path ]
for taget[tuple[[<ast.Name object at 0x7da1b26ad300>, <ast.Name object at 0x7da1b26acdc0>, <ast.Name object at 0x7da1b26afdc0>]]] in starred[call[name[os].walk, parameter[name[path]]]] begin[:]
... | keyword[def] identifier[remove_empty_dirs] ( identifier[path] ):
literal[string]
keyword[for] identifier[root] , identifier[dirs] , identifier[files] keyword[in] identifier[os] . identifier[walk] ( identifier[path] ):
keyword[for] identifier[d] keyword[in] identifier[dirs] :
ide... | def remove_empty_dirs(path):
""" removes empty dirs under a given path """
for (root, dirs, files) in os.walk(path):
for d in dirs:
dir_path = os.path.join(root, d)
if not os.listdir(dir_path):
os.rmdir(dir_path) # depends on [control=['if'], data=[]] # depends ... |
def random_square_mask(shape, fraction):
"""Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
"""
mask =... | def function[random_square_mask, parameter[shape, fraction]]:
constant[Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array ... | keyword[def] identifier[random_square_mask] ( identifier[shape] , identifier[fraction] ):
literal[string]
identifier[mask] = identifier[np] . identifier[ones] ( identifier[shape] )
identifier[patch_area] = identifier[shape] [ literal[int] ]* identifier[shape] [ literal[int] ]* identifier[fraction]
ide... | def random_square_mask(shape, fraction):
"""Create a numpy array with specified shape and masked fraction.
Args:
shape: tuple, shape of the mask to create.
fraction: float, fraction of the mask area to populate with `mask_scalar`.
Returns:
numpy.array: A numpy array storing the mask.
"""
mas... |
def extract_pdbid(string):
"""Use regular expressions to get a PDB ID from a string"""
p = re.compile("[0-9][0-9a-z]{3}")
m = p.search(string.lower())
try:
return m.group()
except AttributeError:
return "UnknownProtein" | def function[extract_pdbid, parameter[string]]:
constant[Use regular expressions to get a PDB ID from a string]
variable[p] assign[=] call[name[re].compile, parameter[constant[[0-9][0-9a-z]{3}]]]
variable[m] assign[=] call[name[p].search, parameter[call[name[string].lower, parameter[]]]]
<as... | keyword[def] identifier[extract_pdbid] ( identifier[string] ):
literal[string]
identifier[p] = identifier[re] . identifier[compile] ( literal[string] )
identifier[m] = identifier[p] . identifier[search] ( identifier[string] . identifier[lower] ())
keyword[try] :
keyword[return] identifi... | def extract_pdbid(string):
"""Use regular expressions to get a PDB ID from a string"""
p = re.compile('[0-9][0-9a-z]{3}')
m = p.search(string.lower())
try:
return m.group() # depends on [control=['try'], data=[]]
except AttributeError:
return 'UnknownProtein' # depends on [control=... |
def list_exes(self):
"""List the installed executables by this project."""
return [path.join(self.env_bin, f)
for f
in os.listdir(self.env_bin)] | def function[list_exes, parameter[self]]:
constant[List the installed executables by this project.]
return[<ast.ListComp object at 0x7da18bcca050>] | keyword[def] identifier[list_exes] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[path] . identifier[join] ( identifier[self] . identifier[env_bin] , identifier[f] )
keyword[for] identifier[f]
keyword[in] identifier[os] . identifier[listdir] ( identifier[sel... | def list_exes(self):
"""List the installed executables by this project."""
return [path.join(self.env_bin, f) for f in os.listdir(self.env_bin)] |
def size_of_generator(generator, memory_efficient=True):
"""Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有... | def function[size_of_generator, parameter[generator, memory_efficient]]:
constant[Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficien... | keyword[def] identifier[size_of_generator] ( identifier[generator] , identifier[memory_efficient] = keyword[True] ):
literal[string]
keyword[if] identifier[memory_efficient] :
identifier[counter] = literal[int]
keyword[for] identifier[_] keyword[in] identifier[generator] :
... | def size_of_generator(generator, memory_efficient=True):
"""Get number of items in a generator function.
- memory_efficient = True, 3 times slower, but memory_efficient.
- memory_efficient = False, faster, but cost more memory.
**中文文档**
计算一个生成器函数中的元素的个数。使用memory_efficient=True的方法可以避免将生成器中的
所有... |
def _get_oauth_session(self):
"""Creates a new OAuth session
:return:
- OAuth2Session object
"""
return self._get_session(
OAuth2Session(
client_id=self.client_id,
token=self.token,
token_updater=self.token_updater... | def function[_get_oauth_session, parameter[self]]:
constant[Creates a new OAuth session
:return:
- OAuth2Session object
]
return[call[name[self]._get_session, parameter[call[name[OAuth2Session], parameter[]]]]] | keyword[def] identifier[_get_oauth_session] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_session] (
identifier[OAuth2Session] (
identifier[client_id] = identifier[self] . identifier[client_id] ,
identifier[token] = identifier[... | def _get_oauth_session(self):
"""Creates a new OAuth session
:return:
- OAuth2Session object
"""
return self._get_session(OAuth2Session(client_id=self.client_id, token=self.token, token_updater=self.token_updater, auto_refresh_url=self.token_url, auto_refresh_kwargs={'client_id': se... |
def _set_box(self):
"""
Set the box size for the molecular assembly
"""
net_volume = 0.0
for idx, mol in enumerate(self.mols):
length = max([np.max(mol.cart_coords[:, i])-np.min(mol.cart_coords[:, i])
for i in range(3)]) + 2.0
ne... | def function[_set_box, parameter[self]]:
constant[
Set the box size for the molecular assembly
]
variable[net_volume] assign[=] constant[0.0]
for taget[tuple[[<ast.Name object at 0x7da204567d30>, <ast.Name object at 0x7da2045674f0>]]] in starred[call[name[enumerate], parameter[na... | keyword[def] identifier[_set_box] ( identifier[self] ):
literal[string]
identifier[net_volume] = literal[int]
keyword[for] identifier[idx] , identifier[mol] keyword[in] identifier[enumerate] ( identifier[self] . identifier[mols] ):
identifier[length] = identifier[max] ([ i... | def _set_box(self):
"""
Set the box size for the molecular assembly
"""
net_volume = 0.0
for (idx, mol) in enumerate(self.mols):
length = max([np.max(mol.cart_coords[:, i]) - np.min(mol.cart_coords[:, i]) for i in range(3)]) + 2.0
net_volume += length ** 3.0 * float(self.para... |
def send_email(self, user, subject, msg):
"""Should be overwritten in the setup"""
print('To:', user)
print('Subject:', subject)
print(msg) | def function[send_email, parameter[self, user, subject, msg]]:
constant[Should be overwritten in the setup]
call[name[print], parameter[constant[To:], name[user]]]
call[name[print], parameter[constant[Subject:], name[subject]]]
call[name[print], parameter[name[msg]]] | keyword[def] identifier[send_email] ( identifier[self] , identifier[user] , identifier[subject] , identifier[msg] ):
literal[string]
identifier[print] ( literal[string] , identifier[user] )
identifier[print] ( literal[string] , identifier[subject] )
identifier[print] ( identifier[... | def send_email(self, user, subject, msg):
"""Should be overwritten in the setup"""
print('To:', user)
print('Subject:', subject)
print(msg) |
def _set_nameserver_cos(self, v, load=False):
"""
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nameser... | def function[_set_nameserver_cos, parameter[self, v, load]]:
constant[
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type)
If this variable is read-only (config: false) in the
source YAN... | keyword[def] identifier[_set_nameserver_cos] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_nameserver_cos(self, v, load=False):
"""
Setter method for nameserver_cos, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail/output/show_nameserver/nameserver_cos (nameserver-cos-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_nameser... |
def create_service_network(self, tenant_name, network, subnet,
dhcp_range=True):
"""Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network
... | def function[create_service_network, parameter[self, tenant_name, network, subnet, dhcp_range]]:
constant[Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network
]
... | keyword[def] identifier[create_service_network] ( identifier[self] , identifier[tenant_name] , identifier[network] , identifier[subnet] ,
identifier[dhcp_range] = keyword[True] ):
literal[string]
identifier[network_info] ={}
identifier[subnet_ip_mask] = identifier[subnet] . identifier[cid... | def create_service_network(self, tenant_name, network, subnet, dhcp_range=True):
"""Create network on the DCNM.
:param tenant_name: name of tenant the network belongs to
:param network: network parameters
:param subnet: subnet parameters of the network
"""
network_info = {}
... |
def get_frame(self, in_data, frame_count, time_info, status):
""" Callback function for the pyaudio stream. Don't use directly. """
while self.keep_listening:
try:
frame = self.queue.get(False, timeout=queue_timeout)
return (frame, pyaudio.paContinue)
except Empty:
pass
return (None, pyaudio.paC... | def function[get_frame, parameter[self, in_data, frame_count, time_info, status]]:
constant[ Callback function for the pyaudio stream. Don't use directly. ]
while name[self].keep_listening begin[:]
<ast.Try object at 0x7da1b25d5a50>
return[tuple[[<ast.Constant object at 0x7da1b25d5e40>, <ast... | keyword[def] identifier[get_frame] ( identifier[self] , identifier[in_data] , identifier[frame_count] , identifier[time_info] , identifier[status] ):
literal[string]
keyword[while] identifier[self] . identifier[keep_listening] :
keyword[try] :
identifier[frame] = identifier[self] . identifier[queue] ... | def get_frame(self, in_data, frame_count, time_info, status):
""" Callback function for the pyaudio stream. Don't use directly. """
while self.keep_listening:
try:
frame = self.queue.get(False, timeout=queue_timeout)
return (frame, pyaudio.paContinue) # depends on [control=['try... |
def add_handler(self, message_type, handler):
"""Manage callbacks for message handlers."""
if message_type not in self._handlers:
self._handlers[message_type] = []
if handler not in self._handlers[message_type]:
self._handlers[message_type].append(handler) | def function[add_handler, parameter[self, message_type, handler]]:
constant[Manage callbacks for message handlers.]
if compare[name[message_type] <ast.NotIn object at 0x7da2590d7190> name[self]._handlers] begin[:]
call[name[self]._handlers][name[message_type]] assign[=] list[[]]
... | keyword[def] identifier[add_handler] ( identifier[self] , identifier[message_type] , identifier[handler] ):
literal[string]
keyword[if] identifier[message_type] keyword[not] keyword[in] identifier[self] . identifier[_handlers] :
identifier[self] . identifier[_handlers] [ identifier... | def add_handler(self, message_type, handler):
"""Manage callbacks for message handlers."""
if message_type not in self._handlers:
self._handlers[message_type] = [] # depends on [control=['if'], data=['message_type']]
if handler not in self._handlers[message_type]:
self._handlers[message_typ... |
def run(self):
"""run"""
if self.callback:
log.info(("{} - using callback={}")
.format(self.name,
self.callback))
self.callback(name=self.response_name,
task_queue=self.task_queue,
... | def function[run, parameter[self]]:
constant[run]
if name[self].callback begin[:]
call[name[log].info, parameter[call[constant[{} - using callback={}].format, parameter[name[self].name, name[self].callback]]]]
call[name[self].callback, parameter[]]
return[None] | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[callback] :
identifier[log] . identifier[info] (( literal[string] )
. identifier[format] ( identifier[self] . identifier[name] ,
identifier[self] . ide... | def run(self):
"""run"""
if self.callback:
log.info('{} - using callback={}'.format(self.name, self.callback))
self.callback(name=self.response_name, task_queue=self.task_queue, result_queue=self.result_queue, shutdown_msg=self.shutdown_msg) # depends on [control=['if'], data=[]]
else:
... |
def get_processid(config):
"""Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- p... | def function[get_processid, parameter[config]]:
constant[Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in ... | keyword[def] identifier[get_processid] ( identifier[config] ):
literal[string]
identifier[pidfile] = identifier[config] . identifier[get] ( literal[string] , literal[string] , identifier[fallback] = keyword[None] )
keyword[if] identifier[pidfile] keyword[is] keyword[None] :
keyword[raise] ... | def get_processid(config):
"""Return process id of anycast-healthchecker.
Arguments:
config (obj): A configparser object with the configuration of
anycast-healthchecker.
Returns:
The process id found in the pid file
Raises:
ValueError in the following cases
- p... |
def _ScanFileSystemForWindowsDirectory(self, path_resolver):
"""Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found.
"""
result = False
for windows_path in se... | def function[_ScanFileSystemForWindowsDirectory, parameter[self, path_resolver]]:
constant[Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found.
]
variable... | keyword[def] identifier[_ScanFileSystemForWindowsDirectory] ( identifier[self] , identifier[path_resolver] ):
literal[string]
identifier[result] = keyword[False]
keyword[for] identifier[windows_path] keyword[in] identifier[self] . identifier[_WINDOWS_DIRECTORIES] :
identifier[windows_path_s... | def _ScanFileSystemForWindowsDirectory(self, path_resolver):
"""Scans a file system for a known Windows directory.
Args:
path_resolver (WindowsPathResolver): Windows path resolver.
Returns:
bool: True if a known Windows directory was found.
"""
result = False
for windows_path in se... |
def inodeusage(args=None):
'''
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
'''
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i'
else:
c... | def function[inodeusage, parameter[args]]:
constant[
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
]
variable[flags] assign[=] call[name[_clean_flags], parameter[name[args], constant[disk.inodeusage... | keyword[def] identifier[inodeusage] ( identifier[args] = keyword[None] ):
literal[string]
identifier[flags] = identifier[_clean_flags] ( identifier[args] , literal[string] )
keyword[if] identifier[__grains__] [ literal[string] ]== literal[string] :
identifier[cmd] = literal[string]
key... | def inodeusage(args=None):
"""
Return inode usage information for volumes mounted on this minion
CLI Example:
.. code-block:: bash
salt '*' disk.inodeusage
"""
flags = _clean_flags(args, 'disk.inodeusage')
if __grains__['kernel'] == 'AIX':
cmd = 'df -i' # depends on [cont... |
def get_padding_bias(x):
"""Calculate bias tensor from padding values in tensor.
Bias tensor that is added to the pre-softmax multi-headed attention logits,
which has shape [batch_size, num_heads, length, length]. The tensor is zero at
non-padding locations, and -1e9 (negative infinity) at padding locations.
... | def function[get_padding_bias, parameter[x]]:
constant[Calculate bias tensor from padding values in tensor.
Bias tensor that is added to the pre-softmax multi-headed attention logits,
which has shape [batch_size, num_heads, length, length]. The tensor is zero at
non-padding locations, and -1e9 (negative ... | keyword[def] identifier[get_padding_bias] ( identifier[x] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
identifier[padding] = identifier[get_padding] ( identifier[x] )
identifier[attention_bias] = identifier[padding] * identifier[_NEG_INF]
identi... | def get_padding_bias(x):
"""Calculate bias tensor from padding values in tensor.
Bias tensor that is added to the pre-softmax multi-headed attention logits,
which has shape [batch_size, num_heads, length, length]. The tensor is zero at
non-padding locations, and -1e9 (negative infinity) at padding locations.... |
def _check_auth(self, username: str, password: str) -> bool:
"""Check if a username/password combination is valid."""
try:
return self.credentials[username] == password
except KeyError:
return False | def function[_check_auth, parameter[self, username, password]]:
constant[Check if a username/password combination is valid.]
<ast.Try object at 0x7da18eb54f70> | keyword[def] identifier[_check_auth] ( identifier[self] , identifier[username] : identifier[str] , identifier[password] : identifier[str] )-> identifier[bool] :
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[credentials] [ identifier[username] ]== identif... | def _check_auth(self, username: str, password: str) -> bool:
"""Check if a username/password combination is valid."""
try:
return self.credentials[username] == password # depends on [control=['try'], data=[]]
except KeyError:
return False # depends on [control=['except'], data=[]] |
def local_machine_uuid():
"""Return local machine unique identifier.
>>> uuid = local_machine_uuid()
"""
result = subprocess.check_output(
'hal-get-property --udi '
'/org/freedesktop/Hal/devices/computer '
'--key system.hardware.uuid'.split()
).strip()
return uuid... | def function[local_machine_uuid, parameter[]]:
constant[Return local machine unique identifier.
>>> uuid = local_machine_uuid()
]
variable[result] assign[=] call[call[name[subprocess].check_output, parameter[call[constant[hal-get-property --udi /org/freedesktop/Hal/devices/computer --key syste... | keyword[def] identifier[local_machine_uuid] ():
literal[string]
identifier[result] = identifier[subprocess] . identifier[check_output] (
literal[string]
literal[string]
literal[string] . identifier[split] ()
). identifier[strip] ()
keyword[return] identifier[uuid] . identifier[... | def local_machine_uuid():
"""Return local machine unique identifier.
>>> uuid = local_machine_uuid()
"""
result = subprocess.check_output('hal-get-property --udi /org/freedesktop/Hal/devices/computer --key system.hardware.uuid'.split()).strip()
return uuid.UUID(hex=result) |
def build_tree(self, data, tagname, attrs=None, depth=0):
r"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. De... | def function[build_tree, parameter[self, data, tagname, attrs, depth]]:
constant[Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth o... | keyword[def] identifier[build_tree] ( identifier[self] , identifier[data] , identifier[tagname] , identifier[attrs] = keyword[None] , identifier[depth] = literal[int] ):
literal[string]
keyword[if] identifier[data] keyword[is] keyword[None] :
identifier[data] = literal[string]
... | def build_tree(self, data, tagname, attrs=None, depth=0):
"""Build xml tree.
:param data: data for build xml.
:param tagname: element tag name.
:param attrs: element attributes. Default:``None``.
:type attrs: dict or None
:param depth: element depth of the hierarchy. Default... |
def cur_model(model=None):
"""Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
"""
if model is None:
... | def function[cur_model, parameter[model]]:
constant[Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
]
... | keyword[def] identifier[cur_model] ( identifier[model] = keyword[None] ):
literal[string]
keyword[if] identifier[model] keyword[is] keyword[None] :
keyword[if] identifier[_system] . identifier[currentmodel] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[_s... | def cur_model(model=None):
"""Get and/or set the current model.
If ``model`` is given, set the current model to ``model`` and return it.
``model`` can be the name of a model object, or a model object itself.
If ``model`` is not given, the current model is returned.
"""
if model is None:
... |
def _get_hanging_wall_distance_term(self, dists, ztor):
"""
Returns the hanging wall distance scaling term (equation 7, page 146)
"""
fhngr = np.ones_like(dists.rjb, dtype=float)
idx = dists.rjb > 0.
if ztor < 1.:
temp_rjb = np.sqrt(dists.rjb[idx] ** 2. + 1.)
... | def function[_get_hanging_wall_distance_term, parameter[self, dists, ztor]]:
constant[
Returns the hanging wall distance scaling term (equation 7, page 146)
]
variable[fhngr] assign[=] call[name[np].ones_like, parameter[name[dists].rjb]]
variable[idx] assign[=] compare[name[dists... | keyword[def] identifier[_get_hanging_wall_distance_term] ( identifier[self] , identifier[dists] , identifier[ztor] ):
literal[string]
identifier[fhngr] = identifier[np] . identifier[ones_like] ( identifier[dists] . identifier[rjb] , identifier[dtype] = identifier[float] )
identifier[idx] =... | def _get_hanging_wall_distance_term(self, dists, ztor):
"""
Returns the hanging wall distance scaling term (equation 7, page 146)
"""
fhngr = np.ones_like(dists.rjb, dtype=float)
idx = dists.rjb > 0.0
if ztor < 1.0:
temp_rjb = np.sqrt(dists.rjb[idx] ** 2.0 + 1.0)
r_max = ... |
def options(self, parser, env):
"""Sets additional command line options."""
Plugin.options(self, parser, env)
parser.add_option(
'--html-file', action='store',
dest='html_file', metavar="FILE",
default=env.get('NOSE_HTML_FILE', 'nosetests.html'),
h... | def function[options, parameter[self, parser, env]]:
constant[Sets additional command line options.]
call[name[Plugin].options, parameter[name[self], name[parser], name[env]]]
call[name[parser].add_option, parameter[constant[--html-file]]] | keyword[def] identifier[options] ( identifier[self] , identifier[parser] , identifier[env] ):
literal[string]
identifier[Plugin] . identifier[options] ( identifier[self] , identifier[parser] , identifier[env] )
identifier[parser] . identifier[add_option] (
literal[string] , identi... | def options(self, parser, env):
"""Sets additional command line options."""
Plugin.options(self, parser, env)
parser.add_option('--html-file', action='store', dest='html_file', metavar='FILE', default=env.get('NOSE_HTML_FILE', 'nosetests.html'), help='Path to html file to store the report in. Default is nos... |
def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
'Main view for a dash app'
_, app = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) | def function[main_view, parameter[request, ident, stateless, cache_id]]:
constant[Main view for a dash app]
<ast.Tuple object at 0x7da207f99b10> assign[=] call[name[DashApp].locate_item, parameter[name[ident], name[stateless]]]
variable[view_func] assign[=] call[name[app].locate_endpoint_functio... | keyword[def] identifier[main_view] ( identifier[request] , identifier[ident] , identifier[stateless] = keyword[False] , identifier[cache_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[_] , identifier[app] = identifier[DashApp] . identifier[locate_item] ( identifier[ident] , identi... | def main_view(request, ident, stateless=False, cache_id=None, **kwargs):
"""Main view for a dash app"""
(_, app) = DashApp.locate_item(ident, stateless, cache_id=cache_id)
view_func = app.locate_endpoint_function()
resp = view_func()
return HttpResponse(resp) |
def forward(self, x, boxes):
"""
Arguments:
x (list[Tensor]): feature maps for each level
boxes (list[BoxList]): boxes to be used to perform the pooling operation.
Returns:
result (Tensor)
"""
num_levels = len(self.poolers)
rois = self.... | def function[forward, parameter[self, x, boxes]]:
constant[
Arguments:
x (list[Tensor]): feature maps for each level
boxes (list[BoxList]): boxes to be used to perform the pooling operation.
Returns:
result (Tensor)
]
variable[num_levels] assig... | keyword[def] identifier[forward] ( identifier[self] , identifier[x] , identifier[boxes] ):
literal[string]
identifier[num_levels] = identifier[len] ( identifier[self] . identifier[poolers] )
identifier[rois] = identifier[self] . identifier[convert_to_roi_format] ( identifier[boxes] )
... | def forward(self, x, boxes):
"""
Arguments:
x (list[Tensor]): feature maps for each level
boxes (list[BoxList]): boxes to be used to perform the pooling operation.
Returns:
result (Tensor)
"""
num_levels = len(self.poolers)
rois = self.convert_to_r... |
def summary_df_from_array(results_array, names, axis=0, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_ar... | def function[summary_df_from_array, parameter[results_array, names, axis]]:
constant[Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
------... | keyword[def] identifier[summary_df_from_array] ( identifier[results_array] , identifier[names] , identifier[axis] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[axis] == literal[int] keyword[or] identifier[axis] == literal[int]
identifier[df] = identifier[pd] .... | def summary_df_from_array(results_array, names, axis=0, **kwargs):
"""Make a panda data frame of the mean and std devs of an array of results,
including the uncertainties on the values.
This function converts the array to a DataFrame and calls summary_df on it.
Parameters
----------
results_ar... |
def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) N-dimensional integer coordinate
@param radius (int) Radius around `coordinate`
@return (numpy.array) List of coordinates
"""... | def function[_neighbors, parameter[coordinate, radius]]:
constant[
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) N-dimensional integer coordinate
@param radius (int) Radius around `coordinate`
@return (numpy.arr... | keyword[def] identifier[_neighbors] ( identifier[coordinate] , identifier[radius] ):
literal[string]
identifier[ranges] =( identifier[xrange] ( identifier[n] - identifier[radius] , identifier[n] + identifier[radius] + literal[int] ) keyword[for] identifier[n] keyword[in] identifier[coordinate] . identif... | def _neighbors(coordinate, radius):
"""
Returns coordinates around given coordinate, within given radius.
Includes given coordinate.
@param coordinate (numpy.array) N-dimensional integer coordinate
@param radius (int) Radius around `coordinate`
@return (numpy.array) List of coordinates
"""... |
def parse_archive_uri(uri):
"""Given an archive URI, parse to a split ident-hash."""
parsed = urlparse(uri)
path = parsed.path.rstrip('/').split('/')
ident_hash = path[-1]
ident_hash = unquote(ident_hash)
return ident_hash | def function[parse_archive_uri, parameter[uri]]:
constant[Given an archive URI, parse to a split ident-hash.]
variable[parsed] assign[=] call[name[urlparse], parameter[name[uri]]]
variable[path] assign[=] call[call[name[parsed].path.rstrip, parameter[constant[/]]].split, parameter[constant[/]]]
... | keyword[def] identifier[parse_archive_uri] ( identifier[uri] ):
literal[string]
identifier[parsed] = identifier[urlparse] ( identifier[uri] )
identifier[path] = identifier[parsed] . identifier[path] . identifier[rstrip] ( literal[string] ). identifier[split] ( literal[string] )
identifier[ident_h... | def parse_archive_uri(uri):
"""Given an archive URI, parse to a split ident-hash."""
parsed = urlparse(uri)
path = parsed.path.rstrip('/').split('/')
ident_hash = path[-1]
ident_hash = unquote(ident_hash)
return ident_hash |
def as_dict(self):
"""
Serializes the object necessary data in a dictionary.
:returns: Serialized data in a dictionary.
:rtype: dict
"""
element_dict = dict()
if hasattr(self, 'namespace'):
element_dict['namespace'] = self.namespace
if hasatt... | def function[as_dict, parameter[self]]:
constant[
Serializes the object necessary data in a dictionary.
:returns: Serialized data in a dictionary.
:rtype: dict
]
variable[element_dict] assign[=] call[name[dict], parameter[]]
if call[name[hasattr], parameter[name[... | keyword[def] identifier[as_dict] ( identifier[self] ):
literal[string]
identifier[element_dict] = identifier[dict] ()
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[element_dict] [ literal[string] ]= identifier[self] . identifier[namespace... | def as_dict(self):
"""
Serializes the object necessary data in a dictionary.
:returns: Serialized data in a dictionary.
:rtype: dict
"""
element_dict = dict()
if hasattr(self, 'namespace'):
element_dict['namespace'] = self.namespace # depends on [control=['if'], dat... |
def dump_all(data_list, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(
data_list,
stream=stream,
Dumper=YAMLDictDumper,
**kwargs
) | def function[dump_all, parameter[data_list, stream]]:
constant[
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
]
return[call[name[yaml].dump_all, parameter[name[data_list]]]] | keyword[def] identifier[dump_all] ( identifier[data_list] , identifier[stream] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[yaml] . identifier[dump_all] (
identifier[data_list] ,
identifier[stream] = identifier[stream] ,
identifier[Dumper] = identifie... | def dump_all(data_list, stream=None, **kwargs):
"""
Serialize YAMLDict into a YAML stream.
If stream is None, return the produced string instead.
"""
return yaml.dump_all(data_list, stream=stream, Dumper=YAMLDictDumper, **kwargs) |
def cancel_order(order):
"""
撤单
:param order: 需要撤销的order对象
:type order: :class:`~Order` object
"""
env = Environment.get_instance()
if env.can_cancel_order(order):
env.broker.cancel_order(order)
return order | def function[cancel_order, parameter[order]]:
constant[
撤单
:param order: 需要撤销的order对象
:type order: :class:`~Order` object
]
variable[env] assign[=] call[name[Environment].get_instance, parameter[]]
if call[name[env].can_cancel_order, parameter[name[order]]] begin[:]
... | keyword[def] identifier[cancel_order] ( identifier[order] ):
literal[string]
identifier[env] = identifier[Environment] . identifier[get_instance] ()
keyword[if] identifier[env] . identifier[can_cancel_order] ( identifier[order] ):
identifier[env] . identifier[broker] . identifier[cancel_orde... | def cancel_order(order):
"""
撤单
:param order: 需要撤销的order对象
:type order: :class:`~Order` object
"""
env = Environment.get_instance()
if env.can_cancel_order(order):
env.broker.cancel_order(order) # depends on [control=['if'], data=[]]
return order |
def __update_siblings_active_labels_states(self, active_label):
"""
Updates given **Active_QLabel** Widget siblings states.
:param active_label: Active label.
:type active_label: Active_QLabel
"""
LOGGER.debug("> Clicked 'Active_QLabel': '{0}'.".format(active_label))
... | def function[__update_siblings_active_labels_states, parameter[self, active_label]]:
constant[
Updates given **Active_QLabel** Widget siblings states.
:param active_label: Active label.
:type active_label: Active_QLabel
]
call[name[LOGGER].debug, parameter[call[constant[... | keyword[def] identifier[__update_siblings_active_labels_states] ( identifier[self] , identifier[active_label] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[active_label] ))
keyword[for] identifier[item] keyword[in] identi... | def __update_siblings_active_labels_states(self, active_label):
"""
Updates given **Active_QLabel** Widget siblings states.
:param active_label: Active label.
:type active_label: Active_QLabel
"""
LOGGER.debug("> Clicked 'Active_QLabel': '{0}'.".format(active_label))
for ite... |
async def patch_register(self, register: Dict, request: 'Request'):
"""
Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches ... | <ast.AsyncFunctionDef object at 0x7da20e9605b0> | keyword[async] keyword[def] identifier[patch_register] ( identifier[self] , identifier[register] : identifier[Dict] , identifier[request] : literal[string] ):
literal[string]
identifier[register] [ literal[string] ]={
identifier[o] . identifier[slug] :{
literal[string] : identif... | async def patch_register(self, register: Dict, request: 'Request'):
"""
Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches more... |
def get_xref_graph(ont):
"""
Creates a basic graph object corresponding to a remote ontology
"""
g = networkx.MultiGraph()
for (c,x) in fetchall_xrefs(ont):
g.add_edge(c,x,source=c)
return g | def function[get_xref_graph, parameter[ont]]:
constant[
Creates a basic graph object corresponding to a remote ontology
]
variable[g] assign[=] call[name[networkx].MultiGraph, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da20e9562c0>, <ast.Name object at 0x7da1b083e470>]]] in sta... | keyword[def] identifier[get_xref_graph] ( identifier[ont] ):
literal[string]
identifier[g] = identifier[networkx] . identifier[MultiGraph] ()
keyword[for] ( identifier[c] , identifier[x] ) keyword[in] identifier[fetchall_xrefs] ( identifier[ont] ):
identifier[g] . identifier[add_edge] ( iden... | def get_xref_graph(ont):
"""
Creates a basic graph object corresponding to a remote ontology
"""
g = networkx.MultiGraph()
for (c, x) in fetchall_xrefs(ont):
g.add_edge(c, x, source=c) # depends on [control=['for'], data=[]]
return g |
def is_all_field_none(self):
"""
:rtype: bool
"""
if self._type_ is not None:
return False
if self._value is not None:
return False
if self._name is not None:
return False
return True | def function[is_all_field_none, parameter[self]]:
constant[
:rtype: bool
]
if compare[name[self]._type_ is_not constant[None]] begin[:]
return[constant[False]]
if compare[name[self]._value is_not constant[None]] begin[:]
return[constant[False]]
if compare[... | keyword[def] identifier[is_all_field_none] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_type_] keyword[is] keyword[not] keyword[None] :
keyword[return] keyword[False]
keyword[if] identifier[self] . identifier[_value] keyword[is] k... | def is_all_field_none(self):
"""
:rtype: bool
"""
if self._type_ is not None:
return False # depends on [control=['if'], data=[]]
if self._value is not None:
return False # depends on [control=['if'], data=[]]
if self._name is not None:
return False # depends o... |
def _get_manager_class(self, register_callables=False):
"""
Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments.
"""
class _EvaluatorSyncManager(managers.BaseManager):
"""
A custom Bas... | def function[_get_manager_class, parameter[self, register_callables]]:
constant[
Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments.
]
class class[_EvaluatorSyncManager, parameter[]] begin[:]
... | keyword[def] identifier[_get_manager_class] ( identifier[self] , identifier[register_callables] = keyword[False] ):
literal[string]
keyword[class] identifier[_EvaluatorSyncManager] ( identifier[managers] . identifier[BaseManager] ):
literal[string]
keyword[pass]
... | def _get_manager_class(self, register_callables=False):
"""
Returns a new 'Manager' subclass with registered methods.
If 'register_callable' is True, defines the 'callable' arguments.
"""
class _EvaluatorSyncManager(managers.BaseManager):
"""
A custom BaseManager.
... |
def corr(self):
'''The correlation matrix'''
cov = self.cov()
N = cov.shape[0]
corr = ndarray((N,N))
for r in range(N):
for c in range(r):
corr[r,c] = corr[c,r] = cov[r,c]/sqrt(cov[r,r]*cov[c,c])
corr[r,r] = 1.
return corr | def function[corr, parameter[self]]:
constant[The correlation matrix]
variable[cov] assign[=] call[name[self].cov, parameter[]]
variable[N] assign[=] call[name[cov].shape][constant[0]]
variable[corr] assign[=] call[name[ndarray], parameter[tuple[[<ast.Name object at 0x7da1b0e17340>, <ast... | keyword[def] identifier[corr] ( identifier[self] ):
literal[string]
identifier[cov] = identifier[self] . identifier[cov] ()
identifier[N] = identifier[cov] . identifier[shape] [ literal[int] ]
identifier[corr] = identifier[ndarray] (( identifier[N] , identifier[N] ))
... | def corr(self):
"""The correlation matrix"""
cov = self.cov()
N = cov.shape[0]
corr = ndarray((N, N))
for r in range(N):
for c in range(r):
corr[r, c] = corr[c, r] = cov[r, c] / sqrt(cov[r, r] * cov[c, c]) # depends on [control=['for'], data=['c']]
corr[r, r] = 1.0 # de... |
def run_once(func):
''' Decorator for making sure a method can only be executed once '''
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return func(*args, **kwargs)
wrapper.has_run = False
return wrapper | def function[run_once, parameter[func]]:
constant[ Decorator for making sure a method can only be executed once ]
def function[wrapper, parameter[]]:
if <ast.UnaryOp object at 0x7da20c991360> begin[:]
name[wrapper].has_run assign[=] constant[True]
retu... | keyword[def] identifier[run_once] ( identifier[func] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
keyword[if] keyword[not] identifier[wrapper] . identifier[has_run] :
identifier[wrapper] . identifier[has_run] = keyword[True]
... | def run_once(func):
""" Decorator for making sure a method can only be executed once """
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return func(*args, **kwargs) # depends on [control=['if'], data=[]]
wrapper.has_run = False
return wrapp... |
def transform_annotation(self, ann, duration):
'''Transform an annotation to dynamic label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... | def function[transform_annotation, parameter[self, ann, duration]]:
constant[Transform an annotation to dynamic label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
... | keyword[def] identifier[transform_annotation] ( identifier[self] , identifier[ann] , identifier[duration] ):
literal[string]
identifier[intervals] , identifier[values] = identifier[ann] . identifier[to_interval_values] ()
identifier[tags] =[]
keyword[for] identifier[v] ... | def transform_annotation(self, ann, duration):
"""Transform an annotation to dynamic label encoding.
Parameters
----------
ann : jams.Annotation
The annotation to convert
duration : number > 0
The duration of the track
Returns
-------
... |
def _get_accepted(self, graph):
"""
Find the accepted states
Args:
graph (DFA): The DFA states
Return:
list: Returns the list of the accepted states
"""
accepted = []
for state in graph.states:
if state.final != TropicalWeight(f... | def function[_get_accepted, parameter[self, graph]]:
constant[
Find the accepted states
Args:
graph (DFA): The DFA states
Return:
list: Returns the list of the accepted states
]
variable[accepted] assign[=] list[[]]
for taget[name[state]] i... | keyword[def] identifier[_get_accepted] ( identifier[self] , identifier[graph] ):
literal[string]
identifier[accepted] =[]
keyword[for] identifier[state] keyword[in] identifier[graph] . identifier[states] :
keyword[if] identifier[state] . identifier[final] != identifier[Tro... | def _get_accepted(self, graph):
"""
Find the accepted states
Args:
graph (DFA): The DFA states
Return:
list: Returns the list of the accepted states
"""
accepted = []
for state in graph.states:
if state.final != TropicalWeight(float('inf')):
... |
def get_mail_addresses(message, header_name):
"""
Retrieve all email addresses from one message header.
"""
headers = [h for h in message.get_all(header_name, [])]
addresses = email.utils.getaddresses(headers)
for index, (address_name, address_email) in enumerate(addresses):
addresses[i... | def function[get_mail_addresses, parameter[message, header_name]]:
constant[
Retrieve all email addresses from one message header.
]
variable[headers] assign[=] <ast.ListComp object at 0x7da2041db250>
variable[addresses] assign[=] call[name[email].utils.getaddresses, parameter[name[heade... | keyword[def] identifier[get_mail_addresses] ( identifier[message] , identifier[header_name] ):
literal[string]
identifier[headers] =[ identifier[h] keyword[for] identifier[h] keyword[in] identifier[message] . identifier[get_all] ( identifier[header_name] ,[])]
identifier[addresses] = identifier[em... | def get_mail_addresses(message, header_name):
"""
Retrieve all email addresses from one message header.
"""
headers = [h for h in message.get_all(header_name, [])]
addresses = email.utils.getaddresses(headers)
for (index, (address_name, address_email)) in enumerate(addresses):
addresses[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.