code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def build_template(self, mapfile, names, renderer):
"""
Build source from global and item templates
"""
AVAILABLE_DUMPS = json.load(open(mapfile, "r"))
manager = self.get_deps_manager(AVAILABLE_DUMPS)
fp = StringIO.StringIO()
for i, item in enumerate(manager.ge... | def function[build_template, parameter[self, mapfile, names, renderer]]:
constant[
Build source from global and item templates
]
variable[AVAILABLE_DUMPS] assign[=] call[name[json].load, parameter[call[name[open], parameter[name[mapfile], constant[r]]]]]
variable[manager] assign[... | keyword[def] identifier[build_template] ( identifier[self] , identifier[mapfile] , identifier[names] , identifier[renderer] ):
literal[string]
identifier[AVAILABLE_DUMPS] = identifier[json] . identifier[load] ( identifier[open] ( identifier[mapfile] , literal[string] ))
identifier[manager... | def build_template(self, mapfile, names, renderer):
"""
Build source from global and item templates
"""
AVAILABLE_DUMPS = json.load(open(mapfile, 'r'))
manager = self.get_deps_manager(AVAILABLE_DUMPS)
fp = StringIO.StringIO()
for (i, item) in enumerate(manager.get_dump_order(names), ... |
def wait_for_zero_canvases(middle_mouse_close=False):
"""
Wait for all canvases to be closed, or CTRL-c.
If `middle_mouse_close`, middle click will shut the canvas.
incpy.ignore
"""
if not __ACTIVE:
wait_failover(wait_for_zero_canvases)
return
@dispatcher
def count_can... | def function[wait_for_zero_canvases, parameter[middle_mouse_close]]:
constant[
Wait for all canvases to be closed, or CTRL-c.
If `middle_mouse_close`, middle click will shut the canvas.
incpy.ignore
]
if <ast.UnaryOp object at 0x7da1b11bf3a0> begin[:]
call[name[wait_fai... | keyword[def] identifier[wait_for_zero_canvases] ( identifier[middle_mouse_close] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[__ACTIVE] :
identifier[wait_failover] ( identifier[wait_for_zero_canvases] )
keyword[return]
@ identifier[dispatcher]
keyw... | def wait_for_zero_canvases(middle_mouse_close=False):
"""
Wait for all canvases to be closed, or CTRL-c.
If `middle_mouse_close`, middle click will shut the canvas.
incpy.ignore
"""
if not __ACTIVE:
wait_failover(wait_for_zero_canvases)
return # depends on [control=['if'], dat... |
def start(self):
"""Launch this postgres server. If it's already running, do nothing.
If the backing storage directory isn't configured, raise
NotInitializedError.
This method is optional. If you're running in an environment
where the DBMS is provided as part of the basic inf... | def function[start, parameter[self]]:
constant[Launch this postgres server. If it's already running, do nothing.
If the backing storage directory isn't configured, raise
NotInitializedError.
This method is optional. If you're running in an environment
where the DBMS is provid... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[log] . identifier[info] ( literal[string] , identifier[self] . identifier[host] , identifier[self] . identifier[port] )
keyword[if] keyword[not] identifier[self] . identifier[base_pathname] :
ide... | def start(self):
"""Launch this postgres server. If it's already running, do nothing.
If the backing storage directory isn't configured, raise
NotInitializedError.
This method is optional. If you're running in an environment
where the DBMS is provided as part of the basic infrast... |
def resizeEvent(self, event):
"""Schedules an item layout if resize mode is \"adjust\". Somehow this is
needed for correctly scaling down items.
The reason this was reimplemented was the CommentDelegate.
:param event: the resize event
:type event: QtCore.QEvent
:returns... | def function[resizeEvent, parameter[self, event]]:
constant[Schedules an item layout if resize mode is "adjust". Somehow this is
needed for correctly scaling down items.
The reason this was reimplemented was the CommentDelegate.
:param event: the resize event
:type event: QtCor... | keyword[def] identifier[resizeEvent] ( identifier[self] , identifier[event] ):
literal[string]
keyword[if] identifier[self] . identifier[resizeMode] ()== identifier[self] . identifier[Adjust] :
identifier[self] . identifier[scheduleDelayedItemsLayout] ()
keyword[return] iden... | def resizeEvent(self, event):
"""Schedules an item layout if resize mode is "adjust". Somehow this is
needed for correctly scaling down items.
The reason this was reimplemented was the CommentDelegate.
:param event: the resize event
:type event: QtCore.QEvent
:returns: None... |
def nii_gzip(imfile, outpath=''):
'''Compress *.gz file'''
import gzip
with open(imfile, 'rb') as f:
d = f.read()
# Now store the compressed data
if outpath=='':
fout = imfile+'.gz'
else:
fout = os.path.join(outpath, os.path.basename(imfile)+'.gz')
# store compressed ... | def function[nii_gzip, parameter[imfile, outpath]]:
constant[Compress *.gz file]
import module[gzip]
with call[name[open], parameter[name[imfile], constant[rb]]] begin[:]
variable[d] assign[=] call[name[f].read, parameter[]]
if compare[name[outpath] equal[==] constant[]] begi... | keyword[def] identifier[nii_gzip] ( identifier[imfile] , identifier[outpath] = literal[string] ):
literal[string]
keyword[import] identifier[gzip]
keyword[with] identifier[open] ( identifier[imfile] , literal[string] ) keyword[as] identifier[f] :
identifier[d] = identifier[f] . identifier... | def nii_gzip(imfile, outpath=''):
"""Compress *.gz file"""
import gzip
with open(imfile, 'rb') as f:
d = f.read() # depends on [control=['with'], data=['f']]
# Now store the compressed data
if outpath == '':
fout = imfile + '.gz' # depends on [control=['if'], data=[]]
else:
... |
def create_scraper(cls, sess=None, **kwargs):
"""
Convenience function for creating a ready-to-go CloudflareScraper object.
"""
scraper = cls(**kwargs)
if sess:
attrs = ["auth", "cert", "cookies", "headers", "hooks", "params", "proxies", "data"]
for attr ... | def function[create_scraper, parameter[cls, sess]]:
constant[
Convenience function for creating a ready-to-go CloudflareScraper object.
]
variable[scraper] assign[=] call[name[cls], parameter[]]
if name[sess] begin[:]
variable[attrs] assign[=] list[[<ast.Constant ... | keyword[def] identifier[create_scraper] ( identifier[cls] , identifier[sess] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[scraper] = identifier[cls] (** identifier[kwargs] )
keyword[if] identifier[sess] :
identifier[attrs] =[ literal[string] , literal... | def create_scraper(cls, sess=None, **kwargs):
"""
Convenience function for creating a ready-to-go CloudflareScraper object.
"""
scraper = cls(**kwargs)
if sess:
attrs = ['auth', 'cert', 'cookies', 'headers', 'hooks', 'params', 'proxies', 'data']
for attr in attrs:
... |
def remove(self, *members):
""" Removes @members from the set
-> #int the number of members that were removed from the set
"""
if self.serialized:
members = list(map(self._dumps, members))
return self._client.srem(self.key_prefix, *members) | def function[remove, parameter[self]]:
constant[ Removes @members from the set
-> #int the number of members that were removed from the set
]
if name[self].serialized begin[:]
variable[members] assign[=] call[name[list], parameter[call[name[map], parameter[name[self].... | keyword[def] identifier[remove] ( identifier[self] ,* identifier[members] ):
literal[string]
keyword[if] identifier[self] . identifier[serialized] :
identifier[members] = identifier[list] ( identifier[map] ( identifier[self] . identifier[_dumps] , identifier[members] ))
keywo... | def remove(self, *members):
""" Removes @members from the set
-> #int the number of members that were removed from the set
"""
if self.serialized:
members = list(map(self._dumps, members)) # depends on [control=['if'], data=[]]
return self._client.srem(self.key_prefix, *members) |
def tuple2dict(mytuple, constructor=dict):
"""
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the Dingo... | def function[tuple2dict, parameter[mytuple, constructor]]:
constant[
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
... | keyword[def] identifier[tuple2dict] ( identifier[mytuple] , identifier[constructor] = identifier[dict] ):
literal[string]
identifier[result] = identifier[constructor] ()
keyword[for] identifier[elt] keyword[in] identifier[mytuple] :
identifier[key] , identifier[value] = identifier[elt]
... | def tuple2dict(mytuple, constructor=dict):
"""
Turn a tuple as returned by dict2tuple back
into a dictionary structure. The optional
parameter "constructor" governs, what class
is used to create the dictionary: by default,
the standard dict class is used, but in DINGO
we mostly use the Dingo... |
def getInitialArguments(self):
"""
Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of
L{initialPerson} and the value of L{initialState}, if they are set.
"""
initialArguments = (self.organizer.storeOwnerPerson.name,)
if self.initialPerson is not None:
... | def function[getInitialArguments, parameter[self]]:
constant[
Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of
L{initialPerson} and the value of L{initialState}, if they are set.
]
variable[initialArguments] assign[=] tuple[[<ast.Attribute object at 0x7da1b0a4f9... | keyword[def] identifier[getInitialArguments] ( identifier[self] ):
literal[string]
identifier[initialArguments] =( identifier[self] . identifier[organizer] . identifier[storeOwnerPerson] . identifier[name] ,)
keyword[if] identifier[self] . identifier[initialPerson] keyword[is] keyword[n... | def getInitialArguments(self):
"""
Include L{organizer}'s C{storeOwnerPerson}'s name, and the name of
L{initialPerson} and the value of L{initialState}, if they are set.
"""
initialArguments = (self.organizer.storeOwnerPerson.name,)
if self.initialPerson is not None:
initialA... |
def open_pspsfile(self, ecut=20, pawecutdg=None):
"""
Calls Abinit to compute the internal tables for the application of the
pseudopotential part. Returns :class:`PspsFile` object providing methods
to plot and analyze the data or None if file is not found or it's not readable.
A... | def function[open_pspsfile, parameter[self, ecut, pawecutdg]]:
constant[
Calls Abinit to compute the internal tables for the application of the
pseudopotential part. Returns :class:`PspsFile` object providing methods
to plot and analyze the data or None if file is not found or it's not r... | keyword[def] identifier[open_pspsfile] ( identifier[self] , identifier[ecut] = literal[int] , identifier[pawecutdg] = keyword[None] ):
literal[string]
keyword[from] identifier[pymatgen] . identifier[io] . identifier[abinit] . identifier[tasks] keyword[import] identifier[AbinitTask]
key... | def open_pspsfile(self, ecut=20, pawecutdg=None):
"""
Calls Abinit to compute the internal tables for the application of the
pseudopotential part. Returns :class:`PspsFile` object providing methods
to plot and analyze the data or None if file is not found or it's not readable.
Args:... |
def secpolicy_sa_secpolicy_defined_policy_policies_policy(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
secpolicy_sa = ET.SubElement(config, "secpolicy-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth")
secpolicy = ET.SubElement(secpolicy_sa, "secpolic... | def function[secpolicy_sa_secpolicy_defined_policy_policies_policy, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[secpolicy_sa] assign[=] call[name[ET].SubElement, parameter[name[config], constant[... | keyword[def] identifier[secpolicy_sa_secpolicy_defined_policy_policies_policy] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[secpolicy_sa] = identifier[ET] . identifier[SubElement] ( ide... | def secpolicy_sa_secpolicy_defined_policy_policies_policy(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
secpolicy_sa = ET.SubElement(config, 'secpolicy-sa', xmlns='urn:brocade.com:mgmt:brocade-fc-auth')
secpolicy = ET.SubElement(secpolicy_sa, 'secpolicy')
defined_... |
def _apply_record_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record checks on `r`."""
for check, modulus in self._record_checks:
if i % modu... | def function[_apply_record_checks, parameter[self, i, r, summarize, report_unexpected_exceptions, context]]:
constant[Apply record checks on `r`.]
for taget[tuple[[<ast.Name object at 0x7da1affe6ad0>, <ast.Name object at 0x7da1affe5db0>]]] in starred[name[self]._record_checks] begin[:]
i... | keyword[def] identifier[_apply_record_checks] ( identifier[self] , identifier[i] , identifier[r] ,
identifier[summarize] = keyword[False] ,
identifier[report_unexpected_exceptions] = keyword[True] ,
identifier[context] = keyword[None] ):
literal[string]
keyword[for] identifier[check] , identif... | def _apply_record_checks(self, i, r, summarize=False, report_unexpected_exceptions=True, context=None):
"""Apply record checks on `r`."""
for (check, modulus) in self._record_checks:
if i % modulus == 0: # support sampling
rdict = self._as_dict(r)
try:
check(rdic... |
def spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program... | def function[spawn_program, parameter[self, name, arguments, timeout, exclusive]]:
constant[Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name... | keyword[def] identifier[spawn_program] ( identifier[self] , identifier[name] , identifier[arguments] =[], identifier[timeout] = literal[int] , identifier[exclusive] = keyword[False] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identifier[exclus... | def spawn_program(self, name, arguments=[], timeout=30, exclusive=False):
"""Spawns a program in the working directory.
This method allows the interaction with the running program,
based on the returned RunningProgram object.
Args:
name (str): The name of the program to ... |
def registerLoggers(info, error, debug):
"""
Add logging functions to this module.
Functions will be called on various severities (log, error, or debug
respectively).
Each function must have the signature:
fn(message, **kwargs)
If Python str.format()-style placeholders are in message,... | def function[registerLoggers, parameter[info, error, debug]]:
constant[
Add logging functions to this module.
Functions will be called on various severities (log, error, or debug
respectively).
Each function must have the signature:
fn(message, **kwargs)
If Python str.format()-sty... | keyword[def] identifier[registerLoggers] ( identifier[info] , identifier[error] , identifier[debug] ):
literal[string]
keyword[global] identifier[log_info]
keyword[global] identifier[log_error]
keyword[global] identifier[log_debug]
identifier[log_info] = identifier[info]
identif... | def registerLoggers(info, error, debug):
"""
Add logging functions to this module.
Functions will be called on various severities (log, error, or debug
respectively).
Each function must have the signature:
fn(message, **kwargs)
If Python str.format()-style placeholders are in message,... |
def create_from_tables(cls, norm_type='eflux',
tab_s="SCANDATA",
tab_e="EBOUNDS"):
"""Create a CastroData object from two tables
Parameters
----------
norm_type : str
Type of normalization to use. Valid options are:
... | def function[create_from_tables, parameter[cls, norm_type, tab_s, tab_e]]:
constant[Create a CastroData object from two tables
Parameters
----------
norm_type : str
Type of normalization to use. Valid options are:
* norm : Normalization w.r.t. to test source
... | keyword[def] identifier[create_from_tables] ( identifier[cls] , identifier[norm_type] = literal[string] ,
identifier[tab_s] = literal[string] ,
identifier[tab_e] = literal[string] ):
literal[string]
keyword[if] identifier[norm_type] keyword[in] [ literal[string] , literal[string] , literal[stri... | def create_from_tables(cls, norm_type='eflux', tab_s='SCANDATA', tab_e='EBOUNDS'):
"""Create a CastroData object from two tables
Parameters
----------
norm_type : str
Type of normalization to use. Valid options are:
* norm : Normalization w.r.t. to test source
... |
def advance(parser):
# type: (Parser) -> None
"""Moves the internal parser object to the next lexed token."""
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) | def function[advance, parameter[parser]]:
constant[Moves the internal parser object to the next lexed token.]
variable[prev_end] assign[=] name[parser].token.end
name[parser].prev_end assign[=] name[prev_end]
name[parser].token assign[=] call[name[parser].lexer.next_token, parameter[name... | keyword[def] identifier[advance] ( identifier[parser] ):
literal[string]
identifier[prev_end] = identifier[parser] . identifier[token] . identifier[end]
identifier[parser] . identifier[prev_end] = identifier[prev_end]
identifier[parser] . identifier[token] = identifier[parser] . identifier[lex... | def advance(parser):
# type: (Parser) -> None
'Moves the internal parser object to the next lexed token.'
prev_end = parser.token.end
parser.prev_end = prev_end
parser.token = parser.lexer.next_token(prev_end) |
def suspendJustTabProviders(installation):
"""
Replace INavigableElements with facades that indicate their suspension.
"""
if installation.suspended:
raise RuntimeError("Installation already suspended")
powerups = list(installation.allPowerups)
for p in powerups:
if INavigableEle... | def function[suspendJustTabProviders, parameter[installation]]:
constant[
Replace INavigableElements with facades that indicate their suspension.
]
if name[installation].suspended begin[:]
<ast.Raise object at 0x7da1b0a4dab0>
variable[powerups] assign[=] call[name[list], paramete... | keyword[def] identifier[suspendJustTabProviders] ( identifier[installation] ):
literal[string]
keyword[if] identifier[installation] . identifier[suspended] :
keyword[raise] identifier[RuntimeError] ( literal[string] )
identifier[powerups] = identifier[list] ( identifier[installation] . iden... | def suspendJustTabProviders(installation):
"""
Replace INavigableElements with facades that indicate their suspension.
"""
if installation.suspended:
raise RuntimeError('Installation already suspended') # depends on [control=['if'], data=[]]
powerups = list(installation.allPowerups)
for... |
def search_one(self, keyword, arg=None, children=None):
"""Return receiver's substmt with `keyword` and optionally `arg`.
"""
if children is None:
children = self.substmts
for ch in children:
if ch.keyword == keyword and (arg is None or ch.arg == arg):
... | def function[search_one, parameter[self, keyword, arg, children]]:
constant[Return receiver's substmt with `keyword` and optionally `arg`.
]
if compare[name[children] is constant[None]] begin[:]
variable[children] assign[=] name[self].substmts
for taget[name[ch]] in starr... | keyword[def] identifier[search_one] ( identifier[self] , identifier[keyword] , identifier[arg] = keyword[None] , identifier[children] = keyword[None] ):
literal[string]
keyword[if] identifier[children] keyword[is] keyword[None] :
identifier[children] = identifier[self] . identifier[... | def search_one(self, keyword, arg=None, children=None):
"""Return receiver's substmt with `keyword` and optionally `arg`.
"""
if children is None:
children = self.substmts # depends on [control=['if'], data=['children']]
for ch in children:
if ch.keyword == keyword and (arg is None ... |
def get_jsapi_signature(self, noncestr, ticket, timestamp, url):
"""
获取 JSAPI 签名
https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/
:param noncestr: nonce string
:param ticket: JS-SDK ticket
:param timestamp: 时间戳
:param url: URL
:return: 签名
... | def function[get_jsapi_signature, parameter[self, noncestr, ticket, timestamp, url]]:
constant[
获取 JSAPI 签名
https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/
:param noncestr: nonce string
:param ticket: JS-SDK ticket
:param timestamp: 时间戳
:param url: UR... | keyword[def] identifier[get_jsapi_signature] ( identifier[self] , identifier[noncestr] , identifier[ticket] , identifier[timestamp] , identifier[url] ):
literal[string]
identifier[data] =[
literal[string] . identifier[format] ( identifier[noncestr] = identifier[noncestr] ),
litera... | def get_jsapi_signature(self, noncestr, ticket, timestamp, url):
"""
获取 JSAPI 签名
https://work.weixin.qq.com/api/doc#90001/90144/90539/签名算法/
:param noncestr: nonce string
:param ticket: JS-SDK ticket
:param timestamp: 时间戳
:param url: URL
:return: 签名
"... |
def btc_is_p2sh_script( script_hex ):
"""
Is the given scriptpubkey a p2sh script?
"""
if script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
return True
else:
return False | def function[btc_is_p2sh_script, parameter[script_hex]]:
constant[
Is the given scriptpubkey a p2sh script?
]
if <ast.BoolOp object at 0x7da1b26f1270> begin[:]
return[constant[True]] | keyword[def] identifier[btc_is_p2sh_script] ( identifier[script_hex] ):
literal[string]
keyword[if] identifier[script_hex] . identifier[startswith] ( literal[string] ) keyword[and] identifier[script_hex] . identifier[endswith] ( literal[string] ) keyword[and] identifier[len] ( identifier[script_hex] )==... | def btc_is_p2sh_script(script_hex):
"""
Is the given scriptpubkey a p2sh script?
"""
if script_hex.startswith('a914') and script_hex.endswith('87') and (len(script_hex) == 46):
return True # depends on [control=['if'], data=[]]
else:
return False |
def get_failed_requests(self, results):
"""Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator
"""
data = {member['guid']: member for member in resu... | def function[get_failed_requests, parameter[self, results]]:
constant[Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator
]
variable[data] assign[=]... | keyword[def] identifier[get_failed_requests] ( identifier[self] , identifier[results] ):
literal[string]
identifier[data] ={ identifier[member] [ literal[string] ]: identifier[member] keyword[for] identifier[member] keyword[in] identifier[results] }
keyword[for] identifier[request] k... | def get_failed_requests(self, results):
"""Return the requests that failed.
:param results: the results of a membership request check
:type results: :class:`list`
:return: the failed requests
:rtype: generator
"""
data = {member['guid']: member for member in results}
... |
def list_assignment_submissions_courses(self, course_id, assignment_id, grouped=None, include=None):
"""
List assignment submissions.
Get all existing submissions for an assignment.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - course... | def function[list_assignment_submissions_courses, parameter[self, course_id, assignment_id, grouped, include]]:
constant[
List assignment submissions.
Get all existing submissions for an assignment.
]
variable[path] assign[=] dictionary[[], []]
variable[data] assign[=] d... | keyword[def] identifier[list_assignment_submissions_courses] ( identifier[self] , identifier[course_id] , identifier[assignment_id] , identifier[grouped] = keyword[None] , identifier[include] = keyword[None] ):
literal[string]
identifier[path] ={}
identifier[data] ={}
identifi... | def list_assignment_submissions_courses(self, course_id, assignment_id, grouped=None, include=None):
"""
List assignment submissions.
Get all existing submissions for an assignment.
"""
path = {}
data = {}
params = {} # REQUIRED - PATH - course_id
'ID'
path['course_id']... |
def _make_ocs_request(self, method, service, action, **kwargs):
"""Makes a OCS API request
:param method: HTTP method
:param service: service name
:param action: action path
:param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts
:returns :class:`... | def function[_make_ocs_request, parameter[self, method, service, action]]:
constant[Makes a OCS API request
:param method: HTTP method
:param service: service name
:param action: action path
:param \*\*kwargs: optional arguments that ``requests.Request.request`` accepts
... | keyword[def] identifier[_make_ocs_request] ( identifier[self] , identifier[method] , identifier[service] , identifier[action] ,** identifier[kwargs] ):
literal[string]
identifier[slash] = literal[string]
keyword[if] identifier[service] :
identifier[slash] = literal[string]
... | def _make_ocs_request(self, method, service, action, **kwargs):
"""Makes a OCS API request
:param method: HTTP method
:param service: service name
:param action: action path
:param \\*\\*kwargs: optional arguments that ``requests.Request.request`` accepts
:returns :class:`re... |
def template_engine(self, entry, startnode):
"""The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
"""
# print("-----")
# print(startnode)
# print(en... | def function[template_engine, parameter[self, entry, startnode]]:
constant[The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
]
variable[startnode_start] assign[=] ca... | keyword[def] identifier[template_engine] ( identifier[self] , identifier[entry] , identifier[startnode] ):
literal[string]
identifier[startnode_start] = identifier[len] ( identifier[self] . identifier[f] . identifier[getvalue] ())
identifier[start] = i... | def template_engine(self, entry, startnode):
"""The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
"""
# print("-----")
# print(startnode)
# print(entry[0])
# pri... |
def _iterClass(cls, prefix=''):
"""
Descend a Klein()'s url_map, and generate ConvertedRule() for each one
"""
iterableRules = [(prefix, cls, cls.app.url_map.iter_rules())]
for prefix, currentClass, i in iter(iterableRules):
for rule in i:
converted = dumpRule(currentClass, rule,... | def function[_iterClass, parameter[cls, prefix]]:
constant[
Descend a Klein()'s url_map, and generate ConvertedRule() for each one
]
variable[iterableRules] assign[=] list[[<ast.Tuple object at 0x7da204620100>]]
for taget[tuple[[<ast.Name object at 0x7da204622da0>, <ast.Name object at 0x... | keyword[def] identifier[_iterClass] ( identifier[cls] , identifier[prefix] = literal[string] ):
literal[string]
identifier[iterableRules] =[( identifier[prefix] , identifier[cls] , identifier[cls] . identifier[app] . identifier[url_map] . identifier[iter_rules] ())]
keyword[for] identifier[prefix] , ... | def _iterClass(cls, prefix=''):
"""
Descend a Klein()'s url_map, and generate ConvertedRule() for each one
"""
iterableRules = [(prefix, cls, cls.app.url_map.iter_rules())]
for (prefix, currentClass, i) in iter(iterableRules):
for rule in i:
converted = dumpRule(currentClass, rul... |
def find_by_attr(node, value, name="name", maxlevel=None):
"""
Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
nam... | def function[find_by_attr, parameter[node, value, name, maxlevel]]:
constant[
Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
value: value which need to match
Keywor... | keyword[def] identifier[find_by_attr] ( identifier[node] , identifier[value] , identifier[name] = literal[string] , identifier[maxlevel] = keyword[None] ):
literal[string]
keyword[return] identifier[_find] ( identifier[node] , identifier[filter_] = keyword[lambda] identifier[n] : identifier[_filter_by_na... | def find_by_attr(node, value, name='name', maxlevel=None):
"""
Search for *single* node with attribute `name` having `value` but stop at `maxlevel`.
Return tuple with matching nodes.
Args:
node: top node, start searching.
value: value which need to match
Keyword Args:
nam... |
def _die(self, msg, lnum):
"""Raise an Exception if file read is unexpected."""
raise Exception("**FATAL {FILE}({LNUM}): {MSG}\n".format(
FILE=self.obo_file, LNUM=lnum, MSG=msg)) | def function[_die, parameter[self, msg, lnum]]:
constant[Raise an Exception if file read is unexpected.]
<ast.Raise object at 0x7da18f58d960> | keyword[def] identifier[_die] ( identifier[self] , identifier[msg] , identifier[lnum] ):
literal[string]
keyword[raise] identifier[Exception] ( literal[string] . identifier[format] (
identifier[FILE] = identifier[self] . identifier[obo_file] , identifier[LNUM] = identifier[lnum] , identif... | def _die(self, msg, lnum):
"""Raise an Exception if file read is unexpected."""
raise Exception('**FATAL {FILE}({LNUM}): {MSG}\n'.format(FILE=self.obo_file, LNUM=lnum, MSG=msg)) |
def rebind(self, **params):
"""Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters.
"""
new_params = self.__params.copy()
new_params.update(params)
return self.__class__(new_params, self.__action) | def function[rebind, parameter[self]]:
constant[Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters.
]
variable[new_params] assign[=] call[name[self].__params.copy, parameter[]]
call[name[new_params].update, parameter[name[params]]]
... | keyword[def] identifier[rebind] ( identifier[self] ,** identifier[params] ):
literal[string]
identifier[new_params] = identifier[self] . identifier[__params] . identifier[copy] ()
identifier[new_params] . identifier[update] ( identifier[params] )
keyword[return] identifier[self] ... | def rebind(self, **params):
"""Rebind the parameters into the URI.
:return: A new `CallAPI` instance with the new parameters.
"""
new_params = self.__params.copy()
new_params.update(params)
return self.__class__(new_params, self.__action) |
async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
"""Send an RPC to a device.
See :meth:`AbstractDeviceAdapter.send_rpc`.
"""
adapter_id = self._get_property(conn_id, 'adapter')
return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payloa... | <ast.AsyncFunctionDef object at 0x7da2049639a0> | keyword[async] keyword[def] identifier[send_rpc] ( identifier[self] , identifier[conn_id] , identifier[address] , identifier[rpc_id] , identifier[payload] , identifier[timeout] ):
literal[string]
identifier[adapter_id] = identifier[self] . identifier[_get_property] ( identifier[conn_id] , literal... | async def send_rpc(self, conn_id, address, rpc_id, payload, timeout):
"""Send an RPC to a device.
See :meth:`AbstractDeviceAdapter.send_rpc`.
"""
adapter_id = self._get_property(conn_id, 'adapter')
return await self.adapters[adapter_id].send_rpc(conn_id, address, rpc_id, payload, timeout) |
def isatty(self): # nocover
"""
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
"""
return (self.redirect is not None and
hasattr(self.redir... | def function[isatty, parameter[self]]:
constant[
Returns true of the redirect is a terminal.
Notes:
Needed for IPython.embed to work properly when this class is used
to override stdout / stderr.
]
return[<ast.BoolOp object at 0x7da1b015aa70>] | keyword[def] identifier[isatty] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[self] . identifier[redirect] keyword[is] keyword[not] keyword[None] keyword[and]
identifier[hasattr] ( identifier[self] . identifier[redirect] , literal[string] ) keyword[and] identifie... | def isatty(self): # nocover
'\n Returns true of the redirect is a terminal.\n\n Notes:\n Needed for IPython.embed to work properly when this class is used\n to override stdout / stderr.\n '
return self.redirect is not None and hasattr(self.redirect, 'isatty') and self... |
def update_configuration(self, **kwargs):
"""
Update configuration using valid kwargs as defined in
the enable constructor.
:param dict kwargs: kwargs to satisfy valid args from `enable`
:rtype: bool
"""
updated = False
if 'announced_networks' in ... | def function[update_configuration, parameter[self]]:
constant[
Update configuration using valid kwargs as defined in
the enable constructor.
:param dict kwargs: kwargs to satisfy valid args from `enable`
:rtype: bool
]
variable[updated] assign[=] constant... | keyword[def] identifier[update_configuration] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[updated] = keyword[False]
keyword[if] literal[string] keyword[in] identifier[kwargs] :
identifier[kwargs] . identifier[update] ( identifier[announced_ne_se... | def update_configuration(self, **kwargs):
"""
Update configuration using valid kwargs as defined in
the enable constructor.
:param dict kwargs: kwargs to satisfy valid args from `enable`
:rtype: bool
"""
updated = False
if 'announced_networks' in kwargs:
... |
def _create_node_matrix_from_coord_section(specs):
"""Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix
Calculates distances between nodes
'MATRIX' key added to `specs`
"""
distances = specs['NODE_COORD_SECTION']
specs['MATRIX'] = {}
for i in distances:
... | def function[_create_node_matrix_from_coord_section, parameter[specs]]:
constant[Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix
Calculates distances between nodes
'MATRIX' key added to `specs`
]
variable[distances] assign[=] call[name[specs]][constant[NODE_C... | keyword[def] identifier[_create_node_matrix_from_coord_section] ( identifier[specs] ):
literal[string]
identifier[distances] = identifier[specs] [ literal[string] ]
identifier[specs] [ literal[string] ]={}
keyword[for] identifier[i] keyword[in] identifier[distances] :
identifier[ori... | def _create_node_matrix_from_coord_section(specs):
"""Transformed parsed data from NODE_COORD_SECTION into an upper triangular matrix
Calculates distances between nodes
'MATRIX' key added to `specs`
"""
distances = specs['NODE_COORD_SECTION']
specs['MATRIX'] = {}
for i in distances:
... |
def _zforce(self,R,z,phi=0.,t=0.,v=None):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
v= curr... | def function[_zforce, parameter[self, R, z, phi, t, v]]:
constant[
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - ti... | keyword[def] identifier[_zforce] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] , identifier[v] = keyword[None] ):
literal[string]
identifier[new_hash] = identifier[hashlib] . identifier[md5] ( identifier[numpy] . identifier[array]... | def _zforce(self, R, z, phi=0.0, t=0.0, v=None):
"""
NAME:
_zforce
PURPOSE:
evaluate the vertical force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
v= c... |
def _get_cct(x, y, z):
"""
Reference
Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999).
Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities.
Applied Optics, 38(27), 5703-5709.
"""
x_e = 0.3320
y_e =... | def function[_get_cct, parameter[x, y, z]]:
constant[
Reference
Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999).
Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities.
Applied Optics, 38(27), 5703-5709.
]
v... | keyword[def] identifier[_get_cct] ( identifier[x] , identifier[y] , identifier[z] ):
literal[string]
identifier[x_e] = literal[int]
identifier[y_e] = literal[int]
identifier[n] =(( identifier[x] /( identifier[x] + identifier[z] + identifier[z] ))- identifier[x_e] )/(( identifie... | def _get_cct(x, y, z):
"""
Reference
Hernandez-Andres, J., Lee, R. L., & Romero, J. (1999).
Calculating correlated color temperatures across the entire gamut of daylight and skylight chromaticities.
Applied Optics, 38(27), 5703-5709.
"""
x_e = 0.332
y_e = 0.1858
n... |
def to_auto(name, value, source='auto', convert_to_human=True):
'''
Convert python value to zfs value
'''
return _auto('to', name, value, source, convert_to_human) | def function[to_auto, parameter[name, value, source, convert_to_human]]:
constant[
Convert python value to zfs value
]
return[call[name[_auto], parameter[constant[to], name[name], name[value], name[source], name[convert_to_human]]]] | keyword[def] identifier[to_auto] ( identifier[name] , identifier[value] , identifier[source] = literal[string] , identifier[convert_to_human] = keyword[True] ):
literal[string]
keyword[return] identifier[_auto] ( literal[string] , identifier[name] , identifier[value] , identifier[source] , identifier[conv... | def to_auto(name, value, source='auto', convert_to_human=True):
"""
Convert python value to zfs value
"""
return _auto('to', name, value, source, convert_to_human) |
def disconnect(self, sock):
"""Handles socket disconnections"""
self.log("Disconnect ", sock, lvl=debug)
try:
if sock in self._sockets:
self.log("Getting socket", lvl=debug)
sockobj = self._sockets[sock]
self.log("Getting clientuuid",... | def function[disconnect, parameter[self, sock]]:
constant[Handles socket disconnections]
call[name[self].log, parameter[constant[Disconnect ], name[sock]]]
<ast.Try object at 0x7da1b0e60340> | keyword[def] identifier[disconnect] ( identifier[self] , identifier[sock] ):
literal[string]
identifier[self] . identifier[log] ( literal[string] , identifier[sock] , identifier[lvl] = identifier[debug] )
keyword[try] :
keyword[if] identifier[sock] keyword[in] identifier[... | def disconnect(self, sock):
"""Handles socket disconnections"""
self.log('Disconnect ', sock, lvl=debug)
try:
if sock in self._sockets:
self.log('Getting socket', lvl=debug)
sockobj = self._sockets[sock]
self.log('Getting clientuuid', lvl=debug)
client... |
def get_metadata_parser(metadata_container, **metadata_defaults):
"""
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_con... | def function[get_metadata_parser, parameter[metadata_container]]:
constant[
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(m... | keyword[def] identifier[get_metadata_parser] ( identifier[metadata_container] ,** identifier[metadata_defaults] ):
literal[string]
identifier[parser_type] = keyword[None]
keyword[if] identifier[isinstance] ( identifier[metadata_container] , identifier[MetadataParser] ):
identifier[parser_... | def get_metadata_parser(metadata_container, **metadata_defaults):
"""
Takes a metadata_container, which may be a type or instance of a parser, a dict, string, or file.
:return: a new instance of a parser corresponding to the standard represented by metadata_container
:see: get_parsed_content(metdata_con... |
def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add... | def function[add_arguments, parameter[self, parser]]:
constant[Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
]
... | keyword[def] identifier[add_arguments] ( identifier[self] , identifier[parser] ):
literal[string]
identifier[group] = identifier[parser] . identifier[add_mutually_exclusive_group] ( identifier[required] = keyword[True] )
identifier[group] . identifier[add_argument] ( literal[string] , lite... | def add_arguments(self, parser):
"""Adds the arguments for the firmware command.
Args:
self (FirmwareCommand): the ``FirmwareCommand`` instance
parser (argparse.ArgumentParser): parser to add the commands to
Returns:
``None``
"""
group = parser.add_mutuall... |
def detect_current_filename():
''' Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected.
'''
import inspect
filename = None
frame = inspect.currentframe()
try:
while frame.f_back and frame.f_globals.get('name') != '_... | def function[detect_current_filename, parameter[]]:
constant[ Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected.
]
import module[inspect]
variable[filename] assign[=] constant[None]
variable[frame] assign[=] call[n... | keyword[def] identifier[detect_current_filename] ():
literal[string]
keyword[import] identifier[inspect]
identifier[filename] = keyword[None]
identifier[frame] = identifier[inspect] . identifier[currentframe] ()
keyword[try] :
keyword[while] identifier[frame] . identifier[f_bac... | def detect_current_filename():
""" Attempt to return the filename of the currently running Python process
Returns None if the filename cannot be detected.
"""
import inspect
filename = None
frame = inspect.currentframe()
try:
while frame.f_back and frame.f_globals.get('name') != '__... |
def handle_event(self, raiden_event: RaidenEvent) -> Greenlet:
"""Spawn a new thread to handle a Raiden event.
This will spawn a new greenlet to handle each event, which is
important for two reasons:
- Blockchain transactions can be queued without interfering with each
other.... | def function[handle_event, parameter[self, raiden_event]]:
constant[Spawn a new thread to handle a Raiden event.
This will spawn a new greenlet to handle each event, which is
important for two reasons:
- Blockchain transactions can be queued without interfering with each
othe... | keyword[def] identifier[handle_event] ( identifier[self] , identifier[raiden_event] : identifier[RaidenEvent] )-> identifier[Greenlet] :
literal[string]
keyword[return] identifier[gevent] . identifier[spawn] ( identifier[self] . identifier[_handle_event] , identifier[raiden_event] ) | def handle_event(self, raiden_event: RaidenEvent) -> Greenlet:
"""Spawn a new thread to handle a Raiden event.
This will spawn a new greenlet to handle each event, which is
important for two reasons:
- Blockchain transactions can be queued without interfering with each
other.
... |
def transaction_retry(max_retries=1):
"""Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
"""
def _outer(fun):
@wraps(fun)
def _inner(*args, **kwargs):
_max_retries = kwargs.pop... | def function[transaction_retry, parameter[max_retries]]:
constant[Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
]
def function[_outer, parameter[fun]]:
def function[_inner, parame... | keyword[def] identifier[transaction_retry] ( identifier[max_retries] = literal[int] ):
literal[string]
keyword[def] identifier[_outer] ( identifier[fun] ):
@ identifier[wraps] ( identifier[fun] )
keyword[def] identifier[_inner] (* identifier[args] ,** identifier[kwargs] ):
... | def transaction_retry(max_retries=1):
"""Decorator for methods doing database operations.
If the database operation fails, it will retry the operation
at most ``max_retries`` times.
"""
def _outer(fun):
@wraps(fun)
def _inner(*args, **kwargs):
_max_retries = kwargs.po... |
def visitShapeOr(self, ctx: ShExDocParser.ShapeOrContext):
""" shapeOr: shapeAnd (KW_OR shapeAnd)* """
if len(ctx.shapeAnd()) > 1:
self.expr = ShapeOr(id=self.label, shapeExprs=[])
for sa in ctx.shapeAnd():
sep = ShexShapeExpressionParser(self.context)
... | def function[visitShapeOr, parameter[self, ctx]]:
constant[ shapeOr: shapeAnd (KW_OR shapeAnd)* ]
if compare[call[name[len], parameter[call[name[ctx].shapeAnd, parameter[]]]] greater[>] constant[1]] begin[:]
name[self].expr assign[=] call[name[ShapeOr], parameter[]]
for t... | keyword[def] identifier[visitShapeOr] ( identifier[self] , identifier[ctx] : identifier[ShExDocParser] . identifier[ShapeOrContext] ):
literal[string]
keyword[if] identifier[len] ( identifier[ctx] . identifier[shapeAnd] ())> literal[int] :
identifier[self] . identifier[expr] = identif... | def visitShapeOr(self, ctx: ShExDocParser.ShapeOrContext):
""" shapeOr: shapeAnd (KW_OR shapeAnd)* """
if len(ctx.shapeAnd()) > 1:
self.expr = ShapeOr(id=self.label, shapeExprs=[])
for sa in ctx.shapeAnd():
sep = ShexShapeExpressionParser(self.context)
sep.visit(sa)
... |
def listen(self, once=False):
"""Listen for changes in all registered listeners.
Use add_listener before calling this funcion to listen for desired
events or set `once` to True to listen for initial room information """
if once:
# we listen for time event and return false so... | def function[listen, parameter[self, once]]:
constant[Listen for changes in all registered listeners.
Use add_listener before calling this funcion to listen for desired
events or set `once` to True to listen for initial room information ]
if name[once] begin[:]
call[name[... | keyword[def] identifier[listen] ( identifier[self] , identifier[once] = keyword[False] ):
literal[string]
keyword[if] identifier[once] :
identifier[self] . identifier[add_listener] ( literal[string] , keyword[lambda] identifier[_] : keyword[False] )
keywor... | def listen(self, once=False):
"""Listen for changes in all registered listeners.
Use add_listener before calling this funcion to listen for desired
events or set `once` to True to listen for initial room information """
if once:
# we listen for time event and return false so our
... |
def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe,
preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None,
max_len=None, blacklist=None, whitelist=None, lower=False,
filter_fun=None, str_type=str):
r"""Segment words (tokens), returning a... | def function[get_words, parameter[s, splitter_regex, preprocessor, postprocessor, min_len, max_len, blacklist, whitelist, lower, filter_fun, str_type]]:
constant[Segment words (tokens), returning a list of all tokens
Does not return any separating whitespace or punctuation marks.
Attempts to return ext... | keyword[def] identifier[get_words] ( identifier[s] , identifier[splitter_regex] = identifier[rex] . identifier[word_sep_except_external_appostrophe] ,
identifier[preprocessor] = identifier[strip_HTML] , identifier[postprocessor] = identifier[strip_edge_punc] , identifier[min_len] = keyword[None] ,
identifier[max_le... | def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe, preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None, max_len=None, blacklist=None, whitelist=None, lower=False, filter_fun=None, str_type=str):
"""Segment words (tokens), returning a list of all tokens
Does not return an... |
def _FormatInode(self, event):
"""Formats the inode.
Args:
event (EventObject): event.
Returns:
str: inode field.
"""
inode = event.inode
if inode is None:
if hasattr(event, 'pathspec') and hasattr(event.pathspec, 'image_inode'):
inode = event.pathspec.image_inode
... | def function[_FormatInode, parameter[self, event]]:
constant[Formats the inode.
Args:
event (EventObject): event.
Returns:
str: inode field.
]
variable[inode] assign[=] name[event].inode
if compare[name[inode] is constant[None]] begin[:]
if <ast.BoolOp o... | keyword[def] identifier[_FormatInode] ( identifier[self] , identifier[event] ):
literal[string]
identifier[inode] = identifier[event] . identifier[inode]
keyword[if] identifier[inode] keyword[is] keyword[None] :
keyword[if] identifier[hasattr] ( identifier[event] , literal[string] ) keywor... | def _FormatInode(self, event):
"""Formats the inode.
Args:
event (EventObject): event.
Returns:
str: inode field.
"""
inode = event.inode
if inode is None:
if hasattr(event, 'pathspec') and hasattr(event.pathspec, 'image_inode'):
inode = event.pathspec.image_ino... |
def clustered_sortind(x, k=10, scorefunc=None):
"""
Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index t... | def function[clustered_sortind, parameter[x, k, scorefunc]]:
constant[
Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
... | keyword[def] identifier[clustered_sortind] ( identifier[x] , identifier[k] = literal[int] , identifier[scorefunc] = keyword[None] ):
literal[string]
keyword[try] :
keyword[from] identifier[sklearn] . identifier[cluster] keyword[import] identifier[MiniBatchKMeans]
keyword[except] identifi... | def clustered_sortind(x, k=10, scorefunc=None):
"""
Uses MiniBatch k-means clustering to cluster matrix into groups.
Each cluster of rows is then sorted by `scorefunc` -- by default, the max
peak height when all rows in a cluster are averaged, or
cluster.mean(axis=0).max().
Returns the index t... |
def calculate_etag(self, expected=None):
"""
calculates a multipart upload etag in the same way as amazon s3
args:
source_path -- The file to calculate the etage for
chunk_size -- The chunk size to calculate for.
expected -- optional If pas... | def function[calculate_etag, parameter[self, expected]]:
constant[
calculates a multipart upload etag in the same way as amazon s3
args:
source_path -- The file to calculate the etage for
chunk_size -- The chunk size to calculate for.
expec... | keyword[def] identifier[calculate_etag] ( identifier[self] , identifier[expected] = keyword[None] ):
literal[string]
identifier[md5s] =[]
keyword[with] identifier[open] ( identifier[self] . identifier[filepath] , literal[string] ) keyword[as] identifier[fp] :
keyword[while] ... | def calculate_etag(self, expected=None):
"""
calculates a multipart upload etag in the same way as amazon s3
args:
source_path -- The file to calculate the etage for
chunk_size -- The chunk size to calculate for.
expected -- optional If passed ... |
def apply_cut(self, cm):
"""Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix.
"""
# Invert the cut matrix, creating a matrix of preserved connections
inverse = np.log... | def function[apply_cut, parameter[self, cm]]:
constant[Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix.
]
variable[inverse] assign[=] call[call[name[np].logical_not, paramet... | keyword[def] identifier[apply_cut] ( identifier[self] , identifier[cm] ):
literal[string]
identifier[inverse] = identifier[np] . identifier[logical_not] ( identifier[self] . identifier[cut_matrix] ( identifier[cm] . identifier[shape] [ literal[int] ])). identifier[astype] ( identifier[int]... | def apply_cut(self, cm):
"""Return a modified connectivity matrix with all connections that are
severed by this cut removed.
Args:
cm (np.ndarray): A connectivity matrix.
"""
# Invert the cut matrix, creating a matrix of preserved connections
inverse = np.logical_not(sel... |
def pretty_plot(width=8, height=None, plt=None, dpi=None,
color_cycle=("qualitative", "Set1_9")):
"""
Provides a publication quality plot, with nice defaults for font sizes etc.
Args:
width (float): Width of plot in inches. Defaults to 8in.
height (float): Height of plot in ... | def function[pretty_plot, parameter[width, height, plt, dpi, color_cycle]]:
constant[
Provides a publication quality plot, with nice defaults for font sizes etc.
Args:
width (float): Width of plot in inches. Defaults to 8in.
height (float): Height of plot in inches. Defaults to width * ... | keyword[def] identifier[pretty_plot] ( identifier[width] = literal[int] , identifier[height] = keyword[None] , identifier[plt] = keyword[None] , identifier[dpi] = keyword[None] ,
identifier[color_cycle] =( literal[string] , literal[string] )):
literal[string]
identifier[ticksize] = identifier[int] ( ident... | def pretty_plot(width=8, height=None, plt=None, dpi=None, color_cycle=('qualitative', 'Set1_9')):
"""
Provides a publication quality plot, with nice defaults for font sizes etc.
Args:
width (float): Width of plot in inches. Defaults to 8in.
height (float): Height of plot in inches. Defaults... |
async def _redirect(self, response_obj):
'''
Calls the _check_redirect method of the supplied response object
in order to determine if the http status code indicates a redirect.
Returns:
Response: May or may not be the result of recursive calls due
to redirects!
... | <ast.AsyncFunctionDef object at 0x7da1b07785b0> | keyword[async] keyword[def] identifier[_redirect] ( identifier[self] , identifier[response_obj] ):
literal[string]
identifier[redirect] , identifier[force_get] , identifier[location] = keyword[False] , keyword[None] , keyword[None]
keyword[if] literal[int] <= identifier[response_obj] . ... | async def _redirect(self, response_obj):
"""
Calls the _check_redirect method of the supplied response object
in order to determine if the http status code indicates a redirect.
Returns:
Response: May or may not be the result of recursive calls due
to redirects!
... |
def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.Magic = reader.ReadUInt32()
self.Command = reader.ReadFixedString(12).decode('utf-8')
self.Length = reader.ReadUInt32()
if self.Length > ... | def function[Deserialize, parameter[self, reader]]:
constant[
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
]
name[self].Magic assign[=] call[name[reader].ReadUInt32, parameter[]]
name[self].Command assign[=] call[call[name[reader].ReadFixedStr... | keyword[def] identifier[Deserialize] ( identifier[self] , identifier[reader] ):
literal[string]
identifier[self] . identifier[Magic] = identifier[reader] . identifier[ReadUInt32] ()
identifier[self] . identifier[Command] = identifier[reader] . identifier[ReadFixedString] ( literal[int] ). ... | def Deserialize(self, reader):
"""
Deserialize full object.
Args:
reader (neo.IO.BinaryReader):
"""
self.Magic = reader.ReadUInt32()
self.Command = reader.ReadFixedString(12).decode('utf-8')
self.Length = reader.ReadUInt32()
if self.Length > self.PayloadMaxSizeIn... |
def command(self):
"""Extract query pattern from operations."""
if not self._command_calculated:
self._command_calculated = True
if self.operation == 'command':
try:
command_idx = self.split_tokens.index('command:')
command... | def function[command, parameter[self]]:
constant[Extract query pattern from operations.]
if <ast.UnaryOp object at 0x7da1b17b6950> begin[:]
name[self]._command_calculated assign[=] constant[True]
if compare[name[self].operation equal[==] constant[command]] begin[:]
... | keyword[def] identifier[command] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_command_calculated] :
identifier[self] . identifier[_command_calculated] = keyword[True]
keyword[if] identifier[self] . identifier[operation]... | def command(self):
"""Extract query pattern from operations."""
if not self._command_calculated:
self._command_calculated = True
if self.operation == 'command':
try:
command_idx = self.split_tokens.index('command:')
command = self.split_tokens[command_... |
def _rpc(self, get, child=None, **kwargs):
"""
This allows you to construct an arbitrary RPC call to retreive common stuff. For example:
Configuration: get: "<get-configuration/>"
Interface information: get: "<get-interface-information/>"
A particular interfacece information:
... | def function[_rpc, parameter[self, get, child]]:
constant[
This allows you to construct an arbitrary RPC call to retreive common stuff. For example:
Configuration: get: "<get-configuration/>"
Interface information: get: "<get-interface-information/>"
A particular interfacece in... | keyword[def] identifier[_rpc] ( identifier[self] , identifier[get] , identifier[child] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[rpc] = identifier[etree] . identifier[fromstring] ( identifier[get] )
keyword[if] identifier[child] :
identifier[rpc] .... | def _rpc(self, get, child=None, **kwargs):
"""
This allows you to construct an arbitrary RPC call to retreive common stuff. For example:
Configuration: get: "<get-configuration/>"
Interface information: get: "<get-interface-information/>"
A particular interfacece information:
... |
def on_validation_batch_end(self):
""" Finalize batch processing """
for callback in self.callbacks:
callback.on_validation_batch_end(self)
# Even with all the experience replay, we count the single rollout as a single batch
self.epoch_info.result_accumulator.calculate(self) | def function[on_validation_batch_end, parameter[self]]:
constant[ Finalize batch processing ]
for taget[name[callback]] in starred[name[self].callbacks] begin[:]
call[name[callback].on_validation_batch_end, parameter[name[self]]]
call[name[self].epoch_info.result_accumulator.calc... | keyword[def] identifier[on_validation_batch_end] ( identifier[self] ):
literal[string]
keyword[for] identifier[callback] keyword[in] identifier[self] . identifier[callbacks] :
identifier[callback] . identifier[on_validation_batch_end] ( identifier[self] )
iden... | def on_validation_batch_end(self):
""" Finalize batch processing """
for callback in self.callbacks:
callback.on_validation_batch_end(self) # depends on [control=['for'], data=['callback']]
# Even with all the experience replay, we count the single rollout as a single batch
self.epoch_info.resu... |
def set_frameworkcontroller_config(experiment_config, port, config_file_name):
'''set kubeflow configuration'''
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_ur... | def function[set_frameworkcontroller_config, parameter[experiment_config, port, config_file_name]]:
constant[set kubeflow configuration]
variable[frameworkcontroller_config_data] assign[=] call[name[dict], parameter[]]
call[name[frameworkcontroller_config_data]][constant[frameworkcontroller_conf... | keyword[def] identifier[set_frameworkcontroller_config] ( identifier[experiment_config] , identifier[port] , identifier[config_file_name] ):
literal[string]
identifier[frameworkcontroller_config_data] = identifier[dict] ()
identifier[frameworkcontroller_config_data] [ literal[string] ]= identifier[exp... | def set_frameworkcontroller_config(experiment_config, port, config_file_name):
"""set kubeflow configuration"""
frameworkcontroller_config_data = dict()
frameworkcontroller_config_data['frameworkcontroller_config'] = experiment_config['frameworkcontrollerConfig']
response = rest_put(cluster_metadata_url... |
def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
glo... | def function[__universal_read, parameter[file_path, file_type]]:
constant[
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
... | keyword[def] identifier[__universal_read] ( identifier[file_path] , identifier[file_type] ):
literal[string]
keyword[global] identifier[files] , identifier[cwd] , identifier[settings]
identifier[correct_ext] = identifier[load_fn_matches_ext] ( identifier[file_path] , identifier[file_type] )
... | def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
glo... |
def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match(r'(Shift+)?(Ctrl+)?(Alt+)?(Meta... | def function[register_key_binding, parameter[self, keydef, callback_or_cmd, mode]]:
constant[Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
]
if <ast.UnaryOp object at 0x7d... | keyword[def] identifier[register_key_binding] ( identifier[self] , identifier[keydef] , identifier[callback_or_cmd] , identifier[mode] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[re] . identifier[match] ( literal[string] , identifier[keydef] ):
keyword[ra... | def register_key_binding(self, keydef, callback_or_cmd, mode='force'):
"""Register a key binding. This takes an mpv keydef and either a string containing a mpv command or a python
callback function. See ``MPV.key_binding`` for details.
"""
if not re.match('(Shift+)?(Ctrl+)?(Alt+)?(Meta+)?(.|\\w... |
def check(self, line):
"""
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param line: String; whole line to ... | def function[check, parameter[self, line]]:
constant[
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param l... | keyword[def] identifier[check] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[line] , identifier[str] ):
keyword[raise] identifier[TypeError] ( literal[string] . identifier[format] ( identifier[type] ( identifier... | def check(self, line):
"""
Find first occurrence of 'line' in file.
This searches each line as a whole, if you want to see if a substring is in a line, use .grep() or .egrep()
If found, return the line; this makes it easier to chain methods.
:param line: String; whole line to find... |
def tryForwarding(self, request: Request):
"""
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
"""
cannot_reason_msg = self.canForward(request)
if cannot_reason_msg... | def function[tryForwarding, parameter[self, request]]:
constant[
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
]
variable[cannot_reason_msg] assign[=] call[name[self].can... | keyword[def] identifier[tryForwarding] ( identifier[self] , identifier[request] : identifier[Request] ):
literal[string]
identifier[cannot_reason_msg] = identifier[self] . identifier[canForward] ( identifier[request] )
keyword[if] identifier[cannot_reason_msg] keyword[is] keyword[None] ... | def tryForwarding(self, request: Request):
"""
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
"""
cannot_reason_msg = self.canForward(request)
if cannot_reason_msg is None:
... |
def check_info(info):
""" Validate info dict.
Raise ValueError if validation fails.
"""
if not isinstance(info, dict):
raise ValueError("bad metainfo - not a dictionary")
pieces = info.get("pieces")
if not isinstance(pieces, basestring) or len(pieces) % 20 != 0:
raise Value... | def function[check_info, parameter[info]]:
constant[ Validate info dict.
Raise ValueError if validation fails.
]
if <ast.UnaryOp object at 0x7da2044c3070> begin[:]
<ast.Raise object at 0x7da2044c1de0>
variable[pieces] assign[=] call[name[info].get, parameter[constant[pieces]... | keyword[def] identifier[check_info] ( identifier[info] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[info] , identifier[dict] ):
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[pieces] = identifier[info] . identifier[get] ( literal[st... | def check_info(info):
""" Validate info dict.
Raise ValueError if validation fails.
"""
if not isinstance(info, dict):
raise ValueError('bad metainfo - not a dictionary') # depends on [control=['if'], data=[]]
pieces = info.get('pieces')
if not isinstance(pieces, basestring) or len... |
def get_epoch_namespace_receive_fees_period( block_height, namespace_id ):
"""
how long can a namespace receive register/renewal fees?
"""
epoch_config = get_epoch_config( block_height )
if epoch_config['namespaces'].has_key(namespace_id):
return epoch_config['namespaces'][namespace_id]['NAM... | def function[get_epoch_namespace_receive_fees_period, parameter[block_height, namespace_id]]:
constant[
how long can a namespace receive register/renewal fees?
]
variable[epoch_config] assign[=] call[name[get_epoch_config], parameter[name[block_height]]]
if call[call[name[epoch_config]][... | keyword[def] identifier[get_epoch_namespace_receive_fees_period] ( identifier[block_height] , identifier[namespace_id] ):
literal[string]
identifier[epoch_config] = identifier[get_epoch_config] ( identifier[block_height] )
keyword[if] identifier[epoch_config] [ literal[string] ]. identifier[has_key] ... | def get_epoch_namespace_receive_fees_period(block_height, namespace_id):
"""
how long can a namespace receive register/renewal fees?
"""
epoch_config = get_epoch_config(block_height)
if epoch_config['namespaces'].has_key(namespace_id):
return epoch_config['namespaces'][namespace_id]['NAMESPA... |
def infer_getattr(node, context=None):
"""Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
"""
obj, attr = _infer_getattr_args(node, context)
if (
obj is uti... | def function[infer_getattr, parameter[node, context]]:
constant[Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
]
<ast.Tuple object at 0x7da1b1da16f0> assign[=]... | keyword[def] identifier[infer_getattr] ( identifier[node] , identifier[context] = keyword[None] ):
literal[string]
identifier[obj] , identifier[attr] = identifier[_infer_getattr_args] ( identifier[node] , identifier[context] )
keyword[if] (
identifier[obj] keyword[is] identifier[util] . identif... | def infer_getattr(node, context=None):
"""Understand getattr calls
If one of the arguments is an Uninferable object, then the
result will be an Uninferable object. Otherwise, the normal attribute
lookup will be done.
"""
(obj, attr) = _infer_getattr_args(node, context)
if obj is util.Uninfe... |
def insert_markers(asm_lines, start_line, end_line):
"""Insert IACA marker into list of ASM instructions at given indices."""
asm_lines = (asm_lines[:start_line] + START_MARKER +
asm_lines[start_line:end_line + 1] + END_MARKER +
asm_lines[end_line + 1:])
return asm_lines | def function[insert_markers, parameter[asm_lines, start_line, end_line]]:
constant[Insert IACA marker into list of ASM instructions at given indices.]
variable[asm_lines] assign[=] binary_operation[binary_operation[binary_operation[binary_operation[call[name[asm_lines]][<ast.Slice object at 0x7da2054a50... | keyword[def] identifier[insert_markers] ( identifier[asm_lines] , identifier[start_line] , identifier[end_line] ):
literal[string]
identifier[asm_lines] =( identifier[asm_lines] [: identifier[start_line] ]+ identifier[START_MARKER] +
identifier[asm_lines] [ identifier[start_line] : identifier[end_line... | def insert_markers(asm_lines, start_line, end_line):
"""Insert IACA marker into list of ASM instructions at given indices."""
asm_lines = asm_lines[:start_line] + START_MARKER + asm_lines[start_line:end_line + 1] + END_MARKER + asm_lines[end_line + 1:]
return asm_lines |
def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.... | def function[tz_path, parameter[name]]:
constant[
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
]
if <ast.UnaryOp object at 0x7da1b191dde0> begin[:]
<ast.Raise object at 0x7da1b191d8d0>
variable[name_parts] as... | keyword[def] identifier[tz_path] ( identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[name_parts] = identifier[name] . identifier[lstrip] ( literal[string] ). identifier[split] ( literal[stri... | def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone') # depends on [control=['if'], data=[]]
name_parts = name.lstrip('/').split('/')
for part in n... |
def submatrix(dmat, indices_col, n_neighbors):
"""Return a submatrix given an orginal matrix and the indices to keep.
Parameters
----------
mat: array, shape (n_samples, n_samples)
Original matrix.
indices_col: array, shape (n_samples, n_neighbors)
Indices to keep. Each row consist... | def function[submatrix, parameter[dmat, indices_col, n_neighbors]]:
constant[Return a submatrix given an orginal matrix and the indices to keep.
Parameters
----------
mat: array, shape (n_samples, n_samples)
Original matrix.
indices_col: array, shape (n_samples, n_neighbors)
In... | keyword[def] identifier[submatrix] ( identifier[dmat] , identifier[indices_col] , identifier[n_neighbors] ):
literal[string]
identifier[n_samples_transform] , identifier[n_samples_fit] = identifier[dmat] . identifier[shape]
identifier[submat] = identifier[np] . identifier[zeros] (( identifier[n_sampl... | def submatrix(dmat, indices_col, n_neighbors):
"""Return a submatrix given an orginal matrix and the indices to keep.
Parameters
----------
mat: array, shape (n_samples, n_samples)
Original matrix.
indices_col: array, shape (n_samples, n_neighbors)
Indices to keep. Each row consist... |
def map_exception_codes():
'''Helper function to intialise CODES_TO_EXCEPTIONS.'''
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for _, e in werkex} | def function[map_exception_codes, parameter[]]:
constant[Helper function to intialise CODES_TO_EXCEPTIONS.]
variable[werkex] assign[=] call[name[inspect].getmembers, parameter[name[exceptions], <ast.Lambda object at 0x7da1b15a1b70>]]
return[<ast.DictComp object at 0x7da1b15a17b0>] | keyword[def] identifier[map_exception_codes] ():
literal[string]
identifier[werkex] = identifier[inspect] . identifier[getmembers] ( identifier[exceptions] , keyword[lambda] identifier[x] : identifier[getattr] ( identifier[x] , literal[string] , keyword[None] ))
keyword[return] { identifier[e] . iden... | def map_exception_codes():
"""Helper function to intialise CODES_TO_EXCEPTIONS."""
werkex = inspect.getmembers(exceptions, lambda x: getattr(x, 'code', None))
return {e.code: e for (_, e) in werkex} |
def config_oauth(app):
" Configure oauth support. "
for name in PROVIDERS:
config = app.config.get('OAUTH_%s' % name.upper())
if not config:
continue
if not name in oauth.remote_apps:
remote_app = oauth.remote_app(name, **config)
else:
remo... | def function[config_oauth, parameter[app]]:
constant[ Configure oauth support. ]
for taget[name[name]] in starred[name[PROVIDERS]] begin[:]
variable[config] assign[=] call[name[app].config.get, parameter[binary_operation[constant[OAUTH_%s] <ast.Mod object at 0x7da2590d6920> call[name[nam... | keyword[def] identifier[config_oauth] ( identifier[app] ):
literal[string]
keyword[for] identifier[name] keyword[in] identifier[PROVIDERS] :
identifier[config] = identifier[app] . identifier[config] . identifier[get] ( literal[string] % identifier[name] . identifier[upper] ())
keywor... | def config_oauth(app):
""" Configure oauth support. """
for name in PROVIDERS:
config = app.config.get('OAUTH_%s' % name.upper())
if not config:
continue # depends on [control=['if'], data=[]]
if not name in oauth.remote_apps:
remote_app = oauth.remote_app(name, ... |
def space(self):
"""Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space
"""
schema = SpaceSchema()
resp = self.service.get(self.base+'space/')
return self.service.decode(schema, resp) | def function[space, parameter[self]]:
constant[Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space
]
variable[schema] assign[=] call[name[SpaceSchema], parameter[]]
variable[resp] assign[=] call[name[self].service.get, p... | keyword[def] identifier[space] ( identifier[self] ):
literal[string]
identifier[schema] = identifier[SpaceSchema] ()
identifier[resp] = identifier[self] . identifier[service] . identifier[get] ( identifier[self] . identifier[base] + literal[string] )
keyword[return] identifier[se... | def space(self):
"""Get system disk space usage.
:return: :class:`system.Space <system.Space>` object
:rtype: system.Space
"""
schema = SpaceSchema()
resp = self.service.get(self.base + 'space/')
return self.service.decode(schema, resp) |
def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
argument_parser = argparse.ArgumentParser(
description='Validates dtFabric format definitions.')
argument_parser.add_argument(
'source', nargs='?', action='store', metavar='PATH', default=None,
... | def function[Main, parameter[]]:
constant[The main program function.
Returns:
bool: True if successful or False if not.
]
variable[argument_parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[argument_parser].add_argument, parameter[constant[source]]]
va... | keyword[def] identifier[Main] ():
literal[string]
identifier[argument_parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] )
identifier[argument_parser] . identifier[add_argument] (
literal[string] , identifier[nargs] = literal[string] , identifier[a... | def Main():
"""The main program function.
Returns:
bool: True if successful or False if not.
"""
argument_parser = argparse.ArgumentParser(description='Validates dtFabric format definitions.')
argument_parser.add_argument('source', nargs='?', action='store', metavar='PATH', default=None, help='path... |
def get_data_path(self, filename, env_prefix=None):
"""
Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
Returns:
... | def function[get_data_path, parameter[self, filename, env_prefix]]:
constant[
Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
... | keyword[def] identifier[get_data_path] ( identifier[self] , identifier[filename] , identifier[env_prefix] = keyword[None] ):
literal[string]
keyword[if] identifier[env_prefix] == keyword[None] :
identifier[target_file] = identifier[filename]
keyword[else] :
iden... | def get_data_path(self, filename, env_prefix=None):
"""
Get data path.
Args:
filename (string) : Name of file inside of /data folder to retrieve.
Kwargs:
env_prefix (string) : Name of subfolder, ex: 'qa' will find files in /data/qa
Returns:
Stri... |
def _read_country_names(self, countries_file=None):
"""Read list of countries from specified country file or default file."""
if not countries_file:
countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT)
with open(countries_file) as f:
countri... | def function[_read_country_names, parameter[self, countries_file]]:
constant[Read list of countries from specified country file or default file.]
if <ast.UnaryOp object at 0x7da18dc052d0> begin[:]
variable[countries_file] assign[=] call[name[os].path.join, parameter[call[name[os].path.di... | keyword[def] identifier[_read_country_names] ( identifier[self] , identifier[countries_file] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[countries_file] :
identifier[countries_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[os] . i... | def _read_country_names(self, countries_file=None):
"""Read list of countries from specified country file or default file."""
if not countries_file:
countries_file = os.path.join(os.path.dirname(__file__), self.COUNTRY_FILE_DEFAULT) # depends on [control=['if'], data=[]]
with open(countries_file) a... |
def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super... | def function[path, parameter[self, which]]:
constant[Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscrip... | keyword[def] identifier[path] ( identifier[self] , identifier[which] = keyword[None] ):
literal[string]
keyword[if] identifier[which] keyword[in] (
literal[string] ,
literal[string] ):
keyword[return] literal[string] . identifier[format] (
identifier[s... | def path(self, which=None):
"""Extend ``nailgun.entity_mixins.Entity.path``.
The format of the returned path depends on the value of ``which``:
add_subscriptions
/hosts/<id>/add_subscriptions
remove_subscriptions
/hosts/<id>/remove_subscriptions
``super`` i... |
def add_children(self, children):
"""Adds new children nodes after filtering for duplicates
Args:
children (list): list of OmniTree nodes to add as children
"""
self._children += [c for c in children if c not in self._children] | def function[add_children, parameter[self, children]]:
constant[Adds new children nodes after filtering for duplicates
Args:
children (list): list of OmniTree nodes to add as children
]
<ast.AugAssign object at 0x7da1b14d0460> | keyword[def] identifier[add_children] ( identifier[self] , identifier[children] ):
literal[string]
identifier[self] . identifier[_children] +=[ identifier[c] keyword[for] identifier[c] keyword[in] identifier[children] keyword[if] identifier[c] keyword[not] keyword[in] identifier[self] . i... | def add_children(self, children):
"""Adds new children nodes after filtering for duplicates
Args:
children (list): list of OmniTree nodes to add as children
"""
self._children += [c for c in children if c not in self._children] |
def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current /... | def function[_every, parameter[times, step_size, index]]:
constant[
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
]
variable[current] assign[=]... | keyword[def] identifier[_every] ( identifier[times] , identifier[step_size] , identifier[index] ):
literal[string]
identifier[current] = identifier[index] * identifier[step_size]
identifier[step] = identifier[current] // identifier[times] * identifier[times]
identifier[reached] ... | def _every(times, step_size, index):
"""
Given a loop over batches of an iterable and an operation that should
be performed every few elements. Determine whether the operation should
be called for the current index.
"""
current = index * step_size
step = current // times * ti... |
def target_partname(self):
"""
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing.
"""
if self.is_external:
msg = ('targ... | def function[target_partname, parameter[self]]:
constant[
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing.
]
if name[self].is_ext... | keyword[def] identifier[target_partname] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_external] :
identifier[msg] =( literal[string]
literal[string] )
keyword[raise] identifier[ValueError] ( identifier[msg] )
... | def target_partname(self):
"""
|PackURI| instance containing partname targeted by this relationship.
Raises ``ValueError`` on reference if target_mode is ``'External'``.
Use :attr:`target_mode` to check before referencing.
"""
if self.is_external:
msg = 'target_partname a... |
def get_causal_out_edges(
graph: BELGraph,
nbunch: Union[BaseEntity, Iterable[BaseEntity]],
) -> Set[Tuple[BaseEntity, BaseEntity]]:
"""Get the out-edges to the given node that are causal.
:return: A set of (source, target) pairs where the source is the given node
"""
return {
(... | def function[get_causal_out_edges, parameter[graph, nbunch]]:
constant[Get the out-edges to the given node that are causal.
:return: A set of (source, target) pairs where the source is the given node
]
return[<ast.SetComp object at 0x7da1afeb4bb0>] | keyword[def] identifier[get_causal_out_edges] (
identifier[graph] : identifier[BELGraph] ,
identifier[nbunch] : identifier[Union] [ identifier[BaseEntity] , identifier[Iterable] [ identifier[BaseEntity] ]],
)-> identifier[Set] [ identifier[Tuple] [ identifier[BaseEntity] , identifier[BaseEntity] ]]:
literal[st... | def get_causal_out_edges(graph: BELGraph, nbunch: Union[BaseEntity, Iterable[BaseEntity]]) -> Set[Tuple[BaseEntity, BaseEntity]]:
"""Get the out-edges to the given node that are causal.
:return: A set of (source, target) pairs where the source is the given node
"""
return {(u, v) for (u, v, k, d) in gr... |
def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=1e10, **kwargs):
"""
Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with log(abs(c... | def function[get_fermi_interextrapolated, parameter[self, c, T, warn, c_ref]]:
constant[
Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with lo... | keyword[def] identifier[get_fermi_interextrapolated] ( identifier[self] , identifier[c] , identifier[T] , identifier[warn] = keyword[True] , identifier[c_ref] = literal[int] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[return] identifier[self] . identifier[get_ferm... | def get_fermi_interextrapolated(self, c, T, warn=True, c_ref=10000000000.0, **kwargs):
"""
Similar to get_fermi except that when get_fermi fails to converge,
an interpolated or extrapolated fermi (depending on c) is returned with
the assumption that the fermi level changes linearly with log(... |
def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs):
# type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict]
"""Download multicolumn csv from url and return dictionary where keys are first column and values are
dictionaries with keys from column header... | def function[download_tabular_rows_as_dicts, parameter[self, url, headers, keycolumn]]:
constant[Download multicolumn csv from url and return dictionary where keys are first column and values are
dictionaries with keys from column headers and values from columns beneath
Args:
url (s... | keyword[def] identifier[download_tabular_rows_as_dicts] ( identifier[self] , identifier[url] , identifier[headers] = literal[int] , identifier[keycolumn] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= identifier[headers]
identifier[stream... | def download_tabular_rows_as_dicts(self, url, headers=1, keycolumn=1, **kwargs):
# type: (str, Union[int, List[int], List[str]], int, Any) -> Dict[Dict]
'Download multicolumn csv from url and return dictionary where keys are first column and values are\n dictionaries with keys from column headers and val... |
def isalive(self):
'''This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
... | def function[isalive, parameter[self]]:
constant[This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if ... | keyword[def] identifier[isalive] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[terminated] :
keyword[return] keyword[False]
keyword[if] identifier[self] . identifier[flag_eof] :
identifier... | def isalive(self):
"""This tests if the child process is running or not. This is
non-blocking. If the child was terminated then this will read the
exitstatus or signalstatus of the child. This returns True if the child
process appears to be running or False if not. It can take literally
... |
def fetchall(self):
""" returns the remainder of records from the query. This is
guaranteed by locking, so that no other thread can grab a few records
while the set is fetched. This has the side effect that other threads
may have to wait for an arbitrary long time until this query is done
before the... | def function[fetchall, parameter[self]]:
constant[ returns the remainder of records from the query. This is
guaranteed by locking, so that no other thread can grab a few records
while the set is fetched. This has the side effect that other threads
may have to wait for an arbitrary long time until this ... | keyword[def] identifier[fetchall] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_cursorLock] . identifier[acquire] ()
identifier[recs] =[]
keyword[while] keyword[True] :
identifier[rec] = identifier[self] . identifier[fetchone] ()
... | def fetchall(self):
""" returns the remainder of records from the query. This is
guaranteed by locking, so that no other thread can grab a few records
while the set is fetched. This has the side effect that other threads
may have to wait for an arbitrary long time until this query is done
before they ca... |
def load_data(self, path, *args, **kwargs):
"""see print instance.doc, e.g. cat=LoadFile(kind='excel')
read how to use cat.load_data, exec: print (cat.doc)"""
self.df = self._load(path,*args, **kwargs)
self.series = self.df.iloc[:,0]
print ("Success! file length: " +str(self.df... | def function[load_data, parameter[self, path]]:
constant[see print instance.doc, e.g. cat=LoadFile(kind='excel')
read how to use cat.load_data, exec: print (cat.doc)]
name[self].df assign[=] call[name[self]._load, parameter[name[path], <ast.Starred object at 0x7da1b09676d0>]]
name[self... | keyword[def] identifier[load_data] ( identifier[self] , identifier[path] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[df] = identifier[self] . identifier[_load] ( identifier[path] ,* identifier[args] ,** identifier[kwargs] )
identifier[self] .... | def load_data(self, path, *args, **kwargs):
"""see print instance.doc, e.g. cat=LoadFile(kind='excel')
read how to use cat.load_data, exec: print (cat.doc)"""
self.df = self._load(path, *args, **kwargs)
self.series = self.df.iloc[:, 0]
print('Success! file length: ' + str(self.df.shape[0])) |
def _change_channel(self, fcid, tcid):
"""
这个貌似没啥用
:params fcid, tcid: string
"""
url = 'https://douban.fm/j/change_channel'
options = {
'fcid': fcid,
'tcid': tcid,
'area': 'system_chis'
}
requests.get(url, params=option... | def function[_change_channel, parameter[self, fcid, tcid]]:
constant[
这个貌似没啥用
:params fcid, tcid: string
]
variable[url] assign[=] constant[https://douban.fm/j/change_channel]
variable[options] assign[=] dictionary[[<ast.Constant object at 0x7da18fe93400>, <ast.Constant o... | keyword[def] identifier[_change_channel] ( identifier[self] , identifier[fcid] , identifier[tcid] ):
literal[string]
identifier[url] = literal[string]
identifier[options] ={
literal[string] : identifier[fcid] ,
literal[string] : identifier[tcid] ,
literal[string... | def _change_channel(self, fcid, tcid):
"""
这个貌似没啥用
:params fcid, tcid: string
"""
url = 'https://douban.fm/j/change_channel'
options = {'fcid': fcid, 'tcid': tcid, 'area': 'system_chis'}
requests.get(url, params=options, cookies=self._cookies, headers=HEADERS) |
def is_modified(self):
"""
Returns whether list is modified or not
"""
if self.__modified_data__ is not None:
return True
for value in self.__original_data__:
try:
if value.is_modified():
return True
except A... | def function[is_modified, parameter[self]]:
constant[
Returns whether list is modified or not
]
if compare[name[self].__modified_data__ is_not constant[None]] begin[:]
return[constant[True]]
for taget[name[value]] in starred[name[self].__original_data__] begin[:]
... | keyword[def] identifier[is_modified] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__modified_data__] keyword[is] keyword[not] keyword[None] :
keyword[return] keyword[True]
keyword[for] identifier[value] keyword[in] identifier[self] .... | def is_modified(self):
"""
Returns whether list is modified or not
"""
if self.__modified_data__ is not None:
return True # depends on [control=['if'], data=[]]
for value in self.__original_data__:
try:
if value.is_modified():
return True # depen... |
def remove_plugin(self, name, force=False):
"""
Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before remo... | def function[remove_plugin, parameter[self, name, force]]:
constant[
Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable t... | keyword[def] identifier[remove_plugin] ( identifier[self] , identifier[name] , identifier[force] = keyword[False] ):
literal[string]
identifier[url] = identifier[self] . identifier[_url] ( literal[string] , identifier[name] )
identifier[res] = identifier[self] . identifier[_delete] ( ident... | def remove_plugin(self, name, force=False):
"""
Remove an installed plugin.
Args:
name (string): Name of the plugin to remove. The ``:latest``
tag is optional, and is the default if omitted.
force (bool): Disable the plugin before removing... |
def get_rendition_size(self, spec, output_scale, crop):
"""
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
"""
if crop:
# Use the cropping rectangle size
_, _, width, height = crop
else:
#... | def function[get_rendition_size, parameter[self, spec, output_scale, crop]]:
constant[
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
]
if name[crop] begin[:]
<ast.Tuple object at 0x7da1b2344100> assign[=] name[crop]
... | keyword[def] identifier[get_rendition_size] ( identifier[self] , identifier[spec] , identifier[output_scale] , identifier[crop] ):
literal[string]
keyword[if] identifier[crop] :
identifier[_] , identifier[_] , identifier[width] , identifier[height] = identifier[crop]
... | def get_rendition_size(self, spec, output_scale, crop):
"""
Wrapper to determine the overall rendition size and cropping box
Returns tuple of (size,box)
"""
if crop:
# Use the cropping rectangle size
(_, _, width, height) = crop # depends on [control=['if'], data=[]]
... |
def get_artist(self):
"""
:returns: the :mod:`Artist <deezer.resources.Artist>` of the resource
:raises AssertionError: if the object is not album or track
"""
# pylint: disable=E1101
assert isinstance(self, (Album, Track))
return self.client.get_artist(self.artis... | def function[get_artist, parameter[self]]:
constant[
:returns: the :mod:`Artist <deezer.resources.Artist>` of the resource
:raises AssertionError: if the object is not album or track
]
assert[call[name[isinstance], parameter[name[self], tuple[[<ast.Name object at 0x7da1b11a3940>, <as... | keyword[def] identifier[get_artist] ( identifier[self] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[self] ,( identifier[Album] , identifier[Track] ))
keyword[return] identifier[self] . identifier[client] . identifier[get_artist] ( identifier[self] . ide... | def get_artist(self):
"""
:returns: the :mod:`Artist <deezer.resources.Artist>` of the resource
:raises AssertionError: if the object is not album or track
"""
# pylint: disable=E1101
assert isinstance(self, (Album, Track))
return self.client.get_artist(self.artist.id) |
def fit(self, X, y, sample_weight=None):
"""
Fit a binary classifier with sample weights to data.
Note
----
Examples at each sample are accepted with probability = weight/Z,
where Z = max(weight) + extra_rej_const.
Larger values for extra_rej_const ensure... | def function[fit, parameter[self, X, y, sample_weight]]:
constant[
Fit a binary classifier with sample weights to data.
Note
----
Examples at each sample are accepted with probability = weight/Z,
where Z = max(weight) + extra_rej_const.
Larger values for ... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[y] , identifier[sample_weight] = keyword[None] ):
literal[string]
keyword[assert] identifier[self] . identifier[extra_rej_const] >= literal[int]
keyword[if] identifier[sample_weight] keyword[is] keyword[None]... | def fit(self, X, y, sample_weight=None):
"""
Fit a binary classifier with sample weights to data.
Note
----
Examples at each sample are accepted with probability = weight/Z,
where Z = max(weight) + extra_rej_const.
Larger values for extra_rej_const ensure tha... |
def get_handler(progname, address=None, proto=None, facility=None,
fmt=None, datefmt=None, **_):
"""Helper function to create a Syslog handler.
See `ulogger.syslog.SyslogHandlerBuilder` for arguments and
supported keyword arguments.
Returns:
(obj): Instance of `logging.SysLogHa... | def function[get_handler, parameter[progname, address, proto, facility, fmt, datefmt]]:
constant[Helper function to create a Syslog handler.
See `ulogger.syslog.SyslogHandlerBuilder` for arguments and
supported keyword arguments.
Returns:
(obj): Instance of `logging.SysLogHandler`
]
... | keyword[def] identifier[get_handler] ( identifier[progname] , identifier[address] = keyword[None] , identifier[proto] = keyword[None] , identifier[facility] = keyword[None] ,
identifier[fmt] = keyword[None] , identifier[datefmt] = keyword[None] ,** identifier[_] ):
literal[string]
identifier[builder] = id... | def get_handler(progname, address=None, proto=None, facility=None, fmt=None, datefmt=None, **_):
"""Helper function to create a Syslog handler.
See `ulogger.syslog.SyslogHandlerBuilder` for arguments and
supported keyword arguments.
Returns:
(obj): Instance of `logging.SysLogHandler`
"""
... |
def _add_y(self, variable, prior=None, family='gaussian', link=None, *args,
**kwargs):
'''Add a dependent (or outcome) variable to the model.
Args:
variable (str): the name of the dataset column containing the
y values.
prior (Prior, int, float, st... | def function[_add_y, parameter[self, variable, prior, family, link]]:
constant[Add a dependent (or outcome) variable to the model.
Args:
variable (str): the name of the dataset column containing the
y values.
prior (Prior, int, float, str): Optional specification... | keyword[def] identifier[_add_y] ( identifier[self] , identifier[variable] , identifier[prior] = keyword[None] , identifier[family] = literal[string] , identifier[link] = keyword[None] ,* identifier[args] ,
** identifier[kwargs] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[fam... | def _add_y(self, variable, prior=None, family='gaussian', link=None, *args, **kwargs):
"""Add a dependent (or outcome) variable to the model.
Args:
variable (str): the name of the dataset column containing the
y values.
prior (Prior, int, float, str): Optional specif... |
def get_parallel_regions_block(batch):
"""CWL target to retrieve block group of callable regions for parallelization.
Uses blocking to handle multicore runs.
"""
samples = [utils.to_single_data(d) for d in batch]
regions = _get_parallel_regions(samples[0])
out = []
# Currently don't have co... | def function[get_parallel_regions_block, parameter[batch]]:
constant[CWL target to retrieve block group of callable regions for parallelization.
Uses blocking to handle multicore runs.
]
variable[samples] assign[=] <ast.ListComp object at 0x7da1b1884670>
variable[regions] assign[=] call... | keyword[def] identifier[get_parallel_regions_block] ( identifier[batch] ):
literal[string]
identifier[samples] =[ identifier[utils] . identifier[to_single_data] ( identifier[d] ) keyword[for] identifier[d] keyword[in] identifier[batch] ]
identifier[regions] = identifier[_get_parallel_regions] ( ide... | def get_parallel_regions_block(batch):
"""CWL target to retrieve block group of callable regions for parallelization.
Uses blocking to handle multicore runs.
"""
samples = [utils.to_single_data(d) for d in batch]
regions = _get_parallel_regions(samples[0])
out = []
# Currently don't have co... |
def get_relation_kwargs(field_name, relation_info):
"""
Creates a default instance of a flat relational field.
"""
model_field, related_model, to_many, to_field, has_through_model = relation_info
kwargs = {
'queryset': related_model._default_manager,
'view_name': get_detail_view_name... | def function[get_relation_kwargs, parameter[field_name, relation_info]]:
constant[
Creates a default instance of a flat relational field.
]
<ast.Tuple object at 0x7da18f723280> assign[=] name[relation_info]
variable[kwargs] assign[=] dictionary[[<ast.Constant object at 0x7da18f721f90>, <... | keyword[def] identifier[get_relation_kwargs] ( identifier[field_name] , identifier[relation_info] ):
literal[string]
identifier[model_field] , identifier[related_model] , identifier[to_many] , identifier[to_field] , identifier[has_through_model] = identifier[relation_info]
identifier[kwargs] ={
... | def get_relation_kwargs(field_name, relation_info):
"""
Creates a default instance of a flat relational field.
"""
(model_field, related_model, to_many, to_field, has_through_model) = relation_info
kwargs = {'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model)... |
def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self.... | def function[add_contents, parameter[self, dest, contents]]:
constant[Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
]... | keyword[def] identifier[add_contents] ( identifier[self] , identifier[dest] , identifier[contents] ):
literal[string]
keyword[assert] keyword[not] identifier[self] . identifier[_closed] , literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[dest] , identifier[z... | def add_contents(self, dest, contents):
"""Add file contents to the archive under ``dest``.
If ``dest`` is a path, it will be added compressed and world-readable
(user-writeable). You may also pass a :py:class:`~zipfile.ZipInfo` for
custom behavior.
"""
assert not self._closed,... |
def abort_request(self, stream, ident, parent):
"""abort a specifig msg by id"""
msg_ids = parent['content'].get('msg_ids', None)
if isinstance(msg_ids, basestring):
msg_ids = [msg_ids]
if not msg_ids:
self.abort_queues()
for mid in msg_ids:
se... | def function[abort_request, parameter[self, stream, ident, parent]]:
constant[abort a specifig msg by id]
variable[msg_ids] assign[=] call[call[name[parent]][constant[content]].get, parameter[constant[msg_ids], constant[None]]]
if call[name[isinstance], parameter[name[msg_ids], name[basestring]]... | keyword[def] identifier[abort_request] ( identifier[self] , identifier[stream] , identifier[ident] , identifier[parent] ):
literal[string]
identifier[msg_ids] = identifier[parent] [ literal[string] ]. identifier[get] ( literal[string] , keyword[None] )
keyword[if] identifier[isinstance] (... | def abort_request(self, stream, ident, parent):
"""abort a specifig msg by id"""
msg_ids = parent['content'].get('msg_ids', None)
if isinstance(msg_ids, basestring):
msg_ids = [msg_ids] # depends on [control=['if'], data=[]]
if not msg_ids:
self.abort_queues() # depends on [control=['i... |
def get_notice_content(self, time: str) -> str:
"""
取得公布欄特定訊息內容
"""
try:
# 取得資料
response = self.__session.get(
self.__url + '/showArticle?time=' + time, timeout=0.5, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
... | def function[get_notice_content, parameter[self, time]]:
constant[
取得公布欄特定訊息內容
]
<ast.Try object at 0x7da204566a10> | keyword[def] identifier[get_notice_content] ( identifier[self] , identifier[time] : identifier[str] )-> identifier[str] :
literal[string]
keyword[try] :
identifier[response] = identifier[self] . identifier[__session] . identifier[get] (
identifier[self] . identifi... | def get_notice_content(self, time: str) -> str:
"""
取得公布欄特定訊息內容
"""
try:
# 取得資料
response = self.__session.get(self.__url + '/showArticle?time=' + time, timeout=0.5, verify=False)
soup = BeautifulSoup(response.text, 'html.parser')
# 回傳結果
return soup.find('p... |
def value_edited(self, path, new_value_str):
""" Adds the value of the semantic data entry
:param path: The path inside the tree store to the target entry
:param str new_value_str: The new value of the target cell
:return:
"""
tree_store_path = self.create_tree_store_pat... | def function[value_edited, parameter[self, path, new_value_str]]:
constant[ Adds the value of the semantic data entry
:param path: The path inside the tree store to the target entry
:param str new_value_str: The new value of the target cell
:return:
]
variable[tree_store... | keyword[def] identifier[value_edited] ( identifier[self] , identifier[path] , identifier[new_value_str] ):
literal[string]
identifier[tree_store_path] = identifier[self] . identifier[create_tree_store_path_from_key_string] ( identifier[path] ) keyword[if] identifier[isinstance] ( identifier[path] ... | def value_edited(self, path, new_value_str):
""" Adds the value of the semantic data entry
:param path: The path inside the tree store to the target entry
:param str new_value_str: The new value of the target cell
:return:
"""
tree_store_path = self.create_tree_store_path_from_k... |
def _labels_from_pyclusters(self):
"""
Computes and returns the list of labels indicating the data points and the corresponding cluster ids.
:return: The list of labels
"""
clusters = self.model.get_clusters()
labels = []
for i in range(0, len(clusters)):
... | def function[_labels_from_pyclusters, parameter[self]]:
constant[
Computes and returns the list of labels indicating the data points and the corresponding cluster ids.
:return: The list of labels
]
variable[clusters] assign[=] call[name[self].model.get_clusters, parameter[]]
... | keyword[def] identifier[_labels_from_pyclusters] ( identifier[self] ):
literal[string]
identifier[clusters] = identifier[self] . identifier[model] . identifier[get_clusters] ()
identifier[labels] =[]
keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] , iden... | def _labels_from_pyclusters(self):
"""
Computes and returns the list of labels indicating the data points and the corresponding cluster ids.
:return: The list of labels
"""
clusters = self.model.get_clusters()
labels = []
for i in range(0, len(clusters)):
for j in cluste... |
def commit(self):
"""
Commits the changes to the current database connection.
:return <bool> success
"""
with self.native(writeAccess=True) as conn:
if not self._closed(conn):
return self._commit(conn) | def function[commit, parameter[self]]:
constant[
Commits the changes to the current database connection.
:return <bool> success
]
with call[name[self].native, parameter[]] begin[:]
if <ast.UnaryOp object at 0x7da2043471c0> begin[:]
return[call[nam... | keyword[def] identifier[commit] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[native] ( identifier[writeAccess] = keyword[True] ) keyword[as] identifier[conn] :
keyword[if] keyword[not] identifier[self] . identifier[_closed] ( identifier[conn] ):... | def commit(self):
"""
Commits the changes to the current database connection.
:return <bool> success
"""
with self.native(writeAccess=True) as conn:
if not self._closed(conn):
return self._commit(conn) # depends on [control=['if'], data=[]] # depends on [contro... |
def get_package_version(self, package):
# type: (str) -> Tuple[int, int, int]
"""
Provides the version of the given package name.
:param package: The name of the package
:return: The version of the specified package as a tuple or (0,0,0)
"""
name = "{0}{1}".forma... | def function[get_package_version, parameter[self, package]]:
constant[
Provides the version of the given package name.
:param package: The name of the package
:return: The version of the specified package as a tuple or (0,0,0)
]
variable[name] assign[=] call[constant[{0}... | keyword[def] identifier[get_package_version] ( identifier[self] , identifier[package] ):
literal[string]
identifier[name] = literal[string] . identifier[format] ( identifier[ENDPOINT_PACKAGE_VERSION_] , identifier[package] )
keyword[try] :
identifier[version] = ident... | def get_package_version(self, package):
# type: (str) -> Tuple[int, int, int]
'\n Provides the version of the given package name.\n\n :param package: The name of the package\n :return: The version of the specified package as a tuple or (0,0,0)\n '
name = '{0}{1}'.format(ENDPOINT_... |
def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]:
"""
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to t... | def function[do_rpc, parameter[self, name, rpc_function]]:
constant[
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to the exception
future, which consumers... | keyword[def] identifier[do_rpc] ( identifier[self] , identifier[name] : identifier[str] , identifier[rpc_function] : identifier[Callable] [..., identifier[Awaitable] [ keyword[None] ]])-> identifier[Callable] [..., identifier[Awaitable] [ keyword[None] ]]:
literal[string]
keyword[async] keyword[de... | def do_rpc(self, name: str, rpc_function: Callable[..., Awaitable[None]]) -> Callable[..., Awaitable[None]]:
"""
Wraps a given RPC function by producing an awaitable function suitable to be run in the asyncio
event loop. The wrapped function catches all unhandled exceptions and reports them to the e... |
def add_process(self, tgt, args=None, kwargs=None, name=None):
'''
Create a processes and args + kwargs
This will deterimine if it is a Process class, otherwise it assumes
it is a function
'''
if args is None:
args = []
if kwargs is None:
... | def function[add_process, parameter[self, tgt, args, kwargs, name]]:
constant[
Create a processes and args + kwargs
This will deterimine if it is a Process class, otherwise it assumes
it is a function
]
if compare[name[args] is constant[None]] begin[:]
var... | keyword[def] identifier[add_process] ( identifier[self] , identifier[tgt] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] , identifier[name] = keyword[None] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
identifier[args] =[]
... | def add_process(self, tgt, args=None, kwargs=None, name=None):
"""
Create a processes and args + kwargs
This will deterimine if it is a Process class, otherwise it assumes
it is a function
"""
if args is None:
args = [] # depends on [control=['if'], data=['args']]
if... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.