code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _mount_repo(repo, wait_for_server=False):
"""
This function will create the VM directory where a repo will be mounted, if it
doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for
the nfs server to start, by retrying mounts that fail with 'Connection Refused'.
If wait_for_... | def function[_mount_repo, parameter[repo, wait_for_server]]:
constant[
This function will create the VM directory where a repo will be mounted, if it
doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for
the nfs server to start, by retrying mounts that fail with 'Connection Re... | keyword[def] identifier[_mount_repo] ( identifier[repo] , identifier[wait_for_server] = keyword[False] ):
literal[string]
identifier[check_call_on_vm] ( literal[string] . identifier[format] ( identifier[repo] . identifier[vm_path] ))
keyword[if] identifier[wait_for_server] :
keyword[for] id... | def _mount_repo(repo, wait_for_server=False):
"""
This function will create the VM directory where a repo will be mounted, if it
doesn't exist. If wait_for_server is set, it will wait up to 10 seconds for
the nfs server to start, by retrying mounts that fail with 'Connection Refused'.
If wait_for_... |
def template(*args, **kwargs):
'''
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
'''
tpl = args[0] if args else None
temp... | def function[template, parameter[]]:
constant[
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
]
variable[tpl] assign[=... | keyword[def] identifier[template] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[tpl] = identifier[args] [ literal[int] ] keyword[if] identifier[args] keyword[else] keyword[None]
identifier[template_adapter] = identifier[kwargs] . identifier[pop] ( literal[string] , ident... | def template(*args, **kwargs):
"""
Get a rendered template as a string iterator.
You can use a name, a filename or a template string as first parameter.
Template rendering arguments can be passed as dictionaries
or directly (as keyword arguments).
"""
tpl = args[0] if args else None
temp... |
def hours_minutes_seconds(value):
"""converts a timestamp to seconds
- hours:minutes:seconds to seconds
- minutes:seconds to seconds
- 11h22m33s to seconds
- 11h to seconds
- 20h15m to seconds
- seconds to seconds
:param value: hh:mm:ss ; 00h00m00s ; seconds
:return: se... | def function[hours_minutes_seconds, parameter[value]]:
constant[converts a timestamp to seconds
- hours:minutes:seconds to seconds
- minutes:seconds to seconds
- 11h22m33s to seconds
- 11h to seconds
- 20h15m to seconds
- seconds to seconds
:param value: hh:mm:ss ; 00h0... | keyword[def] identifier[hours_minutes_seconds] ( identifier[value] ):
literal[string]
keyword[try] :
keyword[return] identifier[int] ( identifier[value] )
keyword[except] identifier[ValueError] :
keyword[pass]
identifier[match] =( identifier[_hours_minutes_seconds_re] . iden... | def hours_minutes_seconds(value):
"""converts a timestamp to seconds
- hours:minutes:seconds to seconds
- minutes:seconds to seconds
- 11h22m33s to seconds
- 11h to seconds
- 20h15m to seconds
- seconds to seconds
:param value: hh:mm:ss ; 00h00m00s ; seconds
:return: se... |
def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, "w") as f:... | def function[store_to_file, parameter[self, filename]]:
constant[Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
]
with c... | keyword[def] identifier[store_to_file] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[with] identifier[tf] . identifier[gfile] . identifier[Open] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
keyword[for] identifier[i] keyword[in] identifier[range]... | def store_to_file(self, filename):
"""Write vocab file to disk.
Vocab files have one token per line. The file ends in a newline. Reserved
tokens are written to the vocab file as well.
Args:
filename: Full path of the file to store the vocab to.
"""
with tf.gfile.Open(filename, 'w') as f:... |
def get_pids_in_revision_chain(client, did):
"""Args: client: d1_client.cnclient.CoordinatingNodeClient or
d1_client.mnclient.MemberNodeClient.
did : str
SID or a PID of any object in a revision chain.
Returns:
list of str:
All PIDs in the chain. The returned list is in the sam... | def function[get_pids_in_revision_chain, parameter[client, did]]:
constant[Args: client: d1_client.cnclient.CoordinatingNodeClient or
d1_client.mnclient.MemberNodeClient.
did : str
SID or a PID of any object in a revision chain.
Returns:
list of str:
All PIDs in the chain. ... | keyword[def] identifier[get_pids_in_revision_chain] ( identifier[client] , identifier[did] ):
literal[string]
keyword[def] identifier[_req] ( identifier[p] ):
keyword[return] identifier[d1_common] . identifier[xml] . identifier[get_req_val] ( identifier[p] )
keyword[def] identifier[_opt]... | def get_pids_in_revision_chain(client, did):
"""Args: client: d1_client.cnclient.CoordinatingNodeClient or
d1_client.mnclient.MemberNodeClient.
did : str
SID or a PID of any object in a revision chain.
Returns:
list of str:
All PIDs in the chain. The returned list is in the sam... |
def service_count(self, block_identifier: BlockSpecification) -> int:
"""Get the number of registered services"""
result = self.proxy.contract.functions.serviceCount().call(
block_identifier=block_identifier,
)
return result | def function[service_count, parameter[self, block_identifier]]:
constant[Get the number of registered services]
variable[result] assign[=] call[call[name[self].proxy.contract.functions.serviceCount, parameter[]].call, parameter[]]
return[name[result]] | keyword[def] identifier[service_count] ( identifier[self] , identifier[block_identifier] : identifier[BlockSpecification] )-> identifier[int] :
literal[string]
identifier[result] = identifier[self] . identifier[proxy] . identifier[contract] . identifier[functions] . identifier[serviceCount] (). ide... | def service_count(self, block_identifier: BlockSpecification) -> int:
"""Get the number of registered services"""
result = self.proxy.contract.functions.serviceCount().call(block_identifier=block_identifier)
return result |
def sim(self, src, tar, qval=2):
r"""Return the Jaccard similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : i... | def function[sim, parameter[self, src, tar, qval]]:
constant[Return the Jaccard similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for com... | keyword[def] identifier[sim] ( identifier[self] , identifier[src] , identifier[tar] , identifier[qval] = literal[int] ):
literal[string]
keyword[return] identifier[super] ( identifier[self] . identifier[__class__] , identifier[self] ). identifier[sim] ( identifier[src] , identifier[tar] , identifi... | def sim(self, src, tar, qval=2):
"""Return the Jaccard similarity of two strings.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target string (or QGrams/Counter objects) for comparison
qval : int
... |
def _generate_base_lsid(self):
"""
Generates and returns a base LSID
:return:
"""
domain = self._generate_domain()
namespace = self._generate_namespace()
# Return the base LSID
return "urn:lsid:" + domain + ":" + namespace | def function[_generate_base_lsid, parameter[self]]:
constant[
Generates and returns a base LSID
:return:
]
variable[domain] assign[=] call[name[self]._generate_domain, parameter[]]
variable[namespace] assign[=] call[name[self]._generate_namespace, parameter[]]
return[... | keyword[def] identifier[_generate_base_lsid] ( identifier[self] ):
literal[string]
identifier[domain] = identifier[self] . identifier[_generate_domain] ()
identifier[namespace] = identifier[self] . identifier[_generate_namespace] ()
keyword[return] literal[string] + ide... | def _generate_base_lsid(self):
"""
Generates and returns a base LSID
:return:
"""
domain = self._generate_domain()
namespace = self._generate_namespace()
# Return the base LSID
return 'urn:lsid:' + domain + ':' + namespace |
def getScreenDims(self):
"""returns a tuple that contains (screen_width,screen_height)
"""
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenHeight(self.obj)
return (width,height) | def function[getScreenDims, parameter[self]]:
constant[returns a tuple that contains (screen_width,screen_height)
]
variable[width] assign[=] call[name[ale_lib].getScreenWidth, parameter[name[self].obj]]
variable[height] assign[=] call[name[ale_lib].getScreenHeight, parameter[name[self].... | keyword[def] identifier[getScreenDims] ( identifier[self] ):
literal[string]
identifier[width] = identifier[ale_lib] . identifier[getScreenWidth] ( identifier[self] . identifier[obj] )
identifier[height] = identifier[ale_lib] . identifier[getScreenHeight] ( identifier[self] . identifier[ob... | def getScreenDims(self):
"""returns a tuple that contains (screen_width,screen_height)
"""
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenHeight(self.obj)
return (width, height) |
def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + ".search", True)
return _extract(doc, "totalResults") | def function[get_total_result_count, parameter[self]]:
constant[Returns the total count of all the results.]
variable[doc] assign[=] call[name[self]._request, parameter[binary_operation[name[self]._ws_prefix + constant[.search]], constant[True]]]
return[call[name[_extract], parameter[name[doc], cons... | keyword[def] identifier[get_total_result_count] ( identifier[self] ):
literal[string]
identifier[doc] = identifier[self] . identifier[_request] ( identifier[self] . identifier[_ws_prefix] + literal[string] , keyword[True] )
keyword[return] identifier[_extract] ( identifier[doc] , litera... | def get_total_result_count(self):
"""Returns the total count of all the results."""
doc = self._request(self._ws_prefix + '.search', True)
return _extract(doc, 'totalResults') |
def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.'))
if id:
ob... | def function[get, parameter[self, request, id]]:
constant[
Handles get requests for either the collection or an object detail.
]
if <ast.UnaryOp object at 0x7da18ede7340> begin[:]
return[call[name[HttpResponseForbidden], parameter[call[name[_], parameter[constant[You do not have ... | keyword[def] identifier[get] ( identifier[self] , identifier[request] , identifier[id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[has_get_permission] ( identifier[request] ):
keyword[return] identifier[HttpRespons... | def get(self, request, id=None, **kwargs):
"""
Handles get requests for either the collection or an object detail.
"""
if not self.has_get_permission(request):
return HttpResponseForbidden(_('You do not have permission to perform this action.')) # depends on [control=['if'], data=[]]
... |
def dual_quaternion(self):
""":obj:`DualQuaternion`: The DualQuaternion corresponding to this
transform.
"""
qr = self.quaternion
qd = np.append([0], self.translation / 2.)
return DualQuaternion(qr, qd) | def function[dual_quaternion, parameter[self]]:
constant[:obj:`DualQuaternion`: The DualQuaternion corresponding to this
transform.
]
variable[qr] assign[=] name[self].quaternion
variable[qd] assign[=] call[name[np].append, parameter[list[[<ast.Constant object at 0x7da1b12b5300>]... | keyword[def] identifier[dual_quaternion] ( identifier[self] ):
literal[string]
identifier[qr] = identifier[self] . identifier[quaternion]
identifier[qd] = identifier[np] . identifier[append] ([ literal[int] ], identifier[self] . identifier[translation] / literal[int] )
keyword[re... | def dual_quaternion(self):
""":obj:`DualQuaternion`: The DualQuaternion corresponding to this
transform.
"""
qr = self.quaternion
qd = np.append([0], self.translation / 2.0)
return DualQuaternion(qr, qd) |
def _apply_labels(
self, autolabel="none", xlabel=None, ylabel=None, data=None, channel_index=0
):
"""Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabe... | def function[_apply_labels, parameter[self, autolabel, xlabel, ylabel, data, channel_index]]:
constant[Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabel : string ... | keyword[def] identifier[_apply_labels] (
identifier[self] , identifier[autolabel] = literal[string] , identifier[xlabel] = keyword[None] , identifier[ylabel] = keyword[None] , identifier[data] = keyword[None] , identifier[channel_index] = literal[int]
):
literal[string]
keyword[if] iden... | def _apply_labels(self, autolabel='none', xlabel=None, ylabel=None, data=None, channel_index=0):
"""Apply x and y labels to axes.
Parameters
----------
autolabel : {'none', 'both', 'x', 'y'} (optional)
Label(s) to apply from data. Default is none.
xlabel : string (option... |
def generate_subid(self, token=None):
'''assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identifier
'''
# Not headless auto-increments
if not token:
token = str(uuid.uuid4())
# Headless doesn't use any folder_... | def function[generate_subid, parameter[self, token]]:
constant[assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identifier
]
if <ast.UnaryOp object at 0x7da18fe93280> begin[:]
variable[token] assign[=] cal... | keyword[def] identifier[generate_subid] ( identifier[self] , identifier[token] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[token] :
identifier[token] = identifier[str] ( identifier[uuid] . identifier[uuid4] ())
keyword[return] literal[string] %( i... | def generate_subid(self, token=None):
"""assumes a flat (file system) database, organized by experiment id, and
subject id, with data (json) organized by subject identifier
"""
# Not headless auto-increments
if not token:
token = str(uuid.uuid4()) # depends on [control=['if'], data=[]]
... |
def write_gpio(self, gpio=None):
"""Write the specified byte value to the GPIO registor. If no value
specified the current buffered value will be written.
"""
if gpio is not None:
self.gpio = gpio
self._device.writeList(self.GPIO, self.gpio) | def function[write_gpio, parameter[self, gpio]]:
constant[Write the specified byte value to the GPIO registor. If no value
specified the current buffered value will be written.
]
if compare[name[gpio] is_not constant[None]] begin[:]
name[self].gpio assign[=] name[gpio]
... | keyword[def] identifier[write_gpio] ( identifier[self] , identifier[gpio] = keyword[None] ):
literal[string]
keyword[if] identifier[gpio] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[gpio] = identifier[gpio]
identifier[self] . identifier[_device]... | def write_gpio(self, gpio=None):
"""Write the specified byte value to the GPIO registor. If no value
specified the current buffered value will be written.
"""
if gpio is not None:
self.gpio = gpio # depends on [control=['if'], data=['gpio']]
self._device.writeList(self.GPIO, self.g... |
def now_time(str=False):
"""Get the current time."""
if str:
return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
return datetime.datetime.now() | def function[now_time, parameter[str]]:
constant[Get the current time.]
if name[str] begin[:]
return[call[call[name[datetime].datetime.now, parameter[]].strftime, parameter[constant[%Y-%m-%d %H:%M:%S]]]]
return[call[name[datetime].datetime.now, parameter[]]] | keyword[def] identifier[now_time] ( identifier[str] = keyword[False] ):
literal[string]
keyword[if] identifier[str] :
keyword[return] identifier[datetime] . identifier[datetime] . identifier[now] (). identifier[strftime] ( literal[string] )
keyword[return] identifier[datetime] . identifier... | def now_time(str=False):
"""Get the current time."""
if str:
return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # depends on [control=['if'], data=[]]
return datetime.datetime.now() |
def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list)
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_CODE.append(s... | def function[add_raw_code, parameter[self, string_or_list]]:
constant[Add raw Gmsh code.
]
if call[name[_is_string], parameter[name[string_or_list]]] begin[:]
call[name[self]._GMSH_CODE.append, parameter[name[string_or_list]]]
return[None] | keyword[def] identifier[add_raw_code] ( identifier[self] , identifier[string_or_list] ):
literal[string]
keyword[if] identifier[_is_string] ( identifier[string_or_list] ):
identifier[self] . identifier[_GMSH_CODE] . identifier[append] ( identifier[string_or_list] )
keyword[el... | def add_raw_code(self, string_or_list):
"""Add raw Gmsh code.
"""
if _is_string(string_or_list):
self._GMSH_CODE.append(string_or_list) # depends on [control=['if'], data=[]]
else:
assert isinstance(string_or_list, list)
for string in string_or_list:
self._GMSH_C... |
def add_new_directory(self, node):
"""
Adds a new directory next to given Node associated path.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Method success.
:rtype: bool
"""
if self.__script_editor.model.is_authoring_n... | def function[add_new_directory, parameter[self, node]]:
constant[
Adds a new directory next to given Node associated path.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Method success.
:rtype: bool
]
if call[name[self]._... | keyword[def] identifier[add_new_directory] ( identifier[self] , identifier[node] ):
literal[string]
keyword[if] identifier[self] . identifier[__script_editor] . identifier[model] . identifier[is_authoring_node] ( identifier[node] ):
keyword[return] keyword[False]
identifi... | def add_new_directory(self, node):
"""
Adds a new directory next to given Node associated path.
:param node: Node.
:type node: ProjectNode or DirectoryNode or FileNode
:return: Method success.
:rtype: bool
"""
if self.__script_editor.model.is_authoring_node(node)... |
def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) | def function[random_id, parameter[k]]:
constant[Random id to use for AWS identifiers.]
return[call[constant[].join, parameter[call[name[random].choices, parameter[binary_operation[name[string].ascii_lowercase + name[string].digits]]]]]] | keyword[def] identifier[random_id] ( identifier[k] = literal[int] ):
literal[string]
keyword[return] literal[string] . identifier[join] ( identifier[random] . identifier[choices] ( identifier[string] . identifier[ascii_lowercase] + identifier[string] . identifier[digits] , identifier[k] = identifier[k] )) | def random_id(k=5):
"""Random id to use for AWS identifiers."""
# https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=k)) |
def view(ctx):
""" Build and view docs.
"""
report.info(ctx, "docs.view", f"viewing documentation")
build_path = ctx.docs.directory / "build" / "html" / "index.html"
build_path = pathname2url(build_path.as_posix())
webbrowser.open(f"file:{build_path!s}") | def function[view, parameter[ctx]]:
constant[ Build and view docs.
]
call[name[report].info, parameter[name[ctx], constant[docs.view], <ast.JoinedStr object at 0x7da1b0e38a60>]]
variable[build_path] assign[=] binary_operation[binary_operation[binary_operation[name[ctx].docs.directory / const... | keyword[def] identifier[view] ( identifier[ctx] ):
literal[string]
identifier[report] . identifier[info] ( identifier[ctx] , literal[string] , literal[string] )
identifier[build_path] = identifier[ctx] . identifier[docs] . identifier[directory] / literal[string] / literal[string] / literal[string]
... | def view(ctx):
""" Build and view docs.
"""
report.info(ctx, 'docs.view', f'viewing documentation')
build_path = ctx.docs.directory / 'build' / 'html' / 'index.html'
build_path = pathname2url(build_path.as_posix())
webbrowser.open(f'file:{build_path!s}') |
def forward(self, input):
"""Feed-forward through the network."""
return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt())) | def function[forward, parameter[self, input]]:
constant[Feed-forward through the network.]
return[call[name[th].nn.functional.linear, parameter[name[input], call[name[self].weight.div, parameter[call[call[call[name[self].weight.pow, parameter[constant[2]]].sum, parameter[constant[0]]].sqrt, parameter[]]]]]]... | keyword[def] identifier[forward] ( identifier[self] , identifier[input] ):
literal[string]
keyword[return] identifier[th] . identifier[nn] . identifier[functional] . identifier[linear] ( identifier[input] , identifier[self] . identifier[weight] . identifier[div] ( identifier[self] . identifier[wei... | def forward(self, input):
"""Feed-forward through the network."""
return th.nn.functional.linear(input, self.weight.div(self.weight.pow(2).sum(0).sqrt())) |
def become(cls, session_token):
"""
通过 session token 获取用户对象
:param session_token: 用户的 session token
:return: leancloud.User
"""
response = client.get('/users/me', params={'session_token': session_token})
content = response.json()
user = cls()
user... | def function[become, parameter[cls, session_token]]:
constant[
通过 session token 获取用户对象
:param session_token: 用户的 session token
:return: leancloud.User
]
variable[response] assign[=] call[name[client].get, parameter[constant[/users/me]]]
variable[content] assign[=... | keyword[def] identifier[become] ( identifier[cls] , identifier[session_token] ):
literal[string]
identifier[response] = identifier[client] . identifier[get] ( literal[string] , identifier[params] ={ literal[string] : identifier[session_token] })
identifier[content] = identifier[response] .... | def become(cls, session_token):
"""
通过 session token 获取用户对象
:param session_token: 用户的 session token
:return: leancloud.User
"""
response = client.get('/users/me', params={'session_token': session_token})
content = response.json()
user = cls()
user._update_data(conten... |
def serialize(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
"""
for transform in self._transforms:
config = transform.transform(config)
return config | def function[serialize, parameter[self, config]]:
constant[
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
]
for taget[name[transform]] in starred[name[self]._transforms] begin[:]
variable[config] assign[=] cal... | keyword[def] identifier[serialize] ( identifier[self] , identifier[config] ):
literal[string]
keyword[for] identifier[transform] keyword[in] identifier[self] . identifier[_transforms] :
identifier[config] = identifier[transform] . identifier[transform] ( identifier[config] )
... | def serialize(self, config):
"""
:param config:
:type config: yowsup.config.base.config.Config
:return:
:rtype: bytes
"""
for transform in self._transforms:
config = transform.transform(config) # depends on [control=['for'], data=['transform']]
return config |
def add_pull_request_comment(self, project, repository, pull_request_id, text):
"""
Add comment into pull request
:param project:
:param repository:
:param pull_request_id: the ID of the pull request within the repository
:param text comment text
:return:
... | def function[add_pull_request_comment, parameter[self, project, repository, pull_request_id, text]]:
constant[
Add comment into pull request
:param project:
:param repository:
:param pull_request_id: the ID of the pull request within the repository
:param text comment tex... | keyword[def] identifier[add_pull_request_comment] ( identifier[self] , identifier[project] , identifier[repository] , identifier[pull_request_id] , identifier[text] ):
literal[string]
identifier[url] = literal[string] . identifier[format] (
identifier[project] = identifier[project] ,
... | def add_pull_request_comment(self, project, repository, pull_request_id, text):
"""
Add comment into pull request
:param project:
:param repository:
:param pull_request_id: the ID of the pull request within the repository
:param text comment text
:return:
"""
... |
def execution_group(id):
"""A decorator designed to be used with both classes and functions. Pass the
decorator some object that represents the Execution Group the decorated object
should be added to. If one test function in an Execution Group fails then no
more tests from that Execution Group will ru... | def function[execution_group, parameter[id]]:
constant[A decorator designed to be used with both classes and functions. Pass the
decorator some object that represents the Execution Group the decorated object
should be added to. If one test function in an Execution Group fails then no
more tests fr... | keyword[def] identifier[execution_group] ( identifier[id] ):
literal[string]
keyword[def] identifier[add_execution_group] ( identifier[class_or_func] ):
identifier[execution_groups] = identifier[getattr] ( identifier[class_or_func] , literal[string] ,[])
identifier[execution_groups] . id... | def execution_group(id):
"""A decorator designed to be used with both classes and functions. Pass the
decorator some object that represents the Execution Group the decorated object
should be added to. If one test function in an Execution Group fails then no
more tests from that Execution Group will ru... |
def make_list(json_arr, client, cls, parent_id=None):
"""
Returns a list of Populated objects of the given class type. This
should not be called outside of the :any:`LinodeClient` class.
:param json_arr: The array of JSON data to make into a list
:param client: The LinodeClient... | def function[make_list, parameter[json_arr, client, cls, parent_id]]:
constant[
Returns a list of Populated objects of the given class type. This
should not be called outside of the :any:`LinodeClient` class.
:param json_arr: The array of JSON data to make into a list
:param cl... | keyword[def] identifier[make_list] ( identifier[json_arr] , identifier[client] , identifier[cls] , identifier[parent_id] = keyword[None] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[obj] keyword[in] identifier[json_arr] :
identifier[id_val] = keyword[N... | def make_list(json_arr, client, cls, parent_id=None):
"""
Returns a list of Populated objects of the given class type. This
should not be called outside of the :any:`LinodeClient` class.
:param json_arr: The array of JSON data to make into a list
:param client: The LinodeClient to ... |
def _fill(self, text = ""):
"Indent a piece of text, according to the current indentation level"
if self._do_indent:
self._write("\n"+" "*self._indent + text)
else:
self._write(text) | def function[_fill, parameter[self, text]]:
constant[Indent a piece of text, according to the current indentation level]
if name[self]._do_indent begin[:]
call[name[self]._write, parameter[binary_operation[binary_operation[constant[
] + binary_operation[constant[ ] * name[self]._inden... | keyword[def] identifier[_fill] ( identifier[self] , identifier[text] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[_do_indent] :
identifier[self] . identifier[_write] ( literal[string] + literal[string] * identifier[self] . identifier[_indent] + identi... | def _fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
if self._do_indent:
self._write('\n' + ' ' * self._indent + text) # depends on [control=['if'], data=[]]
else:
self._write(text) |
def is_generic_union(type_: Type) -> bool:
"""Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
... | def function[is_generic_union, parameter[type_]]:
constant[Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
... | keyword[def] identifier[is_generic_union] ( identifier[type_] : identifier[Type] )-> identifier[bool] :
literal[string]
keyword[if] identifier[hasattr] ( identifier[typing] , literal[string] ):
keyword[return] ( identifier[isinstance] ( identifier[type_] , identifier[typing] . identifier[_Ge... | def is_generic_union(type_: Type) -> bool:
"""Determines whether a type is a Union[...].
How to do this varies for different Python versions, due to the
typing library not having a stable API. This functions smooths
over the differences.
Args:
type_: The type to check.
Returns:
... |
def resetdb():
"""
Clear out the database
"""
from airflow import models
# alembic adds significant import time, so we import it lazily
from alembic.migration import MigrationContext
log.info("Dropping tables that exist")
models.base.Base.metadata.drop_all(settings.engine)
mc = Mi... | def function[resetdb, parameter[]]:
constant[
Clear out the database
]
from relative_module[airflow] import module[models]
from relative_module[alembic.migration] import module[MigrationContext]
call[name[log].info, parameter[constant[Dropping tables that exist]]]
call[name[model... | keyword[def] identifier[resetdb] ():
literal[string]
keyword[from] identifier[airflow] keyword[import] identifier[models]
keyword[from] identifier[alembic] . identifier[migration] keyword[import] identifier[MigrationContext]
identifier[log] . identifier[info] ( literal[string] )
... | def resetdb():
"""
Clear out the database
"""
from airflow import models
# alembic adds significant import time, so we import it lazily
from alembic.migration import MigrationContext
log.info('Dropping tables that exist')
models.base.Base.metadata.drop_all(settings.engine)
mc = Migra... |
def path(self, filename, folder=None):
"""
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... | def function[path, parameter[self, filename, folder]]:
constant[
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the uploa... | keyword[def] identifier[path] ( identifier[self] , identifier[filename] , identifier[folder] = keyword[None] ):
literal[string]
keyword[if] identifier[folder] keyword[is] keyword[not] keyword[None] :
identifier[target_folder] = identifier[os] . identifier[path] . identifier[join] (... | def path(self, filename, folder=None):
"""
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... |
def raise_for_redefined_namespace(self, line: str, position: int, namespace: str) -> None:
"""Raise an exception if a namespace is already defined.
:raises: RedefinedNamespaceError
"""
if self.disallow_redefinition and self.has_namespace(namespace):
raise RedefinedNamespaceE... | def function[raise_for_redefined_namespace, parameter[self, line, position, namespace]]:
constant[Raise an exception if a namespace is already defined.
:raises: RedefinedNamespaceError
]
if <ast.BoolOp object at 0x7da1b0ebcb20> begin[:]
<ast.Raise object at 0x7da1b0ebd570> | keyword[def] identifier[raise_for_redefined_namespace] ( identifier[self] , identifier[line] : identifier[str] , identifier[position] : identifier[int] , identifier[namespace] : identifier[str] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[disallow_redefinition] ke... | def raise_for_redefined_namespace(self, line: str, position: int, namespace: str) -> None:
"""Raise an exception if a namespace is already defined.
:raises: RedefinedNamespaceError
"""
if self.disallow_redefinition and self.has_namespace(namespace):
raise RedefinedNamespaceError(self.ge... |
def named_entities(self):
"""The elements of ``named_entities`` layer."""
if not self.is_tagged(NAMED_ENTITIES):
self.tag_named_entities()
phrases = self.split_by(NAMED_ENTITIES)
return [' '.join(phrase.lemmas) for phrase in phrases] | def function[named_entities, parameter[self]]:
constant[The elements of ``named_entities`` layer.]
if <ast.UnaryOp object at 0x7da18f58fd00> begin[:]
call[name[self].tag_named_entities, parameter[]]
variable[phrases] assign[=] call[name[self].split_by, parameter[name[NAMED_ENTITI... | keyword[def] identifier[named_entities] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_tagged] ( identifier[NAMED_ENTITIES] ):
identifier[self] . identifier[tag_named_entities] ()
identifier[phrases] = identifier[self] . ident... | def named_entities(self):
"""The elements of ``named_entities`` layer."""
if not self.is_tagged(NAMED_ENTITIES):
self.tag_named_entities() # depends on [control=['if'], data=[]]
phrases = self.split_by(NAMED_ENTITIES)
return [' '.join(phrase.lemmas) for phrase in phrases] |
def mapped_repr_stripping_underscores(
obj: Any, attrnames: List[str],
with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Here, you pass a list of internal attributes, and it assumes that the
:func:`__init__` parameter names have th... | def function[mapped_repr_stripping_underscores, parameter[obj, attrnames, with_addr, joiner]]:
constant[
Convenience function for :func:`__repr__`.
Here, you pass a list of internal attributes, and it assumes that the
:func:`__init__` parameter names have the leading underscore dropped.
Args:
... | keyword[def] identifier[mapped_repr_stripping_underscores] (
identifier[obj] : identifier[Any] , identifier[attrnames] : identifier[List] [ identifier[str] ],
identifier[with_addr] : identifier[bool] = keyword[False] , identifier[joiner] : identifier[str] = identifier[COMMA_SPACE] )-> identifier[str] :
literal... | def mapped_repr_stripping_underscores(obj: Any, attrnames: List[str], with_addr: bool=False, joiner: str=COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Here, you pass a list of internal attributes, and it assumes that the
:func:`__init__` parameter names have the leading underscore ... |
def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2:
# Python 2
if encoding is None:
return str(obj)
else:
return obj.encode(encoding)
else:
# Python 3
return byte... | def function[to_binary_string, parameter[obj, encoding]]:
constant[Convert `obj` to binary string (bytes in Python 3, str in Python 2)]
if name[PY2] begin[:]
if compare[name[encoding] is constant[None]] begin[:]
return[call[name[str], parameter[name[obj]]]] | keyword[def] identifier[to_binary_string] ( identifier[obj] , identifier[encoding] = keyword[None] ):
literal[string]
keyword[if] identifier[PY2] :
keyword[if] identifier[encoding] keyword[is] keyword[None] :
keyword[return] identifier[str] ( identifier[obj] )
... | def to_binary_string(obj, encoding=None):
"""Convert `obj` to binary string (bytes in Python 3, str in Python 2)"""
if PY2: # Python 2
if encoding is None:
return str(obj) # depends on [control=['if'], data=[]]
else:
return obj.encode(encoding) # depends on [control=['... |
def visit(self, node):
""" Add OMPDirective from the old node to the new one. """
old_omp = metadata.get(node, OMPDirective)
node = super(DeadCodeElimination, self).visit(node)
if not metadata.get(node, OMPDirective):
for omp_directive in old_omp:
metadata.add... | def function[visit, parameter[self, node]]:
constant[ Add OMPDirective from the old node to the new one. ]
variable[old_omp] assign[=] call[name[metadata].get, parameter[name[node], name[OMPDirective]]]
variable[node] assign[=] call[call[name[super], parameter[name[DeadCodeElimination], name[sel... | keyword[def] identifier[visit] ( identifier[self] , identifier[node] ):
literal[string]
identifier[old_omp] = identifier[metadata] . identifier[get] ( identifier[node] , identifier[OMPDirective] )
identifier[node] = identifier[super] ( identifier[DeadCodeElimination] , identifier[self] ). ... | def visit(self, node):
""" Add OMPDirective from the old node to the new one. """
old_omp = metadata.get(node, OMPDirective)
node = super(DeadCodeElimination, self).visit(node)
if not metadata.get(node, OMPDirective):
for omp_directive in old_omp:
metadata.add(node, omp_directive) #... |
def sign(self, message):
"""
Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
components, as described by the NTLM... | def function[sign, parameter[self, message]]:
constant[
Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
component... | keyword[def] identifier[sign] ( identifier[self] , identifier[message] ):
literal[string]
identifier[hmac_context] = identifier[hmac] . identifier[new] ( identifier[self] . identifier[outgoing_signing_key] )
identifier[hmac_context] . identifier[update] ( identifier[struct] . identifier[pa... | def sign(self, message):
"""
Generates a signature for the supplied message using NTLM2 Session Security
Note: [MS-NLMP] Section 3.4.4
The message signature for NTLM with extended session security is a 16-byte value that contains the following
components, as described by the NTLMSSP_... |
def split_key(key):
"""Splits a node key."""
if key == KEY_SEP:
return ()
key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP))
if key_chunks[0].startswith(KEY_SEP):
return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:]
else:
return key_chunks | def function[split_key, parameter[key]]:
constant[Splits a node key.]
if compare[name[key] equal[==] name[KEY_SEP]] begin[:]
return[tuple[[]]]
variable[key_chunks] assign[=] call[name[tuple], parameter[call[call[name[key].strip, parameter[name[KEY_SEP]]].split, parameter[name[KEY_SEP]]]]... | keyword[def] identifier[split_key] ( identifier[key] ):
literal[string]
keyword[if] identifier[key] == identifier[KEY_SEP] :
keyword[return] ()
identifier[key_chunks] = identifier[tuple] ( identifier[key] . identifier[strip] ( identifier[KEY_SEP] ). identifier[split] ( identifier[KEY_SEP] ))... | def split_key(key):
"""Splits a node key."""
if key == KEY_SEP:
return () # depends on [control=['if'], data=[]]
key_chunks = tuple(key.strip(KEY_SEP).split(KEY_SEP))
if key_chunks[0].startswith(KEY_SEP):
return (key_chunks[0][len(KEY_SEP):],) + key_chunks[1:] # depends on [control=['i... |
def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.... | def function[incr, parameter[self, key, delta]]:
constant[
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
]
variable[value] assign[=] call[name[self].get, parameter[name[key]]]
if compare[name[value] is constant[None]] begin[:]
... | keyword[def] identifier[incr] ( identifier[self] , identifier[key] , identifier[delta] = literal[int] ):
literal[string]
identifier[value] = identifier[self] . identifier[get] ( identifier[key] )
keyword[if] identifier[value] keyword[is] keyword[None] :
keyword[raise] iden... | def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key) # depends on [control=['if'], data=[]]
new_value = value +... |
def _build_doc(func_name,
desc,
arg_names,
arg_types,
arg_desc,
key_var_num_args=None,
ret_type=None):
"""Build docstring for symbolic functions."""
param_str = _build_param_doc(arg_names, arg_types, arg_desc)
if key_v... | def function[_build_doc, parameter[func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args, ret_type]]:
constant[Build docstring for symbolic functions.]
variable[param_str] assign[=] call[name[_build_param_doc], parameter[name[arg_names], name[arg_types], name[arg_desc]]]
if name[key_... | keyword[def] identifier[_build_doc] ( identifier[func_name] ,
identifier[desc] ,
identifier[arg_names] ,
identifier[arg_types] ,
identifier[arg_desc] ,
identifier[key_var_num_args] = keyword[None] ,
identifier[ret_type] = keyword[None] ):
literal[string]
identifier[param_str] = identifier[_build_para... | def _build_doc(func_name, desc, arg_names, arg_types, arg_desc, key_var_num_args=None, ret_type=None):
"""Build docstring for symbolic functions."""
param_str = _build_param_doc(arg_names, arg_types, arg_desc)
if key_var_num_args:
desc += '\nThis function support variable length of positional input.... |
def subscribe_account(self, username, password, service):
"""Subscribe an account for a service.
"""
data = {
'service': service,
'username': username,
'password': password,
}
return self._perform_post_request(self.subscribe_account_endpoint, ... | def function[subscribe_account, parameter[self, username, password, service]]:
constant[Subscribe an account for a service.
]
variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da1b0de5b40>, <ast.Constant object at 0x7da1b0de4fd0>, <ast.Constant object at 0x7da1b0de4fa0>], [<ast.Nam... | keyword[def] identifier[subscribe_account] ( identifier[self] , identifier[username] , identifier[password] , identifier[service] ):
literal[string]
identifier[data] ={
literal[string] : identifier[service] ,
literal[string] : identifier[username] ,
literal[string] : iden... | def subscribe_account(self, username, password, service):
"""Subscribe an account for a service.
"""
data = {'service': service, 'username': username, 'password': password}
return self._perform_post_request(self.subscribe_account_endpoint, data, self.token_header) |
def islitlet_progress(islitlet, islitlet_max):
"""Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
"""
if islitlet % 10 == 0:
cout = str(islitlet // ... | def function[islitlet_progress, parameter[islitlet, islitlet_max]]:
constant[Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
]
if compare[binary_ope... | keyword[def] identifier[islitlet_progress] ( identifier[islitlet] , identifier[islitlet_max] ):
literal[string]
keyword[if] identifier[islitlet] % literal[int] == literal[int] :
identifier[cout] = identifier[str] ( identifier[islitlet] // literal[int] )
keyword[else] :
identifier[co... | def islitlet_progress(islitlet, islitlet_max):
"""Auxiliary function to print out progress in loop of slitlets.
Parameters
----------
islitlet : int
Current slitlet number.
islitlet_max : int
Maximum slitlet number.
"""
if islitlet % 10 == 0:
cout = str(islitlet // ... |
def get_kafka_brokers():
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
# NOTE: The Kafka environment variables need to be present. If using
# Apache Kafka on Heroku, they will be available in your app configuration.
if not os.... | def function[get_kafka_brokers, parameter[]]:
constant[
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
]
if <ast.UnaryOp object at 0x7da1b0c4ef80> begin[:]
<ast.Raise object at 0x7da1b0c4e230>
return[<ast.ListComp object at... | keyword[def] identifier[get_kafka_brokers] ():
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[environ] . identifier[get] ( literal[string] ):
keyword[raise] identifier[RuntimeError] ( literal[string] )
keyword[return] [ literal[string] . identifier[format] ... | def get_kafka_brokers():
"""
Parses the KAKFA_URL and returns a list of hostname:port pairs in the format
that kafka-python expects.
"""
# NOTE: The Kafka environment variables need to be present. If using
# Apache Kafka on Heroku, they will be available in your app configuration.
if not os.... |
def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | def function[phonenumber, parameter[anon, obj, field, val]]:
constant[
Generates a random US-style phone number
]
return[call[name[anon].faker.phone_number, parameter[]]] | keyword[def] identifier[phonenumber] ( identifier[anon] , identifier[obj] , identifier[field] , identifier[val] ):
literal[string]
keyword[return] identifier[anon] . identifier[faker] . identifier[phone_number] ( identifier[field] = identifier[field] ) | def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) |
def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=None):
"""Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum ... | def function[linspace_pix, parameter[self, start, stop, pixel_step, y_vs_x]]:
constant[Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
... | keyword[def] identifier[linspace_pix] ( identifier[self] , identifier[start] = keyword[None] , identifier[stop] = keyword[None] , identifier[pixel_step] = literal[int] , identifier[y_vs_x] = keyword[None] ):
literal[string]
keyword[if] identifier[y_vs_x] :
keyword[if] identifier[sta... | def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=None):
"""Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum pixe... |
def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exp... | def function[_DoubleDecoder, parameter[]]:
constant[Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
]
variable[local_unpack] assign[=] name[struct].unpack
def function[InnerDecode, parameter[buffer, pos]]:
variable[new_po... | keyword[def] identifier[_DoubleDecoder] ():
literal[string]
identifier[local_unpack] = identifier[struct] . identifier[unpack]
keyword[def] identifier[InnerDecode] ( identifier[buffer] , identifier[pos] ):
identifier[new_pos] = identifier[pos] + literal[int]
identifier[double_bytes] = i... | def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 repr... |
def set_quantities(self, product_quantities):
''' Sets the quantities on each of the products on each of the
products specified. Raises an exception (ValidationError) if a limit
is violated. `product_quantities` is an iterable of (product, quantity)
pairs. '''
items_in_cart = co... | def function[set_quantities, parameter[self, product_quantities]]:
constant[ Sets the quantities on each of the products on each of the
products specified. Raises an exception (ValidationError) if a limit
is violated. `product_quantities` is an iterable of (product, quantity)
pairs. ]
... | keyword[def] identifier[set_quantities] ( identifier[self] , identifier[product_quantities] ):
literal[string]
identifier[items_in_cart] = identifier[commerce] . identifier[ProductItem] . identifier[objects] . identifier[filter] ( identifier[cart] = identifier[self] . identifier[cart] )
i... | def set_quantities(self, product_quantities):
""" Sets the quantities on each of the products on each of the
products specified. Raises an exception (ValidationError) if a limit
is violated. `product_quantities` is an iterable of (product, quantity)
pairs. """
items_in_cart = commerce.Pr... |
def merge(cls, *args, **kwargs):
"""Create a new Ent from one or more existing Ents. Keys in the
later Ent objects will overwrite the keys of the previous Ents.
Later keys of different type than in earlier Ents will be bravely
ignored.
The following keyword arguments are recogn... | def function[merge, parameter[cls]]:
constant[Create a new Ent from one or more existing Ents. Keys in the
later Ent objects will overwrite the keys of the previous Ents.
Later keys of different type than in earlier Ents will be bravely
ignored.
The following keyword arguments ... | keyword[def] identifier[merge] ( identifier[cls] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[newkeys] = identifier[bool] ( identifier[kwargs] . identifier[get] ( literal[string] , keyword[False] ))
identifier[ignore] = identifier[kwargs] . identifier[get] ( lit... | def merge(cls, *args, **kwargs):
"""Create a new Ent from one or more existing Ents. Keys in the
later Ent objects will overwrite the keys of the previous Ents.
Later keys of different type than in earlier Ents will be bravely
ignored.
The following keyword arguments are recognized... |
def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False):
"""
Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error
"""
try:
filename = filename.decode('utf-8')
except (Uni... | def function[runfile, parameter[filename, args, wdir, namespace, post_mortem]]:
constant[
Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error
]
<ast.Try object at 0x7da1b054af80>
if name[__umr... | keyword[def] identifier[runfile] ( identifier[filename] , identifier[args] = keyword[None] , identifier[wdir] = keyword[None] , identifier[namespace] = keyword[None] , identifier[post_mortem] = keyword[False] ):
literal[string]
keyword[try] :
identifier[filename] = identifier[filename] . identifie... | def runfile(filename, args=None, wdir=None, namespace=None, post_mortem=False):
"""
Run filename
args: command line arguments (string)
wdir: working directory
post_mortem: boolean, whether to enter post-mortem mode on error
"""
try:
filename = filename.decode('utf-8') # depends on [... |
async def create_payment_address(seed: str = None) -> str:
"""
Creates a payment address inside the wallet.
:param seed: String
Example:
address = await Wallet.create_payment_address('00000000000000000000000001234567')
:return: String
"""
logger = logging.... | <ast.AsyncFunctionDef object at 0x7da18f00f0d0> | keyword[async] keyword[def] identifier[create_payment_address] ( identifier[seed] : identifier[str] = keyword[None] )-> identifier[str] :
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ( identifier[__name__] )
keyword[if] keyword[not] identifier[hasatt... | async def create_payment_address(seed: str=None) -> str:
"""
Creates a payment address inside the wallet.
:param seed: String
Example:
address = await Wallet.create_payment_address('00000000000000000000000001234567')
:return: String
"""
logger = logging.getLogger(... |
def _connect(self):
"""Creates a websocket connection.
:return:
"""
self.log.debug("_connect(): Initializing Connection..")
self.socket = websocket.WebSocketApp(
self.url,
on_open=self._on_open,
on_message=self._on_message,
on_erro... | def function[_connect, parameter[self]]:
constant[Creates a websocket connection.
:return:
]
call[name[self].log.debug, parameter[constant[_connect(): Initializing Connection..]]]
name[self].socket assign[=] call[name[websocket].WebSocketApp, parameter[name[self].url]]
i... | keyword[def] identifier[_connect] ( identifier[self] ):
literal[string]
identifier[self] . identifier[log] . identifier[debug] ( literal[string] )
identifier[self] . identifier[socket] = identifier[websocket] . identifier[WebSocketApp] (
identifier[self] . identifier[url] ,
... | def _connect(self):
"""Creates a websocket connection.
:return:
"""
self.log.debug('_connect(): Initializing Connection..')
self.socket = websocket.WebSocketApp(self.url, on_open=self._on_open, on_message=self._on_message, on_error=self._on_error, on_close=self._on_close)
if 'ca_certs' ... |
def stop(self):
"""
Close the window and stops the worker thread. The main thread will
resume with the next command after the `start()` call.
"""
assert threading.current_thread() == self.thread
assert self.state.running
self.state.running = False | def function[stop, parameter[self]]:
constant[
Close the window and stops the worker thread. The main thread will
resume with the next command after the `start()` call.
]
assert[compare[call[name[threading].current_thread, parameter[]] equal[==] name[self].thread]]
assert[name[se... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
keyword[assert] identifier[threading] . identifier[current_thread] ()== identifier[self] . identifier[thread]
keyword[assert] identifier[self] . identifier[state] . identifier[running]
identifier[self] . ident... | def stop(self):
"""
Close the window and stops the worker thread. The main thread will
resume with the next command after the `start()` call.
"""
assert threading.current_thread() == self.thread
assert self.state.running
self.state.running = False |
def _dispatch(self, method, params):
"""Dispatches the XML-RPC method.
XML-RPC calls are forwarded to a registered function that
matches the called XML-RPC method name. If no such function
exists then the call is forwarded to the registered instance,
if available.
If th... | def function[_dispatch, parameter[self, method, params]]:
constant[Dispatches the XML-RPC method.
XML-RPC calls are forwarded to a registered function that
matches the called XML-RPC method name. If no such function
exists then the call is forwarded to the registered instance,
i... | keyword[def] identifier[_dispatch] ( identifier[self] , identifier[method] , identifier[params] ):
literal[string]
identifier[func] = keyword[None]
keyword[try] :
identifier[func] = identifier[self] . identifier[funcs] [ identifier[method] ]
keyword[except]... | def _dispatch(self, method, params):
"""Dispatches the XML-RPC method.
XML-RPC calls are forwarded to a registered function that
matches the called XML-RPC method name. If no such function
exists then the call is forwarded to the registered instance,
if available.
If the re... |
def _get_fitnesses(self,
problem,
population,
cache_encoded=True,
cache_solution=False,
pool=None):
"""Get the fitness for every solution in a population.
Args:
problem: Proble... | def function[_get_fitnesses, parameter[self, problem, population, cache_encoded, cache_solution, pool]]:
constant[Get the fitness for every solution in a population.
Args:
problem: Problem; The problem that defines fitness.
population: list; List of potential solutions.
... | keyword[def] identifier[_get_fitnesses] ( identifier[self] ,
identifier[problem] ,
identifier[population] ,
identifier[cache_encoded] = keyword[True] ,
identifier[cache_solution] = keyword[False] ,
identifier[pool] = keyword[None] ):
literal[string]
identifier[fitnesses] =[ keyword[None] ]* id... | def _get_fitnesses(self, problem, population, cache_encoded=True, cache_solution=False, pool=None):
"""Get the fitness for every solution in a population.
Args:
problem: Problem; The problem that defines fitness.
population: list; List of potential solutions.
pool: None/... |
def laplacian_reordering(G):
'''Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue.'''
L = G.laplacian()
vals, vecs = np.linalg.eigh(L)
min_positive_idx = np.argmax(vals == vals[vals>0].min())
vec = vecs[:, min_positive_idx]
return permute_graph(G,... | def function[laplacian_reordering, parameter[G]]:
constant[Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue.]
variable[L] assign[=] call[name[G].laplacian, parameter[]]
<ast.Tuple object at 0x7da2046237c0> assign[=] call[name[np].lina... | keyword[def] identifier[laplacian_reordering] ( identifier[G] ):
literal[string]
identifier[L] = identifier[G] . identifier[laplacian] ()
identifier[vals] , identifier[vecs] = identifier[np] . identifier[linalg] . identifier[eigh] ( identifier[L] )
identifier[min_positive_idx] = identifier[np] . identifi... | def laplacian_reordering(G):
"""Reorder vertices using the eigenvector of the graph Laplacian corresponding
to the first positive eigenvalue."""
L = G.laplacian()
(vals, vecs) = np.linalg.eigh(L)
min_positive_idx = np.argmax(vals == vals[vals > 0].min())
vec = vecs[:, min_positive_idx]
return ... |
def to_mapquest_str(self):
"""
Convert Viewbox object to a string that can be used by
`MapQuest <http://www.mapquestapi.com/geocoding/#options>`_
as a query parameter.
"""
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.left, vb.top, vb.right, vb.bottom) | def function[to_mapquest_str, parameter[self]]:
constant[
Convert Viewbox object to a string that can be used by
`MapQuest <http://www.mapquestapi.com/geocoding/#options>`_
as a query parameter.
]
variable[vb] assign[=] call[name[self].convert_srs, parameter[constant[4326... | keyword[def] identifier[to_mapquest_str] ( identifier[self] ):
literal[string]
identifier[vb] = identifier[self] . identifier[convert_srs] ( literal[int] )
keyword[return] literal[string] %( identifier[vb] . identifier[left] , identifier[vb] . identifier[top] , identifier[vb] . identifier... | def to_mapquest_str(self):
"""
Convert Viewbox object to a string that can be used by
`MapQuest <http://www.mapquestapi.com/geocoding/#options>`_
as a query parameter.
"""
vb = self.convert_srs(4326)
return '%s,%s,%s,%s' % (vb.left, vb.top, vb.right, vb.bottom) |
def _generate_union_properties(self, fields):
"""Emits union instance properties from the given fields."""
for field in fields:
# void types do not need properties to store additional state
# information
if not is_void_type(field.data_type):
doc = self... | def function[_generate_union_properties, parameter[self, fields]]:
constant[Emits union instance properties from the given fields.]
for taget[name[field]] in starred[name[fields]] begin[:]
if <ast.UnaryOp object at 0x7da20c76d8a0> begin[:]
variable[doc] assign[=] ... | keyword[def] identifier[_generate_union_properties] ( identifier[self] , identifier[fields] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[fields] :
keyword[if] keyword[not] identifier[is_void_type] ( identifier[field] . identifier[data_... | def _generate_union_properties(self, fields):
"""Emits union instance properties from the given fields."""
for field in fields:
# void types do not need properties to store additional state
# information
if not is_void_type(field.data_type):
doc = self.process_doc(field.doc, ... |
def cprint(text, color=None, on_color=None, attrs=None, **kwargs):
"""Print colorize text.
It accepts arguments of print function.
"""
print((colored(text, color, on_color, attrs)), **kwargs) | def function[cprint, parameter[text, color, on_color, attrs]]:
constant[Print colorize text.
It accepts arguments of print function.
]
call[name[print], parameter[call[name[colored], parameter[name[text], name[color], name[on_color], name[attrs]]]]] | keyword[def] identifier[cprint] ( identifier[text] , identifier[color] = keyword[None] , identifier[on_color] = keyword[None] , identifier[attrs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[print] (( identifier[colored] ( identifier[text] , identifier[color] , identifier[on_color]... | def cprint(text, color=None, on_color=None, attrs=None, **kwargs):
"""Print colorize text.
It accepts arguments of print function.
"""
print(colored(text, color, on_color, attrs), **kwargs) |
def read_astropy_ascii (self, **kwargs):
"""Open as an ASCII table, returning a :class:`astropy.table.Table` object.
Keyword arguments are passed to :func:`astropy.io.ascii.open`; valid
ones likely include:
- ``names = <list>`` (column names)
- ``format`` ('basic', 'cds', 'csv',... | def function[read_astropy_ascii, parameter[self]]:
constant[Open as an ASCII table, returning a :class:`astropy.table.Table` object.
Keyword arguments are passed to :func:`astropy.io.ascii.open`; valid
ones likely include:
- ``names = <list>`` (column names)
- ``format`` ('basic... | keyword[def] identifier[read_astropy_ascii] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[astropy] . identifier[io] keyword[import] identifier[ascii]
keyword[return] identifier[ascii] . identifier[read] ( identifier[text_type] ( identifier[self]... | def read_astropy_ascii(self, **kwargs):
"""Open as an ASCII table, returning a :class:`astropy.table.Table` object.
Keyword arguments are passed to :func:`astropy.io.ascii.open`; valid
ones likely include:
- ``names = <list>`` (column names)
- ``format`` ('basic', 'cds', 'csv', 'ipa... |
def _run_cmd(cmd, ctx, glob, loc): # pragma: no cover
"""Run a command with optionally a debugger, IPython, or profiling."""
if PDB:
_enable_pdb()
if IPYTHON:
from IPython import start_ipython
args_ipy = ['-i', '--gui=qt']
ns = glob.copy()
ns.update(loc)
retu... | def function[_run_cmd, parameter[cmd, ctx, glob, loc]]:
constant[Run a command with optionally a debugger, IPython, or profiling.]
if name[PDB] begin[:]
call[name[_enable_pdb], parameter[]]
if name[IPYTHON] begin[:]
from relative_module[IPython] import module[start_ipytho... | keyword[def] identifier[_run_cmd] ( identifier[cmd] , identifier[ctx] , identifier[glob] , identifier[loc] ):
literal[string]
keyword[if] identifier[PDB] :
identifier[_enable_pdb] ()
keyword[if] identifier[IPYTHON] :
keyword[from] identifier[IPython] keyword[import] identifier[s... | def _run_cmd(cmd, ctx, glob, loc): # pragma: no cover
'Run a command with optionally a debugger, IPython, or profiling.'
if PDB:
_enable_pdb() # depends on [control=['if'], data=[]]
if IPYTHON:
from IPython import start_ipython
args_ipy = ['-i', '--gui=qt']
ns = glob.copy()... |
def matrix_coords(rows, cols, rowh, colw, ox=0, oy=0):
"Generate coords for a matrix of rects"
for i, f, c in rowmajor(rows, cols):
x = ox + c * colw
y = oy + f * rowh
x1 = x + colw
y1 = y + rowh
yield (i, x, y, x1, y1) | def function[matrix_coords, parameter[rows, cols, rowh, colw, ox, oy]]:
constant[Generate coords for a matrix of rects]
for taget[tuple[[<ast.Name object at 0x7da204960e80>, <ast.Name object at 0x7da204963bb0>, <ast.Name object at 0x7da204961a50>]]] in starred[call[name[rowmajor], parameter[name[rows], ... | keyword[def] identifier[matrix_coords] ( identifier[rows] , identifier[cols] , identifier[rowh] , identifier[colw] , identifier[ox] = literal[int] , identifier[oy] = literal[int] ):
literal[string]
keyword[for] identifier[i] , identifier[f] , identifier[c] keyword[in] identifier[rowmajor] ( identifier[r... | def matrix_coords(rows, cols, rowh, colw, ox=0, oy=0):
"""Generate coords for a matrix of rects"""
for (i, f, c) in rowmajor(rows, cols):
x = ox + c * colw
y = oy + f * rowh
x1 = x + colw
y1 = y + rowh
yield (i, x, y, x1, y1) # depends on [control=['for'], data=[]] |
def covfilter(args):
"""
%prog covfilter blastfile fastafile
Fastafile is used to get the sizes of the queries. Two filters can be
applied, the id% and cov%.
"""
from jcvi.algorithms.supermap import supermap
from jcvi.utils.range import range_union
allowed_iterby = ("query", "query_sbj... | def function[covfilter, parameter[args]]:
constant[
%prog covfilter blastfile fastafile
Fastafile is used to get the sizes of the queries. Two filters can be
applied, the id% and cov%.
]
from relative_module[jcvi.algorithms.supermap] import module[supermap]
from relative_module[jcvi.uti... | keyword[def] identifier[covfilter] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[algorithms] . identifier[supermap] keyword[import] identifier[supermap]
keyword[from] identifier[jcvi] . identifier[utils] . identifier[range] keyword[import] identifier[range_un... | def covfilter(args):
"""
%prog covfilter blastfile fastafile
Fastafile is used to get the sizes of the queries. Two filters can be
applied, the id% and cov%.
"""
from jcvi.algorithms.supermap import supermap
from jcvi.utils.range import range_union
allowed_iterby = ('query', 'query_sbjc... |
def geodetic2aer(lat: float, lon: float, h: float,
lat0: float, lon0: float, h0: float,
ell=None, deg: bool = True) -> Tuple[float, float, float]:
"""
gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates.
Parameters
----------... | def function[geodetic2aer, parameter[lat, lon, h, lat0, lon0, h0, ell, deg]]:
constant[
gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates.
Parameters
----------
lat : float or numpy.ndarray of float
target geodetic latitude
lon : float ... | keyword[def] identifier[geodetic2aer] ( identifier[lat] : identifier[float] , identifier[lon] : identifier[float] , identifier[h] : identifier[float] ,
identifier[lat0] : identifier[float] , identifier[lon0] : identifier[float] , identifier[h0] : identifier[float] ,
identifier[ell] = keyword[None] , identifier[deg]... | def geodetic2aer(lat: float, lon: float, h: float, lat0: float, lon0: float, h0: float, ell=None, deg: bool=True) -> Tuple[float, float, float]:
"""
gives azimuth, elevation and slant range from an Observer to a Point with geodetic coordinates.
Parameters
----------
lat : float or numpy.ndarray o... |
def get_logs(self):
"""
print logs from pod
:return: str or None
"""
try:
api_response = self.core_api.read_namespaced_pod_log(self.name, self.namespace)
logger.debug("Logs from pod: %s in namespace: %s", self.name, self.namespace)
for line in ... | def function[get_logs, parameter[self]]:
constant[
print logs from pod
:return: str or None
]
<ast.Try object at 0x7da1b1251600>
return[constant[None]] | keyword[def] identifier[get_logs] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[api_response] = identifier[self] . identifier[core_api] . identifier[read_namespaced_pod_log] ( identifier[self] . identifier[name] , identifier[self] . identifier[namespace] )
... | def get_logs(self):
"""
print logs from pod
:return: str or None
"""
try:
api_response = self.core_api.read_namespaced_pod_log(self.name, self.namespace)
logger.debug('Logs from pod: %s in namespace: %s', self.name, self.namespace)
for line in api_response.split('... |
def _init_from_dt(self, data, nthread):
"""
Initialize data from a datatable Frame.
"""
ptrs = (ctypes.c_void_p * data.ncols)()
if hasattr(data, "internal") and hasattr(data.internal, "column"):
# datatable>0.8.0
for icol in range(data.ncols):
... | def function[_init_from_dt, parameter[self, data, nthread]]:
constant[
Initialize data from a datatable Frame.
]
variable[ptrs] assign[=] call[binary_operation[name[ctypes].c_void_p * name[data].ncols], parameter[]]
if <ast.BoolOp object at 0x7da1b1e9ab90> begin[:]
... | keyword[def] identifier[_init_from_dt] ( identifier[self] , identifier[data] , identifier[nthread] ):
literal[string]
identifier[ptrs] =( identifier[ctypes] . identifier[c_void_p] * identifier[data] . identifier[ncols] )()
keyword[if] identifier[hasattr] ( identifier[data] , literal[strin... | def _init_from_dt(self, data, nthread):
"""
Initialize data from a datatable Frame.
"""
ptrs = (ctypes.c_void_p * data.ncols)()
if hasattr(data, 'internal') and hasattr(data.internal, 'column'):
# datatable>0.8.0
for icol in range(data.ncols):
col = data.internal.... |
def check_method_requirements(func):
"""Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
error_message = "You must provide {error_field} in {cls} to get access to the default {... | def function[check_method_requirements, parameter[func]]:
constant[Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
]
def function[wrapper, parameter[]]:
variable[error_message] assign[=] constant[You must provi... | keyword[def] identifier[check_method_requirements] ( identifier[func] ):
literal[string]
@ identifier[wraps] ( identifier[func] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[error_message] = literal[string]
identifier[error_data] ={ lite... | def check_method_requirements(func):
"""Check methods requirements
:param callable func: the function to decorate
:return callable: the wrapped function
"""
@wraps(func)
def wrapper(*args, **kwargs):
error_message = 'You must provide {error_field} in {cls} to get access to the default ... |
def pack(self):
"""
Pack the structure data into a string
"""
data = []
for field in self.__fields__:
(vtype, vlen) = self.__fields_types__[field]
if vtype == 'char': # string
data.append(getattr(self, field))
elif isinstance(vt... | def function[pack, parameter[self]]:
constant[
Pack the structure data into a string
]
variable[data] assign[=] list[[]]
for taget[name[field]] in starred[name[self].__fields__] begin[:]
<ast.Tuple object at 0x7da18f09cbe0> assign[=] call[name[self].__fields_types... | keyword[def] identifier[pack] ( identifier[self] ):
literal[string]
identifier[data] =[]
keyword[for] identifier[field] keyword[in] identifier[self] . identifier[__fields__] :
( identifier[vtype] , identifier[vlen] )= identifier[self] . identifier[__fields_types__] [ identif... | def pack(self):
"""
Pack the structure data into a string
"""
data = []
for field in self.__fields__:
(vtype, vlen) = self.__fields_types__[field]
if vtype == 'char': # string
data.append(getattr(self, field)) # depends on [control=['if'], data=[]]
elif ... |
def build_managers(app, conf):
"""
Takes in a config file as outlined in job_managers.ini.sample and builds
a dictionary of job manager objects from them.
"""
# Load default options from config file that apply to all
# managers.
default_options = _get_default_options(conf)
manager_descr... | def function[build_managers, parameter[app, conf]]:
constant[
Takes in a config file as outlined in job_managers.ini.sample and builds
a dictionary of job manager objects from them.
]
variable[default_options] assign[=] call[name[_get_default_options], parameter[name[conf]]]
variable... | keyword[def] identifier[build_managers] ( identifier[app] , identifier[conf] ):
literal[string]
identifier[default_options] = identifier[_get_default_options] ( identifier[conf] )
identifier[manager_descriptions] = identifier[ManagerDescriptions] ()
keyword[if] literal[string] keywor... | def build_managers(app, conf):
"""
Takes in a config file as outlined in job_managers.ini.sample and builds
a dictionary of job manager objects from them.
"""
# Load default options from config file that apply to all
# managers.
default_options = _get_default_options(conf)
manager_descri... |
def resolve_sound(self, sound):
"""Function tries to identify a sound in the data.
Notes
-----
The function tries to resolve sounds to take a sound with less complex
features in order to yield the next approximate sound class, if the
transcription data are sound classes.... | def function[resolve_sound, parameter[self, sound]]:
constant[Function tries to identify a sound in the data.
Notes
-----
The function tries to resolve sounds to take a sound with less complex
features in order to yield the next approximate sound class, if the
transcript... | keyword[def] identifier[resolve_sound] ( identifier[self] , identifier[sound] ):
literal[string]
identifier[sound] = identifier[sound] keyword[if] identifier[isinstance] ( identifier[sound] , identifier[Symbol] ) keyword[else] identifier[self] . identifier[system] [ identifier[sound] ]
... | def resolve_sound(self, sound):
"""Function tries to identify a sound in the data.
Notes
-----
The function tries to resolve sounds to take a sound with less complex
features in order to yield the next approximate sound class, if the
transcription data are sound classes.
... |
def collide(cls, data, params):
"""
Calculate boundaries of geometry object
Uses Strategy
"""
xminmax = ['xmin', 'xmax']
data, width = cls._collide_setup(data, params)
if params.get('width', None) is None:
params['width'] = width
# Reorder by... | def function[collide, parameter[cls, data, params]]:
constant[
Calculate boundaries of geometry object
Uses Strategy
]
variable[xminmax] assign[=] list[[<ast.Constant object at 0x7da2044c35b0>, <ast.Constant object at 0x7da2044c17e0>]]
<ast.Tuple object at 0x7da2044c2110... | keyword[def] identifier[collide] ( identifier[cls] , identifier[data] , identifier[params] ):
literal[string]
identifier[xminmax] =[ literal[string] , literal[string] ]
identifier[data] , identifier[width] = identifier[cls] . identifier[_collide_setup] ( identifier[data] , identifier[param... | def collide(cls, data, params):
"""
Calculate boundaries of geometry object
Uses Strategy
"""
xminmax = ['xmin', 'xmax']
(data, width) = cls._collide_setup(data, params)
if params.get('width', None) is None:
params['width'] = width # depends on [control=['if'], data=[]]... |
def validate_and_convert_nexson(nexson, output_version, allow_invalid, **kwargs):
"""Runs the nexson validator and returns a converted 4 object:
nexson, annotation, validation_log, nexson_adaptor
`nexson` is the nexson dict.
`output_version` is the version of nexson syntax to be used after validati... | def function[validate_and_convert_nexson, parameter[nexson, output_version, allow_invalid]]:
constant[Runs the nexson validator and returns a converted 4 object:
nexson, annotation, validation_log, nexson_adaptor
`nexson` is the nexson dict.
`output_version` is the version of nexson syntax to b... | keyword[def] identifier[validate_and_convert_nexson] ( identifier[nexson] , identifier[output_version] , identifier[allow_invalid] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[if] identifier[TRACE_FILES] :
identifier[_write_to_next_free] ( literal[string] , identi... | def validate_and_convert_nexson(nexson, output_version, allow_invalid, **kwargs):
"""Runs the nexson validator and returns a converted 4 object:
nexson, annotation, validation_log, nexson_adaptor
`nexson` is the nexson dict.
`output_version` is the version of nexson syntax to be used after validati... |
def title(value, failure_string='N/A'):
"""
Converts a string into titlecase.
Lifted from Django.
"""
try:
value = value.lower()
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
result = re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
... | def function[title, parameter[value, failure_string]]:
constant[
Converts a string into titlecase.
Lifted from Django.
]
<ast.Try object at 0x7da1b0a4f850> | keyword[def] identifier[title] ( identifier[value] , identifier[failure_string] = literal[string] ):
literal[string]
keyword[try] :
identifier[value] = identifier[value] . identifier[lower] ()
identifier[t] = identifier[re] . identifier[sub] ( literal[string] , keyword[lambda] identifier... | def title(value, failure_string='N/A'):
"""
Converts a string into titlecase.
Lifted from Django.
"""
try:
value = value.lower()
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
result = re.sub('\\d([A-Z])', lambda m: m.group(0).lower(), t)
... |
def backup(self):
"""
Backup the main dataframe
"""
try:
self.backup_df = self.df.copy()
except Exception as e:
self.err(e, "Can not backup data")
return
self.ok("Dataframe backed up") | def function[backup, parameter[self]]:
constant[
Backup the main dataframe
]
<ast.Try object at 0x7da207f99960>
call[name[self].ok, parameter[constant[Dataframe backed up]]] | keyword[def] identifier[backup] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[backup_df] = identifier[self] . identifier[df] . identifier[copy] ()
keyword[except] identifier[Exception] keyword[as] identifier[e] :
identifier[... | def backup(self):
"""
Backup the main dataframe
"""
try:
self.backup_df = self.df.copy() # depends on [control=['try'], data=[]]
except Exception as e:
self.err(e, 'Can not backup data')
return # depends on [control=['except'], data=['e']]
self.ok('Dataframe bac... |
def add_network_ipv6_hosts(
self,
id_vlan,
id_tipo_rede,
num_hosts,
id_ambiente_vip=None):
"""
Add new networkipv6
:param id_vlan: Identifier of the Vlan. Integer value and greater than zero.
:param id_tipo_rede: Identifier of ... | def function[add_network_ipv6_hosts, parameter[self, id_vlan, id_tipo_rede, num_hosts, id_ambiente_vip]]:
constant[
Add new networkipv6
:param id_vlan: Identifier of the Vlan. Integer value and greater than zero.
:param id_tipo_rede: Identifier of the NetworkType. Integer value and grea... | keyword[def] identifier[add_network_ipv6_hosts] (
identifier[self] ,
identifier[id_vlan] ,
identifier[id_tipo_rede] ,
identifier[num_hosts] ,
identifier[id_ambiente_vip] = keyword[None] ):
literal[string]
identifier[vlan_map] = identifier[dict] ()
identifier[vlan_map] [ literal[string... | def add_network_ipv6_hosts(self, id_vlan, id_tipo_rede, num_hosts, id_ambiente_vip=None):
"""
Add new networkipv6
:param id_vlan: Identifier of the Vlan. Integer value and greater than zero.
:param id_tipo_rede: Identifier of the NetworkType. Integer value and greater than zero.
:pa... |
def _multicall_callback(self, values, calls):
"""
Fires when we get information back from the XML-RPC server.
This is processes the raw results of system.multicall into a usable
iterator of values (and/or Faults).
:param values: list of data txkoji.Connection.call()
:pa... | def function[_multicall_callback, parameter[self, values, calls]]:
constant[
Fires when we get information back from the XML-RPC server.
This is processes the raw results of system.multicall into a usable
iterator of values (and/or Faults).
:param values: list of data txkoji.Co... | keyword[def] identifier[_multicall_callback] ( identifier[self] , identifier[values] , identifier[calls] ):
literal[string]
identifier[result] = identifier[KojiMultiCallIterator] ( identifier[values] )
identifier[result] . identifier[connection] = identifier[self] . identifier[connection] ... | def _multicall_callback(self, values, calls):
"""
Fires when we get information back from the XML-RPC server.
This is processes the raw results of system.multicall into a usable
iterator of values (and/or Faults).
:param values: list of data txkoji.Connection.call()
:param ... |
def _astoref(ins):
''' Stores a floating point value into a memory address.
'''
output = _addr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True
else:
indirect = False
if indirect:
output.append('push hl')
output.... | def function[_astoref, parameter[ins]]:
constant[ Stores a floating point value into a memory address.
]
variable[output] assign[=] call[name[_addr], parameter[call[name[ins].quad][constant[1]]]]
variable[value] assign[=] call[name[ins].quad][constant[2]]
if compare[call[name[value]]... | keyword[def] identifier[_astoref] ( identifier[ins] ):
literal[string]
identifier[output] = identifier[_addr] ( identifier[ins] . identifier[quad] [ literal[int] ])
identifier[value] = identifier[ins] . identifier[quad] [ literal[int] ]
keyword[if] identifier[value] [ literal[int] ]== literal[s... | def _astoref(ins):
""" Stores a floating point value into a memory address.
"""
output = _addr(ins.quad[1])
value = ins.quad[2]
if value[0] == '*':
value = value[1:]
indirect = True # depends on [control=['if'], data=[]]
else:
indirect = False
if indirect:
ou... |
def asym_list_diff(list1, list2):
""" Asymmetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list | def function[asym_list_diff, parameter[list1, list2]]:
constant[ Asymmetric list difference ]
variable[diff_list] assign[=] list[[]]
for taget[name[item]] in starred[name[list1]] begin[:]
if <ast.UnaryOp object at 0x7da204621de0> begin[:]
call[name[diff_li... | keyword[def] identifier[asym_list_diff] ( identifier[list1] , identifier[list2] ):
literal[string]
identifier[diff_list] =[]
keyword[for] identifier[item] keyword[in] identifier[list1] :
keyword[if] keyword[not] identifier[item] keyword[in] identifier[list2] :
identifier[d... | def asym_list_diff(list1, list2):
""" Asymmetric list difference """
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['item']]
return diff_list |
def from_dict(cls, dct, project=None, delim=' | '):
r"""
This method converts a correctly formatted dictionary into OpenPNM
objects, and returns a handle to the *project* containing them.
Parameters
----------
dct : dictionary
The Python dictionary containing... | def function[from_dict, parameter[cls, dct, project, delim]]:
constant[
This method converts a correctly formatted dictionary into OpenPNM
objects, and returns a handle to the *project* containing them.
Parameters
----------
dct : dictionary
The Python dictio... | keyword[def] identifier[from_dict] ( identifier[cls] , identifier[dct] , identifier[project] = keyword[None] , identifier[delim] = literal[string] ):
literal[string]
keyword[if] identifier[project] keyword[is] keyword[None] :
identifier[project] = identifier[ws] . identifier[new_pro... | def from_dict(cls, dct, project=None, delim=' | '):
"""
This method converts a correctly formatted dictionary into OpenPNM
objects, and returns a handle to the *project* containing them.
Parameters
----------
dct : dictionary
The Python dictionary containing the ... |
def _normalize_hosts(hosts):
"""
Canonicalize the *hosts* parameter.
>>> _normalize_hosts("host,127.0.0.2:2909")
[('127.0.0.2', 2909), ('host', 9092)]
:param hosts:
A list or comma-separated string of hostnames which may also include
port numbers. All of the following are valid::
... | def function[_normalize_hosts, parameter[hosts]]:
constant[
Canonicalize the *hosts* parameter.
>>> _normalize_hosts("host,127.0.0.2:2909")
[('127.0.0.2', 2909), ('host', 9092)]
:param hosts:
A list or comma-separated string of hostnames which may also include
port numbers. All... | keyword[def] identifier[_normalize_hosts] ( identifier[hosts] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[hosts] , identifier[bytes] ):
identifier[hosts] = identifier[hosts] . identifier[split] ( literal[string] )
keyword[elif] identifier[isinstance] ( identifier[host... | def _normalize_hosts(hosts):
"""
Canonicalize the *hosts* parameter.
>>> _normalize_hosts("host,127.0.0.2:2909")
[('127.0.0.2', 2909), ('host', 9092)]
:param hosts:
A list or comma-separated string of hostnames which may also include
port numbers. All of the following are valid::
... |
def __update_density(self, compound='', element=''):
"""Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
elemen... | def function[__update_density, parameter[self, compound, element]]:
constant[Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of co... | keyword[def] identifier[__update_density] ( identifier[self] , identifier[compound] = literal[string] , identifier[element] = literal[string] ):
literal[string]
identifier[_density_element] = literal[int]
identifier[list_ratio] = identifier[self] . identifier[stack] [ identifier[compound]... | def __update_density(self, compound='', element=''):
"""Re-calculate the density of the element given due to stoichiometric changes as
well as the compound density (if density is not locked)
Parameters:
===========
compound: string (default is '') name of compound
element: s... |
def screencap_exec(self, filename: _PATH = 'screencap.png') -> None:
'''Taking a screenshot of a device display, then copy it to your computer.'''
self._execute('-s', self.device_sn, 'exec-out',
'screencap', '-p', '>', filename, shell=True) | def function[screencap_exec, parameter[self, filename]]:
constant[Taking a screenshot of a device display, then copy it to your computer.]
call[name[self]._execute, parameter[constant[-s], name[self].device_sn, constant[exec-out], constant[screencap], constant[-p], constant[>], name[filename]]] | keyword[def] identifier[screencap_exec] ( identifier[self] , identifier[filename] : identifier[_PATH] = literal[string] )-> keyword[None] :
literal[string]
identifier[self] . identifier[_execute] ( literal[string] , identifier[self] . identifier[device_sn] , literal[string] ,
literal[strin... | def screencap_exec(self, filename: _PATH='screencap.png') -> None:
"""Taking a screenshot of a device display, then copy it to your computer."""
self._execute('-s', self.device_sn, 'exec-out', 'screencap', '-p', '>', filename, shell=True) |
def find_alliteration(self):
"""
Find alliterations in the complete verse.
:return:
"""
if len(self.phonological_features_text) == 0:
logger.error("No phonological transcription found")
raise ValueError
else:
first_sounds = []
... | def function[find_alliteration, parameter[self]]:
constant[
Find alliterations in the complete verse.
:return:
]
if compare[call[name[len], parameter[name[self].phonological_features_text]] equal[==] constant[0]] begin[:]
call[name[logger].error, parameter[constan... | keyword[def] identifier[find_alliteration] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] . identifier[phonological_features_text] )== literal[int] :
identifier[logger] . identifier[error] ( literal[string] )
keyword[raise] identifie... | def find_alliteration(self):
"""
Find alliterations in the complete verse.
:return:
"""
if len(self.phonological_features_text) == 0:
logger.error('No phonological transcription found')
raise ValueError # depends on [control=['if'], data=[]]
else:
first_sound... |
def get_year(self):
"""
Return the year from the database in the format expected by the URL.
"""
year = super(BuildableYearArchiveView, self).get_year()
fmt = self.get_year_format()
return date(int(year), 1, 1).strftime(fmt) | def function[get_year, parameter[self]]:
constant[
Return the year from the database in the format expected by the URL.
]
variable[year] assign[=] call[call[name[super], parameter[name[BuildableYearArchiveView], name[self]]].get_year, parameter[]]
variable[fmt] assign[=] call[nam... | keyword[def] identifier[get_year] ( identifier[self] ):
literal[string]
identifier[year] = identifier[super] ( identifier[BuildableYearArchiveView] , identifier[self] ). identifier[get_year] ()
identifier[fmt] = identifier[self] . identifier[get_year_format] ()
keyword[return] id... | def get_year(self):
"""
Return the year from the database in the format expected by the URL.
"""
year = super(BuildableYearArchiveView, self).get_year()
fmt = self.get_year_format()
return date(int(year), 1, 1).strftime(fmt) |
def get_ar_count(self):
"""Return the ar_count request paramteter
"""
ar_count = 1
try:
ar_count = int(self.request.form.get("ar_count", 1))
except (TypeError, ValueError):
ar_count = 1
return ar_count | def function[get_ar_count, parameter[self]]:
constant[Return the ar_count request paramteter
]
variable[ar_count] assign[=] constant[1]
<ast.Try object at 0x7da1b1d67190>
return[name[ar_count]] | keyword[def] identifier[get_ar_count] ( identifier[self] ):
literal[string]
identifier[ar_count] = literal[int]
keyword[try] :
identifier[ar_count] = identifier[int] ( identifier[self] . identifier[request] . identifier[form] . identifier[get] ( literal[string] , literal[int]... | def get_ar_count(self):
"""Return the ar_count request paramteter
"""
ar_count = 1
try:
ar_count = int(self.request.form.get('ar_count', 1)) # depends on [control=['try'], data=[]]
except (TypeError, ValueError):
ar_count = 1 # depends on [control=['except'], data=[]]
retur... |
def recipe_seurat(adata, log=True, plot=False, copy=False):
"""Normalization and filtering as of Seurat [Satija15]_.
This uses a particular preprocessing.
Expects non-logarithmized data. If using logarithmized data, pass `log=False`.
"""
if copy: adata = adata.copy()
pp.filter_cells(adata, min... | def function[recipe_seurat, parameter[adata, log, plot, copy]]:
constant[Normalization and filtering as of Seurat [Satija15]_.
This uses a particular preprocessing.
Expects non-logarithmized data. If using logarithmized data, pass `log=False`.
]
if name[copy] begin[:]
varia... | keyword[def] identifier[recipe_seurat] ( identifier[adata] , identifier[log] = keyword[True] , identifier[plot] = keyword[False] , identifier[copy] = keyword[False] ):
literal[string]
keyword[if] identifier[copy] : identifier[adata] = identifier[adata] . identifier[copy] ()
identifier[pp] . identifie... | def recipe_seurat(adata, log=True, plot=False, copy=False):
"""Normalization and filtering as of Seurat [Satija15]_.
This uses a particular preprocessing.
Expects non-logarithmized data. If using logarithmized data, pass `log=False`.
"""
if copy:
adata = adata.copy() # depends on [control... |
def register_for_deleted_resource(self, resource_id):
"""Registers for notification of a deleted resource.
``ResourceReceiver.deletedResources()`` is invoked when the
specified resource is deleted or removed from this bin.
arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource`... | def function[register_for_deleted_resource, parameter[self, resource_id]]:
constant[Registers for notification of a deleted resource.
``ResourceReceiver.deletedResources()`` is invoked when the
specified resource is deleted or removed from this bin.
arg: resource_id (osid.id.Id): th... | keyword[def] identifier[register_for_deleted_resource] ( identifier[self] , identifier[resource_id] ):
literal[string]
keyword[if] keyword[not] identifier[MONGO_LISTENER] . identifier[receivers] [ identifier[self] . identifier[_ns] ][ identifier[self] . identifier[_receiver] ][ ... | def register_for_deleted_resource(self, resource_id):
"""Registers for notification of a deleted resource.
``ResourceReceiver.deletedResources()`` is invoked when the
specified resource is deleted or removed from this bin.
arg: resource_id (osid.id.Id): the ``Id`` of the ``Resource``
... |
def process(self, checksum, revision=None):
"""
Process a new revision and detect a revert if it occurred. Note that
you can pass whatever you like as `revision` and it will be returned in
the case that a revert occurs.
:Parameters:
checksum : str
An... | def function[process, parameter[self, checksum, revision]]:
constant[
Process a new revision and detect a revert if it occurred. Note that
you can pass whatever you like as `revision` and it will be returned in
the case that a revert occurs.
:Parameters:
checksum : ... | keyword[def] identifier[process] ( identifier[self] , identifier[checksum] , identifier[revision] = keyword[None] ):
literal[string]
identifier[revert] = keyword[None]
keyword[if] identifier[checksum] keyword[in] identifier[self] :
identifier[reverteds] = identifier[list... | def process(self, checksum, revision=None):
"""
Process a new revision and detect a revert if it occurred. Note that
you can pass whatever you like as `revision` and it will be returned in
the case that a revert occurs.
:Parameters:
checksum : str
Any id... |
def split_to_discretized_mix_logistic_params(inputs):
"""Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard devi... | def function[split_to_discretized_mix_logistic_params, parameter[inputs]]:
constant[Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one ... | keyword[def] identifier[split_to_discretized_mix_logistic_params] ( identifier[inputs] ):
literal[string]
identifier[batch] , identifier[height] , identifier[width] , identifier[output_dim] = identifier[shape_list] ( identifier[inputs] )
identifier[num_mixtures] = identifier[output_dim] // literal[int]
... | def split_to_discretized_mix_logistic_params(inputs):
"""Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard de... |
def out_format(data, out='nested', opts=None, **kwargs):
'''
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configu... | def function[out_format, parameter[data, out, opts]]:
constant[
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of ... | keyword[def] identifier[out_format] ( identifier[data] , identifier[out] = literal[string] , identifier[opts] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[opts] :
identifier[opts] = identifier[__opts__]
keyword[return] identifier[salt] . id... | def out_format(data, out='nested', opts=None, **kwargs):
"""
Return the formatted outputter string for the Python object.
data
The JSON serializable object.
out: ``nested``
The name of the output to use to transform the data. Default: ``nested``.
opts
Dictionary of configu... |
async def async_send(self, request, headers=None, content=None, **config):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to ... | <ast.AsyncFunctionDef object at 0x7da1b03e24d0> | keyword[async] keyword[def] identifier[async_send] ( identifier[self] , identifier[request] , identifier[headers] = keyword[None] , identifier[content] = keyword[None] ,** identifier[config] ):
literal[string]
identifier[loop] = identifier[asyncio] . identifier[get_event_loop] ()
keyword[... | async def async_send(self, request, headers=None, content=None, **config):
"""Prepare and send request object according to configuration.
:param ClientRequest request: The request object to be sent.
:param dict headers: Any headers to add to the request.
:param content: Any body data to add ... |
def _setup_logging():
"""Setup logging to log to nowhere by default.
For details, see:
http://docs.python.org/3/howto/logging.html#library-config
Internal function.
"""
import logging
logger = logging.getLogger('spotify-connect')
handler = logging.NullHandler()
logger.addHandler(h... | def function[_setup_logging, parameter[]]:
constant[Setup logging to log to nowhere by default.
For details, see:
http://docs.python.org/3/howto/logging.html#library-config
Internal function.
]
import module[logging]
variable[logger] assign[=] call[name[logging].getLogger, paramete... | keyword[def] identifier[_setup_logging] ():
literal[string]
keyword[import] identifier[logging]
identifier[logger] = identifier[logging] . identifier[getLogger] ( literal[string] )
identifier[handler] = identifier[logging] . identifier[NullHandler] ()
identifier[logger] . identifier[addHa... | def _setup_logging():
"""Setup logging to log to nowhere by default.
For details, see:
http://docs.python.org/3/howto/logging.html#library-config
Internal function.
"""
import logging
logger = logging.getLogger('spotify-connect')
handler = logging.NullHandler()
logger.addHandler(ha... |
def execute(self, nc_file_list, index_list, in_weight_table,
out_nc, grid_type, mp_lock):
"""The source code of the tool."""
if not os.path.exists(out_nc):
raise Exception("Outfile has not been created. "
"You need to run: generateOutputInfl... | def function[execute, parameter[self, nc_file_list, index_list, in_weight_table, out_nc, grid_type, mp_lock]]:
constant[The source code of the tool.]
if <ast.UnaryOp object at 0x7da204347ee0> begin[:]
<ast.Raise object at 0x7da204345c60>
if compare[call[name[len], parameter[name[nc_file_... | keyword[def] identifier[execute] ( identifier[self] , identifier[nc_file_list] , identifier[index_list] , identifier[in_weight_table] ,
identifier[out_nc] , identifier[grid_type] , identifier[mp_lock] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier... | def execute(self, nc_file_list, index_list, in_weight_table, out_nc, grid_type, mp_lock):
"""The source code of the tool."""
if not os.path.exists(out_nc):
raise Exception('Outfile has not been created. You need to run: generateOutputInflowFile function ...') # depends on [control=['if'], data=[]]
... |
def index(self, element: Element) -> int:
"""
Return the index in the array of the first item whose value is element.
It is an error if there is no such item.
>>> element = String('hello')
>>> array = Array(content=[element])
>>> array.index(element)
0
""... | def function[index, parameter[self, element]]:
constant[
Return the index in the array of the first item whose value is element.
It is an error if there is no such item.
>>> element = String('hello')
>>> array = Array(content=[element])
>>> array.index(element)
0... | keyword[def] identifier[index] ( identifier[self] , identifier[element] : identifier[Element] )-> identifier[int] :
literal[string]
keyword[from] identifier[refract] . identifier[refraction] keyword[import] identifier[refract]
keyword[return] identifier[self] . identifier[content] . ... | def index(self, element: Element) -> int:
"""
Return the index in the array of the first item whose value is element.
It is an error if there is no such item.
>>> element = String('hello')
>>> array = Array(content=[element])
>>> array.index(element)
0
"""
... |
def __init_keystone_session_v3(self, check=False):
"""
Return a new session object, created using Keystone API v3.
.. note::
Note that the only supported authN method is password authentication;
token or other plug-ins are not currently supported.
"""
try:
... | def function[__init_keystone_session_v3, parameter[self, check]]:
constant[
Return a new session object, created using Keystone API v3.
.. note::
Note that the only supported authN method is password authentication;
token or other plug-ins are not currently supported.
... | keyword[def] identifier[__init_keystone_session_v3] ( identifier[self] , identifier[check] = keyword[False] ):
literal[string]
keyword[try] :
keyword[from] identifier[keystoneauth1] . identifier[identity] keyword[import] identifier[v3] keyword[as] identifier[keystone_v3] ... | def __init_keystone_session_v3(self, check=False):
"""
Return a new session object, created using Keystone API v3.
.. note::
Note that the only supported authN method is password authentication;
token or other plug-ins are not currently supported.
"""
try:
#... |
def objIngest(obj_file):
import sys,os,math,re
import pyfits
import MOPfiles
obj=MOPfiles.read(obj_file)
"""
The SQL description of the source table
+-------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra ... | def function[objIngest, parameter[obj_file]]:
import module[sys], module[os], module[math], module[re]
import module[pyfits]
import module[MOPfiles]
variable[obj] assign[=] call[name[MOPfiles].read, parameter[name[obj_file]]]
constant[
The SQL description of the source table
+-------... | keyword[def] identifier[objIngest] ( identifier[obj_file] ):
keyword[import] identifier[sys] , identifier[os] , identifier[math] , identifier[re]
keyword[import] identifier[pyfits]
keyword[import] identifier[MOPfiles]
identifier[obj] = identifier[MOPfiles] . identifier[read] ( identifier[... | def objIngest(obj_file):
import sys, os, math, re
import pyfits
import MOPfiles
obj = MOPfiles.read(obj_file)
'\n The SQL description of the source table\n +-------------+---------+------+-----+---------+----------------+\n | Field | Type | Null | Key | Default | Extra |\n... |
def create_translate_dictionaries(symbols):
u"""create translate dictionaries for text, google, docomo, kddi and softbank via `symbols`
create dictionaries for translate emoji character to carrier from unicode (forward) or to unicode from carrier (reverse).
method return dictionary instance which key i... | def function[create_translate_dictionaries, parameter[symbols]]:
constant[create translate dictionaries for text, google, docomo, kddi and softbank via `symbols`
create dictionaries for translate emoji character to carrier from unicode (forward) or to unicode from carrier (reverse).
method return d... | keyword[def] identifier[create_translate_dictionaries] ( identifier[symbols] ):
literal[string]
identifier[unicode_to_text] ={}
identifier[unicode_to_docomo_img] ={}
identifier[unicode_to_kddi_img] ={}
identifier[unicode_to_softbank_img] ={}
identifier[unicode_to_google] ={}
identi... | def create_translate_dictionaries(symbols):
u"""create translate dictionaries for text, google, docomo, kddi and softbank via `symbols`
create dictionaries for translate emoji character to carrier from unicode (forward) or to unicode from carrier (reverse).
method return dictionary instance which key i... |
def label(self, request, tag):
"""
Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance.
"""
if self.parameter.label:
tag[self.parameter.label]
return tag | def function[label, parameter[self, request, tag]]:
constant[
Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance.
]
if name[self].parameter.label begin[:]
call[name[tag]][name[self].parameter.label]
return[name[tag]] | keyword[def] identifier[label] ( identifier[self] , identifier[request] , identifier[tag] ):
literal[string]
keyword[if] identifier[self] . identifier[parameter] . identifier[label] :
identifier[tag] [ identifier[self] . identifier[parameter] . identifier[label] ]
keyword[ret... | def label(self, request, tag):
"""
Render the label of the wrapped L{Parameter} or L{ChoiceParameter} instance.
"""
if self.parameter.label:
tag[self.parameter.label] # depends on [control=['if'], data=[]]
return tag |
def main(argv=None):
"""General function for converting between ReSpecTh and ChemKED files based on extension.
"""
parser = ArgumentParser(
description='Convert between ReSpecTh XML file and ChemKED YAML file '
'automatically based on file extension.'
)
parser.add_arg... | def function[main, parameter[argv]]:
constant[General function for converting between ReSpecTh and ChemKED files based on extension.
]
variable[parser] assign[=] call[name[ArgumentParser], parameter[]]
call[name[parser].add_argument, parameter[constant[-i], constant[--input]]]
call[n... | keyword[def] identifier[main] ( identifier[argv] = keyword[None] ):
literal[string]
identifier[parser] = identifier[ArgumentParser] (
identifier[description] = literal[string]
literal[string]
)
identifier[parser] . identifier[add_argument] ( literal[string] , literal[string] ,
ide... | def main(argv=None):
"""General function for converting between ReSpecTh and ChemKED files based on extension.
"""
parser = ArgumentParser(description='Convert between ReSpecTh XML file and ChemKED YAML file automatically based on file extension.')
parser.add_argument('-i', '--input', type=str, required... |
def restore(self, name, ttl, value, replace=False):
"""
Create a key using the provided serialized value, previously obtained
using DUMP.
"""
params = [name, ttl, value]
if replace:
params.append('REPLACE')
return self.execute_command('RESTORE', *param... | def function[restore, parameter[self, name, ttl, value, replace]]:
constant[
Create a key using the provided serialized value, previously obtained
using DUMP.
]
variable[params] assign[=] list[[<ast.Name object at 0x7da1b1f95ff0>, <ast.Name object at 0x7da1b1f94e80>, <ast.Name ob... | keyword[def] identifier[restore] ( identifier[self] , identifier[name] , identifier[ttl] , identifier[value] , identifier[replace] = keyword[False] ):
literal[string]
identifier[params] =[ identifier[name] , identifier[ttl] , identifier[value] ]
keyword[if] identifier[replace] :
... | def restore(self, name, ttl, value, replace=False):
"""
Create a key using the provided serialized value, previously obtained
using DUMP.
"""
params = [name, ttl, value]
if replace:
params.append('REPLACE') # depends on [control=['if'], data=[]]
return self.execute_comma... |
def _mainthread_poll_readable(self):
"""Searches for readable client sockets. These sockets are then put in a subthread
to be handled by _handle_readable
"""
events = self._recv_selector.select(self.block_time)
for key, mask in events:
if mask == selectors.EVENT_READ:... | def function[_mainthread_poll_readable, parameter[self]]:
constant[Searches for readable client sockets. These sockets are then put in a subthread
to be handled by _handle_readable
]
variable[events] assign[=] call[name[self]._recv_selector.select, parameter[name[self].block_time]]
... | keyword[def] identifier[_mainthread_poll_readable] ( identifier[self] ):
literal[string]
identifier[events] = identifier[self] . identifier[_recv_selector] . identifier[select] ( identifier[self] . identifier[block_time] )
keyword[for] identifier[key] , identifier[mask] keyword[in] iden... | def _mainthread_poll_readable(self):
"""Searches for readable client sockets. These sockets are then put in a subthread
to be handled by _handle_readable
"""
events = self._recv_selector.select(self.block_time)
for (key, mask) in events:
if mask == selectors.EVENT_READ:
s... |
def download_financialzip():
"""
会创建一个download/文件夹
"""
result = get_filename()
res = []
for item, md5 in result:
if item in os.listdir(download_path) and md5==QA_util_file_md5('{}{}{}'.format(download_path,os.sep,item)):
print('FILE {} is already in {}'.format(it... | def function[download_financialzip, parameter[]]:
constant[
会创建一个download/文件夹
]
variable[result] assign[=] call[name[get_filename], parameter[]]
variable[res] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b2063550>, <ast.Name object at 0x7da1b2062800>]]] in starre... | keyword[def] identifier[download_financialzip] ():
literal[string]
identifier[result] = identifier[get_filename] ()
identifier[res] =[]
keyword[for] identifier[item] , identifier[md5] keyword[in] identifier[result] :
keyword[if] identifier[item] keyword[in] identifier[os] . identif... | def download_financialzip():
"""
会创建一个download/文件夹
"""
result = get_filename()
res = []
for (item, md5) in result:
if item in os.listdir(download_path) and md5 == QA_util_file_md5('{}{}{}'.format(download_path, os.sep, item)):
print('FILE {} is already in {}'.format(item, dow... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.