code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def rename_file(self, fmfile, newname):
"""Rename file in transfer.
:param fmfile: file data from filemail containing fileid
:param newname: new file name
:type fmfile: ``dict``
:type newname: ``str`` or ``unicode``
:rtype: ``bool``
"""
if not isinstance... | def function[rename_file, parameter[self, fmfile, newname]]:
constant[Rename file in transfer.
:param fmfile: file data from filemail containing fileid
:param newname: new file name
:type fmfile: ``dict``
:type newname: ``str`` or ``unicode``
:rtype: ``bool``
]
... | keyword[def] identifier[rename_file] ( identifier[self] , identifier[fmfile] , identifier[newname] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[fmfile] , identifier[dict] ):
keyword[raise] identifier[FMBaseError] ( literal[string] )
iden... | def rename_file(self, fmfile, newname):
"""Rename file in transfer.
:param fmfile: file data from filemail containing fileid
:param newname: new file name
:type fmfile: ``dict``
:type newname: ``str`` or ``unicode``
:rtype: ``bool``
"""
if not isinstance(fmfile, ... |
def equation_of_time_pvcdrom(dayofyear):
"""
Equation of time from PVCDROM.
`PVCDROM`_ is a website by Solar Power Lab at Arizona State
University (ASU)
.. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time
Parameters
----------
dayofyear : numeric
Retu... | def function[equation_of_time_pvcdrom, parameter[dayofyear]]:
constant[
Equation of time from PVCDROM.
`PVCDROM`_ is a website by Solar Power Lab at Arizona State
University (ASU)
.. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time
Parameters
----------
... | keyword[def] identifier[equation_of_time_pvcdrom] ( identifier[dayofyear] ):
literal[string]
identifier[bday] = identifier[_calculate_simple_day_angle] ( identifier[dayofyear] )-( literal[int] * identifier[np] . identifier[pi] / literal[int] )* literal[int]
keyword[return] literal[int] * i... | def equation_of_time_pvcdrom(dayofyear):
"""
Equation of time from PVCDROM.
`PVCDROM`_ is a website by Solar Power Lab at Arizona State
University (ASU)
.. _PVCDROM: http://www.pveducation.org/pvcdrom/2-properties-sunlight/solar-time
Parameters
----------
dayofyear : numeric
Retu... |
def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = [
'image/',
]
mimetype = response.get('mimeType')
if not mimetype:
return True
for bw in blacklist:
if bw in mimetype:
return Fals... | def function[is_valid_mimetype, parameter[response]]:
constant[ Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
]
variable[blacklist] assign[=] list[[<ast.Constant object at 0x7da1b135b520>]]
variable[mimetype] assign[=] call[name[response].get, parameter[constant[mime... | keyword[def] identifier[is_valid_mimetype] ( identifier[response] ):
literal[string]
identifier[blacklist] =[
literal[string] ,
]
identifier[mimetype] = identifier[response] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[mimetype] :
keyword[return] ... | def is_valid_mimetype(response):
""" Return ``True`` if the mimetype is not blacklisted.
:rtype: bool
"""
blacklist = ['image/']
mimetype = response.get('mimeType')
if not mimetype:
return True # depends on [control=['if'], data=[]]
for bw in blacklist:
if bw in mimetype:
... |
def populate_device(dev):
"""! @brief Generates and populates the target defined by a CmsisPackDevice.
The new target class is added to the `#TARGET` list.
@param dev A CmsisPackDevice object.
"""
try:
tgt = PackTargets._generate_pack_target_class(dev)
i... | def function[populate_device, parameter[dev]]:
constant[! @brief Generates and populates the target defined by a CmsisPackDevice.
The new target class is added to the `#TARGET` list.
@param dev A CmsisPackDevice object.
]
<ast.Try object at 0x7da1b18ee5f0> | keyword[def] identifier[populate_device] ( identifier[dev] ):
literal[string]
keyword[try] :
identifier[tgt] = identifier[PackTargets] . identifier[_generate_pack_target_class] ( identifier[dev] )
keyword[if] identifier[tgt] keyword[is] keyword[None] :
... | def populate_device(dev):
"""! @brief Generates and populates the target defined by a CmsisPackDevice.
The new target class is added to the `#TARGET` list.
@param dev A CmsisPackDevice object.
"""
try:
tgt = PackTargets._generate_pack_target_class(dev)
if tgt is None:
... |
def create(self, to, from_, method=values.unset, fallback_url=values.unset,
fallback_method=values.unset, status_callback=values.unset,
status_callback_event=values.unset,
status_callback_method=values.unset, send_digits=values.unset,
timeout=values.unset, rec... | def function[create, parameter[self, to, from_, method, fallback_url, fallback_method, status_callback, status_callback_event, status_callback_method, send_digits, timeout, record, recording_channels, recording_status_callback, recording_status_callback_method, sip_auth_username, sip_auth_password, machine_detection, m... | keyword[def] identifier[create] ( identifier[self] , identifier[to] , identifier[from_] , identifier[method] = identifier[values] . identifier[unset] , identifier[fallback_url] = identifier[values] . identifier[unset] ,
identifier[fallback_method] = identifier[values] . identifier[unset] , identifier[status_callback... | def create(self, to, from_, method=values.unset, fallback_url=values.unset, fallback_method=values.unset, status_callback=values.unset, status_callback_event=values.unset, status_callback_method=values.unset, send_digits=values.unset, timeout=values.unset, record=values.unset, recording_channels=values.unset, recording... |
def msvc14_get_vc_env(plat_spec):
"""
Patched "distutils._msvccompiler._get_vc_env" for support extra
compilers.
Set environment without use of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 14.0:
Microsoft Visual C++ Build Tools 2015 (x86... | def function[msvc14_get_vc_env, parameter[plat_spec]]:
constant[
Patched "distutils._msvccompiler._get_vc_env" for support extra
compilers.
Set environment without use of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 14.0:
Microsoft V... | keyword[def] identifier[msvc14_get_vc_env] ( identifier[plat_spec] ):
literal[string]
keyword[try] :
keyword[return] identifier[get_unpatched] ( identifier[msvc14_get_vc_env] )( identifier[plat_spec] )
keyword[except] identifier[distutils] . identifier[errors] . identifier[DistutilsPla... | def msvc14_get_vc_env(plat_spec):
"""
Patched "distutils._msvccompiler._get_vc_env" for support extra
compilers.
Set environment without use of "vcvarsall.bat".
Known supported compilers
-------------------------
Microsoft Visual C++ 14.0:
Microsoft Visual C++ Build Tools 2015 (x86... |
def _unlockSim(self, pin):
""" Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """
# Unlock the SIM card if needed
try:
cpinResponse = lineStartingWith('+CPIN', self.write('AT+CPIN?', timeout=0.25))
except TimeoutException as timeout:
... | def function[_unlockSim, parameter[self, pin]]:
constant[ Unlocks the SIM card using the specified PIN (if necessary, else does nothing) ]
<ast.Try object at 0x7da18eb56440>
if compare[name[cpinResponse] not_equal[!=] constant[+CPIN: READY]] begin[:]
if compare[name[pin] not_equal[!=... | keyword[def] identifier[_unlockSim] ( identifier[self] , identifier[pin] ):
literal[string]
keyword[try] :
identifier[cpinResponse] = identifier[lineStartingWith] ( literal[string] , identifier[self] . identifier[write] ( literal[string] , identifier[timeout] = literal[int] ))... | def _unlockSim(self, pin):
""" Unlocks the SIM card using the specified PIN (if necessary, else does nothing) """
# Unlock the SIM card if needed
try:
cpinResponse = lineStartingWith('+CPIN', self.write('AT+CPIN?', timeout=0.25)) # depends on [control=['try'], data=[]]
except TimeoutException a... |
def grant_client(self, client_id):
"""
Grant the given client id all the scopes and authorities
needed to work with the access control service.
"""
zone = self.service.settings.data['zone']['oauth-scope']
scopes = ['openid', zone,
'acs.policies.read', '... | def function[grant_client, parameter[self, client_id]]:
constant[
Grant the given client id all the scopes and authorities
needed to work with the access control service.
]
variable[zone] assign[=] call[call[name[self].service.settings.data][constant[zone]]][constant[oauth-scope]... | keyword[def] identifier[grant_client] ( identifier[self] , identifier[client_id] ):
literal[string]
identifier[zone] = identifier[self] . identifier[service] . identifier[settings] . identifier[data] [ literal[string] ][ literal[string] ]
identifier[scopes] =[ literal[string] , identifier... | def grant_client(self, client_id):
"""
Grant the given client id all the scopes and authorities
needed to work with the access control service.
"""
zone = self.service.settings.data['zone']['oauth-scope']
scopes = ['openid', zone, 'acs.policies.read', 'acs.attributes.read', 'acs.poli... |
def check_address(address):
"""
verify that a string is a base58check address
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu')
True
>>> check_address('mk... | def function[check_address, parameter[address]]:
constant[
verify that a string is a base58check address
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu')
... | keyword[def] identifier[check_address] ( identifier[address] ):
literal[string]
keyword[if] keyword[not] identifier[check_string] ( identifier[address] , identifier[min_length] = literal[int] , identifier[max_length] = literal[int] , identifier[pattern] = identifier[OP_ADDRESS_PATTERN] ):
keywor... | def check_address(address):
"""
verify that a string is a base58check address
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJg')
True
>>> check_address('16EMaNw3pkn3v6f2BgnSSs53zAKH4Q8YJh')
False
>>> check_address('mkkJsS22dnDJhD8duFkpGnHNr9uz3JEcWu')
True
>>> check_address('mk... |
def generate_http_basic_token(username, password):
"""
Generates a HTTP basic token from username and password
Returns a token string (not a byte)
"""
token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8')
return token | def function[generate_http_basic_token, parameter[username, password]]:
constant[
Generates a HTTP basic token from username and password
Returns a token string (not a byte)
]
variable[token] assign[=] call[call[name[base64].b64encode, parameter[call[call[constant[{}:{}].format, parameter[n... | keyword[def] identifier[generate_http_basic_token] ( identifier[username] , identifier[password] ):
literal[string]
identifier[token] = identifier[base64] . identifier[b64encode] ( literal[string] . identifier[format] ( identifier[username] , identifier[password] ). identifier[encode] ( literal[string] )).... | def generate_http_basic_token(username, password):
"""
Generates a HTTP basic token from username and password
Returns a token string (not a byte)
"""
token = base64.b64encode('{}:{}'.format(username, password).encode('utf-8')).decode('utf-8')
return token |
def record_add_fields(rec, tag, fields, field_position_local=None,
field_position_global=None):
"""
Add the fields into the record at the required position.
The position is specified by the tag and the field_position_local in the
list of fields.
:param rec: a record structure... | def function[record_add_fields, parameter[rec, tag, fields, field_position_local, field_position_global]]:
constant[
Add the fields into the record at the required position.
The position is specified by the tag and the field_position_local in the
list of fields.
:param rec: a record structure
... | keyword[def] identifier[record_add_fields] ( identifier[rec] , identifier[tag] , identifier[fields] , identifier[field_position_local] = keyword[None] ,
identifier[field_position_global] = keyword[None] ):
literal[string]
keyword[if] identifier[field_position_local] keyword[is] keyword[None] keyword[a... | def record_add_fields(rec, tag, fields, field_position_local=None, field_position_global=None):
"""
Add the fields into the record at the required position.
The position is specified by the tag and the field_position_local in the
list of fields.
:param rec: a record structure
:param tag: the t... |
def get_blank_row(self, filler="-", splitter="+"):
"""Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
"""
return self.get_pretty_row(
... | def function[get_blank_row, parameter[self, filler, splitter]]:
constant[Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
]
return[call[name[se... | keyword[def] identifier[get_blank_row] ( identifier[self] , identifier[filler] = literal[string] , identifier[splitter] = literal[string] ):
literal[string]
keyword[return] identifier[self] . identifier[get_pretty_row] (
[ literal[string] keyword[for] identifier[_] keyword[in] identifi... | def get_blank_row(self, filler='-', splitter='+'):
"""Gets blank row
:param filler: Fill empty columns with this char
:param splitter: Separate columns with this char
:return: Pretty formatted blank row (with no meaningful data in it)
""" # blanks
# fill with this
# split c... |
def confirm(message: Text,
default: bool = True,
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
**kwargs: Any) -> Question:
"""Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
... | def function[confirm, parameter[message, default, qmark, style]]:
constant[Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
of a yes-or-no question. If the user just hits enter, the default
value will be returned.
Args:
... | keyword[def] identifier[confirm] ( identifier[message] : identifier[Text] ,
identifier[default] : identifier[bool] = keyword[True] ,
identifier[qmark] : identifier[Text] = identifier[DEFAULT_QUESTION_PREFIX] ,
identifier[style] : identifier[Optional] [ identifier[Style] ]= keyword[None] ,
** identifier[kwargs] : i... | def confirm(message: Text, default: bool=True, qmark: Text=DEFAULT_QUESTION_PREFIX, style: Optional[Style]=None, **kwargs: Any) -> Question:
"""Prompt the user to confirm or reject.
This question type can be used to prompt the user for a confirmation
of a yes-or-no question. If the user just hits ent... |
def detach_usage_plan_from_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None):
'''
Detaches given usage plan from each of the apis provided in a list of apiId and stage value
.. versionadded:: 2017.7.0
apis
a list of dictionaries, where each dictionary contains the following:... | def function[detach_usage_plan_from_apis, parameter[plan_id, apis, region, key, keyid, profile]]:
constant[
Detaches given usage plan from each of the apis provided in a list of apiId and stage value
.. versionadded:: 2017.7.0
apis
a list of dictionaries, where each dictionary contains the... | keyword[def] identifier[detach_usage_plan_from_apis] ( identifier[plan_id] , identifier[apis] , identifier[region] = keyword[None] , identifier[key] = keyword[None] , identifier[keyid] = keyword[None] , identifier[profile] = keyword[None] ):
literal[string]
keyword[return] identifier[_update_usage_plan_ap... | def detach_usage_plan_from_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None):
"""
Detaches given usage plan from each of the apis provided in a list of apiId and stage value
.. versionadded:: 2017.7.0
apis
a list of dictionaries, where each dictionary contains the following:... |
def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... | def function[set_data_matrix_chunk_size, parameter[df_shape, max_chunk_kb, elem_per_kb]]:
constant[
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chun... | keyword[def] identifier[set_data_matrix_chunk_size] ( identifier[df_shape] , identifier[max_chunk_kb] , identifier[elem_per_kb] ):
literal[string]
identifier[row_chunk_size] = identifier[min] ( identifier[df_shape] [ literal[int] ], literal[int] )
identifier[col_chunk_size] = identifier[min] ((( ident... | def set_data_matrix_chunk_size(df_shape, max_chunk_kb, elem_per_kb):
"""
Sets chunk size to use for writing data matrix.
Note. Calculation used here is for compatibility with cmapM and cmapR.
Input:
- df_shape (tuple): shape of input data_df.
- max_chunk_kb (int, default=1024): The m... |
def resolve_slashed(self, path):
""" Resolve symlinked directories if they end in a '/',
remove trailing '/' otherwise.
"""
if path.endswith(os.sep):
path = path.rstrip(os.sep)
if os.path.islink(path):
real = os.path.realpath(path)
... | def function[resolve_slashed, parameter[self, path]]:
constant[ Resolve symlinked directories if they end in a '/',
remove trailing '/' otherwise.
]
if call[name[path].endswith, parameter[name[os].sep]] begin[:]
variable[path] assign[=] call[name[path].rstrip, paramet... | keyword[def] identifier[resolve_slashed] ( identifier[self] , identifier[path] ):
literal[string]
keyword[if] identifier[path] . identifier[endswith] ( identifier[os] . identifier[sep] ):
identifier[path] = identifier[path] . identifier[rstrip] ( identifier[os] . identifier[sep] )
... | def resolve_slashed(self, path):
""" Resolve symlinked directories if they end in a '/',
remove trailing '/' otherwise.
"""
if path.endswith(os.sep):
path = path.rstrip(os.sep)
if os.path.islink(path):
real = os.path.realpath(path)
self.LOG.debug('Reso... |
def factory(cls, note, fn=None):
"""Register a function as a provider.
Function (name support is optional)::
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector(BaseInjector):
pass
@Injector.factory('echo'... | def function[factory, parameter[cls, note, fn]]:
constant[Register a function as a provider.
Function (name support is optional)::
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector(BaseInjector):
pass
@I... | keyword[def] identifier[factory] ( identifier[cls] , identifier[note] , identifier[fn] = keyword[None] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[f] ):
identifier[provider] = identifier[cls] . identifier[factory_provider] . identifier[bind] ( identifier[f] )
... | def factory(cls, note, fn=None):
"""Register a function as a provider.
Function (name support is optional)::
from jeni import Injector as BaseInjector
from jeni import Provider
class Injector(BaseInjector):
pass
@Injector.factory('echo')
... |
def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('main')) | def function[unauth, parameter[request]]:
constant[
logout and remove all session data
]
if call[name[check_key], parameter[name[request]]] begin[:]
variable[api] assign[=] call[name[get_api], parameter[name[request]]]
call[name[request].session.clear, parameter[]... | keyword[def] identifier[unauth] ( identifier[request] ):
literal[string]
keyword[if] identifier[check_key] ( identifier[request] ):
identifier[api] = identifier[get_api] ( identifier[request] )
identifier[request] . identifier[session] . identifier[clear] ()
identifier[logout] (... | def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request) # depends on [control=['if'], data=[]]
return HttpResponseRedirect(reverse('main')) |
def getRankMaps(self):
"""
Returns a list of dictionaries, one for each preference, that associates the integer
representation of each candidate with its position in the ranking, starting from 1 and
returns a list of the number of times each preference is given.
"""
ran... | def function[getRankMaps, parameter[self]]:
constant[
Returns a list of dictionaries, one for each preference, that associates the integer
representation of each candidate with its position in the ranking, starting from 1 and
returns a list of the number of times each preference is give... | keyword[def] identifier[getRankMaps] ( identifier[self] ):
literal[string]
identifier[rankMaps] =[]
keyword[for] identifier[preference] keyword[in] identifier[self] . identifier[preferences] :
identifier[rankMaps] . identifier[append] ( identifier[preference] . identifier[... | def getRankMaps(self):
"""
Returns a list of dictionaries, one for each preference, that associates the integer
representation of each candidate with its position in the ranking, starting from 1 and
returns a list of the number of times each preference is given.
"""
rankMaps = [... |
def execute_rex_code(self, code, filename=None, shell=None,
parent_environ=None, **Popen_args):
"""Run some rex code in the context.
Note:
This is just a convenience form of `execute_shell`.
Args:
code (str): Rex code to execute.
fil... | def function[execute_rex_code, parameter[self, code, filename, shell, parent_environ]]:
constant[Run some rex code in the context.
Note:
This is just a convenience form of `execute_shell`.
Args:
code (str): Rex code to execute.
filename (str): Filename to re... | keyword[def] identifier[execute_rex_code] ( identifier[self] , identifier[code] , identifier[filename] = keyword[None] , identifier[shell] = keyword[None] ,
identifier[parent_environ] = keyword[None] ,** identifier[Popen_args] ):
literal[string]
keyword[def] identifier[_actions_callback] ( identi... | def execute_rex_code(self, code, filename=None, shell=None, parent_environ=None, **Popen_args):
"""Run some rex code in the context.
Note:
This is just a convenience form of `execute_shell`.
Args:
code (str): Rex code to execute.
filename (str): Filename to repo... |
def add_cert(self, cert):
"""
Explicitely adds certificate to set of trusted in the store
@param cert - X509 object to add
"""
if not isinstance(cert, X509):
raise TypeError("cert should be X509")
libcrypto.X509_STORE_add_cert(self.store, cert.cert) | def function[add_cert, parameter[self, cert]]:
constant[
Explicitely adds certificate to set of trusted in the store
@param cert - X509 object to add
]
if <ast.UnaryOp object at 0x7da1b28b8730> begin[:]
<ast.Raise object at 0x7da1b28ae560>
call[name[libcrypto].X50... | keyword[def] identifier[add_cert] ( identifier[self] , identifier[cert] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[cert] , identifier[X509] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[libcrypto] . identifier[X5... | def add_cert(self, cert):
"""
Explicitely adds certificate to set of trusted in the store
@param cert - X509 object to add
"""
if not isinstance(cert, X509):
raise TypeError('cert should be X509') # depends on [control=['if'], data=[]]
libcrypto.X509_STORE_add_cert(self.stor... |
def create_cells(self, blocks):
"""Turn the list of blocks into a list of notebook cells."""
cells = []
for block in blocks:
if (block['type'] == self.code) and (block['IO'] == 'input'):
code_cell = self.create_code_cell(block)
cells.append(code_cell)
... | def function[create_cells, parameter[self, blocks]]:
constant[Turn the list of blocks into a list of notebook cells.]
variable[cells] assign[=] list[[]]
for taget[name[block]] in starred[name[blocks]] begin[:]
if <ast.BoolOp object at 0x7da1b1218e20> begin[:]
... | keyword[def] identifier[create_cells] ( identifier[self] , identifier[blocks] ):
literal[string]
identifier[cells] =[]
keyword[for] identifier[block] keyword[in] identifier[blocks] :
keyword[if] ( identifier[block] [ literal[string] ]== identifier[self] . identifier[code] )... | def create_cells(self, blocks):
"""Turn the list of blocks into a list of notebook cells."""
cells = []
for block in blocks:
if block['type'] == self.code and block['IO'] == 'input':
code_cell = self.create_code_cell(block)
cells.append(code_cell) # depends on [control=['if'... |
def single(self):
"""
Fetch one of the related nodes
:return: Node
"""
nodes = super(OneOrMore, self).all()
if nodes:
return nodes[0]
raise CardinalityViolation(self, 'none') | def function[single, parameter[self]]:
constant[
Fetch one of the related nodes
:return: Node
]
variable[nodes] assign[=] call[call[name[super], parameter[name[OneOrMore], name[self]]].all, parameter[]]
if name[nodes] begin[:]
return[call[name[nodes]][constant[0]... | keyword[def] identifier[single] ( identifier[self] ):
literal[string]
identifier[nodes] = identifier[super] ( identifier[OneOrMore] , identifier[self] ). identifier[all] ()
keyword[if] identifier[nodes] :
keyword[return] identifier[nodes] [ literal[int] ]
keyword[ra... | def single(self):
"""
Fetch one of the related nodes
:return: Node
"""
nodes = super(OneOrMore, self).all()
if nodes:
return nodes[0] # depends on [control=['if'], data=[]]
raise CardinalityViolation(self, 'none') |
def _expr2sat(ex, litmap): # pragma: no cover
"""Convert an expression to a DIMACS SAT string."""
if isinstance(ex, Literal):
return str(litmap[ex])
elif isinstance(ex, NotOp):
return "-(" + _expr2sat(ex.x, litmap) + ")"
elif isinstance(ex, OrOp):
return "+(" + " ".join(_expr2sat... | def function[_expr2sat, parameter[ex, litmap]]:
constant[Convert an expression to a DIMACS SAT string.]
if call[name[isinstance], parameter[name[ex], name[Literal]]] begin[:]
return[call[name[str], parameter[call[name[litmap]][name[ex]]]]] | keyword[def] identifier[_expr2sat] ( identifier[ex] , identifier[litmap] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[ex] , identifier[Literal] ):
keyword[return] identifier[str] ( identifier[litmap] [ identifier[ex] ])
keyword[elif] identifier[isinstance] ( identifie... | def _expr2sat(ex, litmap): # pragma: no cover
'Convert an expression to a DIMACS SAT string.'
if isinstance(ex, Literal):
return str(litmap[ex]) # depends on [control=['if'], data=[]]
elif isinstance(ex, NotOp):
return '-(' + _expr2sat(ex.x, litmap) + ')' # depends on [control=['if'], dat... |
def create_parser(self, prog_name, subcommand):
"""
Create argument parser and deal with ``add_arguments``.
This method should not be overriden.
:param prog_name: Name of the command (argv[0])
:return: ArgumentParser
"""
parser = argparse.ArgumentParser(p... | def function[create_parser, parameter[self, prog_name, subcommand]]:
constant[
Create argument parser and deal with ``add_arguments``.
This method should not be overriden.
:param prog_name: Name of the command (argv[0])
:return: ArgumentParser
]
variable[parser] ... | keyword[def] identifier[create_parser] ( identifier[self] , identifier[prog_name] , identifier[subcommand] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[prog_name] , identifier[subcommand] )
identifier[self] . identifier... | def create_parser(self, prog_name, subcommand):
"""
Create argument parser and deal with ``add_arguments``.
This method should not be overriden.
:param prog_name: Name of the command (argv[0])
:return: ArgumentParser
"""
parser = argparse.ArgumentParser(prog_name, subcom... |
def execute_put(self, resource, **kwargs):
"""
Execute an HTTP PUT request against the API endpoints.
This method is meant for internal use.
:param resource: The last part of the URI
:param kwargs: Additional parameters for the HTTP call (`request` library)
:return: The ... | def function[execute_put, parameter[self, resource]]:
constant[
Execute an HTTP PUT request against the API endpoints.
This method is meant for internal use.
:param resource: The last part of the URI
:param kwargs: Additional parameters for the HTTP call (`request` library)
... | keyword[def] identifier[execute_put] ( identifier[self] , identifier[resource] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[_request] ( identifier[resource] , identifier[requests] . identifier[put] ,** identifier[kwargs] ). identifier[json] () | def execute_put(self, resource, **kwargs):
"""
Execute an HTTP PUT request against the API endpoints.
This method is meant for internal use.
:param resource: The last part of the URI
:param kwargs: Additional parameters for the HTTP call (`request` library)
:return: The HTTP... |
def strip_columns(tab):
"""Strip whitespace from string columns."""
for colname in tab.colnames:
if tab[colname].dtype.kind in ['S', 'U']:
tab[colname] = np.core.defchararray.strip(tab[colname]) | def function[strip_columns, parameter[tab]]:
constant[Strip whitespace from string columns.]
for taget[name[colname]] in starred[name[tab].colnames] begin[:]
if compare[call[name[tab]][name[colname]].dtype.kind in list[[<ast.Constant object at 0x7da18eb55270>, <ast.Constant object at 0x7... | keyword[def] identifier[strip_columns] ( identifier[tab] ):
literal[string]
keyword[for] identifier[colname] keyword[in] identifier[tab] . identifier[colnames] :
keyword[if] identifier[tab] [ identifier[colname] ]. identifier[dtype] . identifier[kind] keyword[in] [ literal[string] , literal[s... | def strip_columns(tab):
"""Strip whitespace from string columns."""
for colname in tab.colnames:
if tab[colname].dtype.kind in ['S', 'U']:
tab[colname] = np.core.defchararray.strip(tab[colname]) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['colname']] |
def sanitize(meta, diagnostics=False):
""" Try to fix common problems, especially transcode non-standard string encodings.
"""
bad_encodings, bad_fields = set(), set()
def sane_encoding(field, text):
"Transcoding helper."
for encoding in ('utf-8', meta.get('encoding', None), 'cp1252'):
... | def function[sanitize, parameter[meta, diagnostics]]:
constant[ Try to fix common problems, especially transcode non-standard string encodings.
]
<ast.Tuple object at 0x7da18ede4d30> assign[=] tuple[[<ast.Call object at 0x7da18ede6710>, <ast.Call object at 0x7da18ede5600>]]
def function[sane... | keyword[def] identifier[sanitize] ( identifier[meta] , identifier[diagnostics] = keyword[False] ):
literal[string]
identifier[bad_encodings] , identifier[bad_fields] = identifier[set] (), identifier[set] ()
keyword[def] identifier[sane_encoding] ( identifier[field] , identifier[text] ):
lit... | def sanitize(meta, diagnostics=False):
""" Try to fix common problems, especially transcode non-standard string encodings.
"""
(bad_encodings, bad_fields) = (set(), set())
def sane_encoding(field, text):
"""Transcoding helper."""
for encoding in ('utf-8', meta.get('encoding', None), 'cp... |
def fmt_ces(c, title=None):
"""Format a |CauseEffectStructure|."""
if not c:
return '()\n'
if title is None:
title = 'Cause-effect structure'
concepts = '\n'.join(margin(x) for x in c) + '\n'
title = '{} ({} concept{})'.format(
title, len(c), '' if len(c) == 1 else 's')
... | def function[fmt_ces, parameter[c, title]]:
constant[Format a |CauseEffectStructure|.]
if <ast.UnaryOp object at 0x7da1b23466b0> begin[:]
return[constant[()
]]
if compare[name[title] is constant[None]] begin[:]
variable[title] assign[=] constant[Cause-effect structure]
... | keyword[def] identifier[fmt_ces] ( identifier[c] , identifier[title] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[c] :
keyword[return] literal[string]
keyword[if] identifier[title] keyword[is] keyword[None] :
identifier[title] = literal[string]
... | def fmt_ces(c, title=None):
"""Format a |CauseEffectStructure|."""
if not c:
return '()\n' # depends on [control=['if'], data=[]]
if title is None:
title = 'Cause-effect structure' # depends on [control=['if'], data=['title']]
concepts = '\n'.join((margin(x) for x in c)) + '\n'
tit... |
async def generate_waifu_insult(self, avatar):
"""Generate a waifu insult image.
This function is a coroutine.
Parameters:
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
Return Type: image data"""
if not i... | <ast.AsyncFunctionDef object at 0x7da18ede7310> | keyword[async] keyword[def] identifier[generate_waifu_insult] ( identifier[self] , identifier[avatar] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[avatar] , identifier[str] ):
keyword[raise] identifier[TypeError] ( literal[string] )
keywo... | async def generate_waifu_insult(self, avatar):
"""Generate a waifu insult image.
This function is a coroutine.
Parameters:
avatar: str - http/s url pointing to an image, has to have proper headers and be a direct link to an image
Return Type: image data"""
if not isinstanc... |
def bake(src):
"""
Runs the encoder on the given source file
"""
src = os.path.realpath(src)
path = os.path.dirname(src)
filename = os.path.basename(src)
html = _load_file(src).read()
if imghdr.what("", html):
html = "<html><body><img src='{}'/></body></html>".format(cgi.escape(f... | def function[bake, parameter[src]]:
constant[
Runs the encoder on the given source file
]
variable[src] assign[=] call[name[os].path.realpath, parameter[name[src]]]
variable[path] assign[=] call[name[os].path.dirname, parameter[name[src]]]
variable[filename] assign[=] call[name[o... | keyword[def] identifier[bake] ( identifier[src] ):
literal[string]
identifier[src] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[src] )
identifier[path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[src] )
identifier[filename] = identifier[os] . ... | def bake(src):
"""
Runs the encoder on the given source file
"""
src = os.path.realpath(src)
path = os.path.dirname(src)
filename = os.path.basename(src)
html = _load_file(src).read()
if imghdr.what('', html):
html = "<html><body><img src='{}'/></body></html>".format(cgi.escape(f... |
def generate_enums(outf, enums, msgs):
"""Iterate through all enums and create Swift equivalents"""
print("Generating Enums")
for enum in enums:
t.write(outf, """
${formatted_description}public enum ${swift_name}: ${raw_value_type}, Enum {
${{entry:${formatted_description}\tcase ${swift_name} = ${... | def function[generate_enums, parameter[outf, enums, msgs]]:
constant[Iterate through all enums and create Swift equivalents]
call[name[print], parameter[constant[Generating Enums]]]
for taget[name[enum]] in starred[name[enums]] begin[:]
call[name[t].write, parameter[name[outf], c... | keyword[def] identifier[generate_enums] ( identifier[outf] , identifier[enums] , identifier[msgs] ):
literal[string]
identifier[print] ( literal[string] )
keyword[for] identifier[enum] keyword[in] identifier[enums] :
identifier[t] . identifier[write] ( identifier[outf] , literal[string] ... | def generate_enums(outf, enums, msgs):
"""Iterate through all enums and create Swift equivalents"""
print('Generating Enums')
for enum in enums:
t.write(outf, '\n${formatted_description}public enum ${swift_name}: ${raw_value_type}, Enum {\n${{entry:${formatted_description}\tcase ${swift_name} = ${va... |
def rgb_to_hex(cls, color):
"""
Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
Example:
>... | def function[rgb_to_hex, parameter[cls, color]]:
constant[
Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
... | keyword[def] identifier[rgb_to_hex] ( identifier[cls] , identifier[color] ):
literal[string]
keyword[return] literal[string] . identifier[format] (
identifier[cls] . identifier[_bound_color_value] ( identifier[color] [ literal[int] ]),
identifier[cls] . identifier[_bound_color_va... | def rgb_to_hex(cls, color):
"""
Convert an ``(r, g, b)`` color tuple to a hexadecimal string.
Alphabetical characters in the output will be capitalized.
Args:
color (tuple): An rgb color tuple of form: (int, int, int)
Returns: string
Example:
>>> S... |
def recv(self, x=BPF_BUFFER_LENGTH):
"""Receive a frame from the network"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame()
# Get data from BPF
try:
bpf_buffer = os.read(self.ins, x)
except EnvironmentError as... | def function[recv, parameter[self, x]]:
constant[Receive a frame from the network]
if call[name[self].buffered_frames, parameter[]] begin[:]
return[call[name[self].get_frame, parameter[]]]
<ast.Try object at 0x7da1b1fc9420>
call[name[self].extract_frames, parameter[name[bpf_buffer]]]... | keyword[def] identifier[recv] ( identifier[self] , identifier[x] = identifier[BPF_BUFFER_LENGTH] ):
literal[string]
keyword[if] identifier[self] . identifier[buffered_frames] ():
keyword[return] identifier[self] . identifier[get_frame] ()
keyword[try]... | def recv(self, x=BPF_BUFFER_LENGTH):
"""Receive a frame from the network"""
if self.buffered_frames():
# Get a frame from the buffer
return self.get_frame() # depends on [control=['if'], data=[]]
# Get data from BPF
try:
bpf_buffer = os.read(self.ins, x) # depends on [control=[... |
def firmware_download_input_protocol_type_sftp_protocol_sftp_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
input = ET.SubElement(firmware_download, "input")... | def function[firmware_download_input_protocol_type_sftp_protocol_sftp_password, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[firmware_download] assign[=] call[name[ET].Element, parameter[constant[... | keyword[def] identifier[firmware_download_input_protocol_type_sftp_protocol_sftp_password] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[firmware_download] = identifier[ET] . identifier[... | def firmware_download_input_protocol_type_sftp_protocol_sftp_password(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
firmware_download = ET.Element('firmware_download')
config = firmware_download
input = ET.SubElement(firmware_download, 'input')
protocol_type =... |
def append_position(path, position, separator=''):
"""
Concatenate a path and a position,
between the filename and the extension.
"""
filename, extension = os.path.splitext(path)
return ''.join([filename, separator, str(position), extension]) | def function[append_position, parameter[path, position, separator]]:
constant[
Concatenate a path and a position,
between the filename and the extension.
]
<ast.Tuple object at 0x7da1b1d35150> assign[=] call[name[os].path.splitext, parameter[name[path]]]
return[call[constant[].join, para... | keyword[def] identifier[append_position] ( identifier[path] , identifier[position] , identifier[separator] = literal[string] ):
literal[string]
identifier[filename] , identifier[extension] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[path] )
keyword[return] literal[string] ... | def append_position(path, position, separator=''):
"""
Concatenate a path and a position,
between the filename and the extension.
"""
(filename, extension) = os.path.splitext(path)
return ''.join([filename, separator, str(position), extension]) |
def add(self, media, filepath, overwrite=True):
"""Set *media* from local file *filepath*. *overwrite* parameter specify
if the media must be overwrite if it exists remotely.
"""
with open(filepath, 'rb') as fhandler:
self._dokuwiki.send('wiki.putAttachment', media,
... | def function[add, parameter[self, media, filepath, overwrite]]:
constant[Set *media* from local file *filepath*. *overwrite* parameter specify
if the media must be overwrite if it exists remotely.
]
with call[name[open], parameter[name[filepath], constant[rb]]] begin[:]
c... | keyword[def] identifier[add] ( identifier[self] , identifier[media] , identifier[filepath] , identifier[overwrite] = keyword[True] ):
literal[string]
keyword[with] identifier[open] ( identifier[filepath] , literal[string] ) keyword[as] identifier[fhandler] :
identifier[self] . identi... | def add(self, media, filepath, overwrite=True):
"""Set *media* from local file *filepath*. *overwrite* parameter specify
if the media must be overwrite if it exists remotely.
"""
with open(filepath, 'rb') as fhandler:
self._dokuwiki.send('wiki.putAttachment', media, Binary(fhandler.read(... |
def _plot(self):
"""Plot stacked serie lines and stacked secondary lines"""
for serie in self.series[::-1 if self.stack_from_top else 1]:
self.line(serie)
for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:
self.line(serie, True) | def function[_plot, parameter[self]]:
constant[Plot stacked serie lines and stacked secondary lines]
for taget[name[serie]] in starred[call[name[self].series][<ast.Slice object at 0x7da18f811750>]] begin[:]
call[name[self].line, parameter[name[serie]]]
for taget[name[serie]] in s... | keyword[def] identifier[_plot] ( identifier[self] ):
literal[string]
keyword[for] identifier[serie] keyword[in] identifier[self] . identifier[series] [::- literal[int] keyword[if] identifier[self] . identifier[stack_from_top] keyword[else] literal[int] ]:
identifier[self] . iden... | def _plot(self):
"""Plot stacked serie lines and stacked secondary lines"""
for serie in self.series[::-1 if self.stack_from_top else 1]:
self.line(serie) # depends on [control=['for'], data=['serie']]
for serie in self.secondary_series[::-1 if self.stack_from_top else 1]:
self.line(serie, ... |
def _construct_production_name(glyph_name, data=None):
"""Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and... | def function[_construct_production_name, parameter[glyph_name, data]]:
constant[Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single gly... | keyword[def] identifier[_construct_production_name] ( identifier[glyph_name] , identifier[data] = keyword[None] ):
literal[string]
identifier[base_name] , identifier[dot] , identifier[suffix] = identifier[glyph_name] . identifier[partition] ( literal[string] )
identifier[glyphinfo] = identi... | def _construct_production_name(glyph_name, data=None):
"""Return the production name for a glyph name from the GlyphData.xml
database according to the AGL specification.
This should be run only if there is no official entry with a production
name in it.
Handles single glyphs (e.g. "brevecomb") and... |
def deps_used(self, pkg, used):
"""Create dependencies dictionary
"""
if find_package(pkg + self.meta.sp, self.meta.pkg_path):
if pkg not in self.deps_dict.values():
self.deps_dict[pkg] = used
else:
self.deps_dict[pkg] += used | def function[deps_used, parameter[self, pkg, used]]:
constant[Create dependencies dictionary
]
if call[name[find_package], parameter[binary_operation[name[pkg] + name[self].meta.sp], name[self].meta.pkg_path]] begin[:]
if compare[name[pkg] <ast.NotIn object at 0x7da2590d7190> cal... | keyword[def] identifier[deps_used] ( identifier[self] , identifier[pkg] , identifier[used] ):
literal[string]
keyword[if] identifier[find_package] ( identifier[pkg] + identifier[self] . identifier[meta] . identifier[sp] , identifier[self] . identifier[meta] . identifier[pkg_path] ):
k... | def deps_used(self, pkg, used):
"""Create dependencies dictionary
"""
if find_package(pkg + self.meta.sp, self.meta.pkg_path):
if pkg not in self.deps_dict.values():
self.deps_dict[pkg] = used # depends on [control=['if'], data=['pkg']]
else:
self.deps_dict[pkg] ... |
def logarithm(requestContext, seriesList, base=10):
"""
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in
logarithmic format. If base is omitted, the function defaults to base 10.
Example::
&target=log(carbon.agents.hostname.avgUpdateTime,2)
"""
results = []
... | def function[logarithm, parameter[requestContext, seriesList, base]]:
constant[
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in
logarithmic format. If base is omitted, the function defaults to base 10.
Example::
&target=log(carbon.agents.hostname.avgUpdateTime,2)... | keyword[def] identifier[logarithm] ( identifier[requestContext] , identifier[seriesList] , identifier[base] = literal[int] ):
literal[string]
identifier[results] =[]
keyword[for] identifier[series] keyword[in] identifier[seriesList] :
identifier[newValues] =[]
keyword[for] identi... | def logarithm(requestContext, seriesList, base=10):
"""
Takes one metric or a wildcard seriesList, a base, and draws the y-axis in
logarithmic format. If base is omitted, the function defaults to base 10.
Example::
&target=log(carbon.agents.hostname.avgUpdateTime,2)
"""
results = []
... |
def _versioned_lib_suffix(env, suffix, version):
"""Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
Verbose = False
if Verbose:
print("_versioned_lib_suffix: suffix= ", suffix)
print("_versioned_li... | def function[_versioned_lib_suffix, parameter[env, suffix, version]]:
constant[Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll']
variable[Verbose] assign[=] constant[False]
if name[Verbose] begin[:]
... | keyword[def] identifier[_versioned_lib_suffix] ( identifier[env] , identifier[suffix] , identifier[version] ):
literal[string]
identifier[Verbose] = keyword[False]
keyword[if] identifier[Verbose] :
identifier[print] ( literal[string] , identifier[suffix] )
identifier[print] ( liter... | def _versioned_lib_suffix(env, suffix, version):
"""Generate versioned shared library suffix from a unversioned one.
If suffix='.dll', and version='0.1.2', then it returns '-0-1-2.dll'"""
Verbose = False
if Verbose:
print('_versioned_lib_suffix: suffix= ', suffix)
print('_versioned_li... |
def normalize_strategy_parameters(params):
"""Normalize strategy parameters to be a list of strings.
Parameters
----------
params : (space-delimited) string or sequence of strings/numbers Parameters
expected by :class:`SampleStrategy` object, in various forms, where the first
parameter ... | def function[normalize_strategy_parameters, parameter[params]]:
constant[Normalize strategy parameters to be a list of strings.
Parameters
----------
params : (space-delimited) string or sequence of strings/numbers Parameters
expected by :class:`SampleStrategy` object, in various forms, whe... | keyword[def] identifier[normalize_strategy_parameters] ( identifier[params] ):
literal[string]
keyword[def] identifier[fixup_numbers] ( identifier[val] ):
keyword[try] :
keyword[return] identifier[str] ( identifier[float] ( identifier[val] ))
keyword[except] ident... | def normalize_strategy_parameters(params):
"""Normalize strategy parameters to be a list of strings.
Parameters
----------
params : (space-delimited) string or sequence of strings/numbers Parameters
expected by :class:`SampleStrategy` object, in various forms, where the first
parameter ... |
def login_oauth2_user(valid, oauth):
"""Log in a user after having been verified."""
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(),
identity=Identity(oauth.user.i... | def function[login_oauth2_user, parameter[valid, oauth]]:
constant[Log in a user after having been verified.]
if name[valid] begin[:]
name[oauth].user.login_via_oauth2 assign[=] constant[True]
name[_request_ctx_stack].top.user assign[=] name[oauth].user
ca... | keyword[def] identifier[login_oauth2_user] ( identifier[valid] , identifier[oauth] ):
literal[string]
keyword[if] identifier[valid] :
identifier[oauth] . identifier[user] . identifier[login_via_oauth2] = keyword[True]
identifier[_request_ctx_stack] . identifier[top] . identifier[user] =... | def login_oauth2_user(valid, oauth):
"""Log in a user after having been verified."""
if valid:
oauth.user.login_via_oauth2 = True
_request_ctx_stack.top.user = oauth.user
identity_changed.send(current_app._get_current_object(), identity=Identity(oauth.user.id)) # depends on [control=['i... |
def _set_association(self, v, load=False):
"""
Setter method for association, mapped from YANG variable /interface/port_channel/switchport/private_vlan/association (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_association is considered as a private
meth... | def function[_set_association, parameter[self, v, load]]:
constant[
Setter method for association, mapped from YANG variable /interface/port_channel/switchport/private_vlan/association (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_association is conside... | keyword[def] identifier[_set_association] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_association(self, v, load=False):
"""
Setter method for association, mapped from YANG variable /interface/port_channel/switchport/private_vlan/association (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_association is considered as a private
meth... |
def add_x10_device(self, housecode, unitcode, dev_type):
"""Add an X10 device to the PLM."""
device = None
try:
device = self.plm.devices.add_x10_device(self.plm, housecode,
unitcode, dev_type)
except ValueError:
... | def function[add_x10_device, parameter[self, housecode, unitcode, dev_type]]:
constant[Add an X10 device to the PLM.]
variable[device] assign[=] constant[None]
<ast.Try object at 0x7da1b1a44d90>
return[name[device]] | keyword[def] identifier[add_x10_device] ( identifier[self] , identifier[housecode] , identifier[unitcode] , identifier[dev_type] ):
literal[string]
identifier[device] = keyword[None]
keyword[try] :
identifier[device] = identifier[self] . identifier[plm] . identifier[devices] ... | def add_x10_device(self, housecode, unitcode, dev_type):
"""Add an X10 device to the PLM."""
device = None
try:
device = self.plm.devices.add_x10_device(self.plm, housecode, unitcode, dev_type) # depends on [control=['try'], data=[]]
except ValueError:
pass # depends on [control=['exce... |
def units(cls, scale=1):
'''
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
'''
return [cls(x=scale), cls(y=scale), ... | def function[units, parameter[cls, scale]]:
constant[
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
]
return[list[[<ast... | keyword[def] identifier[units] ( identifier[cls] , identifier[scale] = literal[int] ):
literal[string]
keyword[return] [ identifier[cls] ( identifier[x] = identifier[scale] ), identifier[cls] ( identifier[y] = identifier[scale] ), identifier[cls] ( identifier[z] = identifier[scale] )] | def units(cls, scale=1):
"""
:scale: optional integer scaling factor
:return: list of three Point subclass
Returns three points whose coordinates are the head of a
unit vector from the origin ( conventionally i, j and k).
"""
return [cls(x=scale), cls(y=scale), cls(z=sc... |
def connected(self, *, presence=structs.PresenceState(False), **kwargs):
"""
Return a :class:`.node.UseConnected` context manager which does not
modify the presence settings.
The keyword arguments are passed to the :class:`.node.UseConnected`
context manager constructor.
... | def function[connected, parameter[self]]:
constant[
Return a :class:`.node.UseConnected` context manager which does not
modify the presence settings.
The keyword arguments are passed to the :class:`.node.UseConnected`
context manager constructor.
.. versionadded:: 0.8
... | keyword[def] identifier[connected] ( identifier[self] ,*, identifier[presence] = identifier[structs] . identifier[PresenceState] ( keyword[False] ),** identifier[kwargs] ):
literal[string]
keyword[return] identifier[UseConnected] ( identifier[self] , identifier[presence] = identifier[presence] ,**... | def connected(self, *, presence=structs.PresenceState(False), **kwargs):
"""
Return a :class:`.node.UseConnected` context manager which does not
modify the presence settings.
The keyword arguments are passed to the :class:`.node.UseConnected`
context manager constructor.
..... |
def rate_overall(self):
"""Returns the overall average rate based on the start time."""
elapsed = self.elapsed
return self.rate if not elapsed else self.numerator / self.elapsed | def function[rate_overall, parameter[self]]:
constant[Returns the overall average rate based on the start time.]
variable[elapsed] assign[=] name[self].elapsed
return[<ast.IfExp object at 0x7da18f09e2f0>] | keyword[def] identifier[rate_overall] ( identifier[self] ):
literal[string]
identifier[elapsed] = identifier[self] . identifier[elapsed]
keyword[return] identifier[self] . identifier[rate] keyword[if] keyword[not] identifier[elapsed] keyword[else] identifier[self] . identifier[numer... | def rate_overall(self):
"""Returns the overall average rate based on the start time."""
elapsed = self.elapsed
return self.rate if not elapsed else self.numerator / self.elapsed |
def _transition(self, duration, brightness):
""" Complete a transition.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
"""
# Set initial value.
b_start = self.brightness
# Compute ideal step amount.
b_steps = 0
... | def function[_transition, parameter[self, duration, brightness]]:
constant[ Complete a transition.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
]
variable[b_start] assign[=] name[self].brightness
variable[b_steps] assign[=] c... | keyword[def] identifier[_transition] ( identifier[self] , identifier[duration] , identifier[brightness] ):
literal[string]
identifier[b_start] = identifier[self] . identifier[brightness]
identifier[b_steps] = literal[int]
keyword[if] identifier[brightness] ke... | def _transition(self, duration, brightness):
""" Complete a transition.
:param duration: Duration of transition.
:param brightness: Transition to this brightness.
"""
# Set initial value.
b_start = self.brightness
# Compute ideal step amount.
b_steps = 0
if brightness is... |
def _dspace(
irez,
d2201, d2211, d3210, d3222, d4410,
d4422, d5220, d5232, d5421, d5433,
dedt, del1, del2, del3, didt,
dmdt, dnodt, domdt, argpo, argpdot,
t, tc, gsto, xfact, xlamo,
no,
atime, em, argpm, inclm, xli,
... | def function[_dspace, parameter[irez, d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433, dedt, del1, del2, del3, didt, dmdt, dnodt, domdt, argpo, argpdot, t, tc, gsto, xfact, xlamo, no, atime, em, argpm, inclm, xli, mm, xni, nodem, nm]]:
variable[fasx2] assign[=] constant[0.13130908]
... | keyword[def] identifier[_dspace] (
identifier[irez] ,
identifier[d2201] , identifier[d2211] , identifier[d3210] , identifier[d3222] , identifier[d4410] ,
identifier[d4422] , identifier[d5220] , identifier[d5232] , identifier[d5421] , identifier[d5433] ,
identifier[dedt] , identifier[del1] , identifier[del2] , ide... | def _dspace(irez, d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433, dedt, del1, del2, del3, didt, dmdt, dnodt, domdt, argpo, argpdot, t, tc, gsto, xfact, xlamo, no, atime, em, argpm, inclm, xli, mm, xni, nodem, nm):
fasx2 = 0.13130908
fasx4 = 2.8843198
fasx6 = 0.37448087
g22 = 5.7686... |
def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) | def function[set_identifier, parameter[self, uid]]:
constant[
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
]
name[self].uid assign[=] name[uid]
call[name[self].set_unique_metadata, parameter[constant[DC], constant[identifi... | keyword[def] identifier[set_identifier] ( identifier[self] , identifier[uid] ):
literal[string]
identifier[self] . identifier[uid] = identifier[uid]
identifier[self] . identifier[set_unique_metadata] ( literal[string] , literal[string] , identifier[self] . identifier[uid] ,{ literal[str... | def set_identifier(self, uid):
"""
Sets unique id for this epub
:Args:
- uid: Value of unique identifier for this book
"""
self.uid = uid
self.set_unique_metadata('DC', 'identifier', self.uid, {'id': self.IDENTIFIER_ID}) |
def get_vm_by_property(service_instance, name, datacenter=None, vm_properties=None,
traversal_spec=None, parent_ref=None):
'''
Get virtual machine properties based on the traversal specs and properties list,
returns Virtual Machine object with properties.
service_instance
... | def function[get_vm_by_property, parameter[service_instance, name, datacenter, vm_properties, traversal_spec, parent_ref]]:
constant[
Get virtual machine properties based on the traversal specs and properties list,
returns Virtual Machine object with properties.
service_instance
Service ins... | keyword[def] identifier[get_vm_by_property] ( identifier[service_instance] , identifier[name] , identifier[datacenter] = keyword[None] , identifier[vm_properties] = keyword[None] ,
identifier[traversal_spec] = keyword[None] , identifier[parent_ref] = keyword[None] ):
literal[string]
keyword[if] identifie... | def get_vm_by_property(service_instance, name, datacenter=None, vm_properties=None, traversal_spec=None, parent_ref=None):
"""
Get virtual machine properties based on the traversal specs and properties list,
returns Virtual Machine object with properties.
service_instance
Service instance objec... |
def get_subject(self, lang=None):
""" Get the subject of the object
:param lang: Lang to retrieve
:return: Subject string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.subject, lang=lang) | def function[get_subject, parameter[self, lang]]:
constant[ Get the subject of the object
:param lang: Lang to retrieve
:return: Subject string representation
:rtype: Literal
]
return[call[name[self].metadata.get_single, parameter[]]] | keyword[def] identifier[get_subject] ( identifier[self] , identifier[lang] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[metadata] . identifier[get_single] ( identifier[key] = identifier[DC] . identifier[subject] , identifier[lang] = identifier[lang] ) | def get_subject(self, lang=None):
""" Get the subject of the object
:param lang: Lang to retrieve
:return: Subject string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.subject, lang=lang) |
def from_dict(d):
"""
Recreate a KrausModel from the dictionary representation.
:param dict d: The dictionary representing the KrausModel. See `to_dict` for an
example.
:return: The deserialized KrausModel.
:rtype: KrausModel
"""
kraus_ops = [KrausMod... | def function[from_dict, parameter[d]]:
constant[
Recreate a KrausModel from the dictionary representation.
:param dict d: The dictionary representing the KrausModel. See `to_dict` for an
example.
:return: The deserialized KrausModel.
:rtype: KrausModel
]
... | keyword[def] identifier[from_dict] ( identifier[d] ):
literal[string]
identifier[kraus_ops] =[ identifier[KrausModel] . identifier[unpack_kraus_matrix] ( identifier[k] ) keyword[for] identifier[k] keyword[in] identifier[d] [ literal[string] ]]
keyword[return] identifier[KrausModel] ( i... | def from_dict(d):
"""
Recreate a KrausModel from the dictionary representation.
:param dict d: The dictionary representing the KrausModel. See `to_dict` for an
example.
:return: The deserialized KrausModel.
:rtype: KrausModel
"""
kraus_ops = [KrausModel.unpac... |
def _permute_one_sample_iscs(iscs, group_parameters, i, pairwise=False,
summary_statistic='median', group_matrix=None,
exact_permutations=None, prng=None):
"""Applies one-sample permutations to ISC data
Input ISCs should be n_subjects (leave-one-out ap... | def function[_permute_one_sample_iscs, parameter[iscs, group_parameters, i, pairwise, summary_statistic, group_matrix, exact_permutations, prng]]:
constant[Applies one-sample permutations to ISC data
Input ISCs should be n_subjects (leave-one-out approach) or
n_pairs (pairwise approach) by n_voxels or ... | keyword[def] identifier[_permute_one_sample_iscs] ( identifier[iscs] , identifier[group_parameters] , identifier[i] , identifier[pairwise] = keyword[False] ,
identifier[summary_statistic] = literal[string] , identifier[group_matrix] = keyword[None] ,
identifier[exact_permutations] = keyword[None] , identifier[prng]... | def _permute_one_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', group_matrix=None, exact_permutations=None, prng=None):
"""Applies one-sample permutations to ISC data
Input ISCs should be n_subjects (leave-one-out approach) or
n_pairs (pairwise approach) by n_voxels or n... |
def annotateText(self, text, layer, np_labels = None):
''' Applies this chunker on given Text, and adds results of
the chunking as a new annotation layer to the text.
If the NP annotations are provided (via the input list
*np_labels*), uses the given NP annotations, oth... | def function[annotateText, parameter[self, text, layer, np_labels]]:
constant[ Applies this chunker on given Text, and adds results of
the chunking as a new annotation layer to the text.
If the NP annotations are provided (via the input list
*np_labels*), uses the given NP ... | keyword[def] identifier[annotateText] ( identifier[self] , identifier[text] , identifier[layer] , identifier[np_labels] = keyword[None] ):
literal[string]
identifier[input_words] = keyword[None]
keyword[if] identifier[isinstance] ( identifier[text] , identifier[Text] ):
... | def annotateText(self, text, layer, np_labels=None):
""" Applies this chunker on given Text, and adds results of
the chunking as a new annotation layer to the text.
If the NP annotations are provided (via the input list
*np_labels*), uses the given NP annotations, otherwise
... |
def retrieve_document(file_path, directory='sec_filings'):
'''
This function takes a file path beginning with edgar and stores the form in a directory.
The default directory is sec_filings but can be changed through a keyword argument.
'''
ftp = FTP('ftp.sec.gov', timeout=None)
ftp.login... | def function[retrieve_document, parameter[file_path, directory]]:
constant[
This function takes a file path beginning with edgar and stores the form in a directory.
The default directory is sec_filings but can be changed through a keyword argument.
]
variable[ftp] assign[=] call[name... | keyword[def] identifier[retrieve_document] ( identifier[file_path] , identifier[directory] = literal[string] ):
literal[string]
identifier[ftp] = identifier[FTP] ( literal[string] , identifier[timeout] = keyword[None] )
identifier[ftp] . identifier[login] ()
identifier[name] = identifier[file_pat... | def retrieve_document(file_path, directory='sec_filings'):
"""
This function takes a file path beginning with edgar and stores the form in a directory.
The default directory is sec_filings but can be changed through a keyword argument.
"""
ftp = FTP('ftp.sec.gov', timeout=None)
ftp.login... |
def template(self, template_filename, **kwargs):
"""
Render a template
:params template: Template name
:params kwargs: Template parameters
"""
template = renderer.get_template(template_filename)
kwargs["gns3_version"] = __version__
kwargs["gns3_host"] = s... | def function[template, parameter[self, template_filename]]:
constant[
Render a template
:params template: Template name
:params kwargs: Template parameters
]
variable[template] assign[=] call[name[renderer].get_template, parameter[name[template_filename]]]
call[n... | keyword[def] identifier[template] ( identifier[self] , identifier[template_filename] ,** identifier[kwargs] ):
literal[string]
identifier[template] = identifier[renderer] . identifier[get_template] ( identifier[template_filename] )
identifier[kwargs] [ literal[string] ]= identifier[__versi... | def template(self, template_filename, **kwargs):
"""
Render a template
:params template: Template name
:params kwargs: Template parameters
"""
template = renderer.get_template(template_filename)
kwargs['gns3_version'] = __version__
kwargs['gns3_host'] = self._request.hos... |
def type(self):
"""Enum type used for field."""
if self.__type is None:
found_type = find_definition(
self.__type_name, self.message_definition())
if not (found_type is not Enum and
isinstance(found_type, type) and
issubclas... | def function[type, parameter[self]]:
constant[Enum type used for field.]
if compare[name[self].__type is constant[None]] begin[:]
variable[found_type] assign[=] call[name[find_definition], parameter[name[self].__type_name, call[name[self].message_definition, parameter[]]]]
... | keyword[def] identifier[type] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__type] keyword[is] keyword[None] :
identifier[found_type] = identifier[find_definition] (
identifier[self] . identifier[__type_name] , identifier[self] . ident... | def type(self):
"""Enum type used for field."""
if self.__type is None:
found_type = find_definition(self.__type_name, self.message_definition())
if not (found_type is not Enum and isinstance(found_type, type) and issubclass(found_type, Enum)):
raise FieldDefinitionError('Invalid enu... |
def find_task_descriptor(self, task_id):
"""Returns the task_descriptor corresponding to task_id."""
# It is not guaranteed that the index will be task_id - 1 when --tasks is
# used with a min/max range.
for task_descriptor in self.task_descriptors:
if task_descriptor.task_metadata.get('task-id')... | def function[find_task_descriptor, parameter[self, task_id]]:
constant[Returns the task_descriptor corresponding to task_id.]
for taget[name[task_descriptor]] in starred[name[self].task_descriptors] begin[:]
if compare[call[name[task_descriptor].task_metadata.get, parameter[constant[task... | keyword[def] identifier[find_task_descriptor] ( identifier[self] , identifier[task_id] ):
literal[string]
keyword[for] identifier[task_descriptor] keyword[in] identifier[self] . identifier[task_descriptors] :
keyword[if] identifier[task_descriptor] . identifier[task_metadata] . identi... | def find_task_descriptor(self, task_id):
"""Returns the task_descriptor corresponding to task_id."""
# It is not guaranteed that the index will be task_id - 1 when --tasks is
# used with a min/max range.
for task_descriptor in self.task_descriptors:
if task_descriptor.task_metadata.get('task-id'... |
def sync_params(self):
""" Ensure that shared parameters are the same value everywhere """
def _normalize(comps, param):
vals = [c.get_values(param) for c in comps]
diff = any([vals[i] != vals[i+1] for i in range(len(vals)-1)])
if diff:
for c in comps... | def function[sync_params, parameter[self]]:
constant[ Ensure that shared parameters are the same value everywhere ]
def function[_normalize, parameter[comps, param]]:
variable[vals] assign[=] <ast.ListComp object at 0x7da204564490>
variable[diff] assign[=] call[name[any],... | keyword[def] identifier[sync_params] ( identifier[self] ):
literal[string]
keyword[def] identifier[_normalize] ( identifier[comps] , identifier[param] ):
identifier[vals] =[ identifier[c] . identifier[get_values] ( identifier[param] ) keyword[for] identifier[c] keyword[in] identifi... | def sync_params(self):
""" Ensure that shared parameters are the same value everywhere """
def _normalize(comps, param):
vals = [c.get_values(param) for c in comps]
diff = any([vals[i] != vals[i + 1] for i in range(len(vals) - 1)])
if diff:
for c in comps:
c.... |
def Delete(self, n = 1, dl = 0):
"""删除键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.delete_key, n) | def function[Delete, parameter[self, n, dl]]:
constant[删除键n次
]
call[name[self].Delay, parameter[name[dl]]]
call[name[self].keyboard.tap_key, parameter[name[self].keyboard.delete_key, name[n]]] | keyword[def] identifier[Delete] ( identifier[self] , identifier[n] = literal[int] , identifier[dl] = literal[int] ):
literal[string]
identifier[self] . identifier[Delay] ( identifier[dl] )
identifier[self] . identifier[keyboard] . identifier[tap_key] ( identifier[self] . identifier[keyboar... | def Delete(self, n=1, dl=0):
"""删除键n次
"""
self.Delay(dl)
self.keyboard.tap_key(self.keyboard.delete_key, n) |
def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first a... | def function[invoke, parameter[]]:
constant[Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. ... | keyword[def] identifier[invoke] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] , identifier[callback] = identifier[args] [: literal[int] ]
identifier[ctx] = identifier[self]
keyword[if] identifier[isinstance] ( identifi... | def invoke(*args, **kwargs):
"""Invokes a command callback in exactly the way it expects. There
are two ways to invoke this method:
1. the first argument can be a callback and all other arguments and
keyword arguments are forwarded directly to the function.
2. the first argum... |
def modify_file_in_place(self, fp, length, iso_path, rr_name=None, # pylint: disable=unused-argument
joliet_path=None, udf_path=None): # pylint: disable=unused-argument
# type: (BinaryIO, int, str, Optional[str], Optional[str], Optional[str]) -> None
'''
An... | def function[modify_file_in_place, parameter[self, fp, length, iso_path, rr_name, joliet_path, udf_path]]:
constant[
An API to modify a file in place on the ISO. This can be extremely fast
(much faster than calling the write method), but has many restrictions.
1. The original ISO file... | keyword[def] identifier[modify_file_in_place] ( identifier[self] , identifier[fp] , identifier[length] , identifier[iso_path] , identifier[rr_name] = keyword[None] ,
identifier[joliet_path] = keyword[None] , identifier[udf_path] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identi... | def modify_file_in_place(self, fp, length, iso_path, rr_name=None, joliet_path=None, udf_path=None): # pylint: disable=unused-argument
# pylint: disable=unused-argument
# type: (BinaryIO, int, str, Optional[str], Optional[str], Optional[str]) -> None
'\n An API to modify a file in place on the ISO. ... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'sentence') and self.sentence is not None:
_dict['sentence'] = self.sentence
if hasattr(self, 'subject') and self.subject is not None:
_dict['subject'] = self.s... | def function[_to_dict, parameter[self]]:
constant[Return a json dictionary representing this model.]
variable[_dict] assign[=] dictionary[[], []]
if <ast.BoolOp object at 0x7da18bcc8d60> begin[:]
call[name[_dict]][constant[sentence]] assign[=] name[self].sentence
if <ast.... | keyword[def] identifier[_to_dict] ( identifier[self] ):
literal[string]
identifier[_dict] ={}
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ) keyword[and] identifier[self] . identifier[sentence] keyword[is] keyword[not] keyword[None] :
identifier[_d... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'sentence') and self.sentence is not None:
_dict['sentence'] = self.sentence # depends on [control=['if'], data=[]]
if hasattr(self, 'subject') and self.subject is not None:
_dict['su... |
def create_object(self, cls: Type[T], additional_kwargs=None) -> T:
"""Create a new instance, satisfying any dependencies on cls."""
additional_kwargs = additional_kwargs or {}
log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs)
try:
instance ... | def function[create_object, parameter[self, cls, additional_kwargs]]:
constant[Create a new instance, satisfying any dependencies on cls.]
variable[additional_kwargs] assign[=] <ast.BoolOp object at 0x7da18eb55240>
call[name[log].debug, parameter[constant[%sCreating %r object with %r], name[self... | keyword[def] identifier[create_object] ( identifier[self] , identifier[cls] : identifier[Type] [ identifier[T] ], identifier[additional_kwargs] = keyword[None] )-> identifier[T] :
literal[string]
identifier[additional_kwargs] = identifier[additional_kwargs] keyword[or] {}
identifier[log] ... | def create_object(self, cls: Type[T], additional_kwargs=None) -> T:
"""Create a new instance, satisfying any dependencies on cls."""
additional_kwargs = additional_kwargs or {}
log.debug('%sCreating %r object with %r', self._log_prefix, cls, additional_kwargs)
try:
instance = cls.__new__(cls) #... |
def Geometry(*args, **kwargs):
"""Returns an ogr.Geometry instance optionally created from a geojson str
or dict. The spatial reference may also be provided.
"""
# Look for geojson as a positional or keyword arg.
arg = kwargs.pop('geojson', None) or len(args) and args[0]
try:
srs = kwarg... | def function[Geometry, parameter[]]:
constant[Returns an ogr.Geometry instance optionally created from a geojson str
or dict. The spatial reference may also be provided.
]
variable[arg] assign[=] <ast.BoolOp object at 0x7da1b01a4ee0>
<ast.Try object at 0x7da1b01a5660>
if call[name[ha... | keyword[def] identifier[Geometry] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[arg] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) keyword[or] identifier[len] ( identifier[args] ) keyword[and] identifier[args] [ literal[int] ]
keyword[try]... | def Geometry(*args, **kwargs):
"""Returns an ogr.Geometry instance optionally created from a geojson str
or dict. The spatial reference may also be provided.
"""
# Look for geojson as a positional or keyword arg.
arg = kwargs.pop('geojson', None) or (len(args) and args[0])
try:
srs = kwa... |
def parse_log_messages(self, text):
"""Will parse git log messages in the 'short' format"""
regex = r"commit ([0-9a-f]+)\nAuthor: (.*?)\n\n(.*?)(?:\n\n|$)"
messages = re.findall(regex, text, re.DOTALL)
parsed = []
for commit, author, message in messages:
pars... | def function[parse_log_messages, parameter[self, text]]:
constant[Will parse git log messages in the 'short' format]
variable[regex] assign[=] constant[commit ([0-9a-f]+)\nAuthor: (.*?)\n\n(.*?)(?:\n\n|$)]
variable[messages] assign[=] call[name[re].findall, parameter[name[regex], name[text], nam... | keyword[def] identifier[parse_log_messages] ( identifier[self] , identifier[text] ):
literal[string]
identifier[regex] = literal[string]
identifier[messages] = identifier[re] . identifier[findall] ( identifier[regex] , identifier[text] , identifier[re] . identifier[DOTALL] )
ide... | def parse_log_messages(self, text):
"""Will parse git log messages in the 'short' format"""
regex = 'commit ([0-9a-f]+)\\nAuthor: (.*?)\\n\\n(.*?)(?:\\n\\n|$)'
messages = re.findall(regex, text, re.DOTALL)
parsed = []
for (commit, author, message) in messages: # Remove email address if present
... |
def save_pid_eeprom(self):
""" saves the PID values from RAM to EEPROM
"""
pval = self.get_position_p()
ival = self.get_position_i()
dval = self.get_position_d()
#write P value
pvalue_msb = int(pval) >> 8
pvalue_lsb = int(pval) & 0xff
data_p = [... | def function[save_pid_eeprom, parameter[self]]:
constant[ saves the PID values from RAM to EEPROM
]
variable[pval] assign[=] call[name[self].get_position_p, parameter[]]
variable[ival] assign[=] call[name[self].get_position_i, parameter[]]
variable[dval] assign[=] call[name[self... | keyword[def] identifier[save_pid_eeprom] ( identifier[self] ):
literal[string]
identifier[pval] = identifier[self] . identifier[get_position_p] ()
identifier[ival] = identifier[self] . identifier[get_position_i] ()
identifier[dval] = identifier[self] . identifier[get_position_d] (... | def save_pid_eeprom(self):
""" saves the PID values from RAM to EEPROM
"""
pval = self.get_position_p()
ival = self.get_position_i()
dval = self.get_position_d()
#write P value
pvalue_msb = int(pval) >> 8
pvalue_lsb = int(pval) & 255
data_p = []
data_p.append(11)
data_p.... |
def tag_and_stem(text):
"""
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
"""
tokens = tokenize(text)
tagged = nltk.pos_tag(tokens)
out = []
for token,... | def function[tag_and_stem, parameter[text]]:
constant[
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
]
variable[tokens] assign[=] call[name[tokenize], para... | keyword[def] identifier[tag_and_stem] ( identifier[text] ):
literal[string]
identifier[tokens] = identifier[tokenize] ( identifier[text] )
identifier[tagged] = identifier[nltk] . identifier[pos_tag] ( identifier[tokens] )
identifier[out] =[]
keyword[for] identifier[token] , identifier[tag] ... | def tag_and_stem(text):
"""
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
"""
tokens = tokenize(text)
tagged = nltk.pos_tag(tokens)
out = []
for (token... |
def _setup_direct_converter(self, converter):
'''
Given a converter, set up the direct_output routes for conversions,
which is used for transcoding between similar datatypes.
'''
inputs = (
converter.direct_inputs
if hasattr(converter, 'direct_inputs')
... | def function[_setup_direct_converter, parameter[self, converter]]:
constant[
Given a converter, set up the direct_output routes for conversions,
which is used for transcoding between similar datatypes.
]
variable[inputs] assign[=] <ast.IfExp object at 0x7da1b0b83970>
for ... | keyword[def] identifier[_setup_direct_converter] ( identifier[self] , identifier[converter] ):
literal[string]
identifier[inputs] =(
identifier[converter] . identifier[direct_inputs]
keyword[if] identifier[hasattr] ( identifier[converter] , literal[string] )
keyword[els... | def _setup_direct_converter(self, converter):
"""
Given a converter, set up the direct_output routes for conversions,
which is used for transcoding between similar datatypes.
"""
inputs = converter.direct_inputs if hasattr(converter, 'direct_inputs') else converter.inputs
for in_ in ... |
def _format_obj(self, item=None):
""" Determines the type of the object and maps it to the correct
formatter
"""
# Order here matters, odd behavior with tuples
if item is None:
return getattr(self, 'number')(item)
elif isinstance(item, self.str_):
... | def function[_format_obj, parameter[self, item]]:
constant[ Determines the type of the object and maps it to the correct
formatter
]
if compare[name[item] is constant[None]] begin[:]
return[call[call[name[getattr], parameter[name[self], constant[number]]], parameter[name[item... | keyword[def] identifier[_format_obj] ( identifier[self] , identifier[item] = keyword[None] ):
literal[string]
keyword[if] identifier[item] keyword[is] keyword[None] :
keyword[return] identifier[getattr] ( identifier[self] , literal[string] )( identifier[item] )
ke... | def _format_obj(self, item=None):
""" Determines the type of the object and maps it to the correct
formatter
"""
# Order here matters, odd behavior with tuples
if item is None:
return getattr(self, 'number')(item) # depends on [control=['if'], data=['item']]
elif isinstance(... |
def to_bytes_36(self, previous: bytes):
"""
A to-bytes specific to Python 3.6 and above.
"""
# Calculations ahead.
bc = b""
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
bc +=... | def function[to_bytes_36, parameter[self, previous]]:
constant[
A to-bytes specific to Python 3.6 and above.
]
variable[bc] assign[=] constant[b'']
variable[it_bc] assign[=] call[name[util].generate_bytecode_from_obb, parameter[name[self].iterator, name[previous]]]
<ast.AugAs... | keyword[def] identifier[to_bytes_36] ( identifier[self] , identifier[previous] : identifier[bytes] ):
literal[string]
identifier[bc] = literal[string]
identifier[it_bc] = identifier[util] . identifier[generate_bytecode_from_obb] ( identifier[self] . identifier[iterator]... | def to_bytes_36(self, previous: bytes):
"""
A to-bytes specific to Python 3.6 and above.
"""
# Calculations ahead.
bc = b''
# Calculate the length of the iterator.
it_bc = util.generate_bytecode_from_obb(self.iterator, previous)
bc += it_bc
bc += util.ensure_instruction(token... |
def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of stri... | def function[decode_abi, parameter[self, types, data]]:
constant[
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string representations of ... | keyword[def] identifier[decode_abi] ( identifier[self] , identifier[types] : identifier[Iterable] [ identifier[TypeStr] ], identifier[data] : identifier[Decodable] )-> identifier[Tuple] [ identifier[Any] ,...]:
literal[string]
keyword[if] keyword[not] identifier[is_bytes] ( identifier[data] ):
... | def decode_abi(self, types: Iterable[TypeStr], data: Decodable) -> Tuple[Any, ...]:
"""
Decodes the binary value ``data`` as a sequence of values of the ABI types
in ``types`` via the head-tail mechanism into a tuple of equivalent python
values.
:param types: An iterable of string r... |
def remove_environment(environment_var_name, system=False):
"""
Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration file.
... | def function[remove_environment, parameter[environment_var_name, system]]:
constant[
Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration... | keyword[def] identifier[remove_environment] ( identifier[environment_var_name] , identifier[system] = keyword[False] ):
literal[string]
identifier[config_filename] = identifier[_SYSTEM_CONFIG_FILE] keyword[if] identifier[system] keyword[is] keyword[True] keyword[else] identifier[_USER_CONFIG_FILE]
... | def remove_environment(environment_var_name, system=False):
"""
Remove the specified environment setting from the appropriate config file.
:param environment_var_name: The name of the environment setting to remove.
:keyword system: Set to True to modify the system configuration file.
... |
def create_cfg_segment(filename, filecontent, description, auth, url):
'''
Takes a str into var filecontent which represents the entire content of a configuration segment, or partial
configuration file. Takes a str into var description which represents the description of the configuration segment
:param... | def function[create_cfg_segment, parameter[filename, filecontent, description, auth, url]]:
constant[
Takes a str into var filecontent which represents the entire content of a configuration segment, or partial
configuration file. Takes a str into var description which represents the description of the c... | keyword[def] identifier[create_cfg_segment] ( identifier[filename] , identifier[filecontent] , identifier[description] , identifier[auth] , identifier[url] ):
literal[string]
identifier[payload] ={ literal[string] : identifier[filename] ,
literal[string] : literal[string] ,
literal[string] : lite... | def create_cfg_segment(filename, filecontent, description, auth, url):
'''
Takes a str into var filecontent which represents the entire content of a configuration segment, or partial
configuration file. Takes a str into var description which represents the description of the configuration segment
:param... |
def stats(self, details=False):
"""Get statistics and information from the daemon
Returns an object with the daemon identity, the daemon start_time
and some extra properties depending upon the daemon type.
All daemons provide these ones:
- program_start: the Alignak start times... | def function[stats, parameter[self, details]]:
constant[Get statistics and information from the daemon
Returns an object with the daemon identity, the daemon start_time
and some extra properties depending upon the daemon type.
All daemons provide these ones:
- program_start: th... | keyword[def] identifier[stats] ( identifier[self] , identifier[details] = keyword[False] ):
literal[string]
keyword[if] identifier[details] keyword[is] keyword[not] keyword[False] :
identifier[details] = identifier[bool] ( identifier[details] )
identifier[res] = identifier... | def stats(self, details=False):
"""Get statistics and information from the daemon
Returns an object with the daemon identity, the daemon start_time
and some extra properties depending upon the daemon type.
All daemons provide these ones:
- program_start: the Alignak start timestamp... |
def create_storage_class(self, body, **kwargs): # noqa: E501
"""create_storage_class # noqa: E501
create a StorageClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.crea... | def function[create_storage_class, parameter[self, body]]:
constant[create_storage_class # noqa: E501
create a StorageClass # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.c... | keyword[def] identifier[create_storage_class] ( identifier[self] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifi... | def create_storage_class(self, body, **kwargs): # noqa: E501
"create_storage_class # noqa: E501\n\n create a StorageClass # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.creat... |
def Operation(self, x, y):
"""Whether x is fully contained in y."""
if x in y:
return True
# x might be an iterable
# first we need to skip strings or we'll do silly things
if isinstance(x, string_types) or isinstance(x, bytes):
return False
try:
for value in x:
if va... | def function[Operation, parameter[self, x, y]]:
constant[Whether x is fully contained in y.]
if compare[name[x] in name[y]] begin[:]
return[constant[True]]
if <ast.BoolOp object at 0x7da204621f60> begin[:]
return[constant[False]]
<ast.Try object at 0x7da204620dc0> | keyword[def] identifier[Operation] ( identifier[self] , identifier[x] , identifier[y] ):
literal[string]
keyword[if] identifier[x] keyword[in] identifier[y] :
keyword[return] keyword[True]
keyword[if] identifier[isinstance] ( identifier[x] , identifier[string_types] ) keywo... | def Operation(self, x, y):
"""Whether x is fully contained in y."""
if x in y:
return True # depends on [control=['if'], data=[]]
# x might be an iterable
# first we need to skip strings or we'll do silly things
if isinstance(x, string_types) or isinstance(x, bytes):
return False #... |
def set_results(self, results: str):
"""
This method set the results attribute for the SASdata object; it stays in effect till changed
results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'.
:param results: format of results, SASsession.results is de... | def function[set_results, parameter[self, results]]:
constant[
This method set the results attribute for the SASdata object; it stays in effect till changed
results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'.
:param results: format of results, SA... | keyword[def] identifier[set_results] ( identifier[self] , identifier[results] : identifier[str] ):
literal[string]
keyword[if] identifier[results] . identifier[upper] ()== literal[string] :
identifier[self] . identifier[HTML] = literal[int]
keyword[else] :
ident... | def set_results(self, results: str):
"""
This method set the results attribute for the SASdata object; it stays in effect till changed
results - set the default result type for this SASdata object. 'Pandas' or 'HTML' or 'TEXT'.
:param results: format of results, SASsession.results is defaul... |
def despike(self, expdecay_despiker=True, exponent=None,
noise_despiker=True, win=3, nlim=12., maxiter=3):
"""
Applies expdecay_despiker and noise_despiker to data.
Parameters
----------
expdecay_despiker : bool
Whether or not to apply the exponential... | def function[despike, parameter[self, expdecay_despiker, exponent, noise_despiker, win, nlim, maxiter]]:
constant[
Applies expdecay_despiker and noise_despiker to data.
Parameters
----------
expdecay_despiker : bool
Whether or not to apply the exponential decay filte... | keyword[def] identifier[despike] ( identifier[self] , identifier[expdecay_despiker] = keyword[True] , identifier[exponent] = keyword[None] ,
identifier[noise_despiker] = keyword[True] , identifier[win] = literal[int] , identifier[nlim] = literal[int] , identifier[maxiter] = literal[int] ):
literal[string]
... | def despike(self, expdecay_despiker=True, exponent=None, noise_despiker=True, win=3, nlim=12.0, maxiter=3):
"""
Applies expdecay_despiker and noise_despiker to data.
Parameters
----------
expdecay_despiker : bool
Whether or not to apply the exponential decay filter.
... |
def prepare_parameters(self, multi_row_parameters):
""" Attribute sql parameters with meta data for a prepared statement.
Make some basic checks that at least the number of parameters is correct.
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows)
... | def function[prepare_parameters, parameter[self, multi_row_parameters]]:
constant[ Attribute sql parameters with meta data for a prepared statement.
Make some basic checks that at least the number of parameters is correct.
:param multi_row_parameters: A list/tuple containing list/tuples of param... | keyword[def] identifier[prepare_parameters] ( identifier[self] , identifier[multi_row_parameters] ):
literal[string]
identifier[self] . identifier[_multi_row_parameters] = identifier[multi_row_parameters]
identifier[self] . identifier[_num_rows] = identifier[len] ( identifier[multi_row_pa... | def prepare_parameters(self, multi_row_parameters):
""" Attribute sql parameters with meta data for a prepared statement.
Make some basic checks that at least the number of parameters is correct.
:param multi_row_parameters: A list/tuple containing list/tuples of parameters (for multiple rows)
... |
def do_call(self, parser: BasicParser) -> Node:
"""
The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators)
"""
valueparam = []
for v, t in self.param:
if t is Node:
valu... | def function[do_call, parameter[self, parser]]:
constant[
The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators)
]
variable[valueparam] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da... | keyword[def] identifier[do_call] ( identifier[self] , identifier[parser] : identifier[BasicParser] )-> identifier[Node] :
literal[string]
identifier[valueparam] =[]
keyword[for] identifier[v] , identifier[t] keyword[in] identifier[self] . identifier[param] :
keyword[if] id... | def do_call(self, parser: BasicParser) -> Node:
"""
The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators)
"""
valueparam = []
for (v, t) in self.param:
if t is Node:
valueparam.append(pars... |
def draw_jointplot(figname, x, y, data=None, kind="reg", color=None,
xlim=None, ylim=None, format="pdf"):
"""
Wraps around sns.jointplot
"""
import seaborn as sns
sns.set_context('talk')
plt.clf()
register = {"MeanCoverage": "Sample Mean Coverage",
"HD.FDP... | def function[draw_jointplot, parameter[figname, x, y, data, kind, color, xlim, ylim, format]]:
constant[
Wraps around sns.jointplot
]
import module[seaborn] as alias[sns]
call[name[sns].set_context, parameter[constant[talk]]]
call[name[plt].clf, parameter[]]
variable[register... | keyword[def] identifier[draw_jointplot] ( identifier[figname] , identifier[x] , identifier[y] , identifier[data] = keyword[None] , identifier[kind] = literal[string] , identifier[color] = keyword[None] ,
identifier[xlim] = keyword[None] , identifier[ylim] = keyword[None] , identifier[format] = literal[string] ):
... | def draw_jointplot(figname, x, y, data=None, kind='reg', color=None, xlim=None, ylim=None, format='pdf'):
"""
Wraps around sns.jointplot
"""
import seaborn as sns
sns.set_context('talk')
plt.clf()
register = {'MeanCoverage': 'Sample Mean Coverage', 'HD.FDP': 'Depth of full spanning reads', '... |
def search(self, line):
"""CN search."""
if self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) == "solr":
return self._search_solr(line)
raise d1_cli.impl.exceptions.InvalidArguments(
"Unsupported query engine: {}".format(
self._session.get(d1_cli.im... | def function[search, parameter[self, line]]:
constant[CN search.]
if compare[call[name[self]._session.get, parameter[name[d1_cli].impl.session.QUERY_ENGINE_NAME]] equal[==] constant[solr]] begin[:]
return[call[name[self]._search_solr, parameter[name[line]]]]
<ast.Raise object at 0x7da1b19f0d... | keyword[def] identifier[search] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] identifier[self] . identifier[_session] . identifier[get] ( identifier[d1_cli] . identifier[impl] . identifier[session] . identifier[QUERY_ENGINE_NAME] )== literal[string] :
keyword[re... | def search(self, line):
"""CN search."""
if self._session.get(d1_cli.impl.session.QUERY_ENGINE_NAME) == 'solr':
return self._search_solr(line) # depends on [control=['if'], data=[]]
raise d1_cli.impl.exceptions.InvalidArguments('Unsupported query engine: {}'.format(self._session.get(d1_cli.impl.ses... |
def _init_matrix(self, data, index, columns, dtype=None):
"""
Init self from ndarray or list of lists.
"""
data = prep_ndarray(data, copy=False)
index, columns = self._prep_index(data, index, columns)
data = {idx: data[:, i] for i, idx in enumerate(columns)}
retur... | def function[_init_matrix, parameter[self, data, index, columns, dtype]]:
constant[
Init self from ndarray or list of lists.
]
variable[data] assign[=] call[name[prep_ndarray], parameter[name[data]]]
<ast.Tuple object at 0x7da18fe93640> assign[=] call[name[self]._prep_index, para... | keyword[def] identifier[_init_matrix] ( identifier[self] , identifier[data] , identifier[index] , identifier[columns] , identifier[dtype] = keyword[None] ):
literal[string]
identifier[data] = identifier[prep_ndarray] ( identifier[data] , identifier[copy] = keyword[False] )
identifier[index... | def _init_matrix(self, data, index, columns, dtype=None):
"""
Init self from ndarray or list of lists.
"""
data = prep_ndarray(data, copy=False)
(index, columns) = self._prep_index(data, index, columns)
data = {idx: data[:, i] for (i, idx) in enumerate(columns)}
return self._init_dic... |
def get_distance_and_image(
self,
frac_coords1: Vector3Like,
frac_coords2: Vector3Like,
jimage: Optional[Union[List[int], np.ndarray]] = None,
) -> Tuple[float, np.ndarray]:
"""
Gets distance between two frac_coords assuming periodic boundary
conditions. If th... | def function[get_distance_and_image, parameter[self, frac_coords1, frac_coords2, jimage]]:
constant[
Gets distance between two frac_coords assuming periodic boundary
conditions. If the index jimage is not specified it selects the j
image nearest to the i atom and returns the distance and... | keyword[def] identifier[get_distance_and_image] (
identifier[self] ,
identifier[frac_coords1] : identifier[Vector3Like] ,
identifier[frac_coords2] : identifier[Vector3Like] ,
identifier[jimage] : identifier[Optional] [ identifier[Union] [ identifier[List] [ identifier[int] ], identifier[np] . identifier[ndarray] ... | def get_distance_and_image(self, frac_coords1: Vector3Like, frac_coords2: Vector3Like, jimage: Optional[Union[List[int], np.ndarray]]=None) -> Tuple[float, np.ndarray]:
"""
Gets distance between two frac_coords assuming periodic boundary
conditions. If the index jimage is not specified it selects th... |
def change_digital(self, pin_nr, value):
""" Change digital Pin value (boolean). Also PWM supported(float)"""
if not self._board:
return
with self._lock:
self._act_digital[pin_nr].pin.write(value) | def function[change_digital, parameter[self, pin_nr, value]]:
constant[ Change digital Pin value (boolean). Also PWM supported(float)]
if <ast.UnaryOp object at 0x7da20c6a8730> begin[:]
return[None]
with name[self]._lock begin[:]
call[call[name[self]._act_digital][name[pi... | keyword[def] identifier[change_digital] ( identifier[self] , identifier[pin_nr] , identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_board] :
keyword[return]
keyword[with] identifier[self] . identifier[_lock] :
identif... | def change_digital(self, pin_nr, value):
""" Change digital Pin value (boolean). Also PWM supported(float)"""
if not self._board:
return # depends on [control=['if'], data=[]]
with self._lock:
self._act_digital[pin_nr].pin.write(value) # depends on [control=['with'], data=[]] |
def _combine_results(self, match_as_dict):
'''Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
becomes:
... | def function[_combine_results, parameter[self, match_as_dict]]:
constant[Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
... | keyword[def] identifier[_combine_results] ( identifier[self] , identifier[match_as_dict] ):
literal[string]
identifier[keys] =[]
identifier[vals] =[]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[six] . identifier[iteritems] ( identifier[matc... | def _combine_results(self, match_as_dict):
"""Combine results from different parsed parts:
we look for non-empty results in values like
'postal_code_b' or 'postal_code_c' and store
them as main value.
So 'postal_code_b':'123456'
becomes:
... |
def type_match(a, b):
"""Return True of the types of a and b are compatible, False otherwise."""
# If the types are the same, return True
if a['type'] == b['type']:
return True
# Otherwise, look at some special cases
eq_groups = [
{'ONT::GENE-PROTEIN', 'ONT::GENE', 'ONT::PROTEIN'},
... | def function[type_match, parameter[a, b]]:
constant[Return True of the types of a and b are compatible, False otherwise.]
if compare[call[name[a]][constant[type]] equal[==] call[name[b]][constant[type]]] begin[:]
return[constant[True]]
variable[eq_groups] assign[=] list[[<ast.Set object ... | keyword[def] identifier[type_match] ( identifier[a] , identifier[b] ):
literal[string]
keyword[if] identifier[a] [ literal[string] ]== identifier[b] [ literal[string] ]:
keyword[return] keyword[True]
identifier[eq_groups] =[
{ literal[string] , literal[string] , literal[s... | def type_match(a, b):
"""Return True of the types of a and b are compatible, False otherwise."""
# If the types are the same, return True
if a['type'] == b['type']:
return True # depends on [control=['if'], data=[]]
# Otherwise, look at some special cases
eq_groups = [{'ONT::GENE-PROTEIN', ... |
def get_subscribers(cls, active_only=True):
"""Returns a list of Recipient objects subscribed for this message type.
:param bool active_only: Flag whether
:return:
"""
subscribers_raw = Subscription.get_for_message_cls(cls.alias)
subscribers = []
for subscriber ... | def function[get_subscribers, parameter[cls, active_only]]:
constant[Returns a list of Recipient objects subscribed for this message type.
:param bool active_only: Flag whether
:return:
]
variable[subscribers_raw] assign[=] call[name[Subscription].get_for_message_cls, parameter[... | keyword[def] identifier[get_subscribers] ( identifier[cls] , identifier[active_only] = keyword[True] ):
literal[string]
identifier[subscribers_raw] = identifier[Subscription] . identifier[get_for_message_cls] ( identifier[cls] . identifier[alias] )
identifier[subscribers] =[]
key... | def get_subscribers(cls, active_only=True):
"""Returns a list of Recipient objects subscribed for this message type.
:param bool active_only: Flag whether
:return:
"""
subscribers_raw = Subscription.get_for_message_cls(cls.alias)
subscribers = []
for subscriber in subscribers_ra... |
def create_tutorial_layout(self):
""" layout for example tutorial """
lexer, _, _ = get_lexers(self.shell_ctx.lexer, None, None)
layout_full = HSplit([
FloatContainer(
Window(
BufferControl(
input_processors=self.input_proce... | def function[create_tutorial_layout, parameter[self]]:
constant[ layout for example tutorial ]
<ast.Tuple object at 0x7da1b26ae3b0> assign[=] call[name[get_lexers], parameter[name[self].shell_ctx.lexer, constant[None], constant[None]]]
variable[layout_full] assign[=] call[name[HSplit], parameter... | keyword[def] identifier[create_tutorial_layout] ( identifier[self] ):
literal[string]
identifier[lexer] , identifier[_] , identifier[_] = identifier[get_lexers] ( identifier[self] . identifier[shell_ctx] . identifier[lexer] , keyword[None] , keyword[None] )
identifier[layout_full] = identi... | def create_tutorial_layout(self):
""" layout for example tutorial """
(lexer, _, _) = get_lexers(self.shell_ctx.lexer, None, None)
layout_full = HSplit([FloatContainer(Window(BufferControl(input_processors=self.input_processors, lexer=lexer, preview_search=Always()), get_height=get_height), [Float(xcursor=T... |
def get_definition(query):
"""Returns dictionary of id, first names of people who posted on my wall
between start and end time"""
try:
return get_definition_api(query)
except:
raise
# http://api.wordnik.com:80/v4/word.json/discrimination/definitions?limit=200&includeRelated=true&sou... | def function[get_definition, parameter[query]]:
constant[Returns dictionary of id, first names of people who posted on my wall
between start and end time]
<ast.Try object at 0x7da2041da110>
import module[json]
variable[payload] assign[=] dictionary[[<ast.Constant object at 0x7da2041db7c0>, <... | keyword[def] identifier[get_definition] ( identifier[query] ):
literal[string]
keyword[try] :
keyword[return] identifier[get_definition_api] ( identifier[query] )
keyword[except] :
keyword[raise]
keyword[import] identifier[json]
identifier[payload] ={ literal[... | def get_definition(query):
"""Returns dictionary of id, first names of people who posted on my wall
between start and end time"""
try:
return get_definition_api(query) # depends on [control=['try'], data=[]]
except:
raise # depends on [control=['except'], data=[]]
# http://api.word... |
def validate(self, r):
'''
Called automatically by self.result.
'''
if self.show_invalid:
r.valid = True
elif r.valid:
if not r.description:
r.valid = False
if r.size and (r.size + r.offset) > r.file.size:
r.val... | def function[validate, parameter[self, r]]:
constant[
Called automatically by self.result.
]
if name[self].show_invalid begin[:]
name[r].valid assign[=] constant[True]
if name[r].valid begin[:]
if compare[name[r].id equal[==] name[self].one_of_many... | keyword[def] identifier[validate] ( identifier[self] , identifier[r] ):
literal[string]
keyword[if] identifier[self] . identifier[show_invalid] :
identifier[r] . identifier[valid] = keyword[True]
keyword[elif] identifier[r] . identifier[valid] :
keyword[if] ke... | def validate(self, r):
"""
Called automatically by self.result.
"""
if self.show_invalid:
r.valid = True # depends on [control=['if'], data=[]]
elif r.valid:
if not r.description:
r.valid = False # depends on [control=['if'], data=[]]
if r.size and r.siz... |
def log_loss(actual, predicted):
"""Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
... | def function[log_loss, parameter[actual, predicted]]:
constant[Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table o... | keyword[def] identifier[log_loss] ( identifier[actual] , identifier[predicted] ):
literal[string]
identifier[predicted] , identifier[actual] = identifier[np] . identifier[array] ( identifier[predicted] ), identifier[np] . identifier[array] ( identifier[actual] )
identifier[small_value] = literal[int... | def log_loss(actual, predicted):
"""Log of the loss (error) summed over all entries
The negative of the logarithm of the frequency (probability) of the predicted
label given the true binary label for a category.
Arguments:
predicted (np.array of float): 2-D table of probabilities for each
... |
def parse(self):
"""Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy."""
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <... | def function[parse, parameter[self]]:
constant[Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy.]
import module[xml.etree.ElementTree] as alias[ET]
variable[root] assign[=] call[name[ET].fromstring, paramete... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
keyword[import] identifier[xml] . identifier[etree] . identifier[ElementTree] keyword[as] identifier[ET]
identifier[root] = identifier[ET] . identifier[fromstring] ( identifier[self] . identifier[_xml_db_str] )
... | def parse(self):
"""Main entrypoint into the parser. It interprets and creates all the
relevant Lutron objects and stuffs them into the appropriate hierarchy."""
import xml.etree.ElementTree as ET
root = ET.fromstring(self._xml_db_str)
# The structure is something like this:
# <Areas>
# <A... |
def configure_searchfor(self, ns, definition):
"""
Register a relation endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the query string (minimally for pagination)
- return a tuple of (items, count, context) where count is the total nu... | def function[configure_searchfor, parameter[self, ns, definition]]:
constant[
Register a relation endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the query string (minimally for pagination)
- return a tuple of (items, count, context) ... | keyword[def] identifier[configure_searchfor] ( identifier[self] , identifier[ns] , identifier[definition] ):
literal[string]
identifier[paginated_list_schema] = identifier[self] . identifier[page_cls] . identifier[make_paginated_list_schema_class] (
identifier[ns] . identifier[object_ns] ,... | def configure_searchfor(self, ns, definition):
"""
Register a relation endpoint.
The definition's func should be a search function, which must:
- accept kwargs for the query string (minimally for pagination)
- return a tuple of (items, count, context) where count is the total number... |
def get_all_build_configs_by_labels(self, label_selectors):
"""
Returns all builds matching a given set of label selectors. It is up to the
calling function to filter the results.
"""
labels = ['%s=%s' % (field, value) for field, value in label_selectors]
labels = ','.joi... | def function[get_all_build_configs_by_labels, parameter[self, label_selectors]]:
constant[
Returns all builds matching a given set of label selectors. It is up to the
calling function to filter the results.
]
variable[labels] assign[=] <ast.ListComp object at 0x7da1b0fdab90>
... | keyword[def] identifier[get_all_build_configs_by_labels] ( identifier[self] , identifier[label_selectors] ):
literal[string]
identifier[labels] =[ literal[string] %( identifier[field] , identifier[value] ) keyword[for] identifier[field] , identifier[value] keyword[in] identifier[label_selectors]... | def get_all_build_configs_by_labels(self, label_selectors):
"""
Returns all builds matching a given set of label selectors. It is up to the
calling function to filter the results.
"""
labels = ['%s=%s' % (field, value) for (field, value) in label_selectors]
labels = ','.join(labels)
... |
def read_ipx(self, length):
"""Read Internetwork Packet Exchange.
Structure of IPX header [RFC 1132]:
Octets Bits Name Description
0 0 ipx.cksum Checksum
2 16 ipx.len Packet L... | def function[read_ipx, parameter[self, length]]:
constant[Read Internetwork Packet Exchange.
Structure of IPX header [RFC 1132]:
Octets Bits Name Description
0 0 ipx.cksum Checksum
2 16 ipx.l... | keyword[def] identifier[read_ipx] ( identifier[self] , identifier[length] ):
literal[string]
keyword[if] identifier[length] keyword[is] keyword[None] :
identifier[length] = identifier[len] ( identifier[self] )
identifier[_csum] = identifier[self] . identifier[_read_fileng]... | def read_ipx(self, length):
"""Read Internetwork Packet Exchange.
Structure of IPX header [RFC 1132]:
Octets Bits Name Description
0 0 ipx.cksum Checksum
2 16 ipx.len Packet Lengt... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.