code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def translate(cls, f=None, output=0, **kwargs):
"""translate(f=None, *, output=TranslateOutput.code, **kwargs)
Decorator that turns a function into a shellcode emitting function.
Arguments:
f(callable): The function to decorate. If ``f`` is ``None`` a
decorator will ... | def function[translate, parameter[cls, f, output]]:
constant[translate(f=None, *, output=TranslateOutput.code, **kwargs)
Decorator that turns a function into a shellcode emitting function.
Arguments:
f(callable): The function to decorate. If ``f`` is ``None`` a
decor... | keyword[def] identifier[translate] ( identifier[cls] , identifier[f] = keyword[None] , identifier[output] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
@ identifier[functools] . identifier[wraps] ( identifier[f] )
... | def translate(cls, f=None, output=0, **kwargs):
"""translate(f=None, *, output=TranslateOutput.code, **kwargs)
Decorator that turns a function into a shellcode emitting function.
Arguments:
f(callable): The function to decorate. If ``f`` is ``None`` a
decorator will be r... |
def auto_index(mcs):
"""Builds all indices, listed in model's Meta class.
>>> class SomeModel(Model)
... class Meta:
... indices = (
... Index('foo'),
... )
.. note:: this will result in calls to
:... | def function[auto_index, parameter[mcs]]:
constant[Builds all indices, listed in model's Meta class.
>>> class SomeModel(Model)
... class Meta:
... indices = (
... Index('foo'),
... )
.. note:: this will result in c... | keyword[def] identifier[auto_index] ( identifier[mcs] ):
literal[string]
keyword[for] identifier[index] keyword[in] identifier[mcs] . identifier[_meta] . identifier[indices] :
identifier[index] . identifier[ensure] ( identifier[mcs] . identifier[collection] ) | def auto_index(mcs):
"""Builds all indices, listed in model's Meta class.
>>> class SomeModel(Model)
... class Meta:
... indices = (
... Index('foo'),
... )
.. note:: this will result in calls to
:meth... |
def splitlines(self, keepends=False):
"""
S.splitlines(keepends=False) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
# Py2 unicode.splitli... | def function[splitlines, parameter[self, keepends]]:
constant[
S.splitlines(keepends=False) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
]
va... | keyword[def] identifier[splitlines] ( identifier[self] , identifier[keepends] = keyword[False] ):
literal[string]
identifier[parts] = identifier[super] ( identifier[newstr] , identifier[self] ). identifier[splitlines] ( identifier[keepends] )
keyword[return] [ identifier[... | def splitlines(self, keepends=False):
"""
S.splitlines(keepends=False) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
"""
# Py2 unicode.splitlines() ta... |
def trimUTR(args):
"""
%prog trimUTR gffile
Remove UTRs in the annotation set.
If reference GFF3 is provided, reinstate UTRs from reference
transcripts after trimming.
Note: After running trimUTR, it is advised to also run
`python -m jcvi.formats.gff fixboundaries` on the resultant GFF3
... | def function[trimUTR, parameter[args]]:
constant[
%prog trimUTR gffile
Remove UTRs in the annotation set.
If reference GFF3 is provided, reinstate UTRs from reference
transcripts after trimming.
Note: After running trimUTR, it is advised to also run
`python -m jcvi.formats.gff fixboun... | keyword[def] identifier[trimUTR] ( identifier[args] ):
literal[string]
keyword[import] identifier[gffutils]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[base] keyword[import] identifier[SetFile]
identifier[p] = identifier[OptionParser] ( identifier[trimUTR] . identifie... | def trimUTR(args):
"""
%prog trimUTR gffile
Remove UTRs in the annotation set.
If reference GFF3 is provided, reinstate UTRs from reference
transcripts after trimming.
Note: After running trimUTR, it is advised to also run
`python -m jcvi.formats.gff fixboundaries` on the resultant GFF3
... |
def setup_matchedfltr_workflow(workflow, science_segs, datafind_outs,
tmplt_banks, output_dir=None,
injection_file=None, tags=None):
'''
This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function... | def function[setup_matchedfltr_workflow, parameter[workflow, science_segs, datafind_outs, tmplt_banks, output_dir, injection_file, tags]]:
constant[
This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function is intended to support multiple
different... | keyword[def] identifier[setup_matchedfltr_workflow] ( identifier[workflow] , identifier[science_segs] , identifier[datafind_outs] ,
identifier[tmplt_banks] , identifier[output_dir] = keyword[None] ,
identifier[injection_file] = keyword[None] , identifier[tags] = keyword[None] ):
literal[string]
keyword[i... | def setup_matchedfltr_workflow(workflow, science_segs, datafind_outs, tmplt_banks, output_dir=None, injection_file=None, tags=None):
"""
This function aims to be the gateway for setting up a set of matched-filter
jobs in a workflow. This function is intended to support multiple
different ways/codes that... |
def append(self, event, category=None):
"""
Adds a new event to the trace store.
The event may hava a category
Args:
event (spade.message.Message): the event to be stored
category (str, optional): a category to classify the event (Default value = None)
"""
... | def function[append, parameter[self, event, category]]:
constant[
Adds a new event to the trace store.
The event may hava a category
Args:
event (spade.message.Message): the event to be stored
category (str, optional): a category to classify the event (Default value ... | keyword[def] identifier[append] ( identifier[self] , identifier[event] , identifier[category] = keyword[None] ):
literal[string]
identifier[date] = identifier[datetime] . identifier[datetime] . identifier[now] ()
identifier[self] . identifier[store] . identifier[insert] ( literal[int] ,( i... | def append(self, event, category=None):
"""
Adds a new event to the trace store.
The event may hava a category
Args:
event (spade.message.Message): the event to be stored
category (str, optional): a category to classify the event (Default value = None)
"""
d... |
def get_sysid(self):
'''get sysid tuple to use for parameters'''
component = self.target_component
if component == 0:
component = 1
return (self.target_system, component) | def function[get_sysid, parameter[self]]:
constant[get sysid tuple to use for parameters]
variable[component] assign[=] name[self].target_component
if compare[name[component] equal[==] constant[0]] begin[:]
variable[component] assign[=] constant[1]
return[tuple[[<ast.Attribut... | keyword[def] identifier[get_sysid] ( identifier[self] ):
literal[string]
identifier[component] = identifier[self] . identifier[target_component]
keyword[if] identifier[component] == literal[int] :
identifier[component] = literal[int]
keyword[return] ( identifier[se... | def get_sysid(self):
"""get sysid tuple to use for parameters"""
component = self.target_component
if component == 0:
component = 1 # depends on [control=['if'], data=['component']]
return (self.target_system, component) |
def stream(self, handler, whenDone=None):
"""
Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data
"""
self._createConfluence()
headers = ["... | def function[stream, parameter[self, handler, whenDone]]:
constant[
Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data
]
call[name[sel... | keyword[def] identifier[stream] ( identifier[self] , identifier[handler] , identifier[whenDone] = keyword[None] ):
literal[string]
identifier[self] . identifier[_createConfluence] ()
identifier[headers] =[ literal[string] ]+ identifier[self] . identifier[getStreamIds] ()
keyword[for] identifier[... | def stream(self, handler, whenDone=None):
"""
Fetches data from river streams and feeds them into the given function.
:param handler: (function) passed headers [list] and row [list] of the data
for one time step, for every row of data
"""
self._createConfluence()
headers = ['... |
def static_singleton(*args, **kwargs):
"""
STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
def says... | def function[static_singleton, parameter[]]:
constant[
STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
... | keyword[def] identifier[static_singleton] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[__static_singleton_wrapper] ( identifier[cls] ):
keyword[if] identifier[cls] keyword[not] keyword[in] identifier[__singleton_instances] :
identifier[__... | def static_singleton(*args, **kwargs):
"""
STATIC Singleton Design Pattern Decorator
Class is initialized with arguments passed into the decorator.
:Usage:
>>> @static_singleton('yop')
class Bob(Person):
def __init__(arg1):
self.info = arg1
def says... |
def retrieve_tx(self, txid):
"""Returns rawtx for <txid>."""
txid = deserialize.txid(txid)
tx = self.service.get_tx(txid)
return serialize.tx(tx) | def function[retrieve_tx, parameter[self, txid]]:
constant[Returns rawtx for <txid>.]
variable[txid] assign[=] call[name[deserialize].txid, parameter[name[txid]]]
variable[tx] assign[=] call[name[self].service.get_tx, parameter[name[txid]]]
return[call[name[serialize].tx, parameter[name[tx]]... | keyword[def] identifier[retrieve_tx] ( identifier[self] , identifier[txid] ):
literal[string]
identifier[txid] = identifier[deserialize] . identifier[txid] ( identifier[txid] )
identifier[tx] = identifier[self] . identifier[service] . identifier[get_tx] ( identifier[txid] )
keywor... | def retrieve_tx(self, txid):
"""Returns rawtx for <txid>."""
txid = deserialize.txid(txid)
tx = self.service.get_tx(txid)
return serialize.tx(tx) |
def startInventory(self, proto=None, force_regen_rospec=False):
"""Add a ROSpec to the reader and enable it."""
if self.state == LLRPClient.STATE_INVENTORYING:
logger.warn('ignoring startInventory() while already inventorying')
return None
rospec = self.getROSpec(force_n... | def function[startInventory, parameter[self, proto, force_regen_rospec]]:
constant[Add a ROSpec to the reader and enable it.]
if compare[name[self].state equal[==] name[LLRPClient].STATE_INVENTORYING] begin[:]
call[name[logger].warn, parameter[constant[ignoring startInventory() while alr... | keyword[def] identifier[startInventory] ( identifier[self] , identifier[proto] = keyword[None] , identifier[force_regen_rospec] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[state] == identifier[LLRPClient] . identifier[STATE_INVENTORYING] :
identifier[... | def startInventory(self, proto=None, force_regen_rospec=False):
"""Add a ROSpec to the reader and enable it."""
if self.state == LLRPClient.STATE_INVENTORYING:
logger.warn('ignoring startInventory() while already inventorying')
return None # depends on [control=['if'], data=[]]
rospec = sel... |
def __array_op(self, f, x, axis):
"""operation for 3D Field with planes or vector (type = numpy.ndarray) or 2D Field with vector (numpy.ndarray)
:param f: operator function
:param x: array(1D, 2D) or field (2D) or View (2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-p... | def function[__array_op, parameter[self, f, x, axis]]:
constant[operation for 3D Field with planes or vector (type = numpy.ndarray) or 2D Field with vector (numpy.ndarray)
:param f: operator function
:param x: array(1D, 2D) or field (2D) or View (2D)
:param axis: specifies axis, eg. axis... | keyword[def] identifier[__array_op] ( identifier[self] , identifier[f] , identifier[x] , identifier[axis] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[x] , identifier[ndarray] )== keyword[False] keyword[and] identifier[isinstance] ( identifier[x] , identifier[Field] )== key... | def __array_op(self, f, x, axis):
"""operation for 3D Field with planes or vector (type = numpy.ndarray) or 2D Field with vector (numpy.ndarray)
:param f: operator function
:param x: array(1D, 2D) or field (2D) or View (2D)
:param axis: specifies axis, eg. axis = (1,2) plane lies in yz-plane... |
def _draw_text(self, pos, text, font, **kw):
"""
Remember a single drawable tuple to paint later.
"""
self.drawables.append((pos, text, font, kw)) | def function[_draw_text, parameter[self, pos, text, font]]:
constant[
Remember a single drawable tuple to paint later.
]
call[name[self].drawables.append, parameter[tuple[[<ast.Name object at 0x7da18bc72d10>, <ast.Name object at 0x7da18bc71750>, <ast.Name object at 0x7da18bc73880>, <ast.... | keyword[def] identifier[_draw_text] ( identifier[self] , identifier[pos] , identifier[text] , identifier[font] ,** identifier[kw] ):
literal[string]
identifier[self] . identifier[drawables] . identifier[append] (( identifier[pos] , identifier[text] , identifier[font] , identifier[kw] )) | def _draw_text(self, pos, text, font, **kw):
"""
Remember a single drawable tuple to paint later.
"""
self.drawables.append((pos, text, font, kw)) |
def _choose_tuner(self, algorithm_name):
"""
Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal"
"""
if algorithm_name == 'tpe':
return hp.tpe.suggest
if algorithm_name == 'random_search':
... | def function[_choose_tuner, parameter[self, algorithm_name]]:
constant[
Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal"
]
if compare[name[algorithm_name] equal[==] constant[tpe]] begin[:]
return[nam... | keyword[def] identifier[_choose_tuner] ( identifier[self] , identifier[algorithm_name] ):
literal[string]
keyword[if] identifier[algorithm_name] == literal[string] :
keyword[return] identifier[hp] . identifier[tpe] . identifier[suggest]
keyword[if] identifier[algorithm_nam... | def _choose_tuner(self, algorithm_name):
"""
Parameters
----------
algorithm_name : str
algorithm_name includes "tpe", "random_search" and anneal"
"""
if algorithm_name == 'tpe':
return hp.tpe.suggest # depends on [control=['if'], data=[]]
if algorithm_na... |
def smoothing_window(data, window=[1, 1, 1]):
""" This is a smoothing functionality so we can fix misclassifications.
It will run a sliding window of form [border, smoothing, border] on the
signal and if the border elements are the same it will change the
smooth elements to match the border... | def function[smoothing_window, parameter[data, window]]:
constant[ This is a smoothing functionality so we can fix misclassifications.
It will run a sliding window of form [border, smoothing, border] on the
signal and if the border elements are the same it will change the
smooth element... | keyword[def] identifier[smoothing_window] ( identifier[data] , identifier[window] =[ literal[int] , literal[int] , literal[int] ]):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[data] )- identifier[sum] ( identifier[window] )):
identif... | def smoothing_window(data, window=[1, 1, 1]):
""" This is a smoothing functionality so we can fix misclassifications.
It will run a sliding window of form [border, smoothing, border] on the
signal and if the border elements are the same it will change the
smooth elements to match the border... |
def BGPSessionState_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
BGPSessionState = ET.SubElement(config, "BGPSessionState", xmlns="http://brocade.com/ns/brocade-notification-stream")
originator_switch_info = ET... | def function[BGPSessionState_originator_switch_info_switchIpV6Address, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[BGPSessionState] assign[=] call[name[ET].SubElement, parameter[name[config], con... | keyword[def] identifier[BGPSessionState_originator_switch_info_switchIpV6Address] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[BGPSessionState] = identifier[ET] . identifier[SubElement]... | def BGPSessionState_originator_switch_info_switchIpV6Address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
BGPSessionState = ET.SubElement(config, 'BGPSessionState', xmlns='http://brocade.com/ns/brocade-notification-stream')
originator_switch_info = ET.SubElement(BGPS... |
def make_command(command: Callable) -> Callable:
"""Create an command from a method signature."""
@wraps(command)
def actualcommand(self, *args, **kwds): # pylint: disable=missing-docstring
data = command(self, *args, **kwds)
name = command.__name__[3:]
signal = '{uuid}{sep}{event}'... | def function[make_command, parameter[command]]:
constant[Create an command from a method signature.]
def function[actualcommand, parameter[self]]:
variable[data] assign[=] call[name[command], parameter[name[self], <ast.Starred object at 0x7da18ede4ac0>]]
variable[name] as... | keyword[def] identifier[make_command] ( identifier[command] : identifier[Callable] )-> identifier[Callable] :
literal[string]
@ identifier[wraps] ( identifier[command] )
keyword[def] identifier[actualcommand] ( identifier[self] ,* identifier[args] ,** identifier[kwds] ):
identifier[data] = id... | def make_command(command: Callable) -> Callable:
"""Create an command from a method signature."""
@wraps(command)
def actualcommand(self, *args, **kwds): # pylint: disable=missing-docstring
data = command(self, *args, **kwds)
name = command.__name__[3:] # pylint: disable=protected-access
... |
def _read_stderr(self):
"""Read the stderr file of the kernel."""
# We need to read stderr_file as bytes to be able to
# detect its encoding with chardet
f = open(self.stderr_file, 'rb')
try:
stderr_text = f.read()
# This is needed to avoid show... | def function[_read_stderr, parameter[self]]:
constant[Read the stderr file of the kernel.]
variable[f] assign[=] call[name[open], parameter[name[self].stderr_file, constant[rb]]]
<ast.Try object at 0x7da18eb56470> | keyword[def] identifier[_read_stderr] ( identifier[self] ):
literal[string]
identifier[f] = identifier[open] ( identifier[self] . identifier[stderr_file] , literal[string] )
keyword[try] :
identifier[stderr_text] = identifier[f] . identifier[read] ()
... | def _read_stderr(self):
"""Read the stderr file of the kernel.""" # We need to read stderr_file as bytes to be able to
# detect its encoding with chardet
f = open(self.stderr_file, 'rb')
try:
stderr_text = f.read() # This is needed to avoid showing an empty error message
# when the ker... |
def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode("utf-8")
if not result:
raise NoResponseError("No response received from server.")
msg = self._read_message()
if result != "ok":
raise InvalidResponseError(msg)
r... | def function[_read_response, parameter[self]]:
constant[ Reads a complete response packet from the server ]
variable[result] assign[=] call[call[name[self].buf.read_line, parameter[]].decode, parameter[constant[utf-8]]]
if <ast.UnaryOp object at 0x7da20c7ca620> begin[:]
<ast.Raise object... | keyword[def] identifier[_read_response] ( identifier[self] ):
literal[string]
identifier[result] = identifier[self] . identifier[buf] . identifier[read_line] (). identifier[decode] ( literal[string] )
keyword[if] keyword[not] identifier[result] :
keyword[raise] identifier[NoResponseError] ( ... | def _read_response(self):
""" Reads a complete response packet from the server """
result = self.buf.read_line().decode('utf-8')
if not result:
raise NoResponseError('No response received from server.') # depends on [control=['if'], data=[]]
msg = self._read_message()
if result != 'ok':
... |
def ping(self, message=_NOTSET, *, encoding=_NOTSET):
"""Ping the server.
Accept optional echo message.
"""
if message is not _NOTSET:
args = (message,)
else:
args = ()
return self.execute('PING', *args, encoding=encoding) | def function[ping, parameter[self, message]]:
constant[Ping the server.
Accept optional echo message.
]
if compare[name[message] is_not name[_NOTSET]] begin[:]
variable[args] assign[=] tuple[[<ast.Name object at 0x7da18bc73640>]]
return[call[name[self].execute, param... | keyword[def] identifier[ping] ( identifier[self] , identifier[message] = identifier[_NOTSET] ,*, identifier[encoding] = identifier[_NOTSET] ):
literal[string]
keyword[if] identifier[message] keyword[is] keyword[not] identifier[_NOTSET] :
identifier[args] =( identifier[message] ,)
... | def ping(self, message=_NOTSET, *, encoding=_NOTSET):
"""Ping the server.
Accept optional echo message.
"""
if message is not _NOTSET:
args = (message,) # depends on [control=['if'], data=['message']]
else:
args = ()
return self.execute('PING', *args, encoding=encoding) |
def _escape_headers(self, headers):
"""
:param dict(str,str) headers:
"""
for key, val in headers.items():
try:
val = val.replace('\\', '\\\\').replace('\n', '\\n').replace(':', '\\c').replace('\r', '\\r')
except:
pass
h... | def function[_escape_headers, parameter[self, headers]]:
constant[
:param dict(str,str) headers:
]
for taget[tuple[[<ast.Name object at 0x7da18f722200>, <ast.Name object at 0x7da18f720100>]]] in starred[call[name[headers].items, parameter[]]] begin[:]
<ast.Try object at 0x7da18f7... | keyword[def] identifier[_escape_headers] ( identifier[self] , identifier[headers] ):
literal[string]
keyword[for] identifier[key] , identifier[val] keyword[in] identifier[headers] . identifier[items] ():
keyword[try] :
identifier[val] = identifier[val] . identifier[... | def _escape_headers(self, headers):
"""
:param dict(str,str) headers:
"""
for (key, val) in headers.items():
try:
val = val.replace('\\', '\\\\').replace('\n', '\\n').replace(':', '\\c').replace('\r', '\\r') # depends on [control=['try'], data=[]]
except:
... |
def RecurseKeys(self):
"""Recurses the Windows Registry keys starting with the root key.
Yields:
WinRegistryKey: Windows Registry key.
"""
root_key = self.GetRootKey()
if root_key:
for registry_key in root_key.RecurseKeys():
yield registry_key | def function[RecurseKeys, parameter[self]]:
constant[Recurses the Windows Registry keys starting with the root key.
Yields:
WinRegistryKey: Windows Registry key.
]
variable[root_key] assign[=] call[name[self].GetRootKey, parameter[]]
if name[root_key] begin[:]
for ... | keyword[def] identifier[RecurseKeys] ( identifier[self] ):
literal[string]
identifier[root_key] = identifier[self] . identifier[GetRootKey] ()
keyword[if] identifier[root_key] :
keyword[for] identifier[registry_key] keyword[in] identifier[root_key] . identifier[RecurseKeys] ():
key... | def RecurseKeys(self):
"""Recurses the Windows Registry keys starting with the root key.
Yields:
WinRegistryKey: Windows Registry key.
"""
root_key = self.GetRootKey()
if root_key:
for registry_key in root_key.RecurseKeys():
yield registry_key # depends on [control=['for'... |
def configure_panel(self):
"""
Configure templates and routing
"""
webroot = os.path.dirname(__file__)
self.template_path = os.path.join(webroot, 'templates')
aiohttp_jinja2.setup(
self, loader=jinja2.FileSystemLoader(self.template_path),
filters=... | def function[configure_panel, parameter[self]]:
constant[
Configure templates and routing
]
variable[webroot] assign[=] call[name[os].path.dirname, parameter[name[__file__]]]
name[self].template_path assign[=] call[name[os].path.join, parameter[name[webroot], constant[templates]]... | keyword[def] identifier[configure_panel] ( identifier[self] ):
literal[string]
identifier[webroot] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] )
identifier[self] . identifier[template_path] = identifier[os] . identifier[path] . identifier[join] ( ident... | def configure_panel(self):
"""
Configure templates and routing
"""
webroot = os.path.dirname(__file__)
self.template_path = os.path.join(webroot, 'templates')
aiohttp_jinja2.setup(self, loader=jinja2.FileSystemLoader(self.template_path), filters={'sorted': sorted, 'int': int})
self['... |
def install(url=None, auth_username=None, auth_password=None,
submission_interval=None, max_batch_size=None, max_clients=10,
base_tags=None, max_buffer_size=None, trigger_size=None,
sample_probability=1.0):
"""Call this to install/setup the InfluxDB client collector. All argument... | def function[install, parameter[url, auth_username, auth_password, submission_interval, max_batch_size, max_clients, base_tags, max_buffer_size, trigger_size, sample_probability]]:
constant[Call this to install/setup the InfluxDB client collector. All arguments
are optional.
:param str url: The InfluxD... | keyword[def] identifier[install] ( identifier[url] = keyword[None] , identifier[auth_username] = keyword[None] , identifier[auth_password] = keyword[None] ,
identifier[submission_interval] = keyword[None] , identifier[max_batch_size] = keyword[None] , identifier[max_clients] = literal[int] ,
identifier[base_tags] =... | def install(url=None, auth_username=None, auth_password=None, submission_interval=None, max_batch_size=None, max_clients=10, base_tags=None, max_buffer_size=None, trigger_size=None, sample_probability=1.0):
"""Call this to install/setup the InfluxDB client collector. All arguments
are optional.
:param str ... |
def updatePassword(self,
user,
currentPassword,
newPassword):
"""Change the password of a user."""
return self.__post('/api/updatePassword',
data={
'user': user,
... | def function[updatePassword, parameter[self, user, currentPassword, newPassword]]:
constant[Change the password of a user.]
return[call[name[self].__post, parameter[constant[/api/updatePassword]]]] | keyword[def] identifier[updatePassword] ( identifier[self] ,
identifier[user] ,
identifier[currentPassword] ,
identifier[newPassword] ):
literal[string]
keyword[return] identifier[self] . identifier[__post] ( literal[string] ,
identifier[data] ={
literal[string] : identifier[u... | def updatePassword(self, user, currentPassword, newPassword):
"""Change the password of a user."""
return self.__post('/api/updatePassword', data={'user': user, 'currentPassword': currentPassword, 'newPassword': newPassword}) |
def _message(self, beacon_config, invert_hello=False):
""" Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
"""
m = WBeaconGouverneurMessenger._message(self, beacon_config, i... | def function[_message, parameter[self, beacon_config, invert_hello]]:
constant[ Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
]
variable[m] assign[=] call[name... | keyword[def] identifier[_message] ( identifier[self] , identifier[beacon_config] , identifier[invert_hello] = keyword[False] ):
literal[string]
identifier[m] = identifier[WBeaconGouverneurMessenger] . identifier[_message] ( identifier[self] , identifier[beacon_config] , identifier[invert_hello] = identifier[in... | def _message(self, beacon_config, invert_hello=False):
""" Overridden :meth:`.WBeaconGouverneurMessenger._message` method. Appends encoded host group names
to requests and responses.
:param beacon_config: beacon configuration
:return: bytes
"""
m = WBeaconGouverneurMessenger._message(self, beacon_confi... |
def _reformat(p, buf):
""" Apply format of ``p`` to data in 1-d array ``buf``. """
if numpy.ndim(buf) != 1:
raise ValueError("Buffer ``buf`` must be 1-d.")
if hasattr(p, 'keys'):
ans = _gvar.BufferDict(p)
if ans.size != len(buf):
raise ValueError( #
... | def function[_reformat, parameter[p, buf]]:
constant[ Apply format of ``p`` to data in 1-d array ``buf``. ]
if compare[call[name[numpy].ndim, parameter[name[buf]]] not_equal[!=] constant[1]] begin[:]
<ast.Raise object at 0x7da2046239a0>
if call[name[hasattr], parameter[name[p], constant[... | keyword[def] identifier[_reformat] ( identifier[p] , identifier[buf] ):
literal[string]
keyword[if] identifier[numpy] . identifier[ndim] ( identifier[buf] )!= literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] identifier[hasattr] ( identifier[p] , literal[... | def _reformat(p, buf):
""" Apply format of ``p`` to data in 1-d array ``buf``. """
if numpy.ndim(buf) != 1:
raise ValueError('Buffer ``buf`` must be 1-d.') # depends on [control=['if'], data=[]]
if hasattr(p, 'keys'):
ans = _gvar.BufferDict(p)
if ans.size != len(buf): #
... |
def authorized(resp, remote):
"""Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application.
"""
if resp and 'error' in resp:
if resp['error'] == 'bad_verification_code':
# See https://developer.github.com/v3/oauth/#bad-verification-... | def function[authorized, parameter[resp, remote]]:
constant[Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application.
]
if <ast.BoolOp object at 0x7da1b251add0> begin[:]
if compare[call[name[resp]][constant[error]] equal[==] co... | keyword[def] identifier[authorized] ( identifier[resp] , identifier[remote] ):
literal[string]
keyword[if] identifier[resp] keyword[and] literal[string] keyword[in] identifier[resp] :
keyword[if] identifier[resp] [ literal[string] ]== literal[string] :
keyword[... | def authorized(resp, remote):
"""Authorized callback handler for GitHub.
:param resp: The response.
:param remote: The remote application.
"""
if resp and 'error' in resp:
if resp['error'] == 'bad_verification_code':
# See https://developer.github.com/v3/oauth/#bad-verification-... |
def replace_zeros(self, val, zero_thresh=0.0):
""" Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with
"""
new_data = self.data.copy()
new_data[new_data <= zero_thresh] = val
return t... | def function[replace_zeros, parameter[self, val, zero_thresh]]:
constant[ Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with
]
variable[new_data] assign[=] call[name[self].data.copy, parameter[]]
... | keyword[def] identifier[replace_zeros] ( identifier[self] , identifier[val] , identifier[zero_thresh] = literal[int] ):
literal[string]
identifier[new_data] = identifier[self] . identifier[data] . identifier[copy] ()
identifier[new_data] [ identifier[new_data] <= identifier[zero_thresh] ]=... | def replace_zeros(self, val, zero_thresh=0.0):
""" Replaces all zeros in the image with a specified value
Returns
-------
image dtype
value to replace zeros with
"""
new_data = self.data.copy()
new_data[new_data <= zero_thresh] = val
return type(self)(new_da... |
def make_pkh_output(value, pubkey, witness=False):
'''
int, bytearray -> TxOut
'''
return _make_output(
value=utils.i2le_padded(value, 8),
output_script=make_pkh_output_script(pubkey, witness)) | def function[make_pkh_output, parameter[value, pubkey, witness]]:
constant[
int, bytearray -> TxOut
]
return[call[name[_make_output], parameter[]]] | keyword[def] identifier[make_pkh_output] ( identifier[value] , identifier[pubkey] , identifier[witness] = keyword[False] ):
literal[string]
keyword[return] identifier[_make_output] (
identifier[value] = identifier[utils] . identifier[i2le_padded] ( identifier[value] , literal[int] ),
identifier[... | def make_pkh_output(value, pubkey, witness=False):
"""
int, bytearray -> TxOut
"""
return _make_output(value=utils.i2le_padded(value, 8), output_script=make_pkh_output_script(pubkey, witness)) |
def _as_chunk(self):
"""
Allows reconstructing indefinite length values
:return:
A unicode string of bits - 1s and 0s
"""
extra_bits = int_from_bytes(self.contents[0:1])
bit_string = '{0:b}'.format(int_from_bytes(self.contents[1:]))
# Ensure we have... | def function[_as_chunk, parameter[self]]:
constant[
Allows reconstructing indefinite length values
:return:
A unicode string of bits - 1s and 0s
]
variable[extra_bits] assign[=] call[name[int_from_bytes], parameter[call[name[self].contents][<ast.Slice object at 0x7da... | keyword[def] identifier[_as_chunk] ( identifier[self] ):
literal[string]
identifier[extra_bits] = identifier[int_from_bytes] ( identifier[self] . identifier[contents] [ literal[int] : literal[int] ])
identifier[bit_string] = literal[string] . identifier[format] ( identifier[int_from_bytes... | def _as_chunk(self):
"""
Allows reconstructing indefinite length values
:return:
A unicode string of bits - 1s and 0s
"""
extra_bits = int_from_bytes(self.contents[0:1])
bit_string = '{0:b}'.format(int_from_bytes(self.contents[1:]))
# Ensure we have leading zeros sin... |
def evaluate_bound(
distribution,
x_data,
parameters=None,
cache=None,
):
"""
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevan... | def function[evaluate_bound, parameter[distribution, x_data, parameters, cache]]:
constant[
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case ... | keyword[def] identifier[evaluate_bound] (
identifier[distribution] ,
identifier[x_data] ,
identifier[parameters] = keyword[None] ,
identifier[cache] = keyword[None] ,
):
literal[string]
keyword[assert] identifier[len] ( identifier[x_data] )== identifier[len] ( identifier[distribution] )
keyword[a... | def evaluate_bound(distribution, x_data, parameters=None, cache=None):
"""
Evaluate lower and upper bounds.
Args:
distribution (Dist):
Distribution to evaluate.
x_data (numpy.ndarray):
Locations for where evaluate bounds at. Relevant in the case of
multiv... |
def priceItems(items):
""" Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price... | def function[priceItems, parameter[items]]:
constant[ Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the lis... | keyword[def] identifier[priceItems] ( identifier[items] ):
literal[string]
identifier[retItems] =[]
identifier[sendItems] =[]
keyword[for] identifier[item] keyword[in] identifier[items] :
identifier[sendItems] . identifier[append] ( identifier[item] . identifier[na... | def priceItems(items):
""" Takes a list of Item objects and returns a list of Item objects with respective prices modified
Uses the given list of item objects to formulate a query to the item database. Uses the returned
results to populate each item in the list with its respective price, th... |
def find_input_usage(self, full_usage_id):
"""Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist with
targe... | def function[find_input_usage, parameter[self, full_usage_id]]:
constant[Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist wi... | keyword[def] identifier[find_input_usage] ( identifier[self] , identifier[full_usage_id] ):
literal[string]
keyword[for] identifier[report_id] , identifier[report_obj] keyword[in] identifier[self] . identifier[__input_report_templates] . identifier[items] ():
keyword[if] identif... | def find_input_usage(self, full_usage_id):
"""Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist with
target usage. No... |
def wait(self, timeout):
"""
Starts the Timer for timeout seconds, then gives 5 second grace period to join the thread.
:param timeout: Duration for timer.
:return: Nothing
"""
self.timeout = timeout
self.start()
self.join(timeout=5) | def function[wait, parameter[self, timeout]]:
constant[
Starts the Timer for timeout seconds, then gives 5 second grace period to join the thread.
:param timeout: Duration for timer.
:return: Nothing
]
name[self].timeout assign[=] name[timeout]
call[name[self].sta... | keyword[def] identifier[wait] ( identifier[self] , identifier[timeout] ):
literal[string]
identifier[self] . identifier[timeout] = identifier[timeout]
identifier[self] . identifier[start] ()
identifier[self] . identifier[join] ( identifier[timeout] = literal[int] ) | def wait(self, timeout):
"""
Starts the Timer for timeout seconds, then gives 5 second grace period to join the thread.
:param timeout: Duration for timer.
:return: Nothing
"""
self.timeout = timeout
self.start()
self.join(timeout=5) |
def authorize_ip_permission(
self, group_name, ip_protocol, from_port, to_port, cidr_ip):
"""
This is a convenience function that wraps the "authorize ip
permission" functionality of the C{authorize_security_group} method.
For an explanation of the parameters, see C{authorize_se... | def function[authorize_ip_permission, parameter[self, group_name, ip_protocol, from_port, to_port, cidr_ip]]:
constant[
This is a convenience function that wraps the "authorize ip
permission" functionality of the C{authorize_security_group} method.
For an explanation of the parameters, ... | keyword[def] identifier[authorize_ip_permission] (
identifier[self] , identifier[group_name] , identifier[ip_protocol] , identifier[from_port] , identifier[to_port] , identifier[cidr_ip] ):
literal[string]
identifier[d] = identifier[self] . identifier[authorize_security_group] (
identifie... | def authorize_ip_permission(self, group_name, ip_protocol, from_port, to_port, cidr_ip):
"""
This is a convenience function that wraps the "authorize ip
permission" functionality of the C{authorize_security_group} method.
For an explanation of the parameters, see C{authorize_security_group}... |
def get_ordering(self, request, queryset, view):
"""Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array.
"""
params = view.get_request_feature(view.SORT)
... | def function[get_ordering, parameter[self, request, queryset, view]]:
constant[Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array.
]
variable[params] assign[=]... | keyword[def] identifier[get_ordering] ( identifier[self] , identifier[request] , identifier[queryset] , identifier[view] ):
literal[string]
identifier[params] = identifier[view] . identifier[get_request_feature] ( identifier[view] . identifier[SORT] )
keyword[if] identifier[params] :
... | def get_ordering(self, request, queryset, view):
"""Return an ordering for a given request.
DRF expects a comma separated list, while DREST expects an array.
This method overwrites the DRF default so it can parse the array.
"""
params = view.get_request_feature(view.SORT)
if params:... |
def process_multinest_run(file_root, base_dir, **kwargs):
"""Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requ... | def function[process_multinest_run, parameter[file_root, base_dir]]:
constant[Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they ... | keyword[def] identifier[process_multinest_run] ( identifier[file_root] , identifier[base_dir] ,** identifier[kwargs] ):
literal[string]
identifier[dead] = identifier[np] . identifier[loadtxt] ( identifier[os] . identifier[path] . identifier[join] ( identifier[base_dir] , identifier[file_root] )+ liter... | def process_multinest_run(file_root, base_dir, **kwargs):
"""Loads data from a MultiNest run into the nestcheck dictionary format for
analysis.
N.B. producing required output file containing information about the
iso-likelihood contours within which points were sampled (where they were
"born") requ... |
def vq_nearest_neighbor(x, means,
soft_em=False, num_samples=10, temperature=None):
"""Find the nearest element in means to elements in x."""
bottleneck_size = common_layers.shape_list(means)[0]
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum... | def function[vq_nearest_neighbor, parameter[x, means, soft_em, num_samples, temperature]]:
constant[Find the nearest element in means to elements in x.]
variable[bottleneck_size] assign[=] call[call[name[common_layers].shape_list, parameter[name[means]]]][constant[0]]
variable[x_norm_sq] assign[... | keyword[def] identifier[vq_nearest_neighbor] ( identifier[x] , identifier[means] ,
identifier[soft_em] = keyword[False] , identifier[num_samples] = literal[int] , identifier[temperature] = keyword[None] ):
literal[string]
identifier[bottleneck_size] = identifier[common_layers] . identifier[shape_list] ( ident... | def vq_nearest_neighbor(x, means, soft_em=False, num_samples=10, temperature=None):
"""Find the nearest element in means to elements in x."""
bottleneck_size = common_layers.shape_list(means)[0]
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means... |
def active_futures(ticker: str, dt) -> str:
"""
Active futures contract
Args:
ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.
dt: date
Returns:
str: ticker name
"""
t_info = ticker.split()
prefix, asset = ' '.join(t_info[:-1]), t_info[-1]
in... | def function[active_futures, parameter[ticker, dt]]:
constant[
Active futures contract
Args:
ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.
dt: date
Returns:
str: ticker name
]
variable[t_info] assign[=] call[name[ticker].split, parameter[]... | keyword[def] identifier[active_futures] ( identifier[ticker] : identifier[str] , identifier[dt] )-> identifier[str] :
literal[string]
identifier[t_info] = identifier[ticker] . identifier[split] ()
identifier[prefix] , identifier[asset] = literal[string] . identifier[join] ( identifier[t_info] [:- lite... | def active_futures(ticker: str, dt) -> str:
"""
Active futures contract
Args:
ticker: futures ticker, i.e., ESA Index, Z A Index, CLA Comdty, etc.
dt: date
Returns:
str: ticker name
"""
t_info = ticker.split()
(prefix, asset) = (' '.join(t_info[:-1]), t_info[-1])
... |
def send_mail(subject, message, from_email, recipient_list, html_message='',
scheduled_time=None, headers=None, priority=PRIORITY.medium):
"""
Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method.
"""
subject = force_text(subject)
... | def function[send_mail, parameter[subject, message, from_email, recipient_list, html_message, scheduled_time, headers, priority]]:
constant[
Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method.
]
variable[subject] assign[=] call[name[force_... | keyword[def] identifier[send_mail] ( identifier[subject] , identifier[message] , identifier[from_email] , identifier[recipient_list] , identifier[html_message] = literal[string] ,
identifier[scheduled_time] = keyword[None] , identifier[headers] = keyword[None] , identifier[priority] = identifier[PRIORITY] . identifi... | def send_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium):
"""
Add a new message to the mail queue. This is a replacement for Django's
``send_mail`` core email method.
"""
subject = force_text(subject)
status = None ... |
def _read_para_relay_hmac(self, code, cbit, clen, *, desc, length, version):
"""Read HIP RELAY_HMAC parameter.
Structure of HIP RELAY_HMAC parameter [RFC 5770]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 ... | def function[_read_para_relay_hmac, parameter[self, code, cbit, clen]]:
constant[Read HIP RELAY_HMAC parameter.
Structure of HIP RELAY_HMAC parameter [RFC 5770]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6... | keyword[def] identifier[_read_para_relay_hmac] ( identifier[self] , identifier[code] , identifier[cbit] , identifier[clen] ,*, identifier[desc] , identifier[length] , identifier[version] ):
literal[string]
identifier[_hmac] = identifier[self] . identifier[_read_fileng] ( identifier[clen] )
... | def _read_para_relay_hmac(self, code, cbit, clen, *, desc, length, version):
"""Read HIP RELAY_HMAC parameter.
Structure of HIP RELAY_HMAC parameter [RFC 5770]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 ... |
def server_enabled(s_name, **connection_args):
'''
Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName'
'''
server = _server_get(s_name, **connection_args)
return server is not None and server.get_state() == 'ENABLE... | def function[server_enabled, parameter[s_name]]:
constant[
Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName'
]
variable[server] assign[=] call[name[_server_get], parameter[name[s_name]]]
return[<ast.BoolO... | keyword[def] identifier[server_enabled] ( identifier[s_name] ,** identifier[connection_args] ):
literal[string]
identifier[server] = identifier[_server_get] ( identifier[s_name] ,** identifier[connection_args] )
keyword[return] identifier[server] keyword[is] keyword[not] keyword[None] keyword[and... | def server_enabled(s_name, **connection_args):
"""
Check if a server is enabled globally
CLI Example:
.. code-block:: bash
salt '*' netscaler.server_enabled 'serverName'
"""
server = _server_get(s_name, **connection_args)
return server is not None and server.get_state() == 'ENABLE... |
def auth(**kwargs):
''' Authorize device synchronization. '''
"""
kodrive auth <path> <device_id (client)>
1. make sure path has been added to config.xml, server
2. make sure path is not shared by someone
3. add device_id to folder in config.xml, server
4. add device to devices in config.xml, ... | def function[auth, parameter[]]:
constant[ Authorize device synchronization. ]
constant[
kodrive auth <path> <device_id (client)>
1. make sure path has been added to config.xml, server
2. make sure path is not shared by someone
3. add device_id to folder in config.xml, server
4. add... | keyword[def] identifier[auth] (** identifier[kwargs] ):
literal[string]
literal[string]
identifier[option] = literal[string]
identifier[path] = identifier[kwargs] [ literal[string] ]
identifier[key] = identifier[kwargs] [ literal[string] ]
keyword[if] identifier[kwargs] [ literal[string] ]:
... | def auth(**kwargs):
""" Authorize device synchronization. """
'\n kodrive auth <path> <device_id (client)>\n\n 1. make sure path has been added to config.xml, server\n 2. make sure path is not shared by someone\n 3. add device_id to folder in config.xml, server\n 4. add device to devices in confi... |
def stats(args):
"""Create stats from the analysis
"""
logger.info("Reading sequeces")
data = parse_ma_file(args.ma)
logger.info("Get sequences from sam")
is_align = _read_sam(args.sam)
is_json, is_db = _read_json(args.json)
res = _summarise_sam(data, is_align, is_json, is_db)
_write... | def function[stats, parameter[args]]:
constant[Create stats from the analysis
]
call[name[logger].info, parameter[constant[Reading sequeces]]]
variable[data] assign[=] call[name[parse_ma_file], parameter[name[args].ma]]
call[name[logger].info, parameter[constant[Get sequences from sa... | keyword[def] identifier[stats] ( identifier[args] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[data] = identifier[parse_ma_file] ( identifier[args] . identifier[ma] )
identifier[logger] . identifier[info] ( literal[string] )
identifier[is_align] = i... | def stats(args):
"""Create stats from the analysis
"""
logger.info('Reading sequeces')
data = parse_ma_file(args.ma)
logger.info('Get sequences from sam')
is_align = _read_sam(args.sam)
(is_json, is_db) = _read_json(args.json)
res = _summarise_sam(data, is_align, is_json, is_db)
_wri... |
def qqplot(pv, distr = 'log10', alphaLevel = 0.05):
"""
This script makes a Quantile-Quantile plot of the observed
negative log P-value distribution against the theoretical one under the null.
Input:
pv pvalues (numpy array)
distr scale of the distribution (log10 or chi2)
alphaLevel signifi... | def function[qqplot, parameter[pv, distr, alphaLevel]]:
constant[
This script makes a Quantile-Quantile plot of the observed
negative log P-value distribution against the theoretical one under the null.
Input:
pv pvalues (numpy array)
distr scale of the distribution (log10 or chi2)
alphaL... | keyword[def] identifier[qqplot] ( identifier[pv] , identifier[distr] = literal[string] , identifier[alphaLevel] = literal[int] ):
literal[string]
identifier[shape_ok] =( identifier[len] ( identifier[pv] . identifier[shape] )== literal[int] ) keyword[or] (( identifier[len] ( identifier[pv] . identifier[shape] )==... | def qqplot(pv, distr='log10', alphaLevel=0.05):
"""
This script makes a Quantile-Quantile plot of the observed
negative log P-value distribution against the theoretical one under the null.
Input:
pv pvalues (numpy array)
distr scale of the distribution (log10 or chi2)
alphaLevel signific... |
def doc_children(self, doctype, limiters=[]):
"""Finds all grand-children of this element's docstrings that match
the specified doctype. If 'limiters' is specified, only docstrings
with those doctypes are searched.
"""
result = []
for doc in self.docstring:
if... | def function[doc_children, parameter[self, doctype, limiters]]:
constant[Finds all grand-children of this element's docstrings that match
the specified doctype. If 'limiters' is specified, only docstrings
with those doctypes are searched.
]
variable[result] assign[=] list[[]]
... | keyword[def] identifier[doc_children] ( identifier[self] , identifier[doctype] , identifier[limiters] =[]):
literal[string]
identifier[result] =[]
keyword[for] identifier[doc] keyword[in] identifier[self] . identifier[docstring] :
keyword[if] identifier[len] ( identifier[l... | def doc_children(self, doctype, limiters=[]):
"""Finds all grand-children of this element's docstrings that match
the specified doctype. If 'limiters' is specified, only docstrings
with those doctypes are searched.
"""
result = []
for doc in self.docstring:
if len(limiters) =... |
def COSTALD(T, Tc, Vc, omega):
r'''Calculate saturation liquid density using the COSTALD CSP method.
A popular and accurate estimation method. If possible, fit parameters are
used; alternatively critical properties work well.
The density of a liquid is given by:
.. math::
V_s=V^*V^{(0)}[1... | def function[COSTALD, parameter[T, Tc, Vc, omega]]:
constant[Calculate saturation liquid density using the COSTALD CSP method.
A popular and accurate estimation method. If possible, fit parameters are
used; alternatively critical properties work well.
The density of a liquid is given by:
.. m... | keyword[def] identifier[COSTALD] ( identifier[T] , identifier[Tc] , identifier[Vc] , identifier[omega] ):
literal[string]
identifier[Tr] = identifier[T] / identifier[Tc]
identifier[V_delta] =(- literal[int] + literal[int] * identifier[Tr] - literal[int] * identifier[Tr] ** literal[int]
- literal... | def COSTALD(T, Tc, Vc, omega):
"""Calculate saturation liquid density using the COSTALD CSP method.
A popular and accurate estimation method. If possible, fit parameters are
used; alternatively critical properties work well.
The density of a liquid is given by:
.. math::
V_s=V^*V^{(0)}[1-... |
def run_total_dos(self,
sigma=None,
freq_min=None,
freq_max=None,
freq_pitch=None,
use_tetrahedron_method=True):
"""Calculate total DOS from phonons on sampling mesh.
Parameters
-------... | def function[run_total_dos, parameter[self, sigma, freq_min, freq_max, freq_pitch, use_tetrahedron_method]]:
constant[Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
... | keyword[def] identifier[run_total_dos] ( identifier[self] ,
identifier[sigma] = keyword[None] ,
identifier[freq_min] = keyword[None] ,
identifier[freq_max] = keyword[None] ,
identifier[freq_pitch] = keyword[None] ,
identifier[use_tetrahedron_method] = keyword[True] ):
literal[string]
keyword[i... | def run_total_dos(self, sigma=None, freq_min=None, freq_max=None, freq_pitch=None, use_tetrahedron_method=True):
"""Calculate total DOS from phonons on sampling mesh.
Parameters
----------
sigma : float, optional
Smearing width for smearing method. Default is None
freq_m... |
def _t_normals(self):
r"""
Update the throat normals from the voronoi vertices
"""
verts = self['throat.vertices']
value = sp.zeros([len(verts), 3])
for i in range(len(verts)):
if len(sp.unique(verts[i][:, 0])) == 1:
verts_2d = sp.vstack((verts... | def function[_t_normals, parameter[self]]:
constant[
Update the throat normals from the voronoi vertices
]
variable[verts] assign[=] call[name[self]][constant[throat.vertices]]
variable[value] assign[=] call[name[sp].zeros, parameter[list[[<ast.Call object at 0x7da18eb54fa0>, <as... | keyword[def] identifier[_t_normals] ( identifier[self] ):
literal[string]
identifier[verts] = identifier[self] [ literal[string] ]
identifier[value] = identifier[sp] . identifier[zeros] ([ identifier[len] ( identifier[verts] ), literal[int] ])
keyword[for] identifier[i] keyword[... | def _t_normals(self):
"""
Update the throat normals from the voronoi vertices
"""
verts = self['throat.vertices']
value = sp.zeros([len(verts), 3])
for i in range(len(verts)):
if len(sp.unique(verts[i][:, 0])) == 1:
verts_2d = sp.vstack((verts[i][:, 1], verts[i][:, 2]... |
def is_initialized(self):
"""Check if bucket exists.
:return: True if initialized, False otherwise
"""
try:
return self.client.head_bucket(
Bucket=self.db_path)['ResponseMetadata']['HTTPStatusCode'] \
== 200
except botocore.exception... | def function[is_initialized, parameter[self]]:
constant[Check if bucket exists.
:return: True if initialized, False otherwise
]
<ast.Try object at 0x7da1b00f7ee0> | keyword[def] identifier[is_initialized] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[client] . identifier[head_bucket] (
identifier[Bucket] = identifier[self] . identifier[db_path] )[ literal[string] ][ literal[string]... | def is_initialized(self):
"""Check if bucket exists.
:return: True if initialized, False otherwise
"""
try:
return self.client.head_bucket(Bucket=self.db_path)['ResponseMetadata']['HTTPStatusCode'] == 200 # depends on [control=['try'], data=[]]
except botocore.exceptions.ClientError... |
def _cert_callback(callback, der_cert, reason):
"""
Constructs an asn1crypto.x509.Certificate object and calls the export
callback
:param callback:
The callback to call
:param der_cert:
A byte string of the DER-encoded certificate
:param reason:
None if cert is being e... | def function[_cert_callback, parameter[callback, der_cert, reason]]:
constant[
Constructs an asn1crypto.x509.Certificate object and calls the export
callback
:param callback:
The callback to call
:param der_cert:
A byte string of the DER-encoded certificate
:param reason:
... | keyword[def] identifier[_cert_callback] ( identifier[callback] , identifier[der_cert] , identifier[reason] ):
literal[string]
keyword[if] keyword[not] identifier[callback] :
keyword[return]
identifier[callback] ( identifier[x509] . identifier[Certificate] . identifier[load] ( identifier[d... | def _cert_callback(callback, der_cert, reason):
"""
Constructs an asn1crypto.x509.Certificate object and calls the export
callback
:param callback:
The callback to call
:param der_cert:
A byte string of the DER-encoded certificate
:param reason:
None if cert is being e... |
def write(self, file_des, contents):
"""Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
Number of bytes written.
... | def function[write, parameter[self, file_des, contents]]:
constant[Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
... | keyword[def] identifier[write] ( identifier[self] , identifier[file_des] , identifier[contents] ):
literal[string]
identifier[file_handle] = identifier[self] . identifier[filesystem] . identifier[get_open_file] ( identifier[file_des] )
keyword[if] identifier[isinstance] ( identifier[file_... | def write(self, file_des, contents):
"""Write string to file descriptor, returns number of bytes written.
Args:
file_des: An integer file descriptor for the file object requested.
contents: String of bytes to write to file.
Returns:
Number of bytes written.
... |
def update(anchor, handle=None):
"""Update an anchor based on the current contents of its source file.
Args:
anchor: The `Anchor` to be updated.
handle: File-like object containing contents of the anchor's file. If
`None`, then this function will open the file and read it.
Retu... | def function[update, parameter[anchor, handle]]:
constant[Update an anchor based on the current contents of its source file.
Args:
anchor: The `Anchor` to be updated.
handle: File-like object containing contents of the anchor's file. If
`None`, then this function will open the f... | keyword[def] identifier[update] ( identifier[anchor] , identifier[handle] = keyword[None] ):
literal[string]
keyword[if] identifier[handle] keyword[is] keyword[None] :
keyword[with] identifier[anchor] . identifier[file_path] . identifier[open] ( identifier[mode] = literal[string] ) keyword[as]... | def update(anchor, handle=None):
"""Update an anchor based on the current contents of its source file.
Args:
anchor: The `Anchor` to be updated.
handle: File-like object containing contents of the anchor's file. If
`None`, then this function will open the file and read it.
Retu... |
def source_address(self):
"""Return the authorative source of the link."""
# If link is a sender, source is determined by the local
# value, else use the remote.
if self._pn_link.is_sender:
return self._pn_link.source.address
else:
return self._pn_link.rem... | def function[source_address, parameter[self]]:
constant[Return the authorative source of the link.]
if name[self]._pn_link.is_sender begin[:]
return[name[self]._pn_link.source.address] | keyword[def] identifier[source_address] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_pn_link] . identifier[is_sender] :
keyword[return] identifier[self] . identifier[_pn_link] . identifier[source] . identifier[address]
k... | def source_address(self):
"""Return the authorative source of the link."""
# If link is a sender, source is determined by the local
# value, else use the remote.
if self._pn_link.is_sender:
return self._pn_link.source.address # depends on [control=['if'], data=[]]
else:
return self.... |
def verify_sans(amazon_cert: crypto.X509) -> bool:
"""Verifies Subject Alternative Names (SANs) for Amazon certificate.
Args:
amazon_cert: Pycrypto X509 Amazon certificate.
Returns:
result: True if verification was successful, False if not.
"""
cert_extentions = [amazon_cert.get_ex... | def function[verify_sans, parameter[amazon_cert]]:
constant[Verifies Subject Alternative Names (SANs) for Amazon certificate.
Args:
amazon_cert: Pycrypto X509 Amazon certificate.
Returns:
result: True if verification was successful, False if not.
]
variable[cert_extentions]... | keyword[def] identifier[verify_sans] ( identifier[amazon_cert] : identifier[crypto] . identifier[X509] )-> identifier[bool] :
literal[string]
identifier[cert_extentions] =[ identifier[amazon_cert] . identifier[get_extension] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[range] ( id... | def verify_sans(amazon_cert: crypto.X509) -> bool:
"""Verifies Subject Alternative Names (SANs) for Amazon certificate.
Args:
amazon_cert: Pycrypto X509 Amazon certificate.
Returns:
result: True if verification was successful, False if not.
"""
cert_extentions = [amazon_cert.get_ex... |
def read(self, file):
"""Reads the captions file."""
content = self._read_content(file)
self._validate(content)
self._parse(content)
return self | def function[read, parameter[self, file]]:
constant[Reads the captions file.]
variable[content] assign[=] call[name[self]._read_content, parameter[name[file]]]
call[name[self]._validate, parameter[name[content]]]
call[name[self]._parse, parameter[name[content]]]
return[name[self]] | keyword[def] identifier[read] ( identifier[self] , identifier[file] ):
literal[string]
identifier[content] = identifier[self] . identifier[_read_content] ( identifier[file] )
identifier[self] . identifier[_validate] ( identifier[content] )
identifier[self] . identifier[_parse] ( i... | def read(self, file):
"""Reads the captions file."""
content = self._read_content(file)
self._validate(content)
self._parse(content)
return self |
def run(self):
"""The main routine for a thread's work.
The thread pulls tasks from the task queue and executes them until it
encounters a death token. The death token is a tuple of two Nones.
"""
try:
quit_request_detected = False
while True:
... | def function[run, parameter[self]]:
constant[The main routine for a thread's work.
The thread pulls tasks from the task queue and executes them until it
encounters a death token. The death token is a tuple of two Nones.
]
<ast.Try object at 0x7da20c6e58d0> | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[quit_request_detected] = keyword[False]
keyword[while] keyword[True] :
identifier[function] , identifier[arguments] = identifier[self] . identifier[task_queue] .... | def run(self):
"""The main routine for a thread's work.
The thread pulls tasks from the task queue and executes them until it
encounters a death token. The death token is a tuple of two Nones.
"""
try:
quit_request_detected = False
while True:
(function, arg... |
def delete_security_group(self, name=None, group_id=None):
"""
Delete a security group from your account.
:type name: string
:param name: The name of the security group to delete.
:type group_id: string
:param group_id: The ID of the security group to delete within
... | def function[delete_security_group, parameter[self, name, group_id]]:
constant[
Delete a security group from your account.
:type name: string
:param name: The name of the security group to delete.
:type group_id: string
:param group_id: The ID of the security group to d... | keyword[def] identifier[delete_security_group] ( identifier[self] , identifier[name] = keyword[None] , identifier[group_id] = keyword[None] ):
literal[string]
identifier[params] ={}
keyword[if] identifier[name] keyword[is] keyword[not] keyword[None] :
identifier[params] [... | def delete_security_group(self, name=None, group_id=None):
"""
Delete a security group from your account.
:type name: string
:param name: The name of the security group to delete.
:type group_id: string
:param group_id: The ID of the security group to delete within
... |
def atlas_overlap(dset,atlas=None):
'''aligns ``dset`` to the TT_N27 atlas and returns ``(cost,overlap)``'''
atlas = find_atlas(atlas)
if atlas==None:
return None
cost_func = 'crM'
infile = os.path.abspath(dset)
tmpdir = tempfile.mkdtemp()
with nl.run_in(tmpdir):
o = nl.... | def function[atlas_overlap, parameter[dset, atlas]]:
constant[aligns ``dset`` to the TT_N27 atlas and returns ``(cost,overlap)``]
variable[atlas] assign[=] call[name[find_atlas], parameter[name[atlas]]]
if compare[name[atlas] equal[==] constant[None]] begin[:]
return[constant[None]]
... | keyword[def] identifier[atlas_overlap] ( identifier[dset] , identifier[atlas] = keyword[None] ):
literal[string]
identifier[atlas] = identifier[find_atlas] ( identifier[atlas] )
keyword[if] identifier[atlas] == keyword[None] :
keyword[return] keyword[None]
identifier[cost_func] = lit... | def atlas_overlap(dset, atlas=None):
"""aligns ``dset`` to the TT_N27 atlas and returns ``(cost,overlap)``"""
atlas = find_atlas(atlas)
if atlas == None:
return None # depends on [control=['if'], data=[]]
cost_func = 'crM'
infile = os.path.abspath(dset)
tmpdir = tempfile.mkdtemp()
w... |
def bounding_boxes(self, mode='fraction', output='dict'):
"""Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the sheet. If 'a... | def function[bounding_boxes, parameter[self, mode, output]]:
constant[Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the she... | keyword[def] identifier[bounding_boxes] ( identifier[self] , identifier[mode] = literal[string] , identifier[output] = literal[string] ):
literal[string]
identifier[boxes] ={}
keyword[if] identifier[mode] keyword[not] keyword[in] ( literal[string] , literal[string] ):
... | def bounding_boxes(self, mode='fraction', output='dict'):
"""Get the bounding boxes of the labels on a page.
Parameters
----------
mode: 'fraction', 'actual'
If 'fraction', the bounding boxes are expressed as a fraction of the
height and width of the sheet. If 'actua... |
def command_max_delay(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_delay """
try:
max_delay = self.max_delay_var.get()
except ValueError:
max_delay = self.runtime_cfg.max_delay
if max_delay < 0:
max_delay = self.runtime_cfg... | def function[command_max_delay, parameter[self, event]]:
constant[ CPU burst max running time - self.runtime_cfg.max_delay ]
<ast.Try object at 0x7da1b05e0370>
if compare[name[max_delay] less[<] constant[0]] begin[:]
variable[max_delay] assign[=] name[self].runtime_cfg.max_delay
... | keyword[def] identifier[command_max_delay] ( identifier[self] , identifier[event] = keyword[None] ):
literal[string]
keyword[try] :
identifier[max_delay] = identifier[self] . identifier[max_delay_var] . identifier[get] ()
keyword[except] identifier[ValueError] :
... | def command_max_delay(self, event=None):
""" CPU burst max running time - self.runtime_cfg.max_delay """
try:
max_delay = self.max_delay_var.get() # depends on [control=['try'], data=[]]
except ValueError:
max_delay = self.runtime_cfg.max_delay # depends on [control=['except'], data=[]]
... |
def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.string_types):
return value
elif isinstance(value, numbers.Number):
return str(value)
raise ParameterNotValidError | def function[clean, parameter[self, value]]:
constant[Cleans and returns the given value, or raises a ParameterNotValidError exception]
if call[name[isinstance], parameter[name[value], name[six].string_types]] begin[:]
return[name[value]]
<ast.Raise object at 0x7da2054a6350> | keyword[def] identifier[clean] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[six] . identifier[string_types] ):
keyword[return] identifier[value]
keyword[elif] identifier[isinstance] ( identif... | def clean(self, value):
"""Cleans and returns the given value, or raises a ParameterNotValidError exception"""
if isinstance(value, six.string_types):
return value # depends on [control=['if'], data=[]]
elif isinstance(value, numbers.Number):
return str(value) # depends on [control=['if'],... |
def ldap_server_maprole_group_ad_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
maprole = ET.SubElement(ldap_server, "maprole")
group = ET.SubElem... | def function[ldap_server_maprole_group_ad_group, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[ldap_server] assign[=] call[name[ET].SubElement, parameter[name[config], constant[ldap-server]]]
... | keyword[def] identifier[ldap_server_maprole_group_ad_group] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[ldap_server] = identifier[ET] . identifier[SubElement] ( identifier[config] , li... | def ldap_server_maprole_group_ad_group(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
ldap_server = ET.SubElement(config, 'ldap-server', xmlns='urn:brocade.com:mgmt:brocade-aaa')
maprole = ET.SubElement(ldap_server, 'maprole')
group = ET.SubElement(maprole, 'group'... |
def _skip_to_blank(f, spacegroup, setting):
"""Read lines from f until a blank line is encountered."""
while True:
line = f.readline()
if not line:
raise SpacegroupNotFoundError(
'invalid spacegroup %s, setting %i not found in data base' %
( spacegrou... | def function[_skip_to_blank, parameter[f, spacegroup, setting]]:
constant[Read lines from f until a blank line is encountered.]
while constant[True] begin[:]
variable[line] assign[=] call[name[f].readline, parameter[]]
if <ast.UnaryOp object at 0x7da18dc046d0> begin[:]
... | keyword[def] identifier[_skip_to_blank] ( identifier[f] , identifier[spacegroup] , identifier[setting] ):
literal[string]
keyword[while] keyword[True] :
identifier[line] = identifier[f] . identifier[readline] ()
keyword[if] keyword[not] identifier[line] :
keyword[raise] i... | def _skip_to_blank(f, spacegroup, setting):
"""Read lines from f until a blank line is encountered."""
while True:
line = f.readline()
if not line:
raise SpacegroupNotFoundError('invalid spacegroup %s, setting %i not found in data base' % (spacegroup, setting)) # depends on [control... |
def parse_username(username):
"""
Parses the given username or channel access hash, given
a string, username or URL. Returns a tuple consisting of
both the stripped, lowercase username and whether it is
a joinchat/ hash (in which case is not lowercase'd).
Returns ``(None, False)`` if the ``user... | def function[parse_username, parameter[username]]:
constant[
Parses the given username or channel access hash, given
a string, username or URL. Returns a tuple consisting of
both the stripped, lowercase username and whether it is
a joinchat/ hash (in which case is not lowercase'd).
Returns ... | keyword[def] identifier[parse_username] ( identifier[username] ):
literal[string]
identifier[username] = identifier[username] . identifier[strip] ()
identifier[m] = identifier[USERNAME_RE] . identifier[match] ( identifier[username] ) keyword[or] identifier[TG_JOIN_RE] . identifier[match] ( identifier... | def parse_username(username):
"""
Parses the given username or channel access hash, given
a string, username or URL. Returns a tuple consisting of
both the stripped, lowercase username and whether it is
a joinchat/ hash (in which case is not lowercase'd).
Returns ``(None, False)`` if the ``user... |
def _set_node_lists(self, new):
""" Maintains each edge's list of available nodes.
"""
for edge in self.edges:
edge._nodes = self.nodes | def function[_set_node_lists, parameter[self, new]]:
constant[ Maintains each edge's list of available nodes.
]
for taget[name[edge]] in starred[name[self].edges] begin[:]
name[edge]._nodes assign[=] name[self].nodes | keyword[def] identifier[_set_node_lists] ( identifier[self] , identifier[new] ):
literal[string]
keyword[for] identifier[edge] keyword[in] identifier[self] . identifier[edges] :
identifier[edge] . identifier[_nodes] = identifier[self] . identifier[nodes] | def _set_node_lists(self, new):
""" Maintains each edge's list of available nodes.
"""
for edge in self.edges:
edge._nodes = self.nodes # depends on [control=['for'], data=['edge']] |
def rebuild_pipelines(*args):
"""Entry point for rebuilding pipelines.
Use to rebuild all pipelines or a specific group.
"""
rebuild_all = False
rebuild_project = os.getenv("REBUILD_PROJECT")
if args:
LOG.debug('Incoming arguments: %s', args)
command_args, *_ = args
reb... | def function[rebuild_pipelines, parameter[]]:
constant[Entry point for rebuilding pipelines.
Use to rebuild all pipelines or a specific group.
]
variable[rebuild_all] assign[=] constant[False]
variable[rebuild_project] assign[=] call[name[os].getenv, parameter[constant[REBUILD_PROJECT]]... | keyword[def] identifier[rebuild_pipelines] (* identifier[args] ):
literal[string]
identifier[rebuild_all] = keyword[False]
identifier[rebuild_project] = identifier[os] . identifier[getenv] ( literal[string] )
keyword[if] identifier[args] :
identifier[LOG] . identifier[debug] ( literal... | def rebuild_pipelines(*args):
"""Entry point for rebuilding pipelines.
Use to rebuild all pipelines or a specific group.
"""
rebuild_all = False
rebuild_project = os.getenv('REBUILD_PROJECT')
if args:
LOG.debug('Incoming arguments: %s', args)
(command_args, *_) = args
re... |
def PYTHON_VERSION(stats, info):
"""Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
"""
# Some versions of Python have a \n in sys.version!
version = sys.version.replace(' \n', ' ').replace('\n', ' ')
python = ';'.join([str(c) for c in sys.version_info] + [version])... | def function[PYTHON_VERSION, parameter[stats, info]]:
constant[Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
]
variable[version] assign[=] call[call[name[sys].version.replace, parameter[constant[
], constant[ ]]].replace, parameter[constant[
], constant[ ]]]
... | keyword[def] identifier[PYTHON_VERSION] ( identifier[stats] , identifier[info] ):
literal[string]
identifier[version] = identifier[sys] . identifier[version] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] )
identifier[python] =... | def PYTHON_VERSION(stats, info):
"""Python interpreter version.
This is a flag you can pass to `Stats.submit()`.
"""
# Some versions of Python have a \n in sys.version!
version = sys.version.replace(' \n', ' ').replace('\n', ' ')
python = ';'.join([str(c) for c in sys.version_info] + [version])... |
def print_help(self, session, command=None):
"""
Prints the available methods and their documentation, or the
documentation of the given command.
"""
if command:
# Single command mode
if command in self._commands:
# Argument is a name space... | def function[print_help, parameter[self, session, command]]:
constant[
Prints the available methods and their documentation, or the
documentation of the given command.
]
if name[command] begin[:]
if compare[name[command] in name[self]._commands] begin[:]
... | keyword[def] identifier[print_help] ( identifier[self] , identifier[session] , identifier[command] = keyword[None] ):
literal[string]
keyword[if] identifier[command] :
keyword[if] identifier[command] keyword[in] identifier[self] . identifier[_commands] :
... | def print_help(self, session, command=None):
"""
Prints the available methods and their documentation, or the
documentation of the given command.
"""
if command:
# Single command mode
if command in self._commands:
# Argument is a name space
self.__... |
def parse_from_parent(
self,
parent, # type: ET.Element
state # type: _ProcessorState
):
# type: (...) -> Any
"""Parse the array data from the provided parent XML element."""
item_iter = parent.findall(self._item_path)
return self._parse(item_ite... | def function[parse_from_parent, parameter[self, parent, state]]:
constant[Parse the array data from the provided parent XML element.]
variable[item_iter] assign[=] call[name[parent].findall, parameter[name[self]._item_path]]
return[call[name[self]._parse, parameter[name[item_iter], name[state]]]] | keyword[def] identifier[parse_from_parent] (
identifier[self] ,
identifier[parent] ,
identifier[state]
):
literal[string]
identifier[item_iter] = identifier[parent] . identifier[findall] ( identifier[self] . identifier[_item_path] )
keyword[return] identifier[self] . identifier[_pars... | def parse_from_parent(self, parent, state): # type: ET.Element
# type: _ProcessorState
# type: (...) -> Any
'Parse the array data from the provided parent XML element.'
item_iter = parent.findall(self._item_path)
return self._parse(item_iter, state) |
def strictjoin(L, keycols, nullvals=None, renaming=None, Names=None):
"""
Combine two or more numpy ndarray with structured dtypes on common key
column(s).
Merge a list (or dictionary) of numpy arrays, given by `L`, on key
columns listed in `keycols`.
The ``strictjoin`` assumes the following ... | def function[strictjoin, parameter[L, keycols, nullvals, renaming, Names]]:
constant[
Combine two or more numpy ndarray with structured dtypes on common key
column(s).
Merge a list (or dictionary) of numpy arrays, given by `L`, on key
columns listed in `keycols`.
The ``strictjoin`` assume... | keyword[def] identifier[strictjoin] ( identifier[L] , identifier[keycols] , identifier[nullvals] = keyword[None] , identifier[renaming] = keyword[None] , identifier[Names] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[L] , identifier[dict] ):
identifier[Names... | def strictjoin(L, keycols, nullvals=None, renaming=None, Names=None):
"""
Combine two or more numpy ndarray with structured dtypes on common key
column(s).
Merge a list (or dictionary) of numpy arrays, given by `L`, on key
columns listed in `keycols`.
The ``strictjoin`` assumes the following ... |
def find_first_wt_parent(self, with_ip=False):
"""
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict the search to the firs... | def function[find_first_wt_parent, parameter[self, with_ip]]:
constant[
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict t... | keyword[def] identifier[find_first_wt_parent] ( identifier[self] , identifier[with_ip] = keyword[False] ):
literal[string]
identifier[parent_id] = identifier[self] . identifier[part_of_id]
keyword[if] keyword[not] identifier[parent_id] :
keyword[return] keyword[False]
... | def find_first_wt_parent(self, with_ip=False):
"""
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns
a parent Biosample ID if its wild_type attribute is True.
Args:
with_ip: `bool`. True means to restrict the search to the first pa... |
def stats_for(self, dt):
"""
Returns stats for the month containing the given datetime
"""
# TODO - this would be nicer if we formatted the stats
if not isinstance(dt, datetime):
raise TypeError('stats_for requires a datetime object!')
return self._client.get(... | def function[stats_for, parameter[self, dt]]:
constant[
Returns stats for the month containing the given datetime
]
if <ast.UnaryOp object at 0x7da1b0f078b0> begin[:]
<ast.Raise object at 0x7da1b0f07370>
return[call[name[self]._client.get, parameter[call[constant[{}/stats/].f... | keyword[def] identifier[stats_for] ( identifier[self] , identifier[dt] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[dt] , identifier[datetime] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keyword[return] identifier... | def stats_for(self, dt):
"""
Returns stats for the month containing the given datetime
"""
# TODO - this would be nicer if we formatted the stats
if not isinstance(dt, datetime):
raise TypeError('stats_for requires a datetime object!') # depends on [control=['if'], data=[]]
retu... |
def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for ... | def function[filter_by_attrs, parameter[self]]:
constant[Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either `... | keyword[def] identifier[filter_by_attrs] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[selection] =[]
keyword[for] identifier[var_name] , identifier[variable] keyword[in] identifier[self] . identifier[data_vars] . identifier[items] ():
identifier[h... | def filter_by_attrs(self, **kwargs):
"""Returns a ``Dataset`` with variables that match specific conditions.
Can pass in ``key=value`` or ``key=callable``. A Dataset is returned
containing only the variables for which all the filter tests pass.
These tests are either ``key=value`` for whic... |
def _extract(self, path, outdir, filter_func=None):
"""Extract from a zip file, with an optional filter.
:param function filter_func: optional filter with the filename as the parameter. Returns True
if the file should be extracted."""
with open_zip(path) as archive_file:
... | def function[_extract, parameter[self, path, outdir, filter_func]]:
constant[Extract from a zip file, with an optional filter.
:param function filter_func: optional filter with the filename as the parameter. Returns True
if the file should be extracted.]
with call[... | keyword[def] identifier[_extract] ( identifier[self] , identifier[path] , identifier[outdir] , identifier[filter_func] = keyword[None] ):
literal[string]
keyword[with] identifier[open_zip] ( identifier[path] ) keyword[as] identifier[archive_file] :
keyword[for] identifier[name] keyword[in] iden... | def _extract(self, path, outdir, filter_func=None):
"""Extract from a zip file, with an optional filter.
:param function filter_func: optional filter with the filename as the parameter. Returns True
if the file should be extracted."""
with open_zip(path) as archive_file:
... |
def delete(gandi, fqdn, name, type, force):
"""Delete record entry for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % '... | def function[delete, parameter[gandi, fqdn, name, type, force]]:
constant[Delete record entry for a domain.]
variable[domains] assign[=] call[name[gandi].dns.list, parameter[]]
variable[domains] assign[=] <ast.ListComp object at 0x7da20c6e6c50>
if compare[name[fqdn] <ast.NotIn object at ... | keyword[def] identifier[delete] ( identifier[gandi] , identifier[fqdn] , identifier[name] , identifier[type] , identifier[force] ):
literal[string]
identifier[domains] = identifier[gandi] . identifier[dns] . identifier[list] ()
identifier[domains] =[ identifier[domain] [ literal[string] ] keyword[for]... | def delete(gandi, fqdn, name, type, force):
"""Delete record entry for a domain."""
domains = gandi.dns.list()
domains = [domain['fqdn'] for domain in domains]
if fqdn not in domains:
gandi.echo('Sorry domain %s does not exist' % fqdn)
gandi.echo('Please use one of the following: %s' % '... |
def get_items(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields individual JSON `items`.
Yields individual `items` from Webex Teams's top-level {'items': [...]}
JSON objects. Provides native support for RFC5988 Web Linking. The
generator will request additio... | def function[get_items, parameter[self, url, params]]:
constant[Return a generator that GETs and yields individual JSON `items`.
Yields individual `items` from Webex Teams's top-level {'items': [...]}
JSON objects. Provides native support for RFC5988 Web Linking. The
generator will req... | keyword[def] identifier[get_items] ( identifier[self] , identifier[url] , identifier[params] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[pages] = identifier[self] . identifier[get_pages] ( identifier[url] , identifier[params] = identifier[params] ,** identifier[kwa... | def get_items(self, url, params=None, **kwargs):
"""Return a generator that GETs and yields individual JSON `items`.
Yields individual `items` from Webex Teams's top-level {'items': [...]}
JSON objects. Provides native support for RFC5988 Web Linking. The
generator will request additional ... |
def bounding_square_polygon(self, inscribed_circle_radius_km=10.0):
"""
Returns a square polygon (bounding box) that circumscribes the circle having this geopoint as centre and
having the specified radius in kilometers.
The polygon's points calculation is based on theory exposed by: ... | def function[bounding_square_polygon, parameter[self, inscribed_circle_radius_km]]:
constant[
Returns a square polygon (bounding box) that circumscribes the circle having this geopoint as centre and
having the specified radius in kilometers.
The polygon's points calculation is based ... | keyword[def] identifier[bounding_square_polygon] ( identifier[self] , identifier[inscribed_circle_radius_km] = literal[int] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[inscribed_circle_radius_km] , identifier[int] ) keyword[or] identifier[isinstance] ( identifier[inscri... | def bounding_square_polygon(self, inscribed_circle_radius_km=10.0):
"""
Returns a square polygon (bounding box) that circumscribes the circle having this geopoint as centre and
having the specified radius in kilometers.
The polygon's points calculation is based on theory exposed by: http... |
def setup_placeholders(self):
"""
Creates the TensorFlow placeholders, variables, ops and functions for this model.
NOTE: Does not add the internal state placeholders and initialization values to the model yet as that requires
the model's Network (if any) to be generated first.
"... | def function[setup_placeholders, parameter[self]]:
constant[
Creates the TensorFlow placeholders, variables, ops and functions for this model.
NOTE: Does not add the internal state placeholders and initialization values to the model yet as that requires
the model's Network (if any) to be... | keyword[def] identifier[setup_placeholders] ( identifier[self] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[sorted] ( identifier[self] . identifier[states_spec] ):
identifier[self] . identifier[states_input] [ identifier[name] ]= identifier[tf] .... | def setup_placeholders(self):
"""
Creates the TensorFlow placeholders, variables, ops and functions for this model.
NOTE: Does not add the internal state placeholders and initialization values to the model yet as that requires
the model's Network (if any) to be generated first.
"""
... |
def get_elasticache_replication_groups_by_region(self, region):
''' Makes an AWS API call to the list of ElastiCache replication groups
in a particular region.'''
# ElastiCache boto module doesn't provide a get_all_intances method,
# that's why we need to call describe directly (it woul... | def function[get_elasticache_replication_groups_by_region, parameter[self, region]]:
constant[ Makes an AWS API call to the list of ElastiCache replication groups
in a particular region.]
<ast.Try object at 0x7da20c7c88e0>
<ast.Try object at 0x7da20c7cabf0>
for taget[name[replication_gro... | keyword[def] identifier[get_elasticache_replication_groups_by_region] ( identifier[self] , identifier[region] ):
literal[string]
keyword[try] :
identifier[conn] = identifier[elasticache] . identifier[connect_to_region] ( identifier[region] )
key... | def get_elasticache_replication_groups_by_region(self, region):
""" Makes an AWS API call to the list of ElastiCache replication groups
in a particular region."""
# ElastiCache boto module doesn't provide a get_all_intances method,
# that's why we need to call describe directly (it would be called b... |
def islice(self, start, end):
"""
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the start of the range, inclusiv... | def function[islice, parameter[self, start, end]]:
constant[
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the s... | keyword[def] identifier[islice] ( identifier[self] , identifier[start] , identifier[end] ):
literal[string]
identifier[jdt_index] = identifier[self] . identifier[_jdt_index] . identifier[islice] ( identifier[start] , identifier[end] )
keyword[return] identifier[DateTimeIndex] ( identifier... | def islice(self, start, end):
"""
Returns a new DateTimeIndex, containing a subslice of the timestamps in this index,
as specified by the given integer start and end locations.
Parameters
----------
start : int
The location of the start of the range, inclusive.
... |
def set_content(self, value: RequestContent, *,
content_type: str = None):
'''
Sets the content of the request.
'''
assert self._attached_files is None, \
'cannot set content because you already attached files.'
guessed_content_type = 'applicati... | def function[set_content, parameter[self, value]]:
constant[
Sets the content of the request.
]
assert[compare[name[self]._attached_files is constant[None]]]
variable[guessed_content_type] assign[=] constant[application/octet-stream]
if compare[name[value] is constant[None]] ... | keyword[def] identifier[set_content] ( identifier[self] , identifier[value] : identifier[RequestContent] ,*,
identifier[content_type] : identifier[str] = keyword[None] ):
literal[string]
keyword[assert] identifier[self] . identifier[_attached_files] keyword[is] keyword[None] , literal[string]
... | def set_content(self, value: RequestContent, *, content_type: str=None):
"""
Sets the content of the request.
"""
assert self._attached_files is None, 'cannot set content because you already attached files.'
guessed_content_type = 'application/octet-stream'
if value is None:
gues... |
def computeNoCall(fileName):
"""Computes the number of no call.
:param fileName: the name of the file
:type fileName: str
Reads the ``ped`` file created by Plink using the ``recodeA`` options (see
:py:func:`createPedChr24UsingPlink`) and computes the number and percentage
of no calls on the c... | def function[computeNoCall, parameter[fileName]]:
constant[Computes the number of no call.
:param fileName: the name of the file
:type fileName: str
Reads the ``ped`` file created by Plink using the ``recodeA`` options (see
:py:func:`createPedChr24UsingPlink`) and computes the number and perc... | keyword[def] identifier[computeNoCall] ( identifier[fileName] ):
literal[string]
identifier[outputFile] = keyword[None]
keyword[try] :
identifier[outputFile] = identifier[open] ( identifier[fileName] + literal[string] , literal[string] )
keyword[except] identifier[IOError] :
i... | def computeNoCall(fileName):
"""Computes the number of no call.
:param fileName: the name of the file
:type fileName: str
Reads the ``ped`` file created by Plink using the ``recodeA`` options (see
:py:func:`createPedChr24UsingPlink`) and computes the number and percentage
of no calls on the c... |
def to_bytes(graph: BELGraph, protocol: int = HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protoco... | def function[to_bytes, parameter[graph, protocol]]:
constant[Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protocol: Pickling ... | keyword[def] identifier[to_bytes] ( identifier[graph] : identifier[BELGraph] , identifier[protocol] : identifier[int] = identifier[HIGHEST_PROTOCOL] )-> identifier[bytes] :
literal[string]
identifier[raise_for_not_bel] ( identifier[graph] )
keyword[return] identifier[dumps] ( identifier[graph] , iden... | def to_bytes(graph: BELGraph, protocol: int=HIGHEST_PROTOCOL) -> bytes:
"""Convert a graph to bytes with pickle.
Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
pickle, choose 0, 1, or 2.
:param graph: A BEL network
:param protocol:... |
def get_unused_node_id(graph, initial_guess='unknown', _format='{}<%d>'):
"""
Finds an unused node id in `graph`.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:param initial_guess:
Initial node id guess.
:type initial_guess: str, optional
:... | def function[get_unused_node_id, parameter[graph, initial_guess, _format]]:
constant[
Finds an unused node id in `graph`.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:param initial_guess:
Initial node id guess.
:type initial_guess: str, opt... | keyword[def] identifier[get_unused_node_id] ( identifier[graph] , identifier[initial_guess] = literal[string] , identifier[_format] = literal[string] ):
literal[string]
identifier[has_node] = identifier[graph] . identifier[has_node]
identifier[n] = identifier[counter] ()
identifier[node_id_for... | def get_unused_node_id(graph, initial_guess='unknown', _format='{}<%d>'):
"""
Finds an unused node id in `graph`.
:param graph:
A directed graph.
:type graph: networkx.classes.digraph.DiGraph
:param initial_guess:
Initial node id guess.
:type initial_guess: str, optional
:... |
def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):
"""For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each \
plane. To do this, this function iterates over all planes and then galaxies to extrac... | def function[unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf, parameter[planes, padded_grid_stack, psf]]:
constant[For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each plane. To do this, this function iterates over all plane... | keyword[def] identifier[unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf] ( identifier[planes] , identifier[padded_grid_stack] , identifier[psf] ):
literal[string]
keyword[return] [ identifier[plane] . identifier[unmasked_blurred_image_of_galaxies_from_psf] ( identifier[padded_g... | def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):
"""For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each plane. To do this, this function iterates over all planes and then galaxies to extract ... |
def getrecord(**kwargs):
"""Create OAI-PMH response for verb Identify."""
record_dumper = serializer(kwargs['metadataPrefix'])
pid = OAIIDProvider.get(pid_value=kwargs['identifier']).pid
record = Record.get_record(pid.object_uuid)
e_tree, e_getrecord = verb(**kwargs)
e_record = SubElement(e_get... | def function[getrecord, parameter[]]:
constant[Create OAI-PMH response for verb Identify.]
variable[record_dumper] assign[=] call[name[serializer], parameter[call[name[kwargs]][constant[metadataPrefix]]]]
variable[pid] assign[=] call[name[OAIIDProvider].get, parameter[]].pid
variable[rec... | keyword[def] identifier[getrecord] (** identifier[kwargs] ):
literal[string]
identifier[record_dumper] = identifier[serializer] ( identifier[kwargs] [ literal[string] ])
identifier[pid] = identifier[OAIIDProvider] . identifier[get] ( identifier[pid_value] = identifier[kwargs] [ literal[string] ]). ide... | def getrecord(**kwargs):
"""Create OAI-PMH response for verb Identify."""
record_dumper = serializer(kwargs['metadataPrefix'])
pid = OAIIDProvider.get(pid_value=kwargs['identifier']).pid
record = Record.get_record(pid.object_uuid)
(e_tree, e_getrecord) = verb(**kwargs)
e_record = SubElement(e_ge... |
def import_taskfile(self, refobj, taskfileinfo):
"""Import the given taskfileinfo and update the refobj
:param refobj: the refobject
:type refobj: refobject
:param taskfileinfo: the taskfileinfo to reference
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:... | def function[import_taskfile, parameter[self, refobj, taskfileinfo]]:
constant[Import the given taskfileinfo and update the refobj
:param refobj: the refobject
:type refobj: refobject
:param taskfileinfo: the taskfileinfo to reference
:type taskfileinfo: :class:`jukeboxcore.file... | keyword[def] identifier[import_taskfile] ( identifier[self] , identifier[refobj] , identifier[taskfileinfo] ):
literal[string]
keyword[with] identifier[common] . identifier[preserve_namespace] ( literal[string] ):
identifier[jbfile] = identifier[JB_File] ( identifier[taskfile... | def import_taskfile(self, refobj, taskfileinfo):
"""Import the given taskfileinfo and update the refobj
:param refobj: the refobject
:type refobj: refobject
:param taskfileinfo: the taskfileinfo to reference
:type taskfileinfo: :class:`jukeboxcore.filesys.TaskFileInfo`
:retu... |
def add_instance_groups(self, jobflow_id, instance_groups):
"""
Adds instance groups to a running cluster.
:type jobflow_id: str
:param jobflow_id: The id of the jobflow which will take the
new instance groups
:type instance_groups: list(boto.emr.Instanc... | def function[add_instance_groups, parameter[self, jobflow_id, instance_groups]]:
constant[
Adds instance groups to a running cluster.
:type jobflow_id: str
:param jobflow_id: The id of the jobflow which will take the
new instance groups
:type instance_gr... | keyword[def] identifier[add_instance_groups] ( identifier[self] , identifier[jobflow_id] , identifier[instance_groups] ):
literal[string]
keyword[if] identifier[type] ( identifier[instance_groups] )!= identifier[types] . identifier[ListType] :
identifier[instance_groups] =[ identifier... | def add_instance_groups(self, jobflow_id, instance_groups):
"""
Adds instance groups to a running cluster.
:type jobflow_id: str
:param jobflow_id: The id of the jobflow which will take the
new instance groups
:type instance_groups: list(boto.emr.InstanceGro... |
def compare_commits(self, base, head):
"""Compare two commits.
:param str base: (required), base for the comparison
:param str head: (required), compare this against base
:returns: :class:`Comparison <github3.repos.comparison.Comparison>` if
successful, else None
"""... | def function[compare_commits, parameter[self, base, head]]:
constant[Compare two commits.
:param str base: (required), base for the comparison
:param str head: (required), compare this against base
:returns: :class:`Comparison <github3.repos.comparison.Comparison>` if
succes... | keyword[def] identifier[compare_commits] ( identifier[self] , identifier[base] , identifier[head] ):
literal[string]
identifier[url] = identifier[self] . identifier[_build_url] ( literal[string] , identifier[base] + literal[string] + identifier[head] ,
identifier[base_url] = identifier[sel... | def compare_commits(self, base, head):
"""Compare two commits.
:param str base: (required), base for the comparison
:param str head: (required), compare this against base
:returns: :class:`Comparison <github3.repos.comparison.Comparison>` if
successful, else None
"""
... |
def max_pool(x, dim):
"""Max pooling operation."""
return tf.nn.max_pool(
x, ksize=[1, dim, dim, 1], strides=[1, dim, dim, 1],
padding='SAME') | def function[max_pool, parameter[x, dim]]:
constant[Max pooling operation.]
return[call[name[tf].nn.max_pool, parameter[name[x]]]] | keyword[def] identifier[max_pool] ( identifier[x] , identifier[dim] ):
literal[string]
keyword[return] identifier[tf] . identifier[nn] . identifier[max_pool] (
identifier[x] , identifier[ksize] =[ literal[int] , identifier[dim] , identifier[dim] , literal[int] ], identifier[strides] =[ li... | def max_pool(x, dim):
"""Max pooling operation."""
return tf.nn.max_pool(x, ksize=[1, dim, dim, 1], strides=[1, dim, dim, 1], padding='SAME') |
def add_feed(url):
"""add to db"""
with Database("feeds") as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name | def function[add_feed, parameter[url]]:
constant[add to db]
with call[name[Database], parameter[constant[feeds]]] begin[:]
variable[title] assign[=] call[name[feedparser].parse, parameter[name[url]]].feed.title
variable[name] assign[=] call[name[str], parameter[name[title... | keyword[def] identifier[add_feed] ( identifier[url] ):
literal[string]
keyword[with] identifier[Database] ( literal[string] ) keyword[as] identifier[db] :
identifier[title] = identifier[feedparser] . identifier[parse] ( identifier[url] ). identifier[feed] . identifier[title]
identifier... | def add_feed(url):
"""add to db"""
with Database('feeds') as db:
title = feedparser.parse(url).feed.title
name = str(title)
db[name] = url
return name # depends on [control=['with'], data=['db']] |
def tokenize(self, data):
"""
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name... | def function[tokenize, parameter[self, data]]:
constant[
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_na... | keyword[def] identifier[tokenize] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[data] . identifier[replace] ( literal[string] , literal[string] ). identifier[replace] ( literal[string] , literal[string] )
identifier[pos] = identifier[start] = identi... | def tokenize(self, data):
"""
Tokenizes the given string. A token is a 4-tuple of the form:
(token_type, tag_name, tag_options, token_text)
token_type
One of: TOKEN_TAG_START, TOKEN_TAG_END, TOKEN_NEWLINE, TOKEN_DATA
tag_name
The name of ... |
def cached_request(self, request):
"""
Return a cached response if it exists in the cache, otherwise
return False.
"""
cache_url = self.cache_url(request.url)
logger.debug('Looking up "%s" in the cache', cache_url)
cc = self.parse_cache_control(request.headers)
... | def function[cached_request, parameter[self, request]]:
constant[
Return a cached response if it exists in the cache, otherwise
return False.
]
variable[cache_url] assign[=] call[name[self].cache_url, parameter[name[request].url]]
call[name[logger].debug, parameter[consta... | keyword[def] identifier[cached_request] ( identifier[self] , identifier[request] ):
literal[string]
identifier[cache_url] = identifier[self] . identifier[cache_url] ( identifier[request] . identifier[url] )
identifier[logger] . identifier[debug] ( literal[string] , identifier[cache_url] )
... | def cached_request(self, request):
"""
Return a cached response if it exists in the cache, otherwise
return False.
"""
cache_url = self.cache_url(request.url)
logger.debug('Looking up "%s" in the cache', cache_url)
cc = self.parse_cache_control(request.headers)
# Bail out if ... |
def reboot(at_time=None):
'''
Reboot the system
at_time
The wait time in minutes before the system will be rebooted.
CLI Example:
.. code-block:: bash
salt '*' system.reboot
'''
cmd = ['shutdown', '-r', ('{0}'.format(at_time) if at_time else 'now')]
ret = __salt__['cm... | def function[reboot, parameter[at_time]]:
constant[
Reboot the system
at_time
The wait time in minutes before the system will be rebooted.
CLI Example:
.. code-block:: bash
salt '*' system.reboot
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b1c11d... | keyword[def] identifier[reboot] ( identifier[at_time] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] ,( literal[string] . identifier[format] ( identifier[at_time] ) keyword[if] identifier[at_time] keyword[else] literal[string] )]
identifier[ret] = identifier... | def reboot(at_time=None):
"""
Reboot the system
at_time
The wait time in minutes before the system will be rebooted.
CLI Example:
.. code-block:: bash
salt '*' system.reboot
"""
cmd = ['shutdown', '-r', '{0}'.format(at_time) if at_time else 'now']
ret = __salt__['cmd.... |
def get_data(self, field, function=None, default=None):
"""
Get data from the striplog.
"""
f = function or utils.null
data = []
for iv in self:
d = iv.data.get(field)
if d is None:
if default is not None:
d = de... | def function[get_data, parameter[self, field, function, default]]:
constant[
Get data from the striplog.
]
variable[f] assign[=] <ast.BoolOp object at 0x7da1b26af580>
variable[data] assign[=] list[[]]
for taget[name[iv]] in starred[name[self]] begin[:]
var... | keyword[def] identifier[get_data] ( identifier[self] , identifier[field] , identifier[function] = keyword[None] , identifier[default] = keyword[None] ):
literal[string]
identifier[f] = identifier[function] keyword[or] identifier[utils] . identifier[null]
identifier[data] =[]
ke... | def get_data(self, field, function=None, default=None):
"""
Get data from the striplog.
"""
f = function or utils.null
data = []
for iv in self:
d = iv.data.get(field)
if d is None:
if default is not None:
d = default # depends on [control=['i... |
def pad_line_to_ontonotes(line, domain) -> List[str]:
"""
Pad line to conform to ontonotes representation.
"""
word_ind, word = line[ : 2]
pos = 'XX'
oie_tags = line[2 : ]
line_num = 0
parse = "-"
lemma = "-"
return [domain, line_num, word_ind, word, pos, parse, lemma, '-',\
... | def function[pad_line_to_ontonotes, parameter[line, domain]]:
constant[
Pad line to conform to ontonotes representation.
]
<ast.Tuple object at 0x7da2054a7a90> assign[=] call[name[line]][<ast.Slice object at 0x7da2054a56f0>]
variable[pos] assign[=] constant[XX]
variable[oie_tags]... | keyword[def] identifier[pad_line_to_ontonotes] ( identifier[line] , identifier[domain] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[word_ind] , identifier[word] = identifier[line] [: literal[int] ]
identifier[pos] = literal[string]
identifier[oie_tags] = identifier[line] ... | def pad_line_to_ontonotes(line, domain) -> List[str]:
"""
Pad line to conform to ontonotes representation.
"""
(word_ind, word) = line[:2]
pos = 'XX'
oie_tags = line[2:]
line_num = 0
parse = '-'
lemma = '-'
return [domain, line_num, word_ind, word, pos, parse, lemma, '-', '-', '-... |
def calculate_crop_list(full_page_box_list, bounding_box_list, angle_list,
page_nums_to_crop):
"""Given a list of full-page boxes (media boxes) and a list of tight
bounding boxes for each page, calculate and return another list giving the
list o... | def function[calculate_crop_list, parameter[full_page_box_list, bounding_box_list, angle_list, page_nums_to_crop]]:
constant[Given a list of full-page boxes (media boxes) and a list of tight
bounding boxes for each page, calculate and return another list giving the
list of bounding boxes to crop down to... | keyword[def] identifier[calculate_crop_list] ( identifier[full_page_box_list] , identifier[bounding_box_list] , identifier[angle_list] ,
identifier[page_nums_to_crop] ):
literal[string]
identifier[num_pages] = identifier[len] ( identifier[bounding_box_li... | def calculate_crop_list(full_page_box_list, bounding_box_list, angle_list, page_nums_to_crop):
"""Given a list of full-page boxes (media boxes) and a list of tight
bounding boxes for each page, calculate and return another list giving the
list of bounding boxes to crop down to. The parameter `angle_list` i... |
def associate_flavor(self, flavor, body):
"""Associate a Neutron service flavor with a profile."""
return self.post(self.flavor_profile_bindings_path %
(flavor), body=body) | def function[associate_flavor, parameter[self, flavor, body]]:
constant[Associate a Neutron service flavor with a profile.]
return[call[name[self].post, parameter[binary_operation[name[self].flavor_profile_bindings_path <ast.Mod object at 0x7da2590d6920> name[flavor]]]]] | keyword[def] identifier[associate_flavor] ( identifier[self] , identifier[flavor] , identifier[body] ):
literal[string]
keyword[return] identifier[self] . identifier[post] ( identifier[self] . identifier[flavor_profile_bindings_path] %
( identifier[flavor] ), identifier[body] = identifier[... | def associate_flavor(self, flavor, body):
"""Associate a Neutron service flavor with a profile."""
return self.post(self.flavor_profile_bindings_path % flavor, body=body) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.