code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def rule_expand(component, text):
'''expand one rule component'''
global rline_mpstate
if component[0] == '<' and component[-1] == '>':
return component[1:-1].split('|')
if component in rline_mpstate.completion_functions:
return rline_mpstate.completion_functions[component](text)
ret... | def function[rule_expand, parameter[component, text]]:
constant[expand one rule component]
<ast.Global object at 0x7da18ede4910>
if <ast.BoolOp object at 0x7da18ede7400> begin[:]
return[call[call[name[component]][<ast.Slice object at 0x7da18ede7eb0>].split, parameter[constant[|]]]]
i... | keyword[def] identifier[rule_expand] ( identifier[component] , identifier[text] ):
literal[string]
keyword[global] identifier[rline_mpstate]
keyword[if] identifier[component] [ literal[int] ]== literal[string] keyword[and] identifier[component] [- literal[int] ]== literal[string] :
keywo... | def rule_expand(component, text):
"""expand one rule component"""
global rline_mpstate
if component[0] == '<' and component[-1] == '>':
return component[1:-1].split('|') # depends on [control=['if'], data=[]]
if component in rline_mpstate.completion_functions:
return rline_mpstate.compl... |
def connect_s3(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.connection.S3C... | def function[connect_s3, parameter[aws_access_key_id, aws_secret_access_key]]:
constant[
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.con... | keyword[def] identifier[connect_s3] ( identifier[aws_access_key_id] = keyword[None] , identifier[aws_secret_access_key] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[botornado] . identifier[s3] . identifier[connection] keyword[import] identifier[AsyncS3Connection]
... | def connect_s3(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.s3.connection.S3C... |
def get_bgp_neighbors(self):
"""BGP neighbor information.
Currently no VRF support. Supports both IPv4 and IPv6.
"""
supported_afi = ['ipv4', 'ipv6']
bgp_neighbor_data = dict()
bgp_neighbor_data['global'] = {}
# get summary output from device
cmd_bgp_al... | def function[get_bgp_neighbors, parameter[self]]:
constant[BGP neighbor information.
Currently no VRF support. Supports both IPv4 and IPv6.
]
variable[supported_afi] assign[=] list[[<ast.Constant object at 0x7da18dc99660>, <ast.Constant object at 0x7da18dc9a230>]]
variable[bgp_n... | keyword[def] identifier[get_bgp_neighbors] ( identifier[self] ):
literal[string]
identifier[supported_afi] =[ literal[string] , literal[string] ]
identifier[bgp_neighbor_data] = identifier[dict] ()
identifier[bgp_neighbor_data] [ literal[string] ]={}
identifier... | def get_bgp_neighbors(self):
"""BGP neighbor information.
Currently no VRF support. Supports both IPv4 and IPv6.
"""
supported_afi = ['ipv4', 'ipv6']
bgp_neighbor_data = dict()
bgp_neighbor_data['global'] = {}
# get summary output from device
cmd_bgp_all_sum = 'show bgp all summ... |
def _parseSCPDVariableTypes(self, variableListElement, variableTypes):
"""Internal method to parse the SCPD definitions.
:param variableListElement: the xml root node of the variable list
:type variableListElement: xml.etree.ElementTree.Element
:param dict variableTypes: a container to ... | def function[_parseSCPDVariableTypes, parameter[self, variableListElement, variableTypes]]:
constant[Internal method to parse the SCPD definitions.
:param variableListElement: the xml root node of the variable list
:type variableListElement: xml.etree.ElementTree.Element
:param dict var... | keyword[def] identifier[_parseSCPDVariableTypes] ( identifier[self] , identifier[variableListElement] , identifier[variableTypes] ):
literal[string]
keyword[for] identifier[variableElement] keyword[in] identifier[variableListElement] . identifier[getchildren] ():
identifi... | def _parseSCPDVariableTypes(self, variableListElement, variableTypes):
"""Internal method to parse the SCPD definitions.
:param variableListElement: the xml root node of the variable list
:type variableListElement: xml.etree.ElementTree.Element
:param dict variableTypes: a container to stor... |
def reset(self, reset_type=None):
"""! @brief Reset the core.
The reset method is selectable via the reset_type parameter as well as the reset_type
session option. If the reset_type parameter is not specified or None, then the reset_type
option will be used. If the option is not... | def function[reset, parameter[self, reset_type]]:
constant[! @brief Reset the core.
The reset method is selectable via the reset_type parameter as well as the reset_type
session option. If the reset_type parameter is not specified or None, then the reset_type
option will be used... | keyword[def] identifier[reset] ( identifier[self] , identifier[reset_type] = keyword[None] ):
literal[string]
identifier[self] . identifier[notify] ( identifier[Notification] ( identifier[event] = identifier[Target] . identifier[EVENT_PRE_RESET] , identifier[source] = identifier[self] ))
... | def reset(self, reset_type=None):
"""! @brief Reset the core.
The reset method is selectable via the reset_type parameter as well as the reset_type
session option. If the reset_type parameter is not specified or None, then the reset_type
option will be used. If the option is not set... |
def get_perceel_by_id(self, id):
'''
Retrieve a `Perceel` by the Id.
:param string id: the Id of the `Perceel`
:rtype: :class:`Perceel`
'''
def creator():
res = crab_gateway_request(
self.client, 'GetPerceelByIdentificatorPerceel', id
... | def function[get_perceel_by_id, parameter[self, id]]:
constant[
Retrieve a `Perceel` by the Id.
:param string id: the Id of the `Perceel`
:rtype: :class:`Perceel`
]
def function[creator, parameter[]]:
variable[res] assign[=] call[name[crab_gateway_request... | keyword[def] identifier[get_perceel_by_id] ( identifier[self] , identifier[id] ):
literal[string]
keyword[def] identifier[creator] ():
identifier[res] = identifier[crab_gateway_request] (
identifier[self] . identifier[client] , literal[string] , identifier[id]
... | def get_perceel_by_id(self, id):
"""
Retrieve a `Perceel` by the Id.
:param string id: the Id of the `Perceel`
:rtype: :class:`Perceel`
"""
def creator():
res = crab_gateway_request(self.client, 'GetPerceelByIdentificatorPerceel', id)
if res == None:
... |
def splitkeyurl(url):
'''
Splits a Send url into key, urlid and 'prefix' for the Send server
Should handle any hostname, but will brake on key & id length changes
'''
key = url[-22:]
urlid = url[-34:-24]
service = url[:-43]
return service, urlid, key | def function[splitkeyurl, parameter[url]]:
constant[
Splits a Send url into key, urlid and 'prefix' for the Send server
Should handle any hostname, but will brake on key & id length changes
]
variable[key] assign[=] call[name[url]][<ast.Slice object at 0x7da1b11f6230>]
variable... | keyword[def] identifier[splitkeyurl] ( identifier[url] ):
literal[string]
identifier[key] = identifier[url] [- literal[int] :]
identifier[urlid] = identifier[url] [- literal[int] :- literal[int] ]
identifier[service] = identifier[url] [:- literal[int] ]
keyword[return] identifier[service] ,... | def splitkeyurl(url):
"""
Splits a Send url into key, urlid and 'prefix' for the Send server
Should handle any hostname, but will brake on key & id length changes
"""
key = url[-22:]
urlid = url[-34:-24]
service = url[:-43]
return (service, urlid, key) |
def render_from_tag(
cls, context, max_levels=None, use_specific=None,
apply_active_classes=True, allow_repeating_parents=True,
use_absolute_page_urls=False, add_sub_menus_inline=None,
template_name='', **kwargs
):
"""
A template tag should call this method to render ... | def function[render_from_tag, parameter[cls, context, max_levels, use_specific, apply_active_classes, allow_repeating_parents, use_absolute_page_urls, add_sub_menus_inline, template_name]]:
constant[
A template tag should call this method to render a menu.
The ``Context`` instance and option val... | keyword[def] identifier[render_from_tag] (
identifier[cls] , identifier[context] , identifier[max_levels] = keyword[None] , identifier[use_specific] = keyword[None] ,
identifier[apply_active_classes] = keyword[True] , identifier[allow_repeating_parents] = keyword[True] ,
identifier[use_absolute_page_urls] = keywor... | def render_from_tag(cls, context, max_levels=None, use_specific=None, apply_active_classes=True, allow_repeating_parents=True, use_absolute_page_urls=False, add_sub_menus_inline=None, template_name='', **kwargs):
"""
A template tag should call this method to render a menu.
The ``Context`` instance a... |
def dist(self, src, tar):
"""Return the NCD between two strings using BWT plus RLE.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression ... | def function[dist, parameter[self, src, tar]]:
constant[Return the NCD between two strings using BWT plus RLE.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
flo... | keyword[def] identifier[dist] ( identifier[self] , identifier[src] , identifier[tar] ):
literal[string]
keyword[if] identifier[src] == identifier[tar] :
keyword[return] literal[int]
identifier[src_comp] = identifier[self] . identifier[_rle] . identifier[encode] ( identifie... | def dist(self, src, tar):
"""Return the NCD between two strings using BWT plus RLE.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression dist... |
def asyncPipeRename(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously renames or copies fields in the input
source. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf... | def function[asyncPipeRename, parameter[context, _INPUT, conf]]:
constant[An operator that asynchronously renames or copies fields in the input
source. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
... | keyword[def] identifier[asyncPipeRename] ( identifier[context] = keyword[None] , identifier[_INPUT] = keyword[None] , identifier[conf] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[splits] = keyword[yield] identifier[asyncGetSplits] ( identifier[_INPUT] , identifier[conf] [ literal[... | def asyncPipeRename(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously renames or copies fields in the input
source. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf... |
def is_internal_attribute(obj, attr):
"""Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overriden.
>>... | def function[is_internal_attribute, parameter[obj, attr]]:
constant[Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_a... | keyword[def] identifier[is_internal_attribute] ( identifier[obj] , identifier[attr] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[FunctionType] ):
keyword[if] identifier[attr] keyword[in] identifier[UNSAFE_FUNCTION_ATTRIBUTES] :
keyword[retur... | def is_internal_attribute(obj, attr):
"""Test if the attribute given is an internal python attribute. For
example this function returns `True` for the `func_code` attribute of
python objects. This is useful if the environment method
:meth:`~SandboxedEnvironment.is_safe_attribute` is overriden.
>>... |
def format_help(help):
"""Formats the help string."""
help = help.replace("Options:", str(crayons.normal("Options:", bold=True)))
help = help.replace(
"Usage: pipenv", str("Usage: {0}".format(crayons.normal("pipenv", bold=True)))
)
help = help.replace(" check", str(crayons.red(" check", bo... | def function[format_help, parameter[help]]:
constant[Formats the help string.]
variable[help] assign[=] call[name[help].replace, parameter[constant[Options:], call[name[str], parameter[call[name[crayons].normal, parameter[constant[Options:]]]]]]]
variable[help] assign[=] call[name[help].replace,... | keyword[def] identifier[format_help] ( identifier[help] ):
literal[string]
identifier[help] = identifier[help] . identifier[replace] ( literal[string] , identifier[str] ( identifier[crayons] . identifier[normal] ( literal[string] , identifier[bold] = keyword[True] )))
identifier[help] = identifier[hel... | def format_help(help):
"""Formats the help string."""
help = help.replace('Options:', str(crayons.normal('Options:', bold=True)))
help = help.replace('Usage: pipenv', str('Usage: {0}'.format(crayons.normal('pipenv', bold=True))))
help = help.replace(' check', str(crayons.red(' check', bold=True)))
... |
def do_it(self, dbg):
''' Create an XML for console output, error and more (true/false)
<xml>
<output message=output_message></output>
<error message=error_message></error>
<more>true/false</more>
</xml>
'''
try:
frame = dbg.find_fr... | def function[do_it, parameter[self, dbg]]:
constant[ Create an XML for console output, error and more (true/false)
<xml>
<output message=output_message></output>
<error message=error_message></error>
<more>true/false</more>
</xml>
]
<ast.Try object... | keyword[def] identifier[do_it] ( identifier[self] , identifier[dbg] ):
literal[string]
keyword[try] :
identifier[frame] = identifier[dbg] . identifier[find_frame] ( identifier[self] . identifier[thread_id] , identifier[self] . identifier[frame_id] )
keyword[if] identifier... | def do_it(self, dbg):
""" Create an XML for console output, error and more (true/false)
<xml>
<output message=output_message></output>
<error message=error_message></error>
<more>true/false</more>
</xml>
"""
try:
frame = dbg.find_frame(self.thr... |
def perform_exit():
"""perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes.
"""
if SPLUNK_DEBUG:
... | def function[perform_exit, parameter[]]:
constant[perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes.
... | keyword[def] identifier[perform_exit] ():
literal[string]
keyword[if] identifier[SPLUNK_DEBUG] :
identifier[print] ( literal[string] . identifier[format] (
identifier[rnow] ()))
identifier[print] ( literal[string] . identifier[format] (
identifier[rnow] ()))
identi... | def perform_exit():
"""perform_exit
Handling at-the-exit events
---------------------------
This will cleanup each worker process which
could be in the middle of a request/sleep/block
action. This has been tested on python 3 with
Celery and single processes.
"""
if SPLUNK_DEBUG:
... |
def graph_png(self):
"""
Export a graph of the data in png format using graphviz/dot.
"""
if not self.out_file:
ui.error(c.MESSAGES["png_missing_out"])
sys.exit(1)
cli_flags = "-Gsize='{0}' -Gdpi='{1}' {2} ".format(self.size, self.dpi,
... | def function[graph_png, parameter[self]]:
constant[
Export a graph of the data in png format using graphviz/dot.
]
if <ast.UnaryOp object at 0x7da1b0b36200> begin[:]
call[name[ui].error, parameter[call[name[c].MESSAGES][constant[png_missing_out]]]]
call[na... | keyword[def] identifier[graph_png] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[out_file] :
identifier[ui] . identifier[error] ( identifier[c] . identifier[MESSAGES] [ literal[string] ])
identifier[sys] . identifier[exit] (... | def graph_png(self):
"""
Export a graph of the data in png format using graphviz/dot.
"""
if not self.out_file:
ui.error(c.MESSAGES['png_missing_out'])
sys.exit(1) # depends on [control=['if'], data=[]]
cli_flags = "-Gsize='{0}' -Gdpi='{1}' {2} ".format(self.size, self.dpi, ... |
def setup_app(self, app, add_context_processor=True): # pragma: no cover
'''
This method has been deprecated. Please use
:meth:`LoginManager.init_app` instead.
'''
warnings.warn('Warning setup_app is deprecated. Please use init_app.',
DeprecationWarning)
... | def function[setup_app, parameter[self, app, add_context_processor]]:
constant[
This method has been deprecated. Please use
:meth:`LoginManager.init_app` instead.
]
call[name[warnings].warn, parameter[constant[Warning setup_app is deprecated. Please use init_app.], name[Deprecati... | keyword[def] identifier[setup_app] ( identifier[self] , identifier[app] , identifier[add_context_processor] = keyword[True] ):
literal[string]
identifier[warnings] . identifier[warn] ( literal[string] ,
identifier[DeprecationWarning] )
identifier[self] . identifier[init_app] ( ide... | def setup_app(self, app, add_context_processor=True): # pragma: no cover
'\n This method has been deprecated. Please use\n :meth:`LoginManager.init_app` instead.\n '
warnings.warn('Warning setup_app is deprecated. Please use init_app.', DeprecationWarning)
self.init_app(app, add_contex... |
def get_cats(self):
'''Get top keywords categories'''
start_url = 'http://top.taobao.com/index.php?from=tbsy'
rs = self.fetch(start_url)
if not rs: return None
soup = BeautifulSoup(rs.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=hexentityMassage)
ca... | def function[get_cats, parameter[self]]:
constant[Get top keywords categories]
variable[start_url] assign[=] constant[http://top.taobao.com/index.php?from=tbsy]
variable[rs] assign[=] call[name[self].fetch, parameter[name[start_url]]]
if <ast.UnaryOp object at 0x7da1b25adcf0> begin[:]
... | keyword[def] identifier[get_cats] ( identifier[self] ):
literal[string]
identifier[start_url] = literal[string]
identifier[rs] = identifier[self] . identifier[fetch] ( identifier[start_url] )
keyword[if] keyword[not] identifier[rs] : keyword[return] keyword[None]
ide... | def get_cats(self):
"""Get top keywords categories"""
start_url = 'http://top.taobao.com/index.php?from=tbsy'
rs = self.fetch(start_url)
if not rs:
return None # depends on [control=['if'], data=[]]
soup = BeautifulSoup(rs.content, convertEntities=BeautifulSoup.HTML_ENTITIES, markupMassage=... |
def text(self, prompt, default=None):
"""Prompts the user for some text, with optional default"""
prompt = prompt if prompt is not None else 'Enter some text'
prompt += " [{0}]: ".format(default) if default is not None else ': '
return self.input(curry(filter_text, default=default), prom... | def function[text, parameter[self, prompt, default]]:
constant[Prompts the user for some text, with optional default]
variable[prompt] assign[=] <ast.IfExp object at 0x7da20c6c7d60>
<ast.AugAssign object at 0x7da20c6c5d80>
return[call[name[self].input, parameter[call[name[curry], parameter[name[... | keyword[def] identifier[text] ( identifier[self] , identifier[prompt] , identifier[default] = keyword[None] ):
literal[string]
identifier[prompt] = identifier[prompt] keyword[if] identifier[prompt] keyword[is] keyword[not] keyword[None] keyword[else] literal[string]
identifier[prom... | def text(self, prompt, default=None):
"""Prompts the user for some text, with optional default"""
prompt = prompt if prompt is not None else 'Enter some text'
prompt += ' [{0}]: '.format(default) if default is not None else ': '
return self.input(curry(filter_text, default=default), prompt) |
def update(self, request, key):
"""Set an email address as primary address."""
request.UPDATE = http.QueryDict(request.body)
email_addr = request.UPDATE.get('email')
user_id = request.UPDATE.get('user')
if not email_addr:
return http.HttpResponseBadRequest()
... | def function[update, parameter[self, request, key]]:
constant[Set an email address as primary address.]
name[request].UPDATE assign[=] call[name[http].QueryDict, parameter[name[request].body]]
variable[email_addr] assign[=] call[name[request].UPDATE.get, parameter[constant[email]]]
varia... | keyword[def] identifier[update] ( identifier[self] , identifier[request] , identifier[key] ):
literal[string]
identifier[request] . identifier[UPDATE] = identifier[http] . identifier[QueryDict] ( identifier[request] . identifier[body] )
identifier[email_addr] = identifier[request] . iden... | def update(self, request, key):
"""Set an email address as primary address."""
request.UPDATE = http.QueryDict(request.body)
email_addr = request.UPDATE.get('email')
user_id = request.UPDATE.get('user')
if not email_addr:
return http.HttpResponseBadRequest() # depends on [control=['if'], da... |
def check_response_code(resp):
"""
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
"""
if resp["status"] == "OK" or resp["status"] == "ZERO_RESULTS":
return
if resp["status"] == "REQUEST_DENIED":
raise Exception("Google Pla... | def function[check_response_code, parameter[resp]]:
constant[
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
]
if <ast.BoolOp object at 0x7da18f720af0> begin[:]
return[None]
if compare[call[name[resp]][constant[status]]... | keyword[def] identifier[check_response_code] ( identifier[resp] ):
literal[string]
keyword[if] identifier[resp] [ literal[string] ]== literal[string] keyword[or] identifier[resp] [ literal[string] ]== literal[string] :
keyword[return]
keyword[if] identifier[resp] [ literal[string] ]== l... | def check_response_code(resp):
"""
check if query quota has been surpassed or other errors occured
:param resp: json response
:return:
"""
if resp['status'] == 'OK' or resp['status'] == 'ZERO_RESULTS':
return # depends on [control=['if'], data=[]]
if resp['status'] == 'REQUEST_DENIE... |
def concatenate_children(node, concatenate_with, strategy):
"""
Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels
"""
_, _, getter, concatenate_with = [x for x in _HIERARCHY if isinstance(node, x[0])][0]
tokens = [get_text(x, strat... | def function[concatenate_children, parameter[node, concatenate_with, strategy]]:
constant[
Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels
]
<ast.Tuple object at 0x7da1b0383730> assign[=] call[<ast.ListComp object at 0x7da1b0... | keyword[def] identifier[concatenate_children] ( identifier[node] , identifier[concatenate_with] , identifier[strategy] ):
literal[string]
identifier[_] , identifier[_] , identifier[getter] , identifier[concatenate_with] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[_HIERARCHY] key... | def concatenate_children(node, concatenate_with, strategy):
"""
Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels
"""
(_, _, getter, concatenate_with) = [x for x in _HIERARCHY if isinstance(node, x[0])][0]
tokens = [get_text(x, str... |
def remove_uri(self, image):
'''remove_image_uri will return just the image name.
this will also remove all spaces from the uri.
'''
image = image or ''
uri = self.get_uri(image) or ''
image = image.replace('%s://' %uri,'', 1)
return image.strip('-').rstrip('/'... | def function[remove_uri, parameter[self, image]]:
constant[remove_image_uri will return just the image name.
this will also remove all spaces from the uri.
]
variable[image] assign[=] <ast.BoolOp object at 0x7da1b040cc40>
variable[uri] assign[=] <ast.BoolOp object at 0x7da1b04... | keyword[def] identifier[remove_uri] ( identifier[self] , identifier[image] ):
literal[string]
identifier[image] = identifier[image] keyword[or] literal[string]
identifier[uri] = identifier[self] . identifier[get_uri] ( identifier[image] ) keyword[or] literal[string]
identifie... | def remove_uri(self, image):
"""remove_image_uri will return just the image name.
this will also remove all spaces from the uri.
"""
image = image or ''
uri = self.get_uri(image) or ''
image = image.replace('%s://' % uri, '', 1)
return image.strip('-').rstrip('/') |
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = ... | def function[avail_images, parameter[call]]:
constant[
Return a dict of all available VM images on the cloud provider.
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da20c7ca380>
variable[ret] assign[=] dictionary[[], []]
variable[con... | keyword[def] identifier[avail_images] ( identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
identifier[ret] ={}
identifier[c... | def avail_images(call=None):
"""
Return a dict of all available VM images on the cloud provider.
"""
if call == 'action':
raise SaltCloudSystemExit('The avail_images function must be called with -f or --function, or with the --list-images option') # depends on [control=['if'], data=[]]
ret ... |
def analyze_one(self, nm, importernm=None, imptyp=0, level=-1):
"""
break the name being imported up so we get:
a.b.c -> [a, b, c] ; ..z -> ['', '', z]
"""
#print '## analyze_one', nm, importernm, imptyp, level
if not nm:
nm = importernm
importernm... | def function[analyze_one, parameter[self, nm, importernm, imptyp, level]]:
constant[
break the name being imported up so we get:
a.b.c -> [a, b, c] ; ..z -> ['', '', z]
]
if <ast.UnaryOp object at 0x7da1b0e27ca0> begin[:]
variable[nm] assign[=] name[importernm]
... | keyword[def] identifier[analyze_one] ( identifier[self] , identifier[nm] , identifier[importernm] = keyword[None] , identifier[imptyp] = literal[int] , identifier[level] =- literal[int] ):
literal[string]
keyword[if] keyword[not] identifier[nm] :
identifier[nm] = identifier[... | def analyze_one(self, nm, importernm=None, imptyp=0, level=-1):
"""
break the name being imported up so we get:
a.b.c -> [a, b, c] ; ..z -> ['', '', z]
"""
#print '## analyze_one', nm, importernm, imptyp, level
if not nm:
nm = importernm
importernm = None
leve... |
def refresh(self):
"""Update list of files, if there are changes.
Calls underlying list_rtn for the particular science instrument.
Typically, these routines search in the pysat provided path,
pysat_data_dir/platform/name/tag/,
where pysat_data_dir is set by pysat.utils.s... | def function[refresh, parameter[self]]:
constant[Update list of files, if there are changes.
Calls underlying list_rtn for the particular science instrument.
Typically, these routines search in the pysat provided path,
pysat_data_dir/platform/name/tag/,
where pysat_data_... | keyword[def] identifier[refresh] ( identifier[self] ):
literal[string]
identifier[output_str] = literal[string]
identifier[output_str] = identifier[output_str] . identifier[format] ( identifier[platform] = identifier[self] . identifier[_sat] . identifier[platform] ,
identifier[n... | def refresh(self):
"""Update list of files, if there are changes.
Calls underlying list_rtn for the particular science instrument.
Typically, these routines search in the pysat provided path,
pysat_data_dir/platform/name/tag/,
where pysat_data_dir is set by pysat.utils.set_d... |
def tempo(ref, est, **kwargs):
r'''Tempo evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dict
Dictionary... | def function[tempo, parameter[ref, est]]:
constant[Tempo evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dic... | keyword[def] identifier[tempo] ( identifier[ref] , identifier[est] ,** identifier[kwargs] ):
literal[string]
identifier[ref] = identifier[coerce_annotation] ( identifier[ref] , literal[string] )
identifier[est] = identifier[coerce_annotation] ( identifier[est] , literal[string] )
identifier[ref... | def tempo(ref, est, **kwargs):
"""Tempo evaluation
Parameters
----------
ref : jams.Annotation
Reference annotation object
est : jams.Annotation
Estimated annotation object
kwargs
Additional keyword arguments
Returns
-------
scores : dict
Dictionary ... |
def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and 'type' not in data... | def function[factory, parameter[self, data, manager]]:
constant[Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
]
if <ast.BoolOp object at 0x7da1b1fdee90> begin[:]
variable[op] assign[=] call[call[name[lis... | keyword[def] identifier[factory] ( identifier[self] , identifier[data] , identifier[manager] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ) keyword[and] identifier[len] ( identifier[data] )== literal[int] keyword[and] lite... | def factory(self, data, manager=None):
"""Factory func for filters.
data - policy config for filters
manager - resource type manager (ec2, s3, etc)
"""
# Make the syntax a little nicer for common cases.
if isinstance(data, dict) and len(data) == 1 and ('type' not in data):
o... |
def _set_mixed_moments_to_zero(self, closed_central_moments, n_counter):
r"""
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s representing central moments
... | def function[_set_mixed_moments_to_zero, parameter[self, closed_central_moments, n_counter]]:
constant[
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\s repr... | keyword[def] identifier[_set_mixed_moments_to_zero] ( identifier[self] , identifier[closed_central_moments] , identifier[n_counter] ):
literal[string]
identifier[positive_n_counter] =[ identifier[n] keyword[for] identifier[n] keyword[in] identifier[n_counter] keyword[if] identifier[n] . iden... | def _set_mixed_moments_to_zero(self, closed_central_moments, n_counter):
"""
In univariate case, set the cross-terms to 0.
:param closed_central_moments: matrix of closed central moment
:param n_counter: a list of :class:`~means.core.descriptors.Moment`\\s representing central moments
... |
def add_acquisition_source(
self,
method,
date=None,
submission_number=None,
internal_uid=None,
email=None,
orcid=None,
source=None,
datetime=None,
):
"""Add acquisition source.
:type submission_number: integer
:type e... | def function[add_acquisition_source, parameter[self, method, date, submission_number, internal_uid, email, orcid, source, datetime]]:
constant[Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param date: UTC date in isoformat... | keyword[def] identifier[add_acquisition_source] (
identifier[self] ,
identifier[method] ,
identifier[date] = keyword[None] ,
identifier[submission_number] = keyword[None] ,
identifier[internal_uid] = keyword[None] ,
identifier[email] = keyword[None] ,
identifier[orcid] = keyword[None] ,
identifier[source] = k... | def add_acquisition_source(self, method, date=None, submission_number=None, internal_uid=None, email=None, orcid=None, source=None, datetime=None):
"""Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param date: UTC date in isofo... |
def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == ... | def function[interface_endpoints, parameter[self]]:
constant[Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
]
variable[api_version] assign[=] call[name[self]._get_api_ver... | keyword[def] identifier[interface_endpoints] ( identifier[self] ):
literal[string]
identifier[api_version] = identifier[self] . identifier[_get_api_version] ( literal[string] )
keyword[if] identifier[api_version] == literal[string] :
keyword[from] . identifier[v2018_08_01] . ... | def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == '2018-08-01'... |
def get_areas(self, area_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Area
:param area_id: The Id of the area
:type area_id: Integer
:return: List of elements
"""
return self.get_elements(Area, elem_id=area_id, **kwargs) | def function[get_areas, parameter[self, area_id]]:
constant[
Alias for get_elements() but filter the result by Area
:param area_id: The Id of the area
:type area_id: Integer
:return: List of elements
]
return[call[name[self].get_elements, parameter[name[Area]]]] | keyword[def] identifier[get_areas] ( identifier[self] , identifier[area_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[get_elements] ( identifier[Area] , identifier[elem_id] = identifier[area_id] ,** identifier[kwargs] ) | def get_areas(self, area_id=None, **kwargs):
"""
Alias for get_elements() but filter the result by Area
:param area_id: The Id of the area
:type area_id: Integer
:return: List of elements
"""
return self.get_elements(Area, elem_id=area_id, **kwargs) |
def touch(path, content="", encoding="utf-8", overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... | def function[touch, parameter[path, content, encoding, overwrite]]:
constant[Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to writ... | keyword[def] identifier[touch] ( identifier[path] , identifier[content] = literal[string] , identifier[encoding] = literal[string] , identifier[overwrite] = keyword[False] ):
literal[string]
identifier[path] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[path] )
keyword[if] ke... | def touch(path, content='', encoding='utf-8', overwrite=False):
"""Create a file at the given path if it does not already exists.
Args:
path (str): Path to the file.
content (str): Optional content that will be written in the file.
encoding (str): Encoding in which to write the content.... |
def _IDW(self, latitude, longitude, radius=1):
"""
Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function and
return the e... | def function[_IDW, parameter[self, latitude, longitude, radius]]:
constant[
Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function... | keyword[def] identifier[_IDW] ( identifier[self] , identifier[latitude] , identifier[longitude] , identifier[radius] = literal[int] ):
literal[string]
identifier[tile] = identifier[self] . identifier[get_file] ( identifier[latitude] , identifier[longitude] )
keyword[if] identifier[tile] ... | def _IDW(self, latitude, longitude, radius=1):
"""
Return the interpolated elevation at a point.
Load the correct tile for latitude and longitude given.
If the tile doesn't exist, return None. Otherwise,
call the tile's Inverse Distance Weighted function and
return the eleva... |
def version(self) -> str:
'''Show the version number of Android Debug Bridge.'''
output, _ = self._execute('version')
return output.splitlines()[0].split()[-1] | def function[version, parameter[self]]:
constant[Show the version number of Android Debug Bridge.]
<ast.Tuple object at 0x7da18f8117e0> assign[=] call[name[self]._execute, parameter[constant[version]]]
return[call[call[call[call[name[output].splitlines, parameter[]]][constant[0]].split, parameter[]]... | keyword[def] identifier[version] ( identifier[self] )-> identifier[str] :
literal[string]
identifier[output] , identifier[_] = identifier[self] . identifier[_execute] ( literal[string] )
keyword[return] identifier[output] . identifier[splitlines] ()[ literal[int] ]. identifier[split] ()[-... | def version(self) -> str:
"""Show the version number of Android Debug Bridge."""
(output, _) = self._execute('version')
return output.splitlines()[0].split()[-1] |
def load(description, add_arguments_cb = lambda x: None, postprocess_conf_cb = lambda x: None):
"""Loads the global Conf object from command line arguments.
Encode the next argument after +plugin to ensure that
it does not start with a prefix_char
"""
argparser = ArgumentParser... | def function[load, parameter[description, add_arguments_cb, postprocess_conf_cb]]:
constant[Loads the global Conf object from command line arguments.
Encode the next argument after +plugin to ensure that
it does not start with a prefix_char
]
variable[argparser] assign[=] call[n... | keyword[def] identifier[load] ( identifier[description] , identifier[add_arguments_cb] = keyword[lambda] identifier[x] : keyword[None] , identifier[postprocess_conf_cb] = keyword[lambda] identifier[x] : keyword[None] ):
literal[string]
identifier[argparser] = identifier[ArgumentParser] (
... | def load(description, add_arguments_cb=lambda x: None, postprocess_conf_cb=lambda x: None):
"""Loads the global Conf object from command line arguments.
Encode the next argument after +plugin to ensure that
it does not start with a prefix_char
"""
argparser = ArgumentParser(description=... |
def _update_projects(self):
'''Check project update'''
now = time.time()
if (
not self._force_update_project
and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now
):
return
for project in self.projectdb.check_update(self._l... | def function[_update_projects, parameter[self]]:
constant[Check project update]
variable[now] assign[=] call[name[time].time, parameter[]]
if <ast.BoolOp object at 0x7da1b208ee30> begin[:]
return[None]
for taget[name[project]] in starred[call[name[self].projectdb.check_update, pa... | keyword[def] identifier[_update_projects] ( identifier[self] ):
literal[string]
identifier[now] = identifier[time] . identifier[time] ()
keyword[if] (
keyword[not] identifier[self] . identifier[_force_update_project]
keyword[and] identifier[self] . identifier[_last_upd... | def _update_projects(self):
"""Check project update"""
now = time.time()
if not self._force_update_project and self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now:
return # depends on [control=['if'], data=[]]
for project in self.projectdb.check_update(self._last_update_project):
... |
def osm_polygon_download(query, limit=1, polygon_geojson=1):
"""
Geocode a place and download its boundary geometry from OSM's Nominatim API.
Parameters
----------
query : string or dict
query string or structured query dict to geocode/download
limit : int
max number of results ... | def function[osm_polygon_download, parameter[query, limit, polygon_geojson]]:
constant[
Geocode a place and download its boundary geometry from OSM's Nominatim API.
Parameters
----------
query : string or dict
query string or structured query dict to geocode/download
limit : int
... | keyword[def] identifier[osm_polygon_download] ( identifier[query] , identifier[limit] = literal[int] , identifier[polygon_geojson] = literal[int] ):
literal[string]
identifier[params] = identifier[OrderedDict] ()
identifier[params] [ literal[string] ]= literal[string]
identifier[params] [ l... | def osm_polygon_download(query, limit=1, polygon_geojson=1):
"""
Geocode a place and download its boundary geometry from OSM's Nominatim API.
Parameters
----------
query : string or dict
query string or structured query dict to geocode/download
limit : int
max number of results ... |
def update_field(uid, post_id=None, tag_id=None, par_id=None):
'''
Update the field of post2tag.
'''
if post_id:
entry = TabPost2Tag.update(
post_id=post_id
).where(TabPost2Tag.uid == uid)
entry.execute()
if tag_id:
... | def function[update_field, parameter[uid, post_id, tag_id, par_id]]:
constant[
Update the field of post2tag.
]
if name[post_id] begin[:]
variable[entry] assign[=] call[call[name[TabPost2Tag].update, parameter[]].where, parameter[compare[name[TabPost2Tag].uid equal[==] nam... | keyword[def] identifier[update_field] ( identifier[uid] , identifier[post_id] = keyword[None] , identifier[tag_id] = keyword[None] , identifier[par_id] = keyword[None] ):
literal[string]
keyword[if] identifier[post_id] :
identifier[entry] = identifier[TabPost2Tag] . identifier[update]... | def update_field(uid, post_id=None, tag_id=None, par_id=None):
"""
Update the field of post2tag.
"""
if post_id:
entry = TabPost2Tag.update(post_id=post_id).where(TabPost2Tag.uid == uid)
entry.execute() # depends on [control=['if'], data=[]]
if tag_id:
entry2 = TabPo... |
def unload(action, action_space, unload_id):
"""Unload a unit from a transport/bunker/nydus/etc."""
del action_space
action.action_ui.cargo_panel.unit_index = unload_id | def function[unload, parameter[action, action_space, unload_id]]:
constant[Unload a unit from a transport/bunker/nydus/etc.]
<ast.Delete object at 0x7da18f00c3d0>
name[action].action_ui.cargo_panel.unit_index assign[=] name[unload_id] | keyword[def] identifier[unload] ( identifier[action] , identifier[action_space] , identifier[unload_id] ):
literal[string]
keyword[del] identifier[action_space]
identifier[action] . identifier[action_ui] . identifier[cargo_panel] . identifier[unit_index] = identifier[unload_id] | def unload(action, action_space, unload_id):
"""Unload a unit from a transport/bunker/nydus/etc."""
del action_space
action.action_ui.cargo_panel.unit_index = unload_id |
def load_config_file(self, suppress_errors=True):
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
"""
self.log.debug("Sear... | def function[load_config_file, parameter[self, suppress_errors]]:
constant[Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
]
... | keyword[def] identifier[load_config_file] ( identifier[self] , identifier[suppress_errors] = keyword[True] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[self] . identifier[config_file_paths] )
identifier[base_config] = literal[stri... | def load_config_file(self, suppress_errors=True):
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
"""
self.log.debug('Searching pa... |
def _gen_labels_columns(self, list_columns):
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col) | def function[_gen_labels_columns, parameter[self, list_columns]]:
constant[
Auto generates pretty label_columns from list of columns
]
for taget[name[col]] in starred[name[list_columns]] begin[:]
if <ast.UnaryOp object at 0x7da207f02560> begin[:]
... | keyword[def] identifier[_gen_labels_columns] ( identifier[self] , identifier[list_columns] ):
literal[string]
keyword[for] identifier[col] keyword[in] identifier[list_columns] :
keyword[if] keyword[not] identifier[self] . identifier[label_columns] . identifier[get] ( identifier[co... | def _gen_labels_columns(self, list_columns):
"""
Auto generates pretty label_columns from list of columns
"""
for col in list_columns:
if not self.label_columns.get(col):
self.label_columns[col] = self._prettify_column(col) # depends on [control=['if'], data=[]] # depen... |
def allocate_hosting_port(self, context, router_id, port_db, network_type,
hosting_device_id):
"""Allocates a hosting port for a logical port.
We create a hosting port for the router port
"""
l3admin_tenant_id = self._dev_mgr.l3_tenant_id()
hostingp... | def function[allocate_hosting_port, parameter[self, context, router_id, port_db, network_type, hosting_device_id]]:
constant[Allocates a hosting port for a logical port.
We create a hosting port for the router port
]
variable[l3admin_tenant_id] assign[=] call[name[self]._dev_mgr.l3_tena... | keyword[def] identifier[allocate_hosting_port] ( identifier[self] , identifier[context] , identifier[router_id] , identifier[port_db] , identifier[network_type] ,
identifier[hosting_device_id] ):
literal[string]
identifier[l3admin_tenant_id] = identifier[self] . identifier[_dev_mgr] . identifier[l... | def allocate_hosting_port(self, context, router_id, port_db, network_type, hosting_device_id):
"""Allocates a hosting port for a logical port.
We create a hosting port for the router port
"""
l3admin_tenant_id = self._dev_mgr.l3_tenant_id()
hostingport_name = 'hostingport_' + port_db['id'][... |
def can_mark_block_complete_on_view(self, block):
"""
Returns True if the xblock can be marked complete on view.
This is true of any non-customized, non-scorable, completable block.
"""
return (
XBlockCompletionMode.get_mode(block) == XBlockCompletionMode.COMPLETABLE
... | def function[can_mark_block_complete_on_view, parameter[self, block]]:
constant[
Returns True if the xblock can be marked complete on view.
This is true of any non-customized, non-scorable, completable block.
]
return[<ast.BoolOp object at 0x7da20c6c54e0>] | keyword[def] identifier[can_mark_block_complete_on_view] ( identifier[self] , identifier[block] ):
literal[string]
keyword[return] (
identifier[XBlockCompletionMode] . identifier[get_mode] ( identifier[block] )== identifier[XBlockCompletionMode] . identifier[COMPLETABLE]
keyword[... | def can_mark_block_complete_on_view(self, block):
"""
Returns True if the xblock can be marked complete on view.
This is true of any non-customized, non-scorable, completable block.
"""
return XBlockCompletionMode.get_mode(block) == XBlockCompletionMode.COMPLETABLE and (not getattr(block... |
def assign_moving_mean_variance(
mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
var... | def function[assign_moving_mean_variance, parameter[mean_var, variance_var, value, decay, name]]:
constant[Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relati... | keyword[def] identifier[assign_moving_mean_variance] (
identifier[mean_var] , identifier[variance_var] , identifier[value] , identifier[decay] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[compat] . identifier[v1] . identifier[name_scope] ( identifier[name] ,... | def assign_moving_mean_variance(mean_var, variance_var, value, decay, name=None):
"""Compute exponentially weighted moving {mean,variance} of a streaming value.
The `value` updated exponentially weighted moving `mean_var` and
`variance_var` are given by the following recurrence relations:
```python
varian... |
def cache_get(key):
"""
Wrapper for ``cache.get``. The expiry time for the cache entry
is stored with the entry. If the expiry time has past, put the
stale entry back into cache, and don't return it to trigger a
fake cache miss.
"""
packed = cache.get(_hashed_key(key))
if packed is None:... | def function[cache_get, parameter[key]]:
constant[
Wrapper for ``cache.get``. The expiry time for the cache entry
is stored with the entry. If the expiry time has past, put the
stale entry back into cache, and don't return it to trigger a
fake cache miss.
]
variable[packed] assign[=]... | keyword[def] identifier[cache_get] ( identifier[key] ):
literal[string]
identifier[packed] = identifier[cache] . identifier[get] ( identifier[_hashed_key] ( identifier[key] ))
keyword[if] identifier[packed] keyword[is] keyword[None] :
keyword[return] keyword[None]
identifier[value] ... | def cache_get(key):
"""
Wrapper for ``cache.get``. The expiry time for the cache entry
is stored with the entry. If the expiry time has past, put the
stale entry back into cache, and don't return it to trigger a
fake cache miss.
"""
packed = cache.get(_hashed_key(key))
if packed is None:... |
def process_event(self, name, subject, data):
"""
Process a single event.
:param name:
:param subject:
:param data:
"""
method_mapping = Registry.get_event(name)
if not method_mapping:
log.info('@{}.process_event no subscriber for event `{}`'
... | def function[process_event, parameter[self, name, subject, data]]:
constant[
Process a single event.
:param name:
:param subject:
:param data:
]
variable[method_mapping] assign[=] call[name[Registry].get_event, parameter[name[name]]]
if <ast.UnaryOp object... | keyword[def] identifier[process_event] ( identifier[self] , identifier[name] , identifier[subject] , identifier[data] ):
literal[string]
identifier[method_mapping] = identifier[Registry] . identifier[get_event] ( identifier[name] )
keyword[if] keyword[not] identifier[method_mapping] :
... | def process_event(self, name, subject, data):
"""
Process a single event.
:param name:
:param subject:
:param data:
"""
method_mapping = Registry.get_event(name)
if not method_mapping:
log.info('@{}.process_event no subscriber for event `{}`'.format(self.__cla... |
def get(self):
"""Reloads the check with its current values."""
new = self.manager.get(self)
if new:
self._add_details(new._info) | def function[get, parameter[self]]:
constant[Reloads the check with its current values.]
variable[new] assign[=] call[name[self].manager.get, parameter[name[self]]]
if name[new] begin[:]
call[name[self]._add_details, parameter[name[new]._info]] | keyword[def] identifier[get] ( identifier[self] ):
literal[string]
identifier[new] = identifier[self] . identifier[manager] . identifier[get] ( identifier[self] )
keyword[if] identifier[new] :
identifier[self] . identifier[_add_details] ( identifier[new] . identifier[_info] ) | def get(self):
"""Reloads the check with its current values."""
new = self.manager.get(self)
if new:
self._add_details(new._info) # depends on [control=['if'], data=[]] |
def get_assessment_part_item_design_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment part item design service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.authoring.AssessmentPartItemDesig... | def function[get_assessment_part_item_design_session_for_bank, parameter[self, bank_id, proxy]]:
constant[Gets the ``OsidSession`` associated with the assessment part item design service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.author... | keyword[def] identifier[get_assessment_part_item_design_session_for_bank] ( identifier[self] , identifier[bank_id] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_assessment_part_lookup] ():
keyword[raise] identifier[errors] . i... | def get_assessment_part_item_design_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment part item design service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the ``Bank``
return: (osid.assessment.authoring.AssessmentPartItemDesignSes... |
def on_shutdown(self, broker):
"""Request the slave gracefully shut itself down."""
LOG.debug('%r closing CALL_FUNCTION channel', self)
self._send(
mitogen.core.Message(
src_id=mitogen.context_id,
dst_id=self.remote_id,
handle=mitogen.c... | def function[on_shutdown, parameter[self, broker]]:
constant[Request the slave gracefully shut itself down.]
call[name[LOG].debug, parameter[constant[%r closing CALL_FUNCTION channel], name[self]]]
call[name[self]._send, parameter[call[name[mitogen].core.Message, parameter[]]]] | keyword[def] identifier[on_shutdown] ( identifier[self] , identifier[broker] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] , identifier[self] )
identifier[self] . identifier[_send] (
identifier[mitogen] . identifier[core] . identifier[Message] (
... | def on_shutdown(self, broker):
"""Request the slave gracefully shut itself down."""
LOG.debug('%r closing CALL_FUNCTION channel', self)
self._send(mitogen.core.Message(src_id=mitogen.context_id, dst_id=self.remote_id, handle=mitogen.core.SHUTDOWN)) |
def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict'):
"""Ensures an input is bytes, encoding if it is a string.
"""
if isinstance(str_or_bytes, six.text_type):
return str_or_bytes.encode(encoding, errors)
return str_or_bytes | def function[ensure_bytes, parameter[str_or_bytes, encoding, errors]]:
constant[Ensures an input is bytes, encoding if it is a string.
]
if call[name[isinstance], parameter[name[str_or_bytes], name[six].text_type]] begin[:]
return[call[name[str_or_bytes].encode, parameter[name[encoding], nam... | keyword[def] identifier[ensure_bytes] ( identifier[str_or_bytes] , identifier[encoding] = literal[string] , identifier[errors] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[str_or_bytes] , identifier[six] . identifier[text_type] ):
keyword[return] identifie... | def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict'):
"""Ensures an input is bytes, encoding if it is a string.
"""
if isinstance(str_or_bytes, six.text_type):
return str_or_bytes.encode(encoding, errors) # depends on [control=['if'], data=[]]
return str_or_bytes |
def fit(
self,
img_data,
gamma=1.0,
save_freq=-1,
pic_freq=-1,
n_epochs=100,
batch_size=50,
weight_decay=True,
model_path='./VAEGAN_training_model/',
img_path='./VAEGAN_training_images/',
img_out_width=10,
mirroring=False
... | def function[fit, parameter[self, img_data, gamma, save_freq, pic_freq, n_epochs, batch_size, weight_decay, model_path, img_path, img_out_width, mirroring]]:
constant[Fit the VAE/GAN model to the image data.
Parameters
----------
img_data : array-like shape (n_images, n_colors, image_w... | keyword[def] identifier[fit] (
identifier[self] ,
identifier[img_data] ,
identifier[gamma] = literal[int] ,
identifier[save_freq] =- literal[int] ,
identifier[pic_freq] =- literal[int] ,
identifier[n_epochs] = literal[int] ,
identifier[batch_size] = literal[int] ,
identifier[weight_decay] = keyword[True] ,
i... | def fit(self, img_data, gamma=1.0, save_freq=-1, pic_freq=-1, n_epochs=100, batch_size=50, weight_decay=True, model_path='./VAEGAN_training_model/', img_path='./VAEGAN_training_images/', img_out_width=10, mirroring=False):
"""Fit the VAE/GAN model to the image data.
Parameters
----------
i... |
def app_class():
"""Create Flask application class.
Invenio-Files-REST needs to patch the Werkzeug form parsing in order to
support streaming large file uploads. This is done by subclassing the Flask
application class.
"""
try:
pkg_resources.get_distribution('invenio-files-rest')
... | def function[app_class, parameter[]]:
constant[Create Flask application class.
Invenio-Files-REST needs to patch the Werkzeug form parsing in order to
support streaming large file uploads. This is done by subclassing the Flask
application class.
]
<ast.Try object at 0x7da1afea9720>
... | keyword[def] identifier[app_class] ():
literal[string]
keyword[try] :
identifier[pkg_resources] . identifier[get_distribution] ( literal[string] )
keyword[from] identifier[invenio_files_rest] . identifier[app] keyword[import] identifier[Flask] keyword[as] identifier[FlaskBase]
... | def app_class():
"""Create Flask application class.
Invenio-Files-REST needs to patch the Werkzeug form parsing in order to
support streaming large file uploads. This is done by subclassing the Flask
application class.
"""
try:
pkg_resources.get_distribution('invenio-files-rest')
... |
def resetPassword(self, userId):
'''
Changes a user's password to a system-generated value.
'''
self._setHeaders('resetPassword')
return self._sforce.service.resetPassword(userId) | def function[resetPassword, parameter[self, userId]]:
constant[
Changes a user's password to a system-generated value.
]
call[name[self]._setHeaders, parameter[constant[resetPassword]]]
return[call[name[self]._sforce.service.resetPassword, parameter[name[userId]]]] | keyword[def] identifier[resetPassword] ( identifier[self] , identifier[userId] ):
literal[string]
identifier[self] . identifier[_setHeaders] ( literal[string] )
keyword[return] identifier[self] . identifier[_sforce] . identifier[service] . identifier[resetPassword] ( identifier[userId] ) | def resetPassword(self, userId):
"""
Changes a user's password to a system-generated value.
"""
self._setHeaders('resetPassword')
return self._sforce.service.resetPassword(userId) |
def transitive_closure(self):
"""Compute the transitive closure of the matrix."""
data = [[1 if j else 0 for j in i] for i in self.data]
for k in range(self.rows):
for i in range(self.rows):
for j in range(self.rows):
if data[i][k] and data[k][j]:
... | def function[transitive_closure, parameter[self]]:
constant[Compute the transitive closure of the matrix.]
variable[data] assign[=] <ast.ListComp object at 0x7da1b20f9d20>
for taget[name[k]] in starred[call[name[range], parameter[name[self].rows]]] begin[:]
for taget[name[i]] in ... | keyword[def] identifier[transitive_closure] ( identifier[self] ):
literal[string]
identifier[data] =[[ literal[int] keyword[if] identifier[j] keyword[else] literal[int] keyword[for] identifier[j] keyword[in] identifier[i] ] keyword[for] identifier[i] keyword[in] identifier[self] . identi... | def transitive_closure(self):
"""Compute the transitive closure of the matrix."""
data = [[1 if j else 0 for j in i] for i in self.data]
for k in range(self.rows):
for i in range(self.rows):
for j in range(self.rows):
if data[i][k] and data[k][j]:
data... |
def minimum_spanning_subtree(self):
'''Returns the (undirected) minimum spanning tree subgraph.'''
dist = self.matrix('dense', copy=True)
dist[dist==0] = np.inf
np.fill_diagonal(dist, 0)
mst = ssc.minimum_spanning_tree(dist)
return self.__class__.from_adj_matrix(mst + mst.T) | def function[minimum_spanning_subtree, parameter[self]]:
constant[Returns the (undirected) minimum spanning tree subgraph.]
variable[dist] assign[=] call[name[self].matrix, parameter[constant[dense]]]
call[name[dist]][compare[name[dist] equal[==] constant[0]]] assign[=] name[np].inf
call... | keyword[def] identifier[minimum_spanning_subtree] ( identifier[self] ):
literal[string]
identifier[dist] = identifier[self] . identifier[matrix] ( literal[string] , identifier[copy] = keyword[True] )
identifier[dist] [ identifier[dist] == literal[int] ]= identifier[np] . identifier[inf]
identifi... | def minimum_spanning_subtree(self):
"""Returns the (undirected) minimum spanning tree subgraph."""
dist = self.matrix('dense', copy=True)
dist[dist == 0] = np.inf
np.fill_diagonal(dist, 0)
mst = ssc.minimum_spanning_tree(dist)
return self.__class__.from_adj_matrix(mst + mst.T) |
def get_utt_regions(self):
"""
Return the regions of all utterances, assuming all utterances are concatenated.
A region is defined by offset, length (num-frames) and
a list of references to the utterance datasets in the containers.
Returns:
list: List of with a tuple... | def function[get_utt_regions, parameter[self]]:
constant[
Return the regions of all utterances, assuming all utterances are concatenated.
A region is defined by offset, length (num-frames) and
a list of references to the utterance datasets in the containers.
Returns:
... | keyword[def] identifier[get_utt_regions] ( identifier[self] ):
literal[string]
identifier[regions] =[]
identifier[current_offset] = literal[int]
keyword[for] identifier[utt_idx] , identifier[utt_data] keyword[in] identifier[zip] ( identifier[self] . identifier[data] . identi... | def get_utt_regions(self):
"""
Return the regions of all utterances, assuming all utterances are concatenated.
A region is defined by offset, length (num-frames) and
a list of references to the utterance datasets in the containers.
Returns:
list: List of with a tuple for... |
def get(self, name, **kwargs):
"""Get the variable given a name if one exists or create a new one if missing.
Parameters
----------
name : str
name of the variable
**kwargs :
more arguments that's passed to symbol.Variable
"""
name = self.... | def function[get, parameter[self, name]]:
constant[Get the variable given a name if one exists or create a new one if missing.
Parameters
----------
name : str
name of the variable
**kwargs :
more arguments that's passed to symbol.Variable
]
... | keyword[def] identifier[get] ( identifier[self] , identifier[name] ,** identifier[kwargs] ):
literal[string]
identifier[name] = identifier[self] . identifier[_prefix] + identifier[name]
keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[_params] :
... | def get(self, name, **kwargs):
"""Get the variable given a name if one exists or create a new one if missing.
Parameters
----------
name : str
name of the variable
**kwargs :
more arguments that's passed to symbol.Variable
"""
name = self._prefix ... |
def get_info(self):
'''
Get info regarding the current template state
:return: info dictionary
'''
self.render()
info = super(Template, self).get_info()
res = {}
res['name'] = self.get_name()
res['mutation'] = {
'current_index': self._... | def function[get_info, parameter[self]]:
constant[
Get info regarding the current template state
:return: info dictionary
]
call[name[self].render, parameter[]]
variable[info] assign[=] call[call[name[super], parameter[name[Template], name[self]]].get_info, parameter[]]
... | keyword[def] identifier[get_info] ( identifier[self] ):
literal[string]
identifier[self] . identifier[render] ()
identifier[info] = identifier[super] ( identifier[Template] , identifier[self] ). identifier[get_info] ()
identifier[res] ={}
identifier[res] [ literal[string]... | def get_info(self):
"""
Get info regarding the current template state
:return: info dictionary
"""
self.render()
info = super(Template, self).get_info()
res = {}
res['name'] = self.get_name()
res['mutation'] = {'current_index': self._current_index, 'total_number': self.n... |
def copy_file(self, filepath):
"""
Returns flag which says to copy rather than link a file.
"""
copy_file = False
try:
copy_file = self.data[filepath]['copy']
except KeyError:
return False
return copy_file | def function[copy_file, parameter[self, filepath]]:
constant[
Returns flag which says to copy rather than link a file.
]
variable[copy_file] assign[=] constant[False]
<ast.Try object at 0x7da1b0283910>
return[name[copy_file]] | keyword[def] identifier[copy_file] ( identifier[self] , identifier[filepath] ):
literal[string]
identifier[copy_file] = keyword[False]
keyword[try] :
identifier[copy_file] = identifier[self] . identifier[data] [ identifier[filepath] ][ literal[string] ]
keyword[excep... | def copy_file(self, filepath):
"""
Returns flag which says to copy rather than link a file.
"""
copy_file = False
try:
copy_file = self.data[filepath]['copy'] # depends on [control=['try'], data=[]]
except KeyError:
return False # depends on [control=['except'], data=[]... |
def command(execute=None): # noqa: E501
"""Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response
"""
if connexion.request.is_json:
execute = Execute.from_dict(connexion.request.get_jso... | def function[command, parameter[execute]]:
constant[Execute a Command
Execute a command # noqa: E501
:param execute: The data needed to execute this command
:type execute: dict | bytes
:rtype: Response
]
if name[connexion].request.is_json begin[:]
variable[execute]... | keyword[def] identifier[command] ( identifier[execute] = keyword[None] ):
literal[string]
keyword[if] identifier[connexion] . identifier[request] . identifier[is_json] :
identifier[execute] = identifier[Execute] . identifier[from_dict] ( identifier[connexion] . identifier[request] . identifier[ge... | def command(execute=None): # noqa: E501
'Execute a Command\n\n Execute a command # noqa: E501\n\n :param execute: The data needed to execute this command\n :type execute: dict | bytes\n\n :rtype: Response\n '
if connexion.request.is_json:
execute = Execute.from_dict(connexion.request.get... |
def compare_enums(autogen_context, upgrade_ops, schema_names):
"""
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared versio... | def function[compare_enums, parameter[autogen_context, upgrade_ops, schema_names]]:
constant[
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when comp... | keyword[def] identifier[compare_enums] ( identifier[autogen_context] , identifier[upgrade_ops] , identifier[schema_names] ):
literal[string]
identifier[to_add] = identifier[set] ()
keyword[for] identifier[schema] keyword[in] identifier[schema_names] :
identifier[default] = identifier[autog... | def compare_enums(autogen_context, upgrade_ops, schema_names):
"""
Walk the declared SQLAlchemy schema for every referenced Enum, walk the PG
schema for every definde Enum, then generate SyncEnumValuesOp migrations
for each defined enum that has grown new entries when compared to its
declared versio... |
def get_default_realms(self, client_key, request):
"""Default realms of the client."""
log.debug('Get realms for %r', client_key)
if not request.client:
request.client = self._clientgetter(client_key=client_key)
client = request.client
if hasattr(client, 'default_re... | def function[get_default_realms, parameter[self, client_key, request]]:
constant[Default realms of the client.]
call[name[log].debug, parameter[constant[Get realms for %r], name[client_key]]]
if <ast.UnaryOp object at 0x7da1b0382fb0> begin[:]
name[request].client assign[=] call[n... | keyword[def] identifier[get_default_realms] ( identifier[self] , identifier[client_key] , identifier[request] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[client_key] )
keyword[if] keyword[not] identifier[request] . identifier[client] :
... | def get_default_realms(self, client_key, request):
"""Default realms of the client."""
log.debug('Get realms for %r', client_key)
if not request.client:
request.client = self._clientgetter(client_key=client_key) # depends on [control=['if'], data=[]]
client = request.client
if hasattr(clien... |
def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
'''
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from ... | def function[configuration_import, parameter[config_file, rules, file_format]]:
constant[
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be diffe... | keyword[def] identifier[configuration_import] ( identifier[config_file] , identifier[rules] = keyword[None] , identifier[file_format] = literal[string] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[rules] keyword[is] keyword[None] :
identifier[rules] ={}
identifier[defau... | def configuration_import(config_file, rules=None, file_format='xml', **kwargs):
"""
.. versionadded:: 2017.7
Imports Zabbix configuration specified in file to Zabbix server.
:param config_file: File with Zabbix config (local or remote)
:param rules: Optional - Rules that have to be different from ... |
def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None):
"""
Add a new virtual link with the type set to VLAN.
Creates a new vlan device {name} on device {port}.
Will raise an exception if value is already assigned.
:param enode: Engine node to communicate with.
:type enode: topology... | def function[add_link_type_vlan, parameter[enode, portlbl, name, vlan_id, shell]]:
constant[
Add a new virtual link with the type set to VLAN.
Creates a new vlan device {name} on device {port}.
Will raise an exception if value is already assigned.
:param enode: Engine node to communicate with.... | keyword[def] identifier[add_link_type_vlan] ( identifier[enode] , identifier[portlbl] , identifier[name] , identifier[vlan_id] , identifier[shell] = keyword[None] ):
literal[string]
keyword[assert] identifier[name]
keyword[if] identifier[name] keyword[in] identifier[enode] . identifier[ports] :
... | def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None):
"""
Add a new virtual link with the type set to VLAN.
Creates a new vlan device {name} on device {port}.
Will raise an exception if value is already assigned.
:param enode: Engine node to communicate with.
:type enode: topology... |
def right(self, expand=None):
""" Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position as the current region.
... | def function[right, parameter[self, expand]]:
constant[ Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position a... | keyword[def] identifier[right] ( identifier[self] , identifier[expand] = keyword[None] ):
literal[string]
keyword[if] identifier[expand] == keyword[None] :
identifier[x] = identifier[self] . identifier[x] + identifier[self] . identifier[w]
identifier[y] = identifier[self... | def right(self, expand=None):
""" Returns a new Region right of the current region with a width of ``expand`` pixels.
Does not include the current region. If range is omitted, it reaches to the right border
of the screen. The new region has the same height and y-position as the current region.
... |
def decode_struct_tree(self, data_type, obj):
"""
The data_type argument must be a StructTree.
See json_compat_obj_decode() for argument descriptions.
"""
subtype = self.determine_struct_tree_subtype(data_type, obj)
return self.decode_struct(subtype, obj) | def function[decode_struct_tree, parameter[self, data_type, obj]]:
constant[
The data_type argument must be a StructTree.
See json_compat_obj_decode() for argument descriptions.
]
variable[subtype] assign[=] call[name[self].determine_struct_tree_subtype, parameter[name[data_type]... | keyword[def] identifier[decode_struct_tree] ( identifier[self] , identifier[data_type] , identifier[obj] ):
literal[string]
identifier[subtype] = identifier[self] . identifier[determine_struct_tree_subtype] ( identifier[data_type] , identifier[obj] )
keyword[return] identifier[self] . ide... | def decode_struct_tree(self, data_type, obj):
"""
The data_type argument must be a StructTree.
See json_compat_obj_decode() for argument descriptions.
"""
subtype = self.determine_struct_tree_subtype(data_type, obj)
return self.decode_struct(subtype, obj) |
def estimate(items, batch, config):
"""Estimate heterogeneity for a pair of tumor/normal samples. Run in parallel.
"""
hetcallers = {"theta": theta.run,
"phylowgs": phylowgs.run,
"bubbletree": bubbletree.run}
paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for ... | def function[estimate, parameter[items, batch, config]]:
constant[Estimate heterogeneity for a pair of tumor/normal samples. Run in parallel.
]
variable[hetcallers] assign[=] dictionary[[<ast.Constant object at 0x7da18bcc85b0>, <ast.Constant object at 0x7da18bcc9a20>, <ast.Constant object at 0x7da18... | keyword[def] identifier[estimate] ( identifier[items] , identifier[batch] , identifier[config] ):
literal[string]
identifier[hetcallers] ={ literal[string] : identifier[theta] . identifier[run] ,
literal[string] : identifier[phylowgs] . identifier[run] ,
literal[string] : identifier[bubbletree] .... | def estimate(items, batch, config):
"""Estimate heterogeneity for a pair of tumor/normal samples. Run in parallel.
"""
hetcallers = {'theta': theta.run, 'phylowgs': phylowgs.run, 'bubbletree': bubbletree.run}
paired = vcfutils.get_paired_bams([dd.get_align_bam(d) for d in items], items)
calls = _get... |
def _sanity_check_files(item, files):
"""Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs.
"""
msg = None
file_types = set([("bam" if x.endswith(".bam") else "fastq") for x in files if x])
if len(file_types) > 1:
msg = "Found multiple file ... | def function[_sanity_check_files, parameter[item, files]]:
constant[Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs.
]
variable[msg] assign[=] constant[None]
variable[file_types] assign[=] call[name[set], parameter[<ast.ListComp object at ... | keyword[def] identifier[_sanity_check_files] ( identifier[item] , identifier[files] ):
literal[string]
identifier[msg] = keyword[None]
identifier[file_types] = identifier[set] ([( literal[string] keyword[if] identifier[x] . identifier[endswith] ( literal[string] ) keyword[else] literal[string] ) k... | def _sanity_check_files(item, files):
"""Ensure input files correspond with supported approaches.
Handles BAM, fastqs, plus split fastqs.
"""
msg = None
file_types = set(['bam' if x.endswith('.bam') else 'fastq' for x in files if x])
if len(file_types) > 1:
msg = 'Found multiple file ty... |
def split_by_fname_file(self, fname:PathOrStr, path:PathOrStr=None)->'ItemLists':
"Split the data by using the names in `fname` for the validation set. `path` will override `self.path`."
path = Path(ifnone(path, self.path))
valid_names = loadtxt_str(path/fname)
return self.split_by_files... | def function[split_by_fname_file, parameter[self, fname, path]]:
constant[Split the data by using the names in `fname` for the validation set. `path` will override `self.path`.]
variable[path] assign[=] call[name[Path], parameter[call[name[ifnone], parameter[name[path], name[self].path]]]]
varia... | keyword[def] identifier[split_by_fname_file] ( identifier[self] , identifier[fname] : identifier[PathOrStr] , identifier[path] : identifier[PathOrStr] = keyword[None] )-> literal[string] :
literal[string]
identifier[path] = identifier[Path] ( identifier[ifnone] ( identifier[path] , identifier[self]... | def split_by_fname_file(self, fname: PathOrStr, path: PathOrStr=None) -> 'ItemLists':
"""Split the data by using the names in `fname` for the validation set. `path` will override `self.path`."""
path = Path(ifnone(path, self.path))
valid_names = loadtxt_str(path / fname)
return self.split_by_files(valid... |
def file2json(self, jsonfile=None):
""" Convert entire lte file into json like format
USAGE: 1: kwsdictstr = file2json()
2: kwsdictstr = file2json(jsonfile = 'somefile')
show pretty format with pipeline: | jshon, or | pjson
if jsonfile is defined, dump to defined file be... | def function[file2json, parameter[self, jsonfile]]:
constant[ Convert entire lte file into json like format
USAGE: 1: kwsdictstr = file2json()
2: kwsdictstr = file2json(jsonfile = 'somefile')
show pretty format with pipeline: | jshon, or | pjson
if jsonfile is defined, d... | keyword[def] identifier[file2json] ( identifier[self] , identifier[jsonfile] = keyword[None] ):
literal[string]
identifier[kwslist] = identifier[self] . identifier[detectAllKws] ()
identifier[kwsdict] ={}
identifier[idx] = literal[int]
keyword[for] identifier[kw] keywo... | def file2json(self, jsonfile=None):
""" Convert entire lte file into json like format
USAGE: 1: kwsdictstr = file2json()
2: kwsdictstr = file2json(jsonfile = 'somefile')
show pretty format with pipeline: | jshon, or | pjson
if jsonfile is defined, dump to defined file before... |
def decode_bridged_message(rx_data):
"""Decode a (multi-)bridged command.
rx_data: the received message as bytestring
Returns the decoded message as bytestring
"""
while array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE:
rsp = create_message(constants.NETFN_APP + 1,
... | def function[decode_bridged_message, parameter[rx_data]]:
constant[Decode a (multi-)bridged command.
rx_data: the received message as bytestring
Returns the decoded message as bytestring
]
while compare[call[call[name[array], parameter[constant[B], name[rx_data]]]][constant[5]] equal[==] n... | keyword[def] identifier[decode_bridged_message] ( identifier[rx_data] ):
literal[string]
keyword[while] identifier[array] ( literal[string] , identifier[rx_data] )[ literal[int] ]== identifier[constants] . identifier[CMDID_SEND_MESSAGE] :
identifier[rsp] = identifier[create_message] ( identifier... | def decode_bridged_message(rx_data):
"""Decode a (multi-)bridged command.
rx_data: the received message as bytestring
Returns the decoded message as bytestring
"""
while array('B', rx_data)[5] == constants.CMDID_SEND_MESSAGE:
rsp = create_message(constants.NETFN_APP + 1, constants.CMDID_SE... |
def _set_properties(self, data):
"""
set the properties of the app model by the given data dict
"""
for property in data.keys():
if property in vars(self):
setattr(self, property, data[property]) | def function[_set_properties, parameter[self, data]]:
constant[
set the properties of the app model by the given data dict
]
for taget[name[property]] in starred[call[name[data].keys, parameter[]]] begin[:]
if compare[name[property] in call[name[vars], parameter[name[self... | keyword[def] identifier[_set_properties] ( identifier[self] , identifier[data] ):
literal[string]
keyword[for] identifier[property] keyword[in] identifier[data] . identifier[keys] ():
keyword[if] identifier[property] keyword[in] identifier[vars] ( identifier[self] ):
... | def _set_properties(self, data):
"""
set the properties of the app model by the given data dict
"""
for property in data.keys():
if property in vars(self):
setattr(self, property, data[property]) # depends on [control=['if'], data=['property']] # depends on [control=['for']... |
def GetDeviceStringProperty(dev_ref, key):
"""Reads string property from the HID device."""
cf_key = CFStr(key)
type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
cf.CFRelease(cf_key)
if not type_ref:
return None
if cf.CFGetTypeID(type_ref) != cf.CFStringGetTypeID():
raise errors.OsHidError('... | def function[GetDeviceStringProperty, parameter[dev_ref, key]]:
constant[Reads string property from the HID device.]
variable[cf_key] assign[=] call[name[CFStr], parameter[name[key]]]
variable[type_ref] assign[=] call[name[iokit].IOHIDDeviceGetProperty, parameter[name[dev_ref], name[cf_key]]]
... | keyword[def] identifier[GetDeviceStringProperty] ( identifier[dev_ref] , identifier[key] ):
literal[string]
identifier[cf_key] = identifier[CFStr] ( identifier[key] )
identifier[type_ref] = identifier[iokit] . identifier[IOHIDDeviceGetProperty] ( identifier[dev_ref] , identifier[cf_key] )
identifier[cf] ... | def GetDeviceStringProperty(dev_ref, key):
"""Reads string property from the HID device."""
cf_key = CFStr(key)
type_ref = iokit.IOHIDDeviceGetProperty(dev_ref, cf_key)
cf.CFRelease(cf_key)
if not type_ref:
return None # depends on [control=['if'], data=[]]
if cf.CFGetTypeID(type_ref) !... |
def visitInlineShapeAnd(self, ctx: ShExDocParser.InlineShapeAndContext):
""" inlineShapeAnd: inlineShapeNot (KW_AND inlineShapeNot)* """
if len(ctx.inlineShapeNot()) > 1:
self.expr = ShapeAnd(id=self.label, shapeExprs=[])
for sa in ctx.inlineShapeNot():
sep = Shex... | def function[visitInlineShapeAnd, parameter[self, ctx]]:
constant[ inlineShapeAnd: inlineShapeNot (KW_AND inlineShapeNot)* ]
if compare[call[name[len], parameter[call[name[ctx].inlineShapeNot, parameter[]]]] greater[>] constant[1]] begin[:]
name[self].expr assign[=] call[name[ShapeAnd], ... | keyword[def] identifier[visitInlineShapeAnd] ( identifier[self] , identifier[ctx] : identifier[ShExDocParser] . identifier[InlineShapeAndContext] ):
literal[string]
keyword[if] identifier[len] ( identifier[ctx] . identifier[inlineShapeNot] ())> literal[int] :
identifier[self] . identi... | def visitInlineShapeAnd(self, ctx: ShExDocParser.InlineShapeAndContext):
""" inlineShapeAnd: inlineShapeNot (KW_AND inlineShapeNot)* """
if len(ctx.inlineShapeNot()) > 1:
self.expr = ShapeAnd(id=self.label, shapeExprs=[])
for sa in ctx.inlineShapeNot():
sep = ShexShapeExpressionParse... |
def zip(self, *args):
"""
Zip together multiple lists into a single array -- elements that share
an index go together.
"""
args = list(args)
args.insert(0, self.obj)
maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value()
for i, v in enumer... | def function[zip, parameter[self]]:
constant[
Zip together multiple lists into a single array -- elements that share
an index go together.
]
variable[args] assign[=] call[name[list], parameter[name[args]]]
call[name[args].insert, parameter[constant[0], name[self].obj]]
... | keyword[def] identifier[zip] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[args] = identifier[list] ( identifier[args] )
identifier[args] . identifier[insert] ( literal[int] , identifier[self] . identifier[obj] )
identifier[maxLen] = identifier[_] ( identifi... | def zip(self, *args):
"""
Zip together multiple lists into a single array -- elements that share
an index go together.
"""
args = list(args)
args.insert(0, self.obj)
maxLen = _(args).chain().collect(lambda x, *args: len(x)).max().value()
for (i, v) in enumerate(args):
... |
def add(self, function, kind='add', at_pos='end',*args, **kwargs):
"""Add a function to custom processing queue.
Custom functions are applied automatically to associated
pysat instrument whenever instrument.load command called.
Parameters
----------
functio... | def function[add, parameter[self, function, kind, at_pos]]:
constant[Add a function to custom processing queue.
Custom functions are applied automatically to associated
pysat instrument whenever instrument.load command called.
Parameters
----------
function... | keyword[def] identifier[add] ( identifier[self] , identifier[function] , identifier[kind] = literal[string] , identifier[at_pos] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[function] , identifier[str] ):
... | def add(self, function, kind='add', at_pos='end', *args, **kwargs):
"""Add a function to custom processing queue.
Custom functions are applied automatically to associated
pysat instrument whenever instrument.load command called.
Parameters
----------
function :... |
def QA_SU_save_stock_min(engine, client=DATABASE):
"""save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_min(client=client) | def function[QA_SU_save_stock_min, parameter[engine, client]]:
constant[save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
]
variable[engine] assign[=] call[name[select_save_engine], parameter... | keyword[def] identifier[QA_SU_save_stock_min] ( identifier[engine] , identifier[client] = identifier[DATABASE] ):
literal[string]
identifier[engine] = identifier[select_save_engine] ( identifier[engine] )
identifier[engine] . identifier[QA_SU_save_stock_min] ( identifier[client] = identifier[client] ... | def QA_SU_save_stock_min(engine, client=DATABASE):
"""save stock_min
Arguments:
engine {[type]} -- [description]
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
engine = select_save_engine(engine)
engine.QA_SU_save_stock_min(client=client) |
def back(self):
"""
Goes to the previous page for this wizard.
"""
try:
pageId = self._navigation[-2]
last_page = self.page(pageId)
except IndexError:
return
curr_page = self.page(self._navigation.pop())
if not (last_page and c... | def function[back, parameter[self]]:
constant[
Goes to the previous page for this wizard.
]
<ast.Try object at 0x7da204347310>
variable[curr_page] assign[=] call[name[self].page, parameter[call[name[self]._navigation.pop, parameter[]]]]
if <ast.UnaryOp object at 0x7da20cabc55... | keyword[def] identifier[back] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[pageId] = identifier[self] . identifier[_navigation] [- literal[int] ]
identifier[last_page] = identifier[self] . identifier[page] ( identifier[pageId] )
keyword[except] ... | def back(self):
"""
Goes to the previous page for this wizard.
"""
try:
pageId = self._navigation[-2]
last_page = self.page(pageId) # depends on [control=['try'], data=[]]
except IndexError:
return # depends on [control=['except'], data=[]]
curr_page = self.page... |
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs):
"""
Tracks a metric just by count. If you track a metric this way, you won't be able
to query the metric by day, week or month.
:param unique_identifier: Unique string indetifying the object this metric is for
... | def function[track_count, parameter[self, unique_identifier, metric, inc_amt]]:
constant[
Tracks a metric just by count. If you track a metric this way, you won't be able
to query the metric by day, week or month.
:param unique_identifier: Unique string indetifying the object this metri... | keyword[def] identifier[track_count] ( identifier[self] , identifier[unique_identifier] , identifier[metric] , identifier[inc_amt] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_analytics_backend] . identifier[incr] ( identifier[self] . iden... | def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs):
"""
Tracks a metric just by count. If you track a metric this way, you won't be able
to query the metric by day, week or month.
:param unique_identifier: Unique string indetifying the object this metric is for
:p... |
def __add_variables(self, *args, **kwargs):
"""
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
"""
for variable in args:
self.__variables[v... | def function[__add_variables, parameter[self]]:
constant[
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
]
for taget[name[variable]] in starred[name[arg... | keyword[def] identifier[__add_variables] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[variable] keyword[in] identifier[args] :
identifier[self] . identifier[__variables] [ identifier[variable] ]= keyword[None]
id... | def __add_variables(self, *args, **kwargs):
"""
Adds given variables to __variables attribute.
:param \\*args: Variables.
:type \\*args: \\*
:param \\*\\*kwargs: Variables : Values.
:type \\*\\*kwargs: \\*
"""
for variable in args:
self.__variables[variab... |
def progressive(image_field, alt_text=''):
"""
Used as a Jinja2 filter, this function returns a safe HTML chunk.
Usage (in the HTML template):
{{ obj.image|progressive }}
:param django.db.models.fields.files.ImageFieldFile image_field: image
:param str alt_text: str
:return: a safe HT... | def function[progressive, parameter[image_field, alt_text]]:
constant[
Used as a Jinja2 filter, this function returns a safe HTML chunk.
Usage (in the HTML template):
{{ obj.image|progressive }}
:param django.db.models.fields.files.ImageFieldFile image_field: image
:param str alt_text... | keyword[def] identifier[progressive] ( identifier[image_field] , identifier[alt_text] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[image_field] , identifier[ImageFieldFile] ):
keyword[raise] identifier[ValueError] ( literal[string] )
ke... | def progressive(image_field, alt_text=''):
"""
Used as a Jinja2 filter, this function returns a safe HTML chunk.
Usage (in the HTML template):
{{ obj.image|progressive }}
:param django.db.models.fields.files.ImageFieldFile image_field: image
:param str alt_text: str
:return: a safe HT... |
def getMappingsOnThingTypeForLogicalInterface(self, thingTypeId, logicalInterfaceId, draft=False):
"""
Gets the mappings for a logical interface from a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the platform returned id... | def function[getMappingsOnThingTypeForLogicalInterface, parameter[self, thingTypeId, logicalInterfaceId, draft]]:
constant[
Gets the mappings for a logical interface from a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the... | keyword[def] identifier[getMappingsOnThingTypeForLogicalInterface] ( identifier[self] , identifier[thingTypeId] , identifier[logicalInterfaceId] , identifier[draft] = keyword[False] ):
literal[string]
keyword[if] identifier[draft] :
identifier[req] = identifier[ApiClient] . identifier... | def getMappingsOnThingTypeForLogicalInterface(self, thingTypeId, logicalInterfaceId, draft=False):
"""
Gets the mappings for a logical interface from a thing type.
Parameters:
- thingTypeId (string) - the thing type
- logicalInterfaceId (string) - the platform returned id of ... |
def gng_importer(self, corpus_file):
"""Fill in self.ngcorpus from a Google NGram corpus file.
Parameters
----------
corpus_file : file
The Google NGram file from which to initialize the n-gram corpus
"""
with c_open(corpus_file, 'r', encoding='utf-8') as gn... | def function[gng_importer, parameter[self, corpus_file]]:
constant[Fill in self.ngcorpus from a Google NGram corpus file.
Parameters
----------
corpus_file : file
The Google NGram file from which to initialize the n-gram corpus
]
with call[name[c_open], para... | keyword[def] identifier[gng_importer] ( identifier[self] , identifier[corpus_file] ):
literal[string]
keyword[with] identifier[c_open] ( identifier[corpus_file] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[gng] :
keyword[for] identifier[line] ... | def gng_importer(self, corpus_file):
"""Fill in self.ngcorpus from a Google NGram corpus file.
Parameters
----------
corpus_file : file
The Google NGram file from which to initialize the n-gram corpus
"""
with c_open(corpus_file, 'r', encoding='utf-8') as gng:
... |
def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str):
""" Download the latest prices """
if help:
click.echo(ctx.get_help())
ctx.exit()
app = PriceDbApplication()
app.logger = logger
if currency:
currency = currency.strip()
currency ... | def function[download, parameter[ctx, help, symbol, namespace, agent, currency]]:
constant[ Download the latest prices ]
if name[help] begin[:]
call[name[click].echo, parameter[call[name[ctx].get_help, parameter[]]]]
call[name[ctx].exit, parameter[]]
variable[app]... | keyword[def] identifier[download] ( identifier[ctx] , identifier[help] : identifier[bool] , identifier[symbol] : identifier[str] , identifier[namespace] : identifier[str] , identifier[agent] : identifier[str] , identifier[currency] : identifier[str] ):
literal[string]
keyword[if] identifier[help] :
... | def download(ctx, help: bool, symbol: str, namespace: str, agent: str, currency: str):
""" Download the latest prices """
if help:
click.echo(ctx.get_help())
ctx.exit() # depends on [control=['if'], data=[]]
app = PriceDbApplication()
app.logger = logger
if currency:
currenc... |
def from_robot(cls, robot, **kwargs):
"""Construct a Nearest Neighbor forward model from an existing dataset."""
m = cls(len(robot.m_feats), len(robot.s_feats), **kwargs)
return m | def function[from_robot, parameter[cls, robot]]:
constant[Construct a Nearest Neighbor forward model from an existing dataset.]
variable[m] assign[=] call[name[cls], parameter[call[name[len], parameter[name[robot].m_feats]], call[name[len], parameter[name[robot].s_feats]]]]
return[name[m]] | keyword[def] identifier[from_robot] ( identifier[cls] , identifier[robot] ,** identifier[kwargs] ):
literal[string]
identifier[m] = identifier[cls] ( identifier[len] ( identifier[robot] . identifier[m_feats] ), identifier[len] ( identifier[robot] . identifier[s_feats] ),** identifier[kwargs] )
... | def from_robot(cls, robot, **kwargs):
"""Construct a Nearest Neighbor forward model from an existing dataset."""
m = cls(len(robot.m_feats), len(robot.s_feats), **kwargs)
return m |
def _estimate_count(self):
""" Update the count number using the estimation of the unset ratio """
if self.estimate_z == 0:
self.estimate_z = (1.0 / self.nbr_bits)
self.estimate_z = min(self.estimate_z, 0.999999)
self.count = int(-(self.nbr_bits / self.nbr_slices) * np.log(1 ... | def function[_estimate_count, parameter[self]]:
constant[ Update the count number using the estimation of the unset ratio ]
if compare[name[self].estimate_z equal[==] constant[0]] begin[:]
name[self].estimate_z assign[=] binary_operation[constant[1.0] / name[self].nbr_bits]
name[... | keyword[def] identifier[_estimate_count] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[estimate_z] == literal[int] :
identifier[self] . identifier[estimate_z] =( literal[int] / identifier[self] . identifier[nbr_bits] )
identifier[self] . iden... | def _estimate_count(self):
""" Update the count number using the estimation of the unset ratio """
if self.estimate_z == 0:
self.estimate_z = 1.0 / self.nbr_bits # depends on [control=['if'], data=[]]
self.estimate_z = min(self.estimate_z, 0.999999)
self.count = int(-(self.nbr_bits / self.nbr_s... |
def disconnect(self, forced=False):
"""
Given the pipeline topology disconnects ``Pipers`` in the order output
-> input. This also disconnects inputs. See ``Dagger.connect``,
``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True``
``NuMap`` instances will be emptied.... | def function[disconnect, parameter[self, forced]]:
constant[
Given the pipeline topology disconnects ``Pipers`` in the order output
-> input. This also disconnects inputs. See ``Dagger.connect``,
``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True``
``NuMap`` insta... | keyword[def] identifier[disconnect] ( identifier[self] , identifier[forced] = keyword[False] ):
literal[string]
identifier[reversed_postorder] = identifier[reversed] ( identifier[self] . identifier[postorder] ())
identifier[self] . identifier[log] . identifier[debug] ( literal[string] %( i... | def disconnect(self, forced=False):
"""
Given the pipeline topology disconnects ``Pipers`` in the order output
-> input. This also disconnects inputs. See ``Dagger.connect``,
``Piper.connect`` and ``Piper.disconnect``. If "forced" is ``True``
``NuMap`` instances will be emptied.
... |
def ParseForwardedIps(self, forwarded_ips):
"""Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings.
"""
addresses = []
forwarded_ips = forwarded_ips or []
for ip in forwarded_ips:
... | def function[ParseForwardedIps, parameter[self, forwarded_ips]]:
constant[Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings.
]
variable[addresses] assign[=] list[[]]
variabl... | keyword[def] identifier[ParseForwardedIps] ( identifier[self] , identifier[forwarded_ips] ):
literal[string]
identifier[addresses] =[]
identifier[forwarded_ips] = identifier[forwarded_ips] keyword[or] []
keyword[for] identifier[ip] keyword[in] identifier[forwarded_ips] :
keyword[if] i... | def ParseForwardedIps(self, forwarded_ips):
"""Parse and validate forwarded IP addresses.
Args:
forwarded_ips: list, the IP address strings to parse.
Returns:
list, the valid IP address strings.
"""
addresses = []
forwarded_ips = forwarded_ips or []
for ip in forwarded_ips:
... |
def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only smCounter2 calling.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and not paired.normal_bam, ("smCounter2 supports tumor-only variant calling: %s" %
... | def function[run, parameter[align_bams, items, ref_file, assoc_files, region, out_file]]:
constant[Run tumor only smCounter2 calling.
]
variable[paired] assign[=] call[name[vcfutils].get_paired_bams, parameter[name[align_bams], name[items]]]
assert[<ast.BoolOp object at 0x7da1b18d8880>]
... | keyword[def] identifier[run] ( identifier[align_bams] , identifier[items] , identifier[ref_file] , identifier[assoc_files] , identifier[region] = keyword[None] , identifier[out_file] = keyword[None] ):
literal[string]
identifier[paired] = identifier[vcfutils] . identifier[get_paired_bams] ( identifier[alig... | def run(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Run tumor only smCounter2 calling.
"""
paired = vcfutils.get_paired_bams(align_bams, items)
assert paired and (not paired.normal_bam), 'smCounter2 supports tumor-only variant calling: %s' % ','.join([dd.get_sample_name(d) ... |
def assert_valid(self,
name, # type: str
value, # type: Any
error_type=None, # type: Type[ValidationError]
help_msg=None, # type: str
**kw_context_args):
"""
Asserts that t... | def function[assert_valid, parameter[self, name, value, error_type, help_msg]]:
constant[
Asserts that the provided named value is valid with respect to the inner base validation functions. It returns
silently in case of success, and raises a `ValidationError` or a subclass in case of failure. T... | keyword[def] identifier[assert_valid] ( identifier[self] ,
identifier[name] ,
identifier[value] ,
identifier[error_type] = keyword[None] ,
identifier[help_msg] = keyword[None] ,
** identifier[kw_context_args] ):
literal[string]
keyword[try] :
identifier[res] = identifier[s... | def assert_valid(self, name, value, error_type=None, help_msg=None, **kw_context_args): # type: str
# type: Any
# type: Type[ValidationError]
# type: str
"\n Asserts that the provided named value is valid with respect to the inner base validation functions. It returns\n silently in case o... |
def pipeline_getter(self):
"For duck-typing with *Spec types"
if not self.derivable:
raise ArcanaUsageError(
"There is no pipeline getter for {} because it doesn't "
"fallback to a derived spec".format(self))
return self._fallback.pipeline_getter | def function[pipeline_getter, parameter[self]]:
constant[For duck-typing with *Spec types]
if <ast.UnaryOp object at 0x7da204565600> begin[:]
<ast.Raise object at 0x7da204564430>
return[name[self]._fallback.pipeline_getter] | keyword[def] identifier[pipeline_getter] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[derivable] :
keyword[raise] identifier[ArcanaUsageError] (
literal[string]
literal[string] . identifier[format] ( identifi... | def pipeline_getter(self):
"""For duck-typing with *Spec types"""
if not self.derivable:
raise ArcanaUsageError("There is no pipeline getter for {} because it doesn't fallback to a derived spec".format(self)) # depends on [control=['if'], data=[]]
return self._fallback.pipeline_getter |
def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command("touch", DIR.project.joinpath("pathquery", "__init__.py").abspath()).run()
storybook = _storybook({}).only_uninherited()
#storybook.with_params(**{"pyt... | def function[regression, parameter[]]:
constant[
Run regression testing - lint and then run all tests.
]
call[call[name[Command], parameter[constant[touch], call[call[name[DIR].project.joinpath, parameter[constant[pathquery], constant[__init__.py]]].abspath, parameter[]]]].run, parameter[]]
... | keyword[def] identifier[regression] ():
literal[string]
identifier[Command] ( literal[string] , identifier[DIR] . identifier[project] . identifier[joinpath] ( literal[string] , literal[string] ). identifier[abspath] ()). identifier[run] ()
identifier[storybook] = identifier[_storybook] ({}). iden... | def regression():
"""
Run regression testing - lint and then run all tests.
"""
# HACK: Start using hitchbuildpy to get around this.
Command('touch', DIR.project.joinpath('pathquery', '__init__.py').abspath()).run()
storybook = _storybook({}).only_uninherited()
#storybook.with_params(**{"pyt... |
def set_extent_location(self, new_location, tag_location=None):
# type: (int, int) -> None
'''
A method to set the location of this UDF Terminating Descriptor.
Parameters:
new_location - The new extent this UDF Terminating Descriptor should be located at.
tag_location ... | def function[set_extent_location, parameter[self, new_location, tag_location]]:
constant[
A method to set the location of this UDF Terminating Descriptor.
Parameters:
new_location - The new extent this UDF Terminating Descriptor should be located at.
tag_location - The tag loc... | keyword[def] identifier[set_extent_location] ( identifier[self] , identifier[new_location] , identifier[tag_location] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_initialized] :
keyword[raise] identifier[pycdlibexception] . identifier[P... | def set_extent_location(self, new_location, tag_location=None):
# type: (int, int) -> None
'\n A method to set the location of this UDF Terminating Descriptor.\n\n Parameters:\n new_location - The new extent this UDF Terminating Descriptor should be located at.\n tag_location - The... |
def _handle_subscribed(self, dtype, data, ts,):
"""Handles responses to subscribe() commands.
Registers a channel id with the client and assigns a data handler to it.
:param dtype:
:param data:
:param ts:
:return:
"""
self.log.debug("_handle_subscribed: ... | def function[_handle_subscribed, parameter[self, dtype, data, ts]]:
constant[Handles responses to subscribe() commands.
Registers a channel id with the client and assigns a data handler to it.
:param dtype:
:param data:
:param ts:
:return:
]
call[name[se... | keyword[def] identifier[_handle_subscribed] ( identifier[self] , identifier[dtype] , identifier[data] , identifier[ts] ,):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] , identifier[dtype] , identifier[data] , identifier[ts] )
identifier[channel_n... | def _handle_subscribed(self, dtype, data, ts):
"""Handles responses to subscribe() commands.
Registers a channel id with the client and assigns a data handler to it.
:param dtype:
:param data:
:param ts:
:return:
"""
self.log.debug('_handle_subscribed: %s - %s -... |
def plotReceptiveFields(sp, nDim1=8, nDim2=8):
"""
Plot 2D receptive fields for 16 randomly selected columns
:param sp:
:return:
"""
columnNumber = np.product(sp.getColumnDimensions())
fig, ax = plt.subplots(nrows=4, ncols=4)
for rowI in range(4):
for colI in range(4):
col = np.random.randint(... | def function[plotReceptiveFields, parameter[sp, nDim1, nDim2]]:
constant[
Plot 2D receptive fields for 16 randomly selected columns
:param sp:
:return:
]
variable[columnNumber] assign[=] call[name[np].product, parameter[call[name[sp].getColumnDimensions, parameter[]]]]
<ast.Tuple object ... | keyword[def] identifier[plotReceptiveFields] ( identifier[sp] , identifier[nDim1] = literal[int] , identifier[nDim2] = literal[int] ):
literal[string]
identifier[columnNumber] = identifier[np] . identifier[product] ( identifier[sp] . identifier[getColumnDimensions] ())
identifier[fig] , identifier[ax] = ide... | def plotReceptiveFields(sp, nDim1=8, nDim2=8):
"""
Plot 2D receptive fields for 16 randomly selected columns
:param sp:
:return:
"""
columnNumber = np.product(sp.getColumnDimensions())
(fig, ax) = plt.subplots(nrows=4, ncols=4)
for rowI in range(4):
for colI in range(4):
col ... |
def queryAll(self, queryString):
'''
Retrieves data from specified objects, whether or not they have been deleted.
'''
self._setHeaders('queryAll')
return self._sforce.service.queryAll(queryString) | def function[queryAll, parameter[self, queryString]]:
constant[
Retrieves data from specified objects, whether or not they have been deleted.
]
call[name[self]._setHeaders, parameter[constant[queryAll]]]
return[call[name[self]._sforce.service.queryAll, parameter[name[queryString]]]] | keyword[def] identifier[queryAll] ( identifier[self] , identifier[queryString] ):
literal[string]
identifier[self] . identifier[_setHeaders] ( literal[string] )
keyword[return] identifier[self] . identifier[_sforce] . identifier[service] . identifier[queryAll] ( identifier[queryString] ) | def queryAll(self, queryString):
"""
Retrieves data from specified objects, whether or not they have been deleted.
"""
self._setHeaders('queryAll')
return self._sforce.service.queryAll(queryString) |
def _load_library(library_names, library_file_extensions,
library_search_paths, version_check_callback):
"""
Finds, loads and returns the most recent version of the library.
"""
candidates = _find_library_candidates(library_names,
library_file_... | def function[_load_library, parameter[library_names, library_file_extensions, library_search_paths, version_check_callback]]:
constant[
Finds, loads and returns the most recent version of the library.
]
variable[candidates] assign[=] call[name[_find_library_candidates], parameter[name[library_na... | keyword[def] identifier[_load_library] ( identifier[library_names] , identifier[library_file_extensions] ,
identifier[library_search_paths] , identifier[version_check_callback] ):
literal[string]
identifier[candidates] = identifier[_find_library_candidates] ( identifier[library_names] ,
identifier[li... | def _load_library(library_names, library_file_extensions, library_search_paths, version_check_callback):
"""
Finds, loads and returns the most recent version of the library.
"""
candidates = _find_library_candidates(library_names, library_file_extensions, library_search_paths)
library_versions = []
... |
def fault_and_striae_plot(ax, strikes, dips, rakes):
"""Makes a fault-and-striae plot (a.k.a. "Ball of String") for normal faults
with the given strikes, dips, and rakes."""
# Plot the planes
lines = ax.plane(strikes, dips, 'k-', lw=0.5)
# Calculate the position of the rake of the lineations, but d... | def function[fault_and_striae_plot, parameter[ax, strikes, dips, rakes]]:
constant[Makes a fault-and-striae plot (a.k.a. "Ball of String") for normal faults
with the given strikes, dips, and rakes.]
variable[lines] assign[=] call[name[ax].plane, parameter[name[strikes], name[dips], constant[k-]]]
... | keyword[def] identifier[fault_and_striae_plot] ( identifier[ax] , identifier[strikes] , identifier[dips] , identifier[rakes] ):
literal[string]
identifier[lines] = identifier[ax] . identifier[plane] ( identifier[strikes] , identifier[dips] , literal[string] , identifier[lw] = literal[int] )
... | def fault_and_striae_plot(ax, strikes, dips, rakes):
"""Makes a fault-and-striae plot (a.k.a. "Ball of String") for normal faults
with the given strikes, dips, and rakes."""
# Plot the planes
lines = ax.plane(strikes, dips, 'k-', lw=0.5)
# Calculate the position of the rake of the lineations, but do... |
def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == "":
sys.exit()
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
else:
return "try arrow keys,... | def function[process_event, parameter[self, c]]:
constant[Returns a message from tick() to be displayed if game is over]
if compare[name[c] equal[==] constant[]] begin[:]
call[name[sys].exit, parameter[]]
return[call[name[self].tick, parameter[]]] | keyword[def] identifier[process_event] ( identifier[self] , identifier[c] ):
literal[string]
keyword[if] identifier[c] == literal[string] :
identifier[sys] . identifier[exit] ()
keyword[elif] identifier[c] keyword[in] identifier[key_directions] :
identifier[se... | def process_event(self, c):
"""Returns a message from tick() to be displayed if game is over"""
if c == '\x04':
sys.exit() # depends on [control=['if'], data=[]]
elif c in key_directions:
self.move_entity(self.player, *vscale(self.player.speed, key_directions[c])) # depends on [control=['i... |
def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
"""Display the system using a ball and stick representation.
"""
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']]
... | def function[ball_and_sticks, parameter[self, ball_radius, stick_radius, colorlist, opacity]]:
constant[Display the system using a ball and stick representation.
]
if compare[name[colorlist] is constant[None]] begin[:]
variable[colorlist] assign[=] <ast.ListComp object at 0x7da1b... | keyword[def] identifier[ball_and_sticks] ( identifier[self] , identifier[ball_radius] = literal[int] , identifier[stick_radius] = literal[int] , identifier[colorlist] = keyword[None] , identifier[opacity] = literal[int] ):
literal[string]
keyword[if] identifier[colorlist] keyword[is] ... | def ball_and_sticks(self, ball_radius=0.05, stick_radius=0.02, colorlist=None, opacity=1.0):
"""Display the system using a ball and stick representation.
"""
# Add the spheres
if colorlist is None:
colorlist = [get_atom_color(t) for t in self.topology['atom_types']] # depends on [control=['... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.