code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def get_layer_description_from_browser(self, category):
"""Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean is true if layer is
... | def function[get_layer_description_from_browser, parameter[self, category]]:
constant[Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean i... | keyword[def] identifier[get_layer_description_from_browser] ( identifier[self] , identifier[category] ):
literal[string]
keyword[if] identifier[category] == literal[string] :
identifier[browser] = identifier[self] . identifier[tvBrowserHazard]
keyword[elif] identifier[cate... | def get_layer_description_from_browser(self, category):
"""Obtain the description of the browser layer selected by user.
:param category: The category of the layer to get the description.
:type category: string
:returns: Tuple of boolean and string. Boolean is true if layer is
... |
def on_drag_data_received(self, widget, context, x, y, data, info, time):
"""Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:... | def function[on_drag_data_received, parameter[self, widget, context, x, y, data, info, time]]:
constant[Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-... | keyword[def] identifier[on_drag_data_received] ( identifier[self] , identifier[widget] , identifier[context] , identifier[x] , identifier[y] , identifier[data] , identifier[info] , identifier[time] ):
literal[string]
identifier[state_id_insert] = identifier[data] . identifier[get_text] ()
... | def on_drag_data_received(self, widget, context, x, y, data, info, time):
"""Receives state_id from LibraryTree and moves the state to the position of the mouse
:param widget:
:param context:
:param x: Integer: x-position of mouse
:param y: Integer: y-position of mouse
:para... |
def id(opts):
'''
Return a unique ID for this proxy minion. This ID MUST NOT CHANGE.
If it changes while the proxy is running the salt-master will get
really confused and may stop talking to this minion
'''
r = salt.utils.http.query(opts['proxy']['url']+'id', decode_type='json', decode=True)
... | def function[id, parameter[opts]]:
constant[
Return a unique ID for this proxy minion. This ID MUST NOT CHANGE.
If it changes while the proxy is running the salt-master will get
really confused and may stop talking to this minion
]
variable[r] assign[=] call[name[salt].utils.http.query,... | keyword[def] identifier[id] ( identifier[opts] ):
literal[string]
identifier[r] = identifier[salt] . identifier[utils] . identifier[http] . identifier[query] ( identifier[opts] [ literal[string] ][ literal[string] ]+ literal[string] , identifier[decode_type] = literal[string] , identifier[decode] = keyword... | def id(opts):
"""
Return a unique ID for this proxy minion. This ID MUST NOT CHANGE.
If it changes while the proxy is running the salt-master will get
really confused and may stop talking to this minion
"""
r = salt.utils.http.query(opts['proxy']['url'] + 'id', decode_type='json', decode=True)
... |
def build_error_response(self, version, reason, message):
"""
Build a simple ResponseMessage with a single error result.
Args:
version (ProtocolVersion): The protocol version the response
should be addressed with.
reason (ResultReason): An enumeration cla... | def function[build_error_response, parameter[self, version, reason, message]]:
constant[
Build a simple ResponseMessage with a single error result.
Args:
version (ProtocolVersion): The protocol version the response
should be addressed with.
reason (Result... | keyword[def] identifier[build_error_response] ( identifier[self] , identifier[version] , identifier[reason] , identifier[message] ):
literal[string]
identifier[batch_item] = identifier[messages] . identifier[ResponseBatchItem] (
identifier[result_status] = identifier[contents] . identifier... | def build_error_response(self, version, reason, message):
"""
Build a simple ResponseMessage with a single error result.
Args:
version (ProtocolVersion): The protocol version the response
should be addressed with.
reason (ResultReason): An enumeration classif... |
def parse_source(self, filename):
"""
Extract the statements from the given file, look for function calls
`sass_processor(scss_file)` and compile the filename into CSS.
"""
callvisitor = FuncCallVisitor('sass_processor')
tree = ast.parse(open(filename, 'rb').read())
... | def function[parse_source, parameter[self, filename]]:
constant[
Extract the statements from the given file, look for function calls
`sass_processor(scss_file)` and compile the filename into CSS.
]
variable[callvisitor] assign[=] call[name[FuncCallVisitor], parameter[constant[sas... | keyword[def] identifier[parse_source] ( identifier[self] , identifier[filename] ):
literal[string]
identifier[callvisitor] = identifier[FuncCallVisitor] ( literal[string] )
identifier[tree] = identifier[ast] . identifier[parse] ( identifier[open] ( identifier[filename] , literal[string] ).... | def parse_source(self, filename):
"""
Extract the statements from the given file, look for function calls
`sass_processor(scss_file)` and compile the filename into CSS.
"""
callvisitor = FuncCallVisitor('sass_processor')
tree = ast.parse(open(filename, 'rb').read())
callvisitor.v... |
def run_parallel_map_providers_query(data, queue=None):
'''
This function will be called from another process when building the
providers map.
'''
salt.utils.crypt.reinit_crypto()
cloud = Cloud(data['opts'])
try:
with salt.utils.context.func_globals_inject(
cloud.clouds[... | def function[run_parallel_map_providers_query, parameter[data, queue]]:
constant[
This function will be called from another process when building the
providers map.
]
call[name[salt].utils.crypt.reinit_crypto, parameter[]]
variable[cloud] assign[=] call[name[Cloud], parameter[call[na... | keyword[def] identifier[run_parallel_map_providers_query] ( identifier[data] , identifier[queue] = keyword[None] ):
literal[string]
identifier[salt] . identifier[utils] . identifier[crypt] . identifier[reinit_crypto] ()
identifier[cloud] = identifier[Cloud] ( identifier[data] [ literal[string] ])
... | def run_parallel_map_providers_query(data, queue=None):
"""
This function will be called from another process when building the
providers map.
"""
salt.utils.crypt.reinit_crypto()
cloud = Cloud(data['opts'])
try:
with salt.utils.context.func_globals_inject(cloud.clouds[data['fun']], ... |
def install(**kwargs):
"""setup entry point"""
if USE_SETUPTOOLS:
if "--force-manifest" in sys.argv:
sys.argv.remove("--force-manifest")
packages = [modname] + get_packages(join(base_dir, "pylint"), modname)
if USE_SETUPTOOLS:
if install_requires:
kwargs["install_... | def function[install, parameter[]]:
constant[setup entry point]
if name[USE_SETUPTOOLS] begin[:]
if compare[constant[--force-manifest] in name[sys].argv] begin[:]
call[name[sys].argv.remove, parameter[constant[--force-manifest]]]
variable[packages] assign[... | keyword[def] identifier[install] (** identifier[kwargs] ):
literal[string]
keyword[if] identifier[USE_SETUPTOOLS] :
keyword[if] literal[string] keyword[in] identifier[sys] . identifier[argv] :
identifier[sys] . identifier[argv] . identifier[remove] ( literal[string] )
identif... | def install(**kwargs):
"""setup entry point"""
if USE_SETUPTOOLS:
if '--force-manifest' in sys.argv:
sys.argv.remove('--force-manifest') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
packages = [modname] + get_packages(join(base_dir, 'pylint'), modname)
... |
def read_json(cls,
url,
orient='records'):
"""
Reads a JSON file representing a table into an SFrame.
Parameters
----------
url : string
Location of the CSV file or directory to load. If URL is a directory
or a "glob" p... | def function[read_json, parameter[cls, url, orient]]:
constant[
Reads a JSON file representing a table into an SFrame.
Parameters
----------
url : string
Location of the CSV file or directory to load. If URL is a directory
or a "glob" pattern, all matchin... | keyword[def] identifier[read_json] ( identifier[cls] ,
identifier[url] ,
identifier[orient] = literal[string] ):
literal[string]
keyword[if] identifier[orient] == literal[string] :
identifier[g] = identifier[SArray] . identifier[read_json] ( identifier[url] )
keyword[if... | def read_json(cls, url, orient='records'):
"""
Reads a JSON file representing a table into an SFrame.
Parameters
----------
url : string
Location of the CSV file or directory to load. If URL is a directory
or a "glob" pattern, all matching files will be loade... |
def stor(ftp=None):
"""Same as ftplib's storbinary() but just sends dummy data
instead of reading it from a real file.
"""
if ftp is None:
ftp = connect()
quit = True
else:
quit = False
ftp.voidcmd('TYPE I')
with contextlib.closing(ftp.transfercmd("STOR " + TESTFN)) a... | def function[stor, parameter[ftp]]:
constant[Same as ftplib's storbinary() but just sends dummy data
instead of reading it from a real file.
]
if compare[name[ftp] is constant[None]] begin[:]
variable[ftp] assign[=] call[name[connect], parameter[]]
variable[quit] ... | keyword[def] identifier[stor] ( identifier[ftp] = keyword[None] ):
literal[string]
keyword[if] identifier[ftp] keyword[is] keyword[None] :
identifier[ftp] = identifier[connect] ()
identifier[quit] = keyword[True]
keyword[else] :
identifier[quit] = keyword[False]
id... | def stor(ftp=None):
"""Same as ftplib's storbinary() but just sends dummy data
instead of reading it from a real file.
"""
if ftp is None:
ftp = connect()
quit = True # depends on [control=['if'], data=['ftp']]
else:
quit = False
ftp.voidcmd('TYPE I')
with contextlib... |
def _get_hash_object(hash_algo_name):
"""Create a hash object based on given algorithm.
:param hash_algo_name: name of the hashing algorithm.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a hash object based on the given named algorithm.
"""
algorithms = (hashlib.algori... | def function[_get_hash_object, parameter[hash_algo_name]]:
constant[Create a hash object based on given algorithm.
:param hash_algo_name: name of the hashing algorithm.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a hash object based on the given named algorithm.
]
... | keyword[def] identifier[_get_hash_object] ( identifier[hash_algo_name] ):
literal[string]
identifier[algorithms] =( identifier[hashlib] . identifier[algorithms_guaranteed] keyword[if] identifier[six] . identifier[PY3]
keyword[else] identifier[hashlib] . identifier[algorithms] )
keyword[if] i... | def _get_hash_object(hash_algo_name):
"""Create a hash object based on given algorithm.
:param hash_algo_name: name of the hashing algorithm.
:raises: InvalidInputError, on unsupported or invalid input.
:returns: a hash object based on the given named algorithm.
"""
algorithms = hashlib.algorit... |
def update_sis_id(self, course_id, sis_course_id):
"""
Updates the SIS ID for the course identified by the passed course ID.
https://canvas.instructure.com/doc/api/courses.html#method.courses.update
"""
url = COURSES_API.format(course_id)
body = {"course": {"sis_course_i... | def function[update_sis_id, parameter[self, course_id, sis_course_id]]:
constant[
Updates the SIS ID for the course identified by the passed course ID.
https://canvas.instructure.com/doc/api/courses.html#method.courses.update
]
variable[url] assign[=] call[name[COURSES_API].form... | keyword[def] identifier[update_sis_id] ( identifier[self] , identifier[course_id] , identifier[sis_course_id] ):
literal[string]
identifier[url] = identifier[COURSES_API] . identifier[format] ( identifier[course_id] )
identifier[body] ={ literal[string] :{ literal[string] : identifier[sis_... | def update_sis_id(self, course_id, sis_course_id):
"""
Updates the SIS ID for the course identified by the passed course ID.
https://canvas.instructure.com/doc/api/courses.html#method.courses.update
"""
url = COURSES_API.format(course_id)
body = {'course': {'sis_course_id': sis_cour... |
def _load_properties(self):
"""Load User properties from Flickr."""
method = 'flickr.people.getInfo'
data = _doget(method, user_id=self.__id)
self.__loaded = True
person = data.rsp.person
self.__isadmin = person.isadmin
self.__ispro = person.ispro
... | def function[_load_properties, parameter[self]]:
constant[Load User properties from Flickr.]
variable[method] assign[=] constant[flickr.people.getInfo]
variable[data] assign[=] call[name[_doget], parameter[name[method]]]
name[self].__loaded assign[=] constant[True]
variable[perso... | keyword[def] identifier[_load_properties] ( identifier[self] ):
literal[string]
identifier[method] = literal[string]
identifier[data] = identifier[_doget] ( identifier[method] , identifier[user_id] = identifier[self] . identifier[__id] )
identifier[self] . identifier[__loaded] =... | def _load_properties(self):
"""Load User properties from Flickr."""
method = 'flickr.people.getInfo'
data = _doget(method, user_id=self.__id)
self.__loaded = True
person = data.rsp.person
self.__isadmin = person.isadmin
self.__ispro = person.ispro
self.__icon_server = person.iconserver
... |
def check_is_fitted(estimator, attributes, msg=None, all_or_any=all):
"""Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
"all_or_any" of the passed attributes and raises a NotFittedError with the
given message.
Parameters
----------
... | def function[check_is_fitted, parameter[estimator, attributes, msg, all_or_any]]:
constant[Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
"all_or_any" of the passed attributes and raises a NotFittedError with the
given message.
Paramete... | keyword[def] identifier[check_is_fitted] ( identifier[estimator] , identifier[attributes] , identifier[msg] = keyword[None] , identifier[all_or_any] = identifier[all] ):
literal[string]
keyword[if] identifier[msg] keyword[is] keyword[None] :
identifier[msg] =( literal[string]
literal[... | def check_is_fitted(estimator, attributes, msg=None, all_or_any=all):
"""Perform is_fitted validation for estimator.
Checks if the estimator is fitted by verifying the presence of
"all_or_any" of the passed attributes and raises a NotFittedError with the
given message.
Parameters
----------
... |
def save_code(self, authorization_code):
"""
Stores the data belonging to an authorization code token in memcache.
See :class:`oauth2.store.AuthCodeStore`.
"""
key = self._generate_cache_key(authorization_code.code)
self.mc.set(key, {"client_id": authorization_code.cli... | def function[save_code, parameter[self, authorization_code]]:
constant[
Stores the data belonging to an authorization code token in memcache.
See :class:`oauth2.store.AuthCodeStore`.
]
variable[key] assign[=] call[name[self]._generate_cache_key, parameter[name[authorization_cod... | keyword[def] identifier[save_code] ( identifier[self] , identifier[authorization_code] ):
literal[string]
identifier[key] = identifier[self] . identifier[_generate_cache_key] ( identifier[authorization_code] . identifier[code] )
identifier[self] . identifier[mc] . identifier[set] ( identi... | def save_code(self, authorization_code):
"""
Stores the data belonging to an authorization code token in memcache.
See :class:`oauth2.store.AuthCodeStore`.
"""
key = self._generate_cache_key(authorization_code.code)
self.mc.set(key, {'client_id': authorization_code.client_id, 'code... |
def get_ordered_entries(self, queryset=False):
"""
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
... | def function[get_ordered_entries, parameter[self, queryset]]:
constant[
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
... | keyword[def] identifier[get_ordered_entries] ( identifier[self] , identifier[queryset] = keyword[False] ):
literal[string]
keyword[if] identifier[queryset] :
identifier[self] . identifier[queryset] = identifier[queryset]
keyword[else] :
identifier[self] . identi... | def get_ordered_entries(self, queryset=False):
"""
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
- ... |
def create_knowledge_base(project_id, display_name):
"""Creates a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
display_name: The display name of the Knowledge base."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.KnowledgeBasesClient()
proj... | def function[create_knowledge_base, parameter[project_id, display_name]]:
constant[Creates a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
display_name: The display name of the Knowledge base.]
import module[dialogflow_v2beta1] as alias[dialogflow]
var... | keyword[def] identifier[create_knowledge_base] ( identifier[project_id] , identifier[display_name] ):
literal[string]
keyword[import] identifier[dialogflow_v2beta1] keyword[as] identifier[dialogflow]
identifier[client] = identifier[dialogflow] . identifier[KnowledgeBasesClient] ()
identifier[... | def create_knowledge_base(project_id, display_name):
"""Creates a Knowledge base.
Args:
project_id: The GCP project linked with the agent.
display_name: The display name of the Knowledge base."""
import dialogflow_v2beta1 as dialogflow
client = dialogflow.KnowledgeBasesClient()
proj... |
def read(self, filename=None):
"""Read and parse mdp file *filename*."""
self._init_filename(filename)
def BLANK(i):
return "B{0:04d}".format(i)
def COMMENT(i):
return "C{0:04d}".format(i)
data = odict()
iblank = icomment = 0
with open(se... | def function[read, parameter[self, filename]]:
constant[Read and parse mdp file *filename*.]
call[name[self]._init_filename, parameter[name[filename]]]
def function[BLANK, parameter[i]]:
return[call[constant[B{0:04d}].format, parameter[name[i]]]]
def function[COMMENT, parameter[i... | keyword[def] identifier[read] ( identifier[self] , identifier[filename] = keyword[None] ):
literal[string]
identifier[self] . identifier[_init_filename] ( identifier[filename] )
keyword[def] identifier[BLANK] ( identifier[i] ):
keyword[return] literal[string] . identifier[f... | def read(self, filename=None):
"""Read and parse mdp file *filename*."""
self._init_filename(filename)
def BLANK(i):
return 'B{0:04d}'.format(i)
def COMMENT(i):
return 'C{0:04d}'.format(i)
data = odict()
iblank = icomment = 0
with open(self.real_filename) as mdp:
fo... |
def disable_cloud_integration(self, id, **kwargs): # noqa: E501
"""Disable a specific cloud integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.disabl... | def function[disable_cloud_integration, parameter[self, id]]:
constant[Disable a specific cloud integration # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.dis... | keyword[def] identifier[disable_cloud_integration] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] ident... | def disable_cloud_integration(self, id, **kwargs): # noqa: E501
'Disable a specific cloud integration # noqa: E501\n\n # 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.disable... |
def fetch_liked_projects(self, **kwargs):
"""
List liked projects
Fetch projects that the currently authenticated user likes.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked w... | def function[fetch_liked_projects, parameter[self]]:
constant[
List liked projects
Fetch projects that the currently authenticated user likes.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
... | keyword[def] identifier[fetch_liked_projects] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
keyword[return] identifier[self] . identifi... | def fetch_liked_projects(self, **kwargs):
"""
List liked projects
Fetch projects that the currently authenticated user likes.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when ... |
def comunicar_certificado_icpbrasil(self, certificado):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
retorno = super(ClienteSATLocal, self).\
comunica... | def function[comunicar_certificado_icpbrasil, parameter[self, certificado]]:
constant[Sobrepõe :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
]
variable[retorno] assign[=] call[call[na... | keyword[def] identifier[comunicar_certificado_icpbrasil] ( identifier[self] , identifier[certificado] ):
literal[string]
identifier[retorno] = identifier[super] ( identifier[ClienteSATLocal] , identifier[self] ). identifier[comunicar_certificado_icpbrasil] ( identifier[certificado] )
keywo... | def comunicar_certificado_icpbrasil(self, certificado):
"""Sobrepõe :meth:`~satcfe.base.FuncoesSAT.comunicar_certificado_icpbrasil`.
:return: Uma resposta SAT padrão.
:rtype: satcfe.resposta.padrao.RespostaSAT
"""
retorno = super(ClienteSATLocal, self).comunicar_certificado_icpbrasil(ce... |
def _message_symbol(self, msgid):
"""Get the message symbol of the given message id
Return the original message id if the message does not
exist.
"""
try:
return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)]
except UnknownMessageError:
... | def function[_message_symbol, parameter[self, msgid]]:
constant[Get the message symbol of the given message id
Return the original message id if the message does not
exist.
]
<ast.Try object at 0x7da1b02585e0> | keyword[def] identifier[_message_symbol] ( identifier[self] , identifier[msgid] ):
literal[string]
keyword[try] :
keyword[return] [ identifier[md] . identifier[symbol] keyword[for] identifier[md] keyword[in] identifier[self] . identifier[msgs_store] . identifier[get_message_definit... | def _message_symbol(self, msgid):
"""Get the message symbol of the given message id
Return the original message id if the message does not
exist.
"""
try:
return [md.symbol for md in self.msgs_store.get_message_definitions(msgid)] # depends on [control=['try'], data=[]]
exc... |
def read(self, callback=None):
"""
The device returns an MSB and LSB (in that order) for each axis.
These are 12 bit values - that is only the upper 4 bits of the LSB are used.
To make things more confusing, firmata returns each axis as 4 bytes, and reverses the order because
it... | def function[read, parameter[self, callback]]:
constant[
The device returns an MSB and LSB (in that order) for each axis.
These are 12 bit values - that is only the upper 4 bits of the LSB are used.
To make things more confusing, firmata returns each axis as 4 bytes, and reverses the or... | keyword[def] identifier[read] ( identifier[self] , identifier[callback] = keyword[None] ):
literal[string]
identifier[register] = identifier[self] . identifier[MMA8452Q_Register] [ literal[string] ]
identifier[self] . identifier[board] . identifier[i2c_read_request] ( identifier[self] . id... | def read(self, callback=None):
"""
The device returns an MSB and LSB (in that order) for each axis.
These are 12 bit values - that is only the upper 4 bits of the LSB are used.
To make things more confusing, firmata returns each axis as 4 bytes, and reverses the order because
it loo... |
def parse_group(self, stream):
"""Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begi... | def function[parse_group, parameter[self, stream]]:
constant[Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
]
call[na... | keyword[def] identifier[parse_group] ( identifier[self] , identifier[stream] ):
literal[string]
identifier[self] . identifier[expect_in] ( identifier[stream] , identifier[self] . identifier[begin_group_tokens] )
identifier[self] . identifier[ensure_assignment] ( identifier[stream] )
... | def parse_group(self, stream):
"""Block Name must match Block Name in paired End Group Statement if
Block Name is present in End Group Statement.
BeginGroupStmt ::=
BeginGroupKeywd WSC AssignmentSymbol WSC BlockName StatementDelim
"""
self.expect_in(stream, self.begin_group_... |
def main(manual_args=None):
"""Foremast, your ship's support."""
parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.set_defaults(func=parser.print_help)
add_debug(parser)
parser.add_argument(
'-s',
'--short-log',
... | def function[main, parameter[manual_args]]:
constant[Foremast, your ship's support.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
call[name[parser].set_defaults, parameter[]]
call[name[add_debug], parameter[name[parser]]]
call[name[parser].add_argum... | keyword[def] identifier[main] ( identifier[manual_args] = keyword[None] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[description] = identifier[main] . identifier[__doc__] , identifier[formatter_class] = identifier[argparse] . identifier[ArgumentDefa... | def main(manual_args=None):
"""Foremast, your ship's support."""
parser = argparse.ArgumentParser(description=main.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.set_defaults(func=parser.print_help)
add_debug(parser)
parser.add_argument('-s', '--short-log', action='store_con... |
def convert_to_process_params_dict(opt):
"""
Takes the namespace object (opt) from the multi-detector interface and
returns a dictionary of command line options that will be handled correctly
by the register_to_process_params ligolw function.
"""
opt = copy.deepcopy(opt)
for arg, val in vars... | def function[convert_to_process_params_dict, parameter[opt]]:
constant[
Takes the namespace object (opt) from the multi-detector interface and
returns a dictionary of command line options that will be handled correctly
by the register_to_process_params ligolw function.
]
variable[opt] as... | keyword[def] identifier[convert_to_process_params_dict] ( identifier[opt] ):
literal[string]
identifier[opt] = identifier[copy] . identifier[deepcopy] ( identifier[opt] )
keyword[for] identifier[arg] , identifier[val] keyword[in] identifier[vars] ( identifier[opt] ). identifier[items] ():
... | def convert_to_process_params_dict(opt):
"""
Takes the namespace object (opt) from the multi-detector interface and
returns a dictionary of command line options that will be handled correctly
by the register_to_process_params ligolw function.
"""
opt = copy.deepcopy(opt)
for (arg, val) in va... |
def get(self, workflow_id, email_id):
"""
Get information about an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:t... | def function[get, parameter[self, workflow_id, email_id]]:
constant[
Get information about an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation... | keyword[def] identifier[get] ( identifier[self] , identifier[workflow_id] , identifier[email_id] ):
literal[string]
identifier[self] . identifier[workflow_id] = identifier[workflow_id]
identifier[self] . identifier[email_id] = identifier[email_id]
keyword[return] identifier[sel... | def get(self, workflow_id, email_id):
"""
Get information about an individual Automation workflow email.
:param workflow_id: The unique id for the Automation workflow.
:type workflow_id: :py:class:`str`
:param email_id: The unique id for the Automation workflow email.
:type ... |
def add_health_monitor(self, type, delay=10, timeout=10,
attemptsBeforeDeactivation=3, path="/", statusRegex=None,
bodyRegex=None, hostHeader=None):
"""
Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied settings.
... | def function[add_health_monitor, parameter[self, type, delay, timeout, attemptsBeforeDeactivation, path, statusRegex, bodyRegex, hostHeader]]:
constant[
Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied settings.
]
variable[a... | keyword[def] identifier[add_health_monitor] ( identifier[self] , identifier[type] , identifier[delay] = literal[int] , identifier[timeout] = literal[int] ,
identifier[attemptsBeforeDeactivation] = literal[int] , identifier[path] = literal[string] , identifier[statusRegex] = keyword[None] ,
identifier[bodyRegex] = k... | def add_health_monitor(self, type, delay=10, timeout=10, attemptsBeforeDeactivation=3, path='/', statusRegex=None, bodyRegex=None, hostHeader=None):
"""
Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied settings.
"""
abd = attemptsBe... |
def get(cls, resolvable_string, options_builder=None, interpreter=None):
"""Get a :class:`Resolvable` from a string.
:returns: A :class:`Resolvable` or ``None`` if no implementation was appropriate.
"""
options_builder = options_builder or ResolverOptionsBuilder()
for resolvable_impl in cls._REGIST... | def function[get, parameter[cls, resolvable_string, options_builder, interpreter]]:
constant[Get a :class:`Resolvable` from a string.
:returns: A :class:`Resolvable` or ``None`` if no implementation was appropriate.
]
variable[options_builder] assign[=] <ast.BoolOp object at 0x7da2041dafb0>
... | keyword[def] identifier[get] ( identifier[cls] , identifier[resolvable_string] , identifier[options_builder] = keyword[None] , identifier[interpreter] = keyword[None] ):
literal[string]
identifier[options_builder] = identifier[options_builder] keyword[or] identifier[ResolverOptionsBuilder] ()
keywor... | def get(cls, resolvable_string, options_builder=None, interpreter=None):
"""Get a :class:`Resolvable` from a string.
:returns: A :class:`Resolvable` or ``None`` if no implementation was appropriate.
"""
options_builder = options_builder or ResolverOptionsBuilder()
for resolvable_impl in cls._REGIST... |
def pltnp(point, v1, v2, v3):
"""
Find the nearest point on a triangular plate to a given point.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html
:param point: A point in 3-dimensional space.
:type point: 3-Element Array of floats
:param v1: Vertices of a triangu... | def function[pltnp, parameter[point, v1, v2, v3]]:
constant[
Find the nearest point on a triangular plate to a given point.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html
:param point: A point in 3-dimensional space.
:type point: 3-Element Array of floats
:... | keyword[def] identifier[pltnp] ( identifier[point] , identifier[v1] , identifier[v2] , identifier[v3] ):
literal[string]
identifier[point] = identifier[stypes] . identifier[toDoubleVector] ( identifier[point] )
identifier[v1] = identifier[stypes] . identifier[toDoubleVector] ( identifier[v1] )
id... | def pltnp(point, v1, v2, v3):
"""
Find the nearest point on a triangular plate to a given point.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pltnp_c.html
:param point: A point in 3-dimensional space.
:type point: 3-Element Array of floats
:param v1: Vertices of a triangu... |
def mode(self, predicate, args, recall=1, head=False):
'''
Emits mode declarations in Aleph-like format.
:param predicate: predicate name
:param args: predicate arguments with input/output specification, e.g.:
>>> [('+', 'train'), ('-', 'car')]
:param r... | def function[mode, parameter[self, predicate, args, recall, head]]:
constant[
Emits mode declarations in Aleph-like format.
:param predicate: predicate name
:param args: predicate arguments with input/output specification, e.g.:
>>> [('+', 'train'), ('-', 'car')]
... | keyword[def] identifier[mode] ( identifier[self] , identifier[predicate] , identifier[args] , identifier[recall] = literal[int] , identifier[head] = keyword[False] ):
literal[string]
keyword[return] literal[string] %(
literal[string] keyword[if] identifier[head] keyword[else] literal[... | def mode(self, predicate, args, recall=1, head=False):
"""
Emits mode declarations in Aleph-like format.
:param predicate: predicate name
:param args: predicate arguments with input/output specification, e.g.:
>>> [('+', 'train'), ('-', 'car')]
:param recal... |
def _ends_with_vowel(self, letter_group: str) -> bool:
"""Check if a string ends with a vowel."""
if len(letter_group) == 0:
return False
return self._contains_vowels(letter_group[-1]) | def function[_ends_with_vowel, parameter[self, letter_group]]:
constant[Check if a string ends with a vowel.]
if compare[call[name[len], parameter[name[letter_group]]] equal[==] constant[0]] begin[:]
return[constant[False]]
return[call[name[self]._contains_vowels, parameter[call[name[letter_... | keyword[def] identifier[_ends_with_vowel] ( identifier[self] , identifier[letter_group] : identifier[str] )-> identifier[bool] :
literal[string]
keyword[if] identifier[len] ( identifier[letter_group] )== literal[int] :
keyword[return] keyword[False]
keyword[return] identif... | def _ends_with_vowel(self, letter_group: str) -> bool:
"""Check if a string ends with a vowel."""
if len(letter_group) == 0:
return False # depends on [control=['if'], data=[]]
return self._contains_vowels(letter_group[-1]) |
def get_abbreviations(self):
"""
Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available).
"""
abbreviations = []
try:
type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation"
... | def function[get_abbreviations, parameter[self]]:
constant[
Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available).
]
variable[abbreviations] assign[=] list[[]]
<ast.Try object at 0x7da2041d99c0> | keyword[def] identifier[get_abbreviations] ( identifier[self] ):
literal[string]
identifier[abbreviations] =[]
keyword[try] :
identifier[type_abbreviation] = identifier[self] . identifier[session] . identifier[get_resource] ( identifier[BASE_URI_TYPES] % literal[string]
... | def get_abbreviations(self):
"""
Get abbreviations of the names of the author.
:return: a list of strings (empty list if no abbreviations available).
"""
abbreviations = []
try:
type_abbreviation = self.session.get_resource(BASE_URI_TYPES % 'abbreviation', self.session.get_c... |
def update_consumer_group(self, project, logstore, consumer_group, timeout=None, in_order=None):
""" Update consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
... | def function[update_consumer_group, parameter[self, project, logstore, consumer_group, timeout, in_order]]:
constant[ Update consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: st... | keyword[def] identifier[update_consumer_group] ( identifier[self] , identifier[project] , identifier[logstore] , identifier[consumer_group] , identifier[timeout] = keyword[None] , identifier[in_order] = keyword[None] ):
literal[string]
keyword[if] identifier[in_order] keyword[is] keyword[None]... | def update_consumer_group(self, project, logstore, consumer_group, timeout=None, in_order=None):
""" Update consumer group
:type project: string
:param project: project name
:type logstore: string
:param logstore: logstore name
:type consumer_group: string
:param c... |
def run_to_selected_state(self, path, state_machine_id=None):
"""Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task
"""
if self.state_machine_manager.get_active_state_machine() is not None:
self.state_machine_manager.get_activ... | def function[run_to_selected_state, parameter[self, path, state_machine_id]]:
constant[Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task
]
if compare[call[name[self].state_machine_manager.get_active_state_machine, parameter[]] is_not con... | keyword[def] identifier[run_to_selected_state] ( identifier[self] , identifier[path] , identifier[state_machine_id] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[state_machine_manager] . identifier[get_active_state_machine] () keyword[is] keyword[not] keyword[None]... | def run_to_selected_state(self, path, state_machine_id=None):
"""Execute the state machine until a specific state. This state won't be executed. This is an asynchronous task
"""
if self.state_machine_manager.get_active_state_machine() is not None:
self.state_machine_manager.get_active_state_mach... |
def callMLlibFunc(name, *args):
""" Call API in PythonMLLibAPI """
sc = SparkContext.getOrCreate()
api = getattr(sc._jvm.PythonMLLibAPI(), name)
return callJavaFunc(sc, api, *args) | def function[callMLlibFunc, parameter[name]]:
constant[ Call API in PythonMLLibAPI ]
variable[sc] assign[=] call[name[SparkContext].getOrCreate, parameter[]]
variable[api] assign[=] call[name[getattr], parameter[call[name[sc]._jvm.PythonMLLibAPI, parameter[]], name[name]]]
return[call[name[c... | keyword[def] identifier[callMLlibFunc] ( identifier[name] ,* identifier[args] ):
literal[string]
identifier[sc] = identifier[SparkContext] . identifier[getOrCreate] ()
identifier[api] = identifier[getattr] ( identifier[sc] . identifier[_jvm] . identifier[PythonMLLibAPI] (), identifier[name] )
key... | def callMLlibFunc(name, *args):
""" Call API in PythonMLLibAPI """
sc = SparkContext.getOrCreate()
api = getattr(sc._jvm.PythonMLLibAPI(), name)
return callJavaFunc(sc, api, *args) |
def _humanize_bytes(num_bytes, precision=1):
"""
Return a humanized string representation of a number of num_bytes.
from:
http://code.activestate.com/recipes/
577081-humanized-representation-of-a-number-of-num_bytes/
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
... | def function[_humanize_bytes, parameter[num_bytes, precision]]:
constant[
Return a humanized string representation of a number of num_bytes.
from:
http://code.activestate.com/recipes/
577081-humanized-representation-of-a-number-of-num_bytes/
Assumes `from __future__ import division`... | keyword[def] identifier[_humanize_bytes] ( identifier[num_bytes] , identifier[precision] = literal[int] ):
literal[string]
keyword[if] identifier[num_bytes] == literal[int] :
keyword[return] literal[string]
keyword[if] identifier[num_bytes] == literal[int] :
keyword[return] lite... | def _humanize_bytes(num_bytes, precision=1):
"""
Return a humanized string representation of a number of num_bytes.
from:
http://code.activestate.com/recipes/
577081-humanized-representation-of-a-number-of-num_bytes/
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
... |
def pdb_downloader_and_metadata(self, outdir=None, pdb_file_type=None, force_rerun=False):
"""Download ALL mapped experimental structures to each protein's structures directory.
Args:
outdir (str): Path to output directory, if GEM-PRO directories were not set or other output directory is
... | def function[pdb_downloader_and_metadata, parameter[self, outdir, pdb_file_type, force_rerun]]:
constant[Download ALL mapped experimental structures to each protein's structures directory.
Args:
outdir (str): Path to output directory, if GEM-PRO directories were not set or other output dire... | keyword[def] identifier[pdb_downloader_and_metadata] ( identifier[self] , identifier[outdir] = keyword[None] , identifier[pdb_file_type] = keyword[None] , identifier[force_rerun] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[pdb_file_type] :
identifier[pdb_... | def pdb_downloader_and_metadata(self, outdir=None, pdb_file_type=None, force_rerun=False):
"""Download ALL mapped experimental structures to each protein's structures directory.
Args:
outdir (str): Path to output directory, if GEM-PRO directories were not set or other output directory is
... |
def wrap(query, container, namespace):
"""
NORMALIZE QUERY SO IT CAN STILL BE JSON
"""
if is_op(query, QueryOp) or query == None:
return query
query = wrap(query)
table = container.get_table(query['from'])
schema = table.schema
output = QueryO... | def function[wrap, parameter[query, container, namespace]]:
constant[
NORMALIZE QUERY SO IT CAN STILL BE JSON
]
if <ast.BoolOp object at 0x7da1b0ab48e0> begin[:]
return[name[query]]
variable[query] assign[=] call[name[wrap], parameter[name[query]]]
variable[table]... | keyword[def] identifier[wrap] ( identifier[query] , identifier[container] , identifier[namespace] ):
literal[string]
keyword[if] identifier[is_op] ( identifier[query] , identifier[QueryOp] ) keyword[or] identifier[query] == keyword[None] :
keyword[return] identifier[query]
... | def wrap(query, container, namespace):
"""
NORMALIZE QUERY SO IT CAN STILL BE JSON
"""
if is_op(query, QueryOp) or query == None:
return query # depends on [control=['if'], data=[]]
query = wrap(query)
table = container.get_table(query['from'])
schema = table.schema
outp... |
def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
for key, value in data.items():
if "__classname__" not in value: # pragma: no cover
raise ValueError
na... | def function[load, parameter[cls, data]]:
constant[Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
]
if compare[call[name[len], parameter[name[data]]] equal[==] constant[1]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da1b0b3a380>, <ast.Name ... | keyword[def] identifier[load] ( identifier[cls] , identifier[data] ):
literal[string]
keyword[if] identifier[len] ( identifier[data] )== literal[int] :
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[data] . identifier[items] ():
keyword[if]... | def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
for (key, value) in data.items():
if '__classname__' not in value: # pragma: no cover
raise ValueError # depends on [control=['if'], data=... |
def _parse_decorated_functions(self, code):
"""Return URL rule, HTTP methods and docstring."""
matches = re.finditer(r"""
# @rest decorators
(?P<decorators>
(?:@rest\(.+?\)\n)+ # one or more @rest decorators inside
)
# ... | def function[_parse_decorated_functions, parameter[self, code]]:
constant[Return URL rule, HTTP methods and docstring.]
variable[matches] assign[=] call[name[re].finditer, parameter[constant[
# @rest decorators
(?P<decorators>
(?:@rest\(.+?\)\n)+ # on... | keyword[def] identifier[_parse_decorated_functions] ( identifier[self] , identifier[code] ):
literal[string]
identifier[matches] = identifier[re] . identifier[finditer] ( literal[string] , identifier[code] , identifier[re] . identifier[VERBOSE] | identifier[re] . identifier[DOTALL] )
keyw... | def _parse_decorated_functions(self, code):
"""Return URL rule, HTTP methods and docstring."""
matches = re.finditer('\n # @rest decorators\n (?P<decorators>\n (?:@rest\\(.+?\\)\\n)+ # one or more @rest decorators inside\n )\n # doc... |
def remove_members(self, project, params={}, **options):
"""Removes the specified list of members from the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to remove members from.
[data] : {Object} Data for the request
- me... | def function[remove_members, parameter[self, project, params]]:
constant[Removes the specified list of members from the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to remove members from.
[data] : {Object} Data for the request
... | keyword[def] identifier[remove_members] ( identifier[self] , identifier[project] , identifier[params] ={},** identifier[options] ):
literal[string]
identifier[path] = literal[string] %( identifier[project] )
keyword[return] identifier[self] . identifier[client] . identifier[post] ( identi... | def remove_members(self, project, params={}, **options):
"""Removes the specified list of members from the project. Returns the updated project record.
Parameters
----------
project : {Id} The project to remove members from.
[data] : {Object} Data for the request
- members... |
def encode_request(request_line, **headers):
'''Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
value pairs to pres... | def function[encode_request, parameter[request_line]]:
constant[Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
... | keyword[def] identifier[encode_request] ( identifier[request_line] ,** identifier[headers] ):
literal[string]
identifier[lines] =[ identifier[request_line] ]
identifier[lines] . identifier[extend] ([ literal[string] % identifier[kv] keyword[for] identifier[kv] keyword[in] identifier[headers] . ide... | def encode_request(request_line, **headers):
"""Creates the data for a SSDP request.
Args:
request_line (string): The request line for the request (e.g.
``"M-SEARCH * HTTP/1.1"``).
headers (dict of string -> string): Dictionary of header name - header
value pairs to pres... |
def figure_chronological(self):
"""plot every sweep of an ABF file (with comments)."""
self.log.debug("creating chronological plot")
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
self.setColorBySweep()
if self.abf.derivati... | def function[figure_chronological, parameter[self]]:
constant[plot every sweep of an ABF file (with comments).]
call[name[self].log.debug, parameter[constant[creating chronological plot]]]
call[name[self].figure, parameter[]]
for taget[name[sweep]] in starred[call[name[range], parameter[... | keyword[def] identifier[figure_chronological] ( identifier[self] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[figure] ()
keyword[for] identifier[sweep] keyword[in] identifier[range] ( identifier[self... | def figure_chronological(self):
"""plot every sweep of an ABF file (with comments)."""
self.log.debug('creating chronological plot')
self.figure()
for sweep in range(self.abf.sweeps):
self.abf.setsweep(sweep)
self.setColorBySweep()
if self.abf.derivative:
plt.plot(sel... |
def data_size(self):
""" Returns the size of the :attr:`data` object in bytes (read-only)."""
# Container
if is_container(self._data):
byte_length, bit_length = self._data.container_size()
return byte_length + math.ceil(bit_length / 8)
# Field
elif is_fiel... | def function[data_size, parameter[self]]:
constant[ Returns the size of the :attr:`data` object in bytes (read-only).]
if call[name[is_container], parameter[name[self]._data]] begin[:]
<ast.Tuple object at 0x7da1b209d4e0> assign[=] call[name[self]._data.container_size, parameter[]]
... | keyword[def] identifier[data_size] ( identifier[self] ):
literal[string]
keyword[if] identifier[is_container] ( identifier[self] . identifier[_data] ):
identifier[byte_length] , identifier[bit_length] = identifier[self] . identifier[_data] . identifier[container_size] ()
... | def data_size(self):
""" Returns the size of the :attr:`data` object in bytes (read-only)."""
# Container
if is_container(self._data):
(byte_length, bit_length) = self._data.container_size()
return byte_length + math.ceil(bit_length / 8) # depends on [control=['if'], data=[]]
# Field
... |
async def vcx_agent_provision(config: str) -> None:
"""
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey... | <ast.AsyncFunctionDef object at 0x7da18f09e650> | keyword[async] keyword[def] identifier[vcx_agent_provision] ( identifier[config] : identifier[str] )-> keyword[None] :
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
keyword[if] keyword[not] identifier[hasattr] ( identifier[vcx_agent_provi... | async def vcx_agent_provision(config: str) -> None:
"""
Provision an agent in the agency, populate configuration and wallet for this agent.
Example:
import json
enterprise_config = {
'agency_url': 'http://localhost:8080',
'agency_did': 'VsKV7grR1BUE29mG2Fm2kX',
'agency_verkey... |
def as_mpl_artists(shape_list,
properties_func=None,
text_offset=5.0, origin=1):
"""
Converts a region list to a list of patches and a list of artists.
Optional Keywords:
[ text_offset ] - If there is text associated with the regions, add
some vertical offset ... | def function[as_mpl_artists, parameter[shape_list, properties_func, text_offset, origin]]:
constant[
Converts a region list to a list of patches and a list of artists.
Optional Keywords:
[ text_offset ] - If there is text associated with the regions, add
some vertical offset (in pixels) to the... | keyword[def] identifier[as_mpl_artists] ( identifier[shape_list] ,
identifier[properties_func] = keyword[None] ,
identifier[text_offset] = literal[int] , identifier[origin] = literal[int] ):
literal[string]
identifier[patch_list] =[]
identifier[artist_list] =[]
keyword[if] identifier[propert... | def as_mpl_artists(shape_list, properties_func=None, text_offset=5.0, origin=1):
"""
Converts a region list to a list of patches and a list of artists.
Optional Keywords:
[ text_offset ] - If there is text associated with the regions, add
some vertical offset (in pixels) to the text so that it doe... |
def Grieves_Thodos(zs, Tcs, Aijs):
r'''Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \sum_{i} \frac{T_{ci}}{1 + (1/x_i)\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = \frac{T_{c1}}{1 + (x_2/x_1)A_... | def function[Grieves_Thodos, parameter[zs, Tcs, Aijs]]:
constant[Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \sum_{i} \frac{T_{ci}}{1 + (1/x_i)\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} =... | keyword[def] identifier[Grieves_Thodos] ( identifier[zs] , identifier[Tcs] , identifier[Aijs] ):
literal[string]
keyword[if] keyword[not] identifier[none_and_length_check] ([ identifier[zs] , identifier[Tcs] ]):
keyword[raise] identifier[Exception] ( literal[string] )
identifier[Tcm] = lit... | def Grieves_Thodos(zs, Tcs, Aijs):
"""Calculates critical temperature of a mixture according to
mixing rules in [1]_.
.. math::
T_{cm} = \\sum_{i} \\frac{T_{ci}}{1 + (1/x_i)\\sum_j A_{ij} x_j}
For a binary mxiture, this simplifies to:
.. math::
T_{cm} = \\frac{T_{c1}}{1 + (x_2/x_1... |
def import_or_die(module_name, entrypoint_names):
'''
Import user code; return reference to usercode function.
(str) -> function reference
'''
log_debug("Importing {}".format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
module_name,ext = o... | def function[import_or_die, parameter[module_name, entrypoint_names]]:
constant[
Import user code; return reference to usercode function.
(str) -> function reference
]
call[name[log_debug], parameter[call[constant[Importing {}].format, parameter[name[module_name]]]]]
variable[module... | keyword[def] identifier[import_or_die] ( identifier[module_name] , identifier[entrypoint_names] ):
literal[string]
identifier[log_debug] ( literal[string] . identifier[format] ( identifier[module_name] ))
identifier[module_name] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[mo... | def import_or_die(module_name, entrypoint_names):
"""
Import user code; return reference to usercode function.
(str) -> function reference
"""
log_debug('Importing {}'.format(module_name))
module_name = os.path.abspath(module_name)
if module_name.endswith('.py'):
(module_name, ext) ... |
def _getBlobFromURL(cls, url, exists=False):
"""
Gets the blob specified by the url.
caution: makes no api request. blob may not ACTUALLY exist
:param urlparse.ParseResult url: the URL
:param bool exists: if True, then syncs local blob object with cloud
and raises exce... | def function[_getBlobFromURL, parameter[cls, url, exists]]:
constant[
Gets the blob specified by the url.
caution: makes no api request. blob may not ACTUALLY exist
:param urlparse.ParseResult url: the URL
:param bool exists: if True, then syncs local blob object with cloud
... | keyword[def] identifier[_getBlobFromURL] ( identifier[cls] , identifier[url] , identifier[exists] = keyword[False] ):
literal[string]
identifier[bucketName] = identifier[url] . identifier[netloc]
identifier[fileName] = identifier[url] . identifier[path]
keyword[if] id... | def _getBlobFromURL(cls, url, exists=False):
"""
Gets the blob specified by the url.
caution: makes no api request. blob may not ACTUALLY exist
:param urlparse.ParseResult url: the URL
:param bool exists: if True, then syncs local blob object with cloud
and raises exceptio... |
def text(self, x, y, text):
"""Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
"""
for i, char in enumerate(text):
... | def function[text, parameter[self, x, y, text]]:
constant[Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
]
for taget[... | keyword[def] identifier[text] ( identifier[self] , identifier[x] , identifier[y] , identifier[text] ):
literal[string]
keyword[for] identifier[i] , identifier[char] keyword[in] identifier[enumerate] ( identifier[text] ):
identifier[self] . identifier[point] ( identifier[x] + identif... | def text(self, x, y, text):
"""Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
"""
for (i, char) in enumerate(text):
s... |
def localize(self):
"""
Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
:rtype: toil.resourc... | def function[localize, parameter[self]]:
constant[
Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
... | keyword[def] identifier[localize] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_runningOnWorker] ():
identifier[log] . identifier[warn] ( literal[string] )
identifier[resource] = identifier[Resource] . identifier[lookup] ( iden... | def localize(self):
"""
Check if this module was saved as a resource. If it was, return a new module descriptor
that points to a local copy of that resource. Should only be called on a worker node. On
the leader, this method returns this resource, i.e. self.
:rtype: toil.resource.Re... |
def color_normalize(src, mean, std=None):
"""Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDAr... | def function[color_normalize, parameter[src, mean, std]]:
constant[Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
... | keyword[def] identifier[color_normalize] ( identifier[src] , identifier[mean] , identifier[std] = keyword[None] ):
literal[string]
keyword[if] identifier[mean] keyword[is] keyword[not] keyword[None] :
identifier[src] -= identifier[mean]
keyword[if] identifier[std] keyword[is] keyword[... | def color_normalize(src, mean, std=None):
"""Normalize src with mean and std.
Parameters
----------
src : NDArray
Input image
mean : NDArray
RGB mean to be subtracted
std : NDArray
RGB standard deviation to be divided
Returns
-------
NDArray
An `NDAr... |
def trending(limit=DEFAULT_SEARCH_LIMIT, api_key=GIPHY_PUBLIC_KEY,
strict=False, rating=None):
"""
Shorthand for creating a Giphy api wrapper with the given api key
and then calling the trending method. Note that this will return
a generator
"""
return Giphy(api_key=api_key, strict=... | def function[trending, parameter[limit, api_key, strict, rating]]:
constant[
Shorthand for creating a Giphy api wrapper with the given api key
and then calling the trending method. Note that this will return
a generator
]
return[call[call[name[Giphy], parameter[]].trending, parameter[]]] | keyword[def] identifier[trending] ( identifier[limit] = identifier[DEFAULT_SEARCH_LIMIT] , identifier[api_key] = identifier[GIPHY_PUBLIC_KEY] ,
identifier[strict] = keyword[False] , identifier[rating] = keyword[None] ):
literal[string]
keyword[return] identifier[Giphy] ( identifier[api_key] = identifier[... | def trending(limit=DEFAULT_SEARCH_LIMIT, api_key=GIPHY_PUBLIC_KEY, strict=False, rating=None):
"""
Shorthand for creating a Giphy api wrapper with the given api key
and then calling the trending method. Note that this will return
a generator
"""
return Giphy(api_key=api_key, strict=strict).trend... |
def get_rules(scenario_id, **kwargs):
"""
Get all the rules for a given scenario.
"""
rules = db.DBSession.query(Rule).filter(Rule.scenario_id==scenario_id, Rule.status=='A').all()
return rules | def function[get_rules, parameter[scenario_id]]:
constant[
Get all the rules for a given scenario.
]
variable[rules] assign[=] call[call[call[name[db].DBSession.query, parameter[name[Rule]]].filter, parameter[compare[name[Rule].scenario_id equal[==] name[scenario_id]], compare[name[Rule].sta... | keyword[def] identifier[get_rules] ( identifier[scenario_id] ,** identifier[kwargs] ):
literal[string]
identifier[rules] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[Rule] ). identifier[filter] ( identifier[Rule] . identifier[scenario_id] == identifier[scenario_id] , identifier... | def get_rules(scenario_id, **kwargs):
"""
Get all the rules for a given scenario.
"""
rules = db.DBSession.query(Rule).filter(Rule.scenario_id == scenario_id, Rule.status == 'A').all()
return rules |
def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> act... | def function[switch, parameter[self]]:
constant[Switch if time for eAgc has come]
variable[t] assign[=] name[self].system.dae.t
for taget[name[idx]] in starred[call[name[range], parameter[constant[0], name[self].n]]] begin[:]
if compare[name[t] greater_or_equal[>=] call[name[self... | keyword[def] identifier[switch] ( identifier[self] ):
literal[string]
identifier[t] = identifier[self] . identifier[system] . identifier[dae] . identifier[t]
keyword[for] identifier[idx] keyword[in] identifier[range] ( literal[int] , identifier[self] . identifier[n] ):
key... | def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info('Extended ACE <{}> activated at t = {}.'.format(self.idx[idx], t)) # depen... |
def send(self, peer, typename, data):
"""
Sends a packet to a peer.
"""
def attempt_to_send(_):
if peer not in self._connections:
d = self._connect(peer)
d.addCallback(attempt_to_send)
return d
else:
... | def function[send, parameter[self, peer, typename, data]]:
constant[
Sends a packet to a peer.
]
def function[attempt_to_send, parameter[_]]:
if compare[name[peer] <ast.NotIn object at 0x7da2590d7190> name[self]._connections] begin[:]
variable[d] a... | keyword[def] identifier[send] ( identifier[self] , identifier[peer] , identifier[typename] , identifier[data] ):
literal[string]
keyword[def] identifier[attempt_to_send] ( identifier[_] ):
keyword[if] identifier[peer] keyword[not] keyword[in] identifier[self] . identifier[_conne... | def send(self, peer, typename, data):
"""
Sends a packet to a peer.
"""
def attempt_to_send(_):
if peer not in self._connections:
d = self._connect(peer)
d.addCallback(attempt_to_send)
return d # depends on [control=['if'], data=['peer']]
els... |
def write_hdf5_dict(tsdict, h5f, group=None, **kwargs):
"""Write a `TimeSeriesBaseDict` to HDF5
Each series in the dict is written as a dataset in the group
"""
# create group if needed
if group and group not in h5f:
h5g = h5f.create_group(group)
elif group:
h5g = h5f[group]
... | def function[write_hdf5_dict, parameter[tsdict, h5f, group]]:
constant[Write a `TimeSeriesBaseDict` to HDF5
Each series in the dict is written as a dataset in the group
]
if <ast.BoolOp object at 0x7da1b060ace0> begin[:]
variable[h5g] assign[=] call[name[h5f].create_group, param... | keyword[def] identifier[write_hdf5_dict] ( identifier[tsdict] , identifier[h5f] , identifier[group] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[group] keyword[and] identifier[group] keyword[not] keyword[in] identifier[h5f] :
identifier[h5g] = identif... | def write_hdf5_dict(tsdict, h5f, group=None, **kwargs):
"""Write a `TimeSeriesBaseDict` to HDF5
Each series in the dict is written as a dataset in the group
"""
# create group if needed
if group and group not in h5f:
h5g = h5f.create_group(group) # depends on [control=['if'], data=[]]
... |
def get_form(self, request, obj=None, **kwargs):
"""Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request."""
template = get_template_from_request(request, obj)
#model = create_page_model(get_pl... | def function[get_form, parameter[self, request, obj]]:
constant[Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request.]
variable[template] assign[=] call[name[get_template_from_request], parameter[name[re... | keyword[def] identifier[get_form] ( identifier[self] , identifier[request] , identifier[obj] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[template] = identifier[get_template_from_request] ( identifier[request] , identifier[obj] )
identifier[form] = ident... | def get_form(self, request, obj=None, **kwargs):
"""Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request."""
template = get_template_from_request(request, obj)
#model = create_page_model(get_placeholders(tem... |
def _classify_section(cls, section):
"""Attempt to find the canonical name of this section."""
name = section.lower()
if name in frozenset(['args', 'arguments', "params", "parameters"]):
return cls.ARGS_SECTION
if name in frozenset(['returns', 'return']):
retur... | def function[_classify_section, parameter[cls, section]]:
constant[Attempt to find the canonical name of this section.]
variable[name] assign[=] call[name[section].lower, parameter[]]
if compare[name[name] in call[name[frozenset], parameter[list[[<ast.Constant object at 0x7da1b026ebc0>, <ast.Con... | keyword[def] identifier[_classify_section] ( identifier[cls] , identifier[section] ):
literal[string]
identifier[name] = identifier[section] . identifier[lower] ()
keyword[if] identifier[name] keyword[in] identifier[frozenset] ([ literal[string] , literal[string] , literal[string] , l... | def _classify_section(cls, section):
"""Attempt to find the canonical name of this section."""
name = section.lower()
if name in frozenset(['args', 'arguments', 'params', 'parameters']):
return cls.ARGS_SECTION # depends on [control=['if'], data=[]]
if name in frozenset(['returns', 'return']):
... |
def _init_session(self):
""" 初始化 requests.Session
"""
self.session = requests.Session()
self.session.mount('http://', adapter=requests.adapters.HTTPAdapter(
pool_connections=10,
pool_maxsize=100)) | def function[_init_session, parameter[self]]:
constant[ 初始化 requests.Session
]
name[self].session assign[=] call[name[requests].Session, parameter[]]
call[name[self].session.mount, parameter[constant[http://]]] | keyword[def] identifier[_init_session] ( identifier[self] ):
literal[string]
identifier[self] . identifier[session] = identifier[requests] . identifier[Session] ()
identifier[self] . identifier[session] . identifier[mount] ( literal[string] , identifier[adapter] = identifier[requests] . id... | def _init_session(self):
""" 初始化 requests.Session
"""
self.session = requests.Session()
self.session.mount('http://', adapter=requests.adapters.HTTPAdapter(pool_connections=10, pool_maxsize=100)) |
def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Default... | def function[make_elements, parameter[tokens, text, start, end, fallback]]:
constant[Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where pars... | keyword[def] identifier[make_elements] ( identifier[tokens] , identifier[text] , identifier[start] = literal[int] , identifier[end] = keyword[None] , identifier[fallback] = keyword[None] ):
literal[string]
identifier[result] =[]
identifier[end] = identifier[end] keyword[or] identifier[len] ( identif... | def make_elements(tokens, text, start=0, end=None, fallback=None):
"""Make elements from a list of parsed tokens.
It will turn all unmatched holes into fallback elements.
:param tokens: a list of parsed tokens.
:param text: the original tet.
:param start: the offset of where parsing starts. Default... |
def raise_right_error(response):
"""Raise appropriate error when bad response received."""
if response.status_code == 200:
return
if response.status_code == 500:
raise ServerError('Clef servers are down.')
if response.status_code == 403:
message = response.json().get('error')
... | def function[raise_right_error, parameter[response]]:
constant[Raise appropriate error when bad response received.]
if compare[name[response].status_code equal[==] constant[200]] begin[:]
return[None]
if compare[name[response].status_code equal[==] constant[500]] begin[:]
<ast.Ra... | keyword[def] identifier[raise_right_error] ( identifier[response] ):
literal[string]
keyword[if] identifier[response] . identifier[status_code] == literal[int] :
keyword[return]
keyword[if] identifier[response] . identifier[status_code] == literal[int] :
keyword[raise] identifier... | def raise_right_error(response):
"""Raise appropriate error when bad response received."""
if response.status_code == 200:
return # depends on [control=['if'], data=[]]
if response.status_code == 500:
raise ServerError('Clef servers are down.') # depends on [control=['if'], data=[]]
if... |
def make_diffuse_comp_info_dict(**kwargs):
"""Build and return the information about the diffuse components
"""
library_yamlfile = kwargs.pop('library', 'models/library.yaml')
components = kwargs.pop('components', None)
if components is None:
comp_yamlfile = kwargs.pop('comp', 'config/binnin... | def function[make_diffuse_comp_info_dict, parameter[]]:
constant[Build and return the information about the diffuse components
]
variable[library_yamlfile] assign[=] call[name[kwargs].pop, parameter[constant[library], constant[models/library.yaml]]]
variable[components] assign[=] call[name[k... | keyword[def] identifier[make_diffuse_comp_info_dict] (** identifier[kwargs] ):
literal[string]
identifier[library_yamlfile] = identifier[kwargs] . identifier[pop] ( literal[string] , literal[string] )
identifier[components] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] )
... | def make_diffuse_comp_info_dict(**kwargs):
"""Build and return the information about the diffuse components
"""
library_yamlfile = kwargs.pop('library', 'models/library.yaml')
components = kwargs.pop('components', None)
if components is None:
comp_yamlfile = kwargs.pop('comp', 'config/binnin... |
def _setup_chassis(self):
"""
Sets up the router with the corresponding chassis
(create slots and insert default adapters).
"""
# With 1751 and 1760, WICs in WIC slot 1 show up as in slot 1, not 0
# e.g. s1/0 not s0/2
if self._chassis in ['1751', '1760']:
... | def function[_setup_chassis, parameter[self]]:
constant[
Sets up the router with the corresponding chassis
(create slots and insert default adapters).
]
if compare[name[self]._chassis in list[[<ast.Constant object at 0x7da2047e92d0>, <ast.Constant object at 0x7da2047e9240>]]] beg... | keyword[def] identifier[_setup_chassis] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_chassis] keyword[in] [ literal[string] , literal[string] ]:
identifier[self] . identifier[_create_slots] ( literal[int] )
identifie... | def _setup_chassis(self):
"""
Sets up the router with the corresponding chassis
(create slots and insert default adapters).
"""
# With 1751 and 1760, WICs in WIC slot 1 show up as in slot 1, not 0
# e.g. s1/0 not s0/2
if self._chassis in ['1751', '1760']:
self._create_slo... |
def first_derivative(f, **kwargs):
"""Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If ... | def function[first_derivative, parameter[f]]:
constant[Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projec... | keyword[def] identifier[first_derivative] ( identifier[f] ,** identifier[kwargs] ):
literal[string]
identifier[n] , identifier[axis] , identifier[delta] = identifier[_process_deriv_args] ( identifier[f] , identifier[kwargs] )
identifier[slice0] =[ identifier[slice] ( keyword[None] )]* identifier... | def first_derivative(f, **kwargs):
"""Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If ... |
def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence()
finally:
_on... | def function[_get_candidate_names, parameter[]]:
constant[Common setup sequence for all user-callable interfaces.]
<ast.Global object at 0x7da1b25934c0>
if compare[name[_name_sequence] is constant[None]] begin[:]
call[name[_once_lock].acquire, parameter[]]
<ast.Try object at ... | keyword[def] identifier[_get_candidate_names] ():
literal[string]
keyword[global] identifier[_name_sequence]
keyword[if] identifier[_name_sequence] keyword[is] keyword[None] :
identifier[_once_lock] . identifier[acquire] ()
keyword[try] :
keyword[if] identifier[_n... | def _get_candidate_names():
"""Common setup sequence for all user-callable interfaces."""
global _name_sequence
if _name_sequence is None:
_once_lock.acquire()
try:
if _name_sequence is None:
_name_sequence = _RandomNameSequence() # depends on [control=['if'], da... |
def _start_callbacks(self, result, exception):
"""Perform the callback chain going back and forth between the callback
and errback as needed.
If an exception is raised and the entire chain is gone through without a valid
errback then its simply logged.
"""
if self._canc... | def function[_start_callbacks, parameter[self, result, exception]]:
constant[Perform the callback chain going back and forth between the callback
and errback as needed.
If an exception is raised and the entire chain is gone through without a valid
errback then its simply logged.
... | keyword[def] identifier[_start_callbacks] ( identifier[self] , identifier[result] , identifier[exception] ):
literal[string]
keyword[if] identifier[self] . identifier[_cancelled] :
keyword[raise] identifier[CancelledError] ()
keyword[if] identifier[self] . identifier[called... | def _start_callbacks(self, result, exception):
"""Perform the callback chain going back and forth between the callback
and errback as needed.
If an exception is raised and the entire chain is gone through without a valid
errback then its simply logged.
"""
if self._cancelled:
... |
def connect(self):
"""Connect to device."""
return self.loop.create_connection(lambda: self, self.host, self.port) | def function[connect, parameter[self]]:
constant[Connect to device.]
return[call[name[self].loop.create_connection, parameter[<ast.Lambda object at 0x7da18fe91840>, name[self].host, name[self].port]]] | keyword[def] identifier[connect] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[loop] . identifier[create_connection] ( keyword[lambda] : identifier[self] , identifier[self] . identifier[host] , identifier[self] . identifier[port] ) | def connect(self):
"""Connect to device."""
return self.loop.create_connection(lambda : self, self.host, self.port) |
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for c in orm["contenttypes.contenttype"].objects.all():
if c.app_label == "DublinCore":
c.app_label = "dublincore"
... | def function[forwards, parameter[self, orm]]:
constant[Write your forwards methods here.]
for taget[name[c]] in starred[call[call[name[orm]][constant[contenttypes.contenttype]].objects.all, parameter[]]] begin[:]
if compare[name[c].app_label equal[==] constant[DublinCore]] begin[:]
... | keyword[def] identifier[forwards] ( identifier[self] , identifier[orm] ):
literal[string]
keyword[for] identifier[c] keyword[in] identifier[orm] [ literal[string] ]. identifier[objects] . identifier[all] ():
keyword[if] identifier[c] . identifier[app_label] == literal[stri... | def forwards(self, orm):
"""Write your forwards methods here."""
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for c in orm['contenttypes.contenttype'].objects.all():
if c.app_label == 'DublinCore':
c.app_label = 'dublincore'
c.save() ... |
def update_variogram_model(self, variogram_model, variogram_parameters=None,
variogram_function=None, nlags=6, weight=False,
anisotropy_scaling=1., anisotropy_angle=0.):
"""Allows user to update variogram type and/or
variogram model param... | def function[update_variogram_model, parameter[self, variogram_model, variogram_parameters, variogram_function, nlags, weight, anisotropy_scaling, anisotropy_angle]]:
constant[Allows user to update variogram type and/or
variogram model parameters.
Parameters
----------
variogram... | keyword[def] identifier[update_variogram_model] ( identifier[self] , identifier[variogram_model] , identifier[variogram_parameters] = keyword[None] ,
identifier[variogram_function] = keyword[None] , identifier[nlags] = literal[int] , identifier[weight] = keyword[False] ,
identifier[anisotropy_scaling] = literal[i... | def update_variogram_model(self, variogram_model, variogram_parameters=None, variogram_function=None, nlags=6, weight=False, anisotropy_scaling=1.0, anisotropy_angle=0.0):
"""Allows user to update variogram type and/or
variogram model parameters.
Parameters
----------
variogram_mode... |
def get_workers_with_qualification(self, qualification_id):
"""Get workers with the given qualification."""
done = False
next_token = None
while not done:
if next_token is not None:
response = self.mturk.list_workers_with_qualification_type(
... | def function[get_workers_with_qualification, parameter[self, qualification_id]]:
constant[Get workers with the given qualification.]
variable[done] assign[=] constant[False]
variable[next_token] assign[=] constant[None]
while <ast.UnaryOp object at 0x7da1b03833d0> begin[:]
... | keyword[def] identifier[get_workers_with_qualification] ( identifier[self] , identifier[qualification_id] ):
literal[string]
identifier[done] = keyword[False]
identifier[next_token] = keyword[None]
keyword[while] keyword[not] identifier[done] :
keyword[if] identi... | def get_workers_with_qualification(self, qualification_id):
"""Get workers with the given qualification."""
done = False
next_token = None
while not done:
if next_token is not None:
response = self.mturk.list_workers_with_qualification_type(QualificationTypeId=qualification_id, MaxRe... |
def _deserialize(
self, data, fields_dict, error_store, many=False, partial=False,
unknown=RAISE, dict_class=dict, index_errors=True, index=None,
):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict... | def function[_deserialize, parameter[self, data, fields_dict, error_store, many, partial, unknown, dict_class, index_errors, index]]:
constant[Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict fields_dict: Mapping of fiel... | keyword[def] identifier[_deserialize] (
identifier[self] , identifier[data] , identifier[fields_dict] , identifier[error_store] , identifier[many] = keyword[False] , identifier[partial] = keyword[False] ,
identifier[unknown] = identifier[RAISE] , identifier[dict_class] = identifier[dict] , identifier[index_errors] ... | def _deserialize(self, data, fields_dict, error_store, many=False, partial=False, unknown=RAISE, dict_class=dict, index_errors=True, index=None):
"""Deserialize ``data`` based on the schema defined by ``fields_dict``.
:param dict data: The data to deserialize.
:param dict fields_dict: Mapping of fi... |
def isel_variable_and_index(
name: Hashable,
variable: Variable,
index: pd.Index,
indexers: Mapping[Any, Union[slice, Variable]],
) -> Tuple[Variable, Optional[pd.Index]]:
"""Index a Variable and pandas.Index together."""
if not indexers:
# nothing to index
return variable.copy(d... | def function[isel_variable_and_index, parameter[name, variable, index, indexers]]:
constant[Index a Variable and pandas.Index together.]
if <ast.UnaryOp object at 0x7da18f09e650> begin[:]
return[tuple[[<ast.Call object at 0x7da18f09ff40>, <ast.Name object at 0x7da18f09d480>]]]
if compare... | keyword[def] identifier[isel_variable_and_index] (
identifier[name] : identifier[Hashable] ,
identifier[variable] : identifier[Variable] ,
identifier[index] : identifier[pd] . identifier[Index] ,
identifier[indexers] : identifier[Mapping] [ identifier[Any] , identifier[Union] [ identifier[slice] , identifier[Vari... | def isel_variable_and_index(name: Hashable, variable: Variable, index: pd.Index, indexers: Mapping[Any, Union[slice, Variable]]) -> Tuple[Variable, Optional[pd.Index]]:
"""Index a Variable and pandas.Index together."""
if not indexers:
# nothing to index
return (variable.copy(deep=False), index)... |
def lonlat_to_laea(lon, lat, lon0, lat0, f_e=0.0, f_n=0.0):
"""
Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection (km), with respect to an origin point
:param numpy.ndarray lon:
Longitudes
:param numpy.ndarray lat:
Latitude
:param float lon0... | def function[lonlat_to_laea, parameter[lon, lat, lon0, lat0, f_e, f_n]]:
constant[
Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection (km), with respect to an origin point
:param numpy.ndarray lon:
Longitudes
:param numpy.ndarray lat:
Latitud... | keyword[def] identifier[lonlat_to_laea] ( identifier[lon] , identifier[lat] , identifier[lon0] , identifier[lat0] , identifier[f_e] = literal[int] , identifier[f_n] = literal[int] ):
literal[string]
identifier[lon] = identifier[np] . identifier[radians] ( identifier[lon] )
identifier[lat] = identifier... | def lonlat_to_laea(lon, lat, lon0, lat0, f_e=0.0, f_n=0.0):
"""
Converts vectors of longitude and latitude into Lambert Azimuthal
Equal Area projection (km), with respect to an origin point
:param numpy.ndarray lon:
Longitudes
:param numpy.ndarray lat:
Latitude
:param float lon0... |
def _term_size(self):
"""
Method returns lines and columns according to terminal size
"""
for fd in (0, 1, 2):
try:
return self._ioctl_GWINSZ(fd)
except:
pass
# try os.ctermid()
try:
fd = os.open(os.cterm... | def function[_term_size, parameter[self]]:
constant[
Method returns lines and columns according to terminal size
]
for taget[name[fd]] in starred[tuple[[<ast.Constant object at 0x7da18f09e5c0>, <ast.Constant object at 0x7da18f09d180>, <ast.Constant object at 0x7da18f09edd0>]]] begin[:]
... | keyword[def] identifier[_term_size] ( identifier[self] ):
literal[string]
keyword[for] identifier[fd] keyword[in] ( literal[int] , literal[int] , literal[int] ):
keyword[try] :
keyword[return] identifier[self] . identifier[_ioctl_GWINSZ] ( identifier[fd] )
... | def _term_size(self):
"""
Method returns lines and columns according to terminal size
"""
for fd in (0, 1, 2):
try:
return self._ioctl_GWINSZ(fd) # depends on [control=['try'], data=[]]
except:
pass # depends on [control=['except'], data=[]] # depends o... |
def stack(recs, fields=None):
"""Stack common fields in multiple record arrays (concatenate them).
Parameters
----------
recs : list
List of NumPy record arrays
fields : list of strings, optional (default=None)
The list of fields to include in the stacked array. If None, then
... | def function[stack, parameter[recs, fields]]:
constant[Stack common fields in multiple record arrays (concatenate them).
Parameters
----------
recs : list
List of NumPy record arrays
fields : list of strings, optional (default=None)
The list of fields to include in the stacked a... | keyword[def] identifier[stack] ( identifier[recs] , identifier[fields] = keyword[None] ):
literal[string]
keyword[if] identifier[fields] keyword[is] keyword[None] :
identifier[fields] = identifier[list] ( identifier[set] . identifier[intersection] (
*[ identifier[set] ( identifier[rec] ... | def stack(recs, fields=None):
"""Stack common fields in multiple record arrays (concatenate them).
Parameters
----------
recs : list
List of NumPy record arrays
fields : list of strings, optional (default=None)
The list of fields to include in the stacked array. If None, then
... |
def search(self): # pylint: disable=no-self-use
"""
Request available queries
Posted data: {u'target': u''}
Return the list of available target queries
:return: See upper comment
:rtype: list
"""
logger.debug("Grafana search... %s", cherrypy.request.me... | def function[search, parameter[self]]:
constant[
Request available queries
Posted data: {u'target': u''}
Return the list of available target queries
:return: See upper comment
:rtype: list
]
call[name[logger].debug, parameter[constant[Grafana search... ... | keyword[def] identifier[search] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[cherrypy] . identifier[request] . identifier[method] )
keyword[if] identifier[cherrypy] . identifier[request] . identifier[method] == literal[string]... | def search(self): # pylint: disable=no-self-use
"\n Request available queries\n\n Posted data: {u'target': u''}\n\n Return the list of available target queries\n\n :return: See upper comment\n :rtype: list\n "
logger.debug('Grafana search... %s', cherrypy.request.metho... |
def close(self, session):
"""Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: VISAStatus
... | def function[close, parameter[self, session]]:
constant[Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
... | keyword[def] identifier[close] ( identifier[self] , identifier[session] ):
literal[string]
keyword[try] :
identifier[sess] = identifier[self] . identifier[sessions] [ identifier[session] ]
keyword[if] identifier[sess] keyword[is] keyword[not] identifier[self] :
... | def close(self, session):
"""Closes the specified session, event, or find list.
Corresponds to viClose function of the VISA library.
:param session: Unique logical identifier to a session, event, or find list.
:return: return value of the library call.
:rtype: VISAStatus
""... |
def _get_win_argv():
"""Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`]
"""
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(
winapi.GetCommandLineW(), ctypes.byref(argc))
except WindowsErr... | def function[_get_win_argv, parameter[]]:
constant[Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`]
]
assert[name[is_win]]
variable[argc] assign[=] call[name[ctypes].c_int, parameter[]]
<ast.Try object at 0x7da1b1e97730>
if <... | keyword[def] identifier[_get_win_argv] ():
literal[string]
keyword[assert] identifier[is_win]
identifier[argc] = identifier[ctypes] . identifier[c_int] ()
keyword[try] :
identifier[argv] = identifier[winapi] . identifier[CommandLineToArgvW] (
identifier[winapi] . identifier[... | def _get_win_argv():
"""Returns a unicode argv under Windows and standard sys.argv otherwise
Returns:
List[`fsnative`]
"""
assert is_win
argc = ctypes.c_int()
try:
argv = winapi.CommandLineToArgvW(winapi.GetCommandLineW(), ctypes.byref(argc)) # depends on [control=['try'], data... |
def _load_disktype_data(self):
"""Calls the :command:`disktype` command and obtains the disk GUID from GPT volume systems. As we
are running the tool anyway, the label is also extracted from the tool if it is not yet set.
The disktype data is only loaded and not assigned to volumes yet.
... | def function[_load_disktype_data, parameter[self]]:
constant[Calls the :command:`disktype` command and obtains the disk GUID from GPT volume systems. As we
are running the tool anyway, the label is also extracted from the tool if it is not yet set.
The disktype data is only loaded and not assig... | keyword[def] identifier[_load_disktype_data] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[_util] . identifier[command_exists] ( literal[string] ):
identifier[logger] . identifier[warning] ( literal[string] )
keyword[return] keyword[None]
... | def _load_disktype_data(self):
"""Calls the :command:`disktype` command and obtains the disk GUID from GPT volume systems. As we
are running the tool anyway, the label is also extracted from the tool if it is not yet set.
The disktype data is only loaded and not assigned to volumes yet.
"""... |
def _get_filename(self, path):
"""
This function gets the base filename from the path, if a language code
is present the filename will start from there.
"""
match = re.search("[a-z]{2,3}_[A-Z]{2}", path)
if match:
start = match.start(0)
filename =... | def function[_get_filename, parameter[self, path]]:
constant[
This function gets the base filename from the path, if a language code
is present the filename will start from there.
]
variable[match] assign[=] call[name[re].search, parameter[constant[[a-z]{2,3}_[A-Z]{2}], name[path... | keyword[def] identifier[_get_filename] ( identifier[self] , identifier[path] ):
literal[string]
identifier[match] = identifier[re] . identifier[search] ( literal[string] , identifier[path] )
keyword[if] identifier[match] :
identifier[start] = identifier[match] . identifier[s... | def _get_filename(self, path):
"""
This function gets the base filename from the path, if a language code
is present the filename will start from there.
"""
match = re.search('[a-z]{2,3}_[A-Z]{2}', path)
if match:
start = match.start(0)
filename = path[start:] # depe... |
def unique(input_list):
"""
Return a list of unique items (similar to set functionality).
Parameters
----------
input_list : list
A list containg some items that can occur more than once.
Returns
-------
list
A list with only unique occurances of an item.
"""
o... | def function[unique, parameter[input_list]]:
constant[
Return a list of unique items (similar to set functionality).
Parameters
----------
input_list : list
A list containg some items that can occur more than once.
Returns
-------
list
A list with only unique occura... | keyword[def] identifier[unique] ( identifier[input_list] ):
literal[string]
identifier[output] =[]
keyword[for] identifier[item] keyword[in] identifier[input_list] :
keyword[if] identifier[item] keyword[not] keyword[in] identifier[output] :
identifier[output] . identifier[... | def unique(input_list):
"""
Return a list of unique items (similar to set functionality).
Parameters
----------
input_list : list
A list containg some items that can occur more than once.
Returns
-------
list
A list with only unique occurances of an item.
"""
o... |
def _deriv_growth(z, **cosmo):
""" Returns derivative of the linear growth factor at z
for a given cosmology **cosmo """
inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5)
fz = (1 + z) * inv_h**3
deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\
1.5 * c... | def function[_deriv_growth, parameter[z]]:
constant[ Returns derivative of the linear growth factor at z
for a given cosmology **cosmo ]
variable[inv_h] assign[=] binary_operation[binary_operation[binary_operation[call[name[cosmo]][constant[omega_M_0]] * binary_operation[binary_operation[constan... | keyword[def] identifier[_deriv_growth] ( identifier[z] ,** identifier[cosmo] ):
literal[string]
identifier[inv_h] =( identifier[cosmo] [ literal[string] ]*( literal[int] + identifier[z] )** literal[int] + identifier[cosmo] [ literal[string] ])**(- literal[int] )
identifier[fz] =( literal[int] + ident... | def _deriv_growth(z, **cosmo):
""" Returns derivative of the linear growth factor at z
for a given cosmology **cosmo """
inv_h = (cosmo['omega_M_0'] * (1 + z) ** 3 + cosmo['omega_lambda_0']) ** (-0.5)
fz = (1 + z) * inv_h ** 3
deriv_g = growthfactor(z, norm=True, **cosmo) * inv_h ** 2 * 1.5 * co... |
def read(self, n=-1):
"""Read and return up to n bytes.
If the argument is omitted, None, or negative, data is read and returned until EOF is reached..
"""
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset... | def function[read, parameter[self, n]]:
constant[Read and return up to n bytes.
If the argument is omitted, None, or negative, data is read and returned until EOF is reached..
]
if <ast.BoolOp object at 0x7da18c4ccbe0> begin[:]
variable[buf] assign[=] call[name[self]._rea... | keyword[def] identifier[read] ( identifier[self] , identifier[n] =- literal[int] ):
literal[string]
keyword[if] identifier[n] keyword[is] keyword[None] keyword[or] identifier[n] < literal[int] :
identifier[buf] = identifier[self] . identifier[_readbuffer] [ identifier[self] . iden... | def read(self, n=-1):
"""Read and return up to n bytes.
If the argument is omitted, None, or negative, data is read and returned until EOF is reached..
"""
if n is None or n < 0:
buf = self._readbuffer[self._offset:]
self._readbuffer = b''
self._offset = 0
while n... |
def update_channels(cls, installation_id, channels_to_add=set(),
channels_to_remove=set(), **kw):
"""
Allow an application to manually subscribe or unsubscribe an
installation to a certain push channel in a unified operation.
this is based on:
https://www... | def function[update_channels, parameter[cls, installation_id, channels_to_add, channels_to_remove]]:
constant[
Allow an application to manually subscribe or unsubscribe an
installation to a certain push channel in a unified operation.
this is based on:
https://www.parse.com/docs... | keyword[def] identifier[update_channels] ( identifier[cls] , identifier[installation_id] , identifier[channels_to_add] = identifier[set] (),
identifier[channels_to_remove] = identifier[set] (),** identifier[kw] ):
literal[string]
identifier[installation_url] = identifier[cls] . identifier[_get_ins... | def update_channels(cls, installation_id, channels_to_add=set(), channels_to_remove=set(), **kw):
"""
Allow an application to manually subscribe or unsubscribe an
installation to a certain push channel in a unified operation.
this is based on:
https://www.parse.com/docs/rest#install... |
def connect(self, broker, port=1883, client_id="", clean_session=True):
""" Connect to an MQTT broker. This is a pre-requisite step for publish
and subscribe keywords.
`broker` MQTT broker host
`port` broker port (default 1883)
`client_id` if not specified, a random id is gene... | def function[connect, parameter[self, broker, port, client_id, clean_session]]:
constant[ Connect to an MQTT broker. This is a pre-requisite step for publish
and subscribe keywords.
`broker` MQTT broker host
`port` broker port (default 1883)
`client_id` if not specified, a ran... | keyword[def] identifier[connect] ( identifier[self] , identifier[broker] , identifier[port] = literal[int] , identifier[client_id] = literal[string] , identifier[clean_session] = keyword[True] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] %( identifier[broker] , identif... | def connect(self, broker, port=1883, client_id='', clean_session=True):
""" Connect to an MQTT broker. This is a pre-requisite step for publish
and subscribe keywords.
`broker` MQTT broker host
`port` broker port (default 1883)
`client_id` if not specified, a random id is generate... |
def rpc_get_calltip(self, filename, source, offset):
"""Get the calltip for the function at the offset.
"""
return self._call_backend("rpc_get_calltip", None, filename,
get_source(source), offset) | def function[rpc_get_calltip, parameter[self, filename, source, offset]]:
constant[Get the calltip for the function at the offset.
]
return[call[name[self]._call_backend, parameter[constant[rpc_get_calltip], constant[None], name[filename], call[name[get_source], parameter[name[source]]], name[offse... | keyword[def] identifier[rpc_get_calltip] ( identifier[self] , identifier[filename] , identifier[source] , identifier[offset] ):
literal[string]
keyword[return] identifier[self] . identifier[_call_backend] ( literal[string] , keyword[None] , identifier[filename] ,
identifier[get_source] ( ... | def rpc_get_calltip(self, filename, source, offset):
"""Get the calltip for the function at the offset.
"""
return self._call_backend('rpc_get_calltip', None, filename, get_source(source), offset) |
def post_run_cell(self):
"""Runs after the user-entered code in a cell has been executed. It
detects any new, decoratable objects that haven't been decorated yet and
then decorates them.
"""
#We just want to detect any new, decoratable objects that haven't been
#decorated... | def function[post_run_cell, parameter[self]]:
constant[Runs after the user-entered code in a cell has been executed. It
detects any new, decoratable objects that haven't been decorated yet and
then decorates them.
]
variable[decorlist] assign[=] <ast.DictComp object at 0x7da1b14e... | keyword[def] identifier[post_run_cell] ( identifier[self] ):
literal[string]
identifier[decorlist] ={ identifier[k] :[] keyword[for] identifier[k] keyword[in] identifier[self] . identifier[atypes] }
keyword[for] identifier[atype] keyword[in] identifier[self] . ident... | def post_run_cell(self):
"""Runs after the user-entered code in a cell has been executed. It
detects any new, decoratable objects that haven't been decorated yet and
then decorates them.
"""
#We just want to detect any new, decoratable objects that haven't been
#decorated yet.
de... |
def channel_axis(self, batch):
"""Interface to model.channel_axis for attacks.
Parameters
----------
batch : bool
Controls whether the index of the axis for a batch of images
(4 dimensions) or a single image (3 dimensions) should be returned.
"""
... | def function[channel_axis, parameter[self, batch]]:
constant[Interface to model.channel_axis for attacks.
Parameters
----------
batch : bool
Controls whether the index of the axis for a batch of images
(4 dimensions) or a single image (3 dimensions) should be ret... | keyword[def] identifier[channel_axis] ( identifier[self] , identifier[batch] ):
literal[string]
identifier[axis] = identifier[self] . identifier[__model] . identifier[channel_axis] ()
keyword[if] keyword[not] identifier[batch] :
identifier[axis] = identifier[axis] - literal[... | def channel_axis(self, batch):
"""Interface to model.channel_axis for attacks.
Parameters
----------
batch : bool
Controls whether the index of the axis for a batch of images
(4 dimensions) or a single image (3 dimensions) should be returned.
"""
axis = ... |
def has_function(function_name, libraries=None):
"""Checks if a given functions exists in the current platform."""
compiler = distutils.ccompiler.new_compiler()
with muted(sys.stdout, sys.stderr):
result = compiler.has_function(
function_name, libraries=libraries)
if os.path.exists('a.out'):
os.... | def function[has_function, parameter[function_name, libraries]]:
constant[Checks if a given functions exists in the current platform.]
variable[compiler] assign[=] call[name[distutils].ccompiler.new_compiler, parameter[]]
with call[name[muted], parameter[name[sys].stdout, name[sys].stderr]] begi... | keyword[def] identifier[has_function] ( identifier[function_name] , identifier[libraries] = keyword[None] ):
literal[string]
identifier[compiler] = identifier[distutils] . identifier[ccompiler] . identifier[new_compiler] ()
keyword[with] identifier[muted] ( identifier[sys] . identifier[stdout] , identifier... | def has_function(function_name, libraries=None):
"""Checks if a given functions exists in the current platform."""
compiler = distutils.ccompiler.new_compiler()
with muted(sys.stdout, sys.stderr):
result = compiler.has_function(function_name, libraries=libraries) # depends on [control=['with'], dat... |
def delete_event_ticket_class(self, id, ticket_class_id, **data):
"""
DELETE /events/:id/ticket_classes/:ticket_class_id/
Deletes the ticket class. Returns ``{"deleted": true}``.
"""
return self.delete("/events/{0}/ticket_classes/{0}/".format(id,ticket_class_id), data=da... | def function[delete_event_ticket_class, parameter[self, id, ticket_class_id]]:
constant[
DELETE /events/:id/ticket_classes/:ticket_class_id/
Deletes the ticket class. Returns ``{"deleted": true}``.
]
return[call[name[self].delete, parameter[call[constant[/events/{0}/ticket_classes/{0... | keyword[def] identifier[delete_event_ticket_class] ( identifier[self] , identifier[id] , identifier[ticket_class_id] ,** identifier[data] ):
literal[string]
keyword[return] identifier[self] . identifier[delete] ( literal[string] . identifier[format] ( identifier[id] , identifier[ticket_class_id] ... | def delete_event_ticket_class(self, id, ticket_class_id, **data):
"""
DELETE /events/:id/ticket_classes/:ticket_class_id/
Deletes the ticket class. Returns ``{"deleted": true}``.
"""
return self.delete('/events/{0}/ticket_classes/{0}/'.format(id, ticket_class_id), data=data) |
def insert_order(self, order):
'''
:param order: QA_Order类型
:return:
'''
#print(" *>> QAOrder!insert_order {}".format(order))
# QUEUED = 300 # queued 用于表示在order_queue中 实际表达的意思是订单存活 待成交
#order.status = ORDER_STATUS.QUEUED
# 🛠 todo 是为了速度快把order对象转换成 d... | def function[insert_order, parameter[self, order]]:
constant[
:param order: QA_Order类型
:return:
]
if compare[name[order] is_not constant[None]] begin[:]
call[name[self].order_list][name[order].order_id] assign[=] name[order]
return[name[order]] | keyword[def] identifier[insert_order] ( identifier[self] , identifier[order] ):
literal[string]
keyword[if] identifier[order] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[order_list] [ identifier[order]... | def insert_order(self, order):
"""
:param order: QA_Order类型
:return:
"""
#print(" *>> QAOrder!insert_order {}".format(order))
# QUEUED = 300 # queued 用于表示在order_queue中 实际表达的意思是订单存活 待成交
#order.status = ORDER_STATUS.QUEUED
# 🛠 todo 是为了速度快把order对象转换成 df 对象的吗?
#self.qu... |
def set_time_items(glob):
"""
This function prepares the benchmark items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a = glob['args']
l = glob['logger']
class __TimeManager(object):
def __init__(self):
... | def function[set_time_items, parameter[glob]]:
constant[
This function prepares the benchmark items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
]
variable[a] assign[=] call[name[glob]][constant[args]]
variable[l]... | keyword[def] identifier[set_time_items] ( identifier[glob] ):
literal[string]
identifier[a] = identifier[glob] [ literal[string] ]
identifier[l] = identifier[glob] [ literal[string] ]
keyword[class] identifier[__TimeManager] ( identifier[object] ):
keyword[def] identifier[__init__] ( ... | def set_time_items(glob):
"""
This function prepares the benchmark items for inclusion in main script's
global scope.
:param glob: main script's global scope dictionary reference
"""
a = glob['args']
l = glob['logger']
class __TimeManager(object):
def __init__(self):
... |
def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value | def function[visit_NameConstant, parameter[self, node]]:
constant[Forward the node value as a result.]
call[name[self].recomputed_values][name[node]] assign[=] name[node].value
return[name[node].value] | keyword[def] identifier[visit_NameConstant] ( identifier[self] , identifier[node] : identifier[ast] . identifier[NameConstant] )-> identifier[Any] :
literal[string]
identifier[self] . identifier[recomputed_values] [ identifier[node] ]= identifier[node] . identifier[value]
keyword[return] ... | def visit_NameConstant(self, node: ast.NameConstant) -> Any:
"""Forward the node value as a result."""
self.recomputed_values[node] = node.value
return node.value |
def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) | def function[find_task_by_id, parameter[self, id, session]]:
constant[
Find task with the given record ID.
]
with call[name[self]._session, parameter[name[session]]] begin[:]
return[call[call[name[session].query, parameter[name[TaskRecord]]].get, parameter[name[id]]]] | keyword[def] identifier[find_task_by_id] ( identifier[self] , identifier[id] , identifier[session] = keyword[None] ):
literal[string]
keyword[with] identifier[self] . identifier[_session] ( identifier[session] ) keyword[as] identifier[session] :
keyword[return] identifier[session] .... | def find_task_by_id(self, id, session=None):
"""
Find task with the given record ID.
"""
with self._session(session) as session:
return session.query(TaskRecord).get(id) # depends on [control=['with'], data=['session']] |
def _get_daily_message(self, dt, algo, metrics_tracker):
"""
Get a perf message for the given datetime.
"""
perf_message = metrics_tracker.handle_market_close(
dt,
self.data_portal,
)
perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars... | def function[_get_daily_message, parameter[self, dt, algo, metrics_tracker]]:
constant[
Get a perf message for the given datetime.
]
variable[perf_message] assign[=] call[name[metrics_tracker].handle_market_close, parameter[name[dt], name[self].data_portal]]
call[call[name[perf_m... | keyword[def] identifier[_get_daily_message] ( identifier[self] , identifier[dt] , identifier[algo] , identifier[metrics_tracker] ):
literal[string]
identifier[perf_message] = identifier[metrics_tracker] . identifier[handle_market_close] (
identifier[dt] ,
identifier[self] . identi... | def _get_daily_message(self, dt, algo, metrics_tracker):
"""
Get a perf message for the given datetime.
"""
perf_message = metrics_tracker.handle_market_close(dt, self.data_portal)
perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars
return perf_message |
def read_format_from_metadata(text, ext):
"""Return the format of the file, when that information is available from the metadata"""
metadata = read_metadata(text, ext)
rearrange_jupytext_metadata(metadata)
return format_name_for_ext(metadata, ext, explicit_default=False) | def function[read_format_from_metadata, parameter[text, ext]]:
constant[Return the format of the file, when that information is available from the metadata]
variable[metadata] assign[=] call[name[read_metadata], parameter[name[text], name[ext]]]
call[name[rearrange_jupytext_metadata], parameter[... | keyword[def] identifier[read_format_from_metadata] ( identifier[text] , identifier[ext] ):
literal[string]
identifier[metadata] = identifier[read_metadata] ( identifier[text] , identifier[ext] )
identifier[rearrange_jupytext_metadata] ( identifier[metadata] )
keyword[return] identifier[format_na... | def read_format_from_metadata(text, ext):
"""Return the format of the file, when that information is available from the metadata"""
metadata = read_metadata(text, ext)
rearrange_jupytext_metadata(metadata)
return format_name_for_ext(metadata, ext, explicit_default=False) |
def path_to_reference(path):
"""Convert an object path reference to a reference."""
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
... | def function[path_to_reference, parameter[path]]:
constant[Convert an object path reference to a reference.]
variable[path] assign[=] call[name[str], parameter[name[path]]]
if compare[constant[.] <ast.NotIn object at 0x7da2590d7190> name[path]] begin[:]
<ast.Try object at 0x7da18f00ef80>... | keyword[def] identifier[path_to_reference] ( identifier[path] ):
literal[string]
identifier[path] = identifier[str] ( identifier[path] )
keyword[if] literal[string] keyword[not] keyword[in] identifier[path] :
keyword[try] :
keyword[return] identifier[gl... | def path_to_reference(path):
"""Convert an object path reference to a reference."""
# By default JSON decodes strings as unicode. The Python __import__ does
# not like that choice. So we'll just cast all function paths to a string.
# NOTE: that there is no corresponding unit test for the classmethod
... |
def main():
"""Create a new Cheroot instance with arguments from the command line."""
parser = argparse.ArgumentParser(
description='Start an instance of the Cheroot WSGI/HTTP server.',
)
for arg, spec in _arg_spec.items():
parser.add_argument(arg, **spec)
raw_args = parser.parse_arg... | def function[main, parameter[]]:
constant[Create a new Cheroot instance with arguments from the command line.]
variable[parser] assign[=] call[name[argparse].ArgumentParser, parameter[]]
for taget[tuple[[<ast.Name object at 0x7da20c6e58d0>, <ast.Name object at 0x7da20c6e4850>]]] in starred[call[... | keyword[def] identifier[main] ():
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] (
identifier[description] = literal[string] ,
)
keyword[for] identifier[arg] , identifier[spec] keyword[in] identifier[_arg_spec] . identifier[items] ():
identi... | def main():
"""Create a new Cheroot instance with arguments from the command line."""
parser = argparse.ArgumentParser(description='Start an instance of the Cheroot WSGI/HTTP server.')
for (arg, spec) in _arg_spec.items():
parser.add_argument(arg, **spec) # depends on [control=['for'], data=[]]
... |
def _get_file(db, user_id, api_path, query_fields, decrypt_func):
"""
Get file data for the given user_id, path, and query_fields. The
query_fields parameter specifies which database fields should be
included in the returned file data.
"""
result = db.execute(
_select_file(user_id, api_... | def function[_get_file, parameter[db, user_id, api_path, query_fields, decrypt_func]]:
constant[
Get file data for the given user_id, path, and query_fields. The
query_fields parameter specifies which database fields should be
included in the returned file data.
]
variable[result] assig... | keyword[def] identifier[_get_file] ( identifier[db] , identifier[user_id] , identifier[api_path] , identifier[query_fields] , identifier[decrypt_func] ):
literal[string]
identifier[result] = identifier[db] . identifier[execute] (
identifier[_select_file] ( identifier[user_id] , identifier[api_path] , ... | def _get_file(db, user_id, api_path, query_fields, decrypt_func):
"""
Get file data for the given user_id, path, and query_fields. The
query_fields parameter specifies which database fields should be
included in the returned file data.
"""
result = db.execute(_select_file(user_id, api_path, que... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.