code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def avail_locations(conn=None, call=None):
'''
Return a dict of all available VM locations on the cloud provider with
relevant data
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the -... | def function[avail_locations, parameter[conn, call]]:
constant[
Return a dict of all available VM locations on the cloud provider with
relevant data
]
if compare[name[call] equal[==] constant[action]] begin[:]
<ast.Raise object at 0x7da1b2345450>
if <ast.UnaryOp object at 0x7... | keyword[def] identifier[avail_locations] ( identifier[conn] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[string]
literal[string]
)
... | def avail_locations(conn=None, call=None):
"""
Return a dict of all available VM locations on the cloud provider with
relevant data
"""
if call == 'action':
raise SaltCloudSystemExit('The avail_locations function must be called with -f or --function, or with the --list-locations option') # ... |
def draw(self, size=None, background_threshold=0.01, background_class_id=None, colors=None,
return_foreground_mask=False):
"""
Render the segmentation map as an RGB image.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
... | def function[draw, parameter[self, size, background_threshold, background_class_id, colors, return_foreground_mask]]:
constant[
Render the segmentation map as an RGB image.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
S... | keyword[def] identifier[draw] ( identifier[self] , identifier[size] = keyword[None] , identifier[background_threshold] = literal[int] , identifier[background_class_id] = keyword[None] , identifier[colors] = keyword[None] ,
identifier[return_foreground_mask] = keyword[False] ):
literal[string]
iden... | def draw(self, size=None, background_threshold=0.01, background_class_id=None, colors=None, return_foreground_mask=False):
"""
Render the segmentation map as an RGB image.
Parameters
----------
size : None or float or iterable of int or iterable of float, optional
Size o... |
def extract_data(self, page):
"""Extract the AppNexus object or list of objects from the response"""
response_keys = set(page.keys())
uncommon_keys = response_keys - self.common_keys
for possible_data_key in uncommon_keys:
element = page[possible_data_key]
if isi... | def function[extract_data, parameter[self, page]]:
constant[Extract the AppNexus object or list of objects from the response]
variable[response_keys] assign[=] call[name[set], parameter[call[name[page].keys, parameter[]]]]
variable[uncommon_keys] assign[=] binary_operation[name[response_keys] - ... | keyword[def] identifier[extract_data] ( identifier[self] , identifier[page] ):
literal[string]
identifier[response_keys] = identifier[set] ( identifier[page] . identifier[keys] ())
identifier[uncommon_keys] = identifier[response_keys] - identifier[self] . identifier[common_keys]
... | def extract_data(self, page):
"""Extract the AppNexus object or list of objects from the response"""
response_keys = set(page.keys())
uncommon_keys = response_keys - self.common_keys
for possible_data_key in uncommon_keys:
element = page[possible_data_key]
if isinstance(element, dict):
... |
def line_range(self, line_number):
"""Return a slice for the given line number"""
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.')
if line_number not in self.logical_lines:
return slice(line_number, line_number + 1)
el... | def function[line_range, parameter[self, line_number]]:
constant[Return a slice for the given line number]
if <ast.BoolOp object at 0x7da1b1e5c160> begin[:]
<ast.Raise object at 0x7da1b1e5fe50>
if compare[name[line_number] <ast.NotIn object at 0x7da2590d7190> name[self].logical_lines] be... | keyword[def] identifier[line_range] ( identifier[self] , identifier[line_number] ):
literal[string]
keyword[if] identifier[line_number] <= literal[int] keyword[or] identifier[line_number] > identifier[len] ( identifier[self] . identifier[lines] ):
keyword[raise] identifier[IndexError] ( literal[... | def line_range(self, line_number):
"""Return a slice for the given line number"""
if line_number <= 0 or line_number > len(self.lines):
raise IndexError('NOTE: Python file line numbers are offset by 1.') # depends on [control=['if'], data=[]]
if line_number not in self.logical_lines:
return... |
def create_or_update_group_alias(self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point=DEFAULT_MOUNT_POINT):
"""Creates or update a group alias.
Supported methods:
POST: /{mount_point}/group-alias. Produces: 200 application/json
:param alias_id: ID of the g... | def function[create_or_update_group_alias, parameter[self, name, alias_id, mount_accessor, canonical_id, mount_point]]:
constant[Creates or update a group alias.
Supported methods:
POST: /{mount_point}/group-alias. Produces: 200 application/json
:param alias_id: ID of the group ali... | keyword[def] identifier[create_or_update_group_alias] ( identifier[self] , identifier[name] , identifier[alias_id] = keyword[None] , identifier[mount_accessor] = keyword[None] , identifier[canonical_id] = keyword[None] , identifier[mount_point] = identifier[DEFAULT_MOUNT_POINT] ):
literal[string]
i... | def create_or_update_group_alias(self, name, alias_id=None, mount_accessor=None, canonical_id=None, mount_point=DEFAULT_MOUNT_POINT):
"""Creates or update a group alias.
Supported methods:
POST: /{mount_point}/group-alias. Produces: 200 application/json
:param alias_id: ID of the group... |
def check_list(var, num_terms):
""" Check if a variable is a list and is the correct length.
If variable is not a list it will make it a list of the correct length with
all terms identical.
"""
if not isinstance(var, list):
if isinstance(var, tuple):
var = list(var)
else... | def function[check_list, parameter[var, num_terms]]:
constant[ Check if a variable is a list and is the correct length.
If variable is not a list it will make it a list of the correct length with
all terms identical.
]
if <ast.UnaryOp object at 0x7da18dc054b0> begin[:]
if ca... | keyword[def] identifier[check_list] ( identifier[var] , identifier[num_terms] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[var] , identifier[list] ):
keyword[if] identifier[isinstance] ( identifier[var] , identifier[tuple] ):
identifier[var] = ide... | def check_list(var, num_terms):
""" Check if a variable is a list and is the correct length.
If variable is not a list it will make it a list of the correct length with
all terms identical.
"""
if not isinstance(var, list):
if isinstance(var, tuple):
var = list(var) # depends o... |
def removeDataset(self, dataset):
"""
Removes the specified dataset from this repository. This performs
a cascading removal of all items within this dataset.
"""
for datasetRecord in models.Dataset.select().where(
models.Dataset.id == dataset.getId()):
... | def function[removeDataset, parameter[self, dataset]]:
constant[
Removes the specified dataset from this repository. This performs
a cascading removal of all items within this dataset.
]
for taget[name[datasetRecord]] in starred[call[call[name[models].Dataset.select, parameter[]]... | keyword[def] identifier[removeDataset] ( identifier[self] , identifier[dataset] ):
literal[string]
keyword[for] identifier[datasetRecord] keyword[in] identifier[models] . identifier[Dataset] . identifier[select] (). identifier[where] (
identifier[models] . identifier[Dataset] . identifi... | def removeDataset(self, dataset):
"""
Removes the specified dataset from this repository. This performs
a cascading removal of all items within this dataset.
"""
for datasetRecord in models.Dataset.select().where(models.Dataset.id == dataset.getId()):
datasetRecord.delete_instanc... |
def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.lock_disable and not self.session_config_lock:
self._unlock() | def function[discard_config, parameter[self]]:
constant[Discard changes (rollback 0).]
call[name[self].device.cu.rollback, parameter[]]
if <ast.BoolOp object at 0x7da1b1c10160> begin[:]
call[name[self]._unlock, parameter[]] | keyword[def] identifier[discard_config] ( identifier[self] ):
literal[string]
identifier[self] . identifier[device] . identifier[cu] . identifier[rollback] ( identifier[rb_id] = literal[int] )
keyword[if] keyword[not] identifier[self] . identifier[lock_disable] keyword[and] keyword[not... | def discard_config(self):
"""Discard changes (rollback 0)."""
self.device.cu.rollback(rb_id=0)
if not self.lock_disable and (not self.session_config_lock):
self._unlock() # depends on [control=['if'], data=[]] |
def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs):
"""
Gets all api usages by type for a given period an api.
"""
if query is None:
query = {}
mandatory_query = {
'filters[usagePeriod]': usage_period_id,
'filters[me... | def function[all, parameter[self, usage_type, usage_period_id, api, query]]:
constant[
Gets all api usages by type for a given period an api.
]
if compare[name[query] is constant[None]] begin[:]
variable[query] assign[=] dictionary[[], []]
variable[mandatory_query... | keyword[def] identifier[all] ( identifier[self] , identifier[usage_type] , identifier[usage_period_id] , identifier[api] , identifier[query] = keyword[None] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[query] keyword[is] keyword[None] :
ident... | def all(self, usage_type, usage_period_id, api, query=None, *args, **kwargs):
"""
Gets all api usages by type for a given period an api.
"""
if query is None:
query = {} # depends on [control=['if'], data=['query']]
mandatory_query = {'filters[usagePeriod]': usage_period_id, 'filter... |
def convert_header(cls, old_header, new_version):
""" Converts a header to a another version
Parameters
----------
old_header: the old header instance
new_version: float or str
Returns
-------
The converted header
>>> old_header = HeaderFactory... | def function[convert_header, parameter[cls, old_header, new_version]]:
constant[ Converts a header to a another version
Parameters
----------
old_header: the old header instance
new_version: float or str
Returns
-------
The converted header
>>>... | keyword[def] identifier[convert_header] ( identifier[cls] , identifier[old_header] , identifier[new_version] ):
literal[string]
identifier[new_header_class] = identifier[cls] . identifier[header_class_for_version] ( identifier[new_version] )
identifier[b] = identifier[bytearray] ( identif... | def convert_header(cls, old_header, new_version):
""" Converts a header to a another version
Parameters
----------
old_header: the old header instance
new_version: float or str
Returns
-------
The converted header
>>> old_header = HeaderFactory.new... |
def expand_path(path: Union[str, Path]) -> Path:
"""Convert relative paths to absolute with resolving user directory."""
return Path(path).expanduser().resolve() | def function[expand_path, parameter[path]]:
constant[Convert relative paths to absolute with resolving user directory.]
return[call[call[call[name[Path], parameter[name[path]]].expanduser, parameter[]].resolve, parameter[]]] | keyword[def] identifier[expand_path] ( identifier[path] : identifier[Union] [ identifier[str] , identifier[Path] ])-> identifier[Path] :
literal[string]
keyword[return] identifier[Path] ( identifier[path] ). identifier[expanduser] (). identifier[resolve] () | def expand_path(path: Union[str, Path]) -> Path:
"""Convert relative paths to absolute with resolving user directory."""
return Path(path).expanduser().resolve() |
def roller(timestamps, contract_dates, get_weights, **kwargs):
"""
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate wei... | def function[roller, parameter[timestamps, contract_dates, get_weights]]:
constant[
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timest... | keyword[def] identifier[roller] ( identifier[timestamps] , identifier[contract_dates] , identifier[get_weights] ,** identifier[kwargs] ):
literal[string]
identifier[timestamps] = identifier[sorted] ( identifier[timestamps] )
identifier[contract_dates] = identifier[contract_dates] . identifier[sort_val... | def roller(timestamps, contract_dates, get_weights, **kwargs):
"""
Calculate weight allocations to tradeable instruments for generic futures
at a set of timestamps for a given root generic.
Paramters
---------
timestamps: iterable
Sorted iterable of of pandas.Timestamps to calculate wei... |
def _next_argsig(s):
"""
given a string, find the next complete argument signature and
return it and a new string advanced past that point
"""
c = s[0]
if c in "BCDFIJSVZ":
result = (c, s[1:])
elif c == "[":
d, s = _next_argsig(s[1:])
result = (c + d, s[len(d) + 1:... | def function[_next_argsig, parameter[s]]:
constant[
given a string, find the next complete argument signature and
return it and a new string advanced past that point
]
variable[c] assign[=] call[name[s]][constant[0]]
if compare[name[c] in constant[BCDFIJSVZ]] begin[:]
... | keyword[def] identifier[_next_argsig] ( identifier[s] ):
literal[string]
identifier[c] = identifier[s] [ literal[int] ]
keyword[if] identifier[c] keyword[in] literal[string] :
identifier[result] =( identifier[c] , identifier[s] [ literal[int] :])
keyword[elif] identifier[c] == lit... | def _next_argsig(s):
"""
given a string, find the next complete argument signature and
return it and a new string advanced past that point
"""
c = s[0]
if c in 'BCDFIJSVZ':
result = (c, s[1:]) # depends on [control=['if'], data=['c']]
elif c == '[':
(d, s) = _next_argsig(s[1... |
def update(self, user, identity):
"""
Update specified identity for the specified user
:param user: User object or id
:param identity: Identity object to be updated.
:return: The updated Identity
"""
return UserIdentityRequest(self).put(self.endpoint.update, user... | def function[update, parameter[self, user, identity]]:
constant[
Update specified identity for the specified user
:param user: User object or id
:param identity: Identity object to be updated.
:return: The updated Identity
]
return[call[call[name[UserIdentityRequest]... | keyword[def] identifier[update] ( identifier[self] , identifier[user] , identifier[identity] ):
literal[string]
keyword[return] identifier[UserIdentityRequest] ( identifier[self] ). identifier[put] ( identifier[self] . identifier[endpoint] . identifier[update] , identifier[user] , identifier[ident... | def update(self, user, identity):
"""
Update specified identity for the specified user
:param user: User object or id
:param identity: Identity object to be updated.
:return: The updated Identity
"""
return UserIdentityRequest(self).put(self.endpoint.update, user, identi... |
def _local_uri_rewriter(raw_uri):
"""Rewrite local file URIs as required by the rewrite_uris method.
Local file paths, unlike GCS paths, may have their raw URI simplified by
os.path.normpath which collapses extraneous indirect characters.
>>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')
('/tmp/B_PA... | def function[_local_uri_rewriter, parameter[raw_uri]]:
constant[Rewrite local file URIs as required by the rewrite_uris method.
Local file paths, unlike GCS paths, may have their raw URI simplified by
os.path.normpath which collapses extraneous indirect characters.
>>> _local_uri_rewriter('/tmp/a_path/.... | keyword[def] identifier[_local_uri_rewriter] ( identifier[raw_uri] ):
literal[string]
identifier[raw_path] , identifier[filename] = identifier[os] . identifier[path] . identifier[split] ( identifier[raw_uri] )
identifier[prefix_replacements] =[( literal[string] , literal[string] ),( literal[stri... | def _local_uri_rewriter(raw_uri):
"""Rewrite local file URIs as required by the rewrite_uris method.
Local file paths, unlike GCS paths, may have their raw URI simplified by
os.path.normpath which collapses extraneous indirect characters.
>>> _local_uri_rewriter('/tmp/a_path/../B_PATH/file.txt')
('/tmp/B_... |
def quit(self, reason=''):
"""
Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting.
"""
with self.lock:
self.keep_going = False
self._quit(reason)
... | def function[quit, parameter[self, reason]]:
constant[
Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting.
]
with name[self].lock begin[:]
name[self].keep_going assi... | keyword[def] identifier[quit] ( identifier[self] , identifier[reason] = literal[string] ):
literal[string]
keyword[with] identifier[self] . identifier[lock] :
identifier[self] . identifier[keep_going] = keyword[False]
identifier[self] . identifier[_quit] ( identifier[rea... | def quit(self, reason=''):
"""
Sends a QUIT message, closes the connection and -
ends Lurklib's main loop.
Optional arguments:
* reason='' - Reason for quitting.
"""
with self.lock:
self.keep_going = False
self._quit(reason)
self._socket.shutdo... |
def _build_page(self, filepath):
""" To build from filepath, relative to pages_dir """
filename = filepath.split("/")[-1]
# If filename starts with _ (underscore) or . (dot) do not build
if not filename.startswith(("_", ".")) and (filename.endswith(PAGE_FORMAT)):
meta = self.... | def function[_build_page, parameter[self, filepath]]:
constant[ To build from filepath, relative to pages_dir ]
variable[filename] assign[=] call[call[name[filepath].split, parameter[constant[/]]]][<ast.UnaryOp object at 0x7da2054a40d0>]
if <ast.BoolOp object at 0x7da2054a4d00> begin[:]
... | keyword[def] identifier[_build_page] ( identifier[self] , identifier[filepath] ):
literal[string]
identifier[filename] = identifier[filepath] . identifier[split] ( literal[string] )[- literal[int] ]
keyword[if] keyword[not] identifier[filename] . identifier[startswith] (( litera... | def _build_page(self, filepath):
""" To build from filepath, relative to pages_dir """
filename = filepath.split('/')[-1]
# If filename starts with _ (underscore) or . (dot) do not build
if not filename.startswith(('_', '.')) and filename.endswith(PAGE_FORMAT):
meta = self._get_page_meta(filepat... |
def read(self, file_or_path):
"""Read template from cache or file."""
if file_or_path in self._cached_templates:
return self._cached_templates[file_or_path]
if is_filelike(file_or_path):
template = file_or_path.read()
dirname = None
else:
... | def function[read, parameter[self, file_or_path]]:
constant[Read template from cache or file.]
if compare[name[file_or_path] in name[self]._cached_templates] begin[:]
return[call[name[self]._cached_templates][name[file_or_path]]]
if call[name[is_filelike], parameter[name[file_or_path]]] ... | keyword[def] identifier[read] ( identifier[self] , identifier[file_or_path] ):
literal[string]
keyword[if] identifier[file_or_path] keyword[in] identifier[self] . identifier[_cached_templates] :
keyword[return] identifier[self] . identifier[_cached_templates] [ identifier[file_or_p... | def read(self, file_or_path):
"""Read template from cache or file."""
if file_or_path in self._cached_templates:
return self._cached_templates[file_or_path] # depends on [control=['if'], data=['file_or_path']]
if is_filelike(file_or_path):
template = file_or_path.read()
dirname = No... |
def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value():
return queryset.filter(country=self.value())
else:
return quer... | def function[queryset, parameter[self, request, queryset]]:
constant[
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
]
if call[name[self].value, parameter[]] begin[:]
return[call[name[queryset].fil... | keyword[def] identifier[queryset] ( identifier[self] , identifier[request] , identifier[queryset] ):
literal[string]
keyword[if] identifier[self] . identifier[value] ():
keyword[return] identifier[queryset] . identifier[filter] ( identifier[country] = identifier[self] . identifier[va... | def queryset(self, request, queryset):
"""
Returns the filtered queryset based on the value
provided in the query string and retrievable via
`self.value()`.
"""
if self.value():
return queryset.filter(country=self.value()) # depends on [control=['if'], data=[]]
else:... |
def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None,
domain=None, datacenter=None, nic_speed=None,
public_ip=None, private_ip=None, **kwargs):
"""List all hardware (servers and bare metal computing instances).
:param list tags: filter bas... | def function[list_hardware, parameter[self, tags, cpus, memory, hostname, domain, datacenter, nic_speed, public_ip, private_ip]]:
constant[List all hardware (servers and bare metal computing instances).
:param list tags: filter based on tags
:param integer cpus: filter based on number of CPUS
... | keyword[def] identifier[list_hardware] ( identifier[self] , identifier[tags] = keyword[None] , identifier[cpus] = keyword[None] , identifier[memory] = keyword[None] , identifier[hostname] = keyword[None] ,
identifier[domain] = keyword[None] , identifier[datacenter] = keyword[None] , identifier[nic_speed] = keyword[N... | def list_hardware(self, tags=None, cpus=None, memory=None, hostname=None, domain=None, datacenter=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs):
"""List all hardware (servers and bare metal computing instances).
:param list tags: filter based on tags
:param integer cpus: filter b... |
def gitrepo(cwd):
"""Return hash of Git data that can be used to display more information to
users.
Example:
"git": {
"head": {
"id": "5e837ce92220be64821128a70f6093f836dd2c05",
"author_name": "Wil Gieseler",
"author_email": "wil@example.c... | def function[gitrepo, parameter[cwd]]:
constant[Return hash of Git data that can be used to display more information to
users.
Example:
"git": {
"head": {
"id": "5e837ce92220be64821128a70f6093f836dd2c05",
"author_name": "Wil Gieseler",
... | keyword[def] identifier[gitrepo] ( identifier[cwd] ):
literal[string]
identifier[repo] = identifier[Repository] ( identifier[cwd] )
keyword[if] keyword[not] identifier[repo] . identifier[valid] ():
keyword[return] {}
keyword[return] {
literal[string] :{
literal[string] : ide... | def gitrepo(cwd):
"""Return hash of Git data that can be used to display more information to
users.
Example:
"git": {
"head": {
"id": "5e837ce92220be64821128a70f6093f836dd2c05",
"author_name": "Wil Gieseler",
"author_email": "wil@example.c... |
def encode_filesystem_name(input_str):
"""Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or dashes
(".", "_", or "-"). No... | def function[encode_filesystem_name, parameter[input_str]]:
constant[Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or das... | keyword[def] identifier[encode_filesystem_name] ( identifier[input_str] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[input_str] , identifier[str] ):
identifier[input_str] = identifier[unicode] ( identifier[input_str] )
keyword[elif] keyword[not] identifier[isinstance]... | def encode_filesystem_name(input_str):
"""Encodes an arbitrary unicode string to a generic filesystem-compatible
non-unicode filename.
The result after encoding will only contain the standard ascii lowercase
letters (a-z), the digits (0-9), or periods, underscores, or dashes
(".", "_", or "-"). No... |
def _process_json(data):
"""
return a list of GradLeave objects.
"""
requests = []
for item in data:
leave = GradLeave()
leave.reason = item.get('leaveReason')
leave.submit_date = datetime_from_string(item.get('submitDate'))
if item.get('status') is not None and len(i... | def function[_process_json, parameter[data]]:
constant[
return a list of GradLeave objects.
]
variable[requests] assign[=] list[[]]
for taget[name[item]] in starred[name[data]] begin[:]
variable[leave] assign[=] call[name[GradLeave], parameter[]]
name[leav... | keyword[def] identifier[_process_json] ( identifier[data] ):
literal[string]
identifier[requests] =[]
keyword[for] identifier[item] keyword[in] identifier[data] :
identifier[leave] = identifier[GradLeave] ()
identifier[leave] . identifier[reason] = identifier[item] . identifier[ge... | def _process_json(data):
"""
return a list of GradLeave objects.
"""
requests = []
for item in data:
leave = GradLeave()
leave.reason = item.get('leaveReason')
leave.submit_date = datetime_from_string(item.get('submitDate'))
if item.get('status') is not None and len(i... |
def add_extra_tags(self, image_id, main_tag, extra_tags, add_latest):
"""
Adds extra tags to an image after de-duplicating tag names.
:param image_id: Id of the image.
:type image_id: unicode | str
:param main_tag: Repo / tag specification that has been used to build the image. ... | def function[add_extra_tags, parameter[self, image_id, main_tag, extra_tags, add_latest]]:
constant[
Adds extra tags to an image after de-duplicating tag names.
:param image_id: Id of the image.
:type image_id: unicode | str
:param main_tag: Repo / tag specification that has bee... | keyword[def] identifier[add_extra_tags] ( identifier[self] , identifier[image_id] , identifier[main_tag] , identifier[extra_tags] , identifier[add_latest] ):
literal[string]
identifier[repo] , identifier[__] , identifier[i_tag] = identifier[main_tag] . identifier[rpartition] ( literal[string] )
... | def add_extra_tags(self, image_id, main_tag, extra_tags, add_latest):
"""
Adds extra tags to an image after de-duplicating tag names.
:param image_id: Id of the image.
:type image_id: unicode | str
:param main_tag: Repo / tag specification that has been used to build the image. If p... |
def _check_send_batch(self, result=None):
"""Check if we have enough messages/bytes to send
Since this can be called from the callback chain, we
pass through our first (non-self) arg
"""
if (
(self.batch_every_n and self.batch_every_n <= self._waitingMsgCount) or
... | def function[_check_send_batch, parameter[self, result]]:
constant[Check if we have enough messages/bytes to send
Since this can be called from the callback chain, we
pass through our first (non-self) arg
]
if <ast.BoolOp object at 0x7da1b0415900> begin[:]
call[na... | keyword[def] identifier[_check_send_batch] ( identifier[self] , identifier[result] = keyword[None] ):
literal[string]
keyword[if] (
( identifier[self] . identifier[batch_every_n] keyword[and] identifier[self] . identifier[batch_every_n] <= identifier[self] . identifier[_waitingMsgCount] )... | def _check_send_batch(self, result=None):
"""Check if we have enough messages/bytes to send
Since this can be called from the callback chain, we
pass through our first (non-self) arg
"""
if self.batch_every_n and self.batch_every_n <= self._waitingMsgCount or (self.batch_every_b and self... |
def tokenize_words(string):
"""
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
"""
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) | def function[tokenize_words, parameter[string]]:
constant[
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
]
variable[string] assign[=] call[name[six].text_type, parameter[name[string]]]
return... | keyword[def] identifier[tokenize_words] ( identifier[string] ):
literal[string]
identifier[string] = identifier[six] . identifier[text_type] ( identifier[string] )
keyword[return] identifier[re] . identifier[findall] ( identifier[WORD_TOKENIZATION_RULES] , identifier[string] ) | def tokenize_words(string):
"""
Tokenize input text to words.
:param string: Text to tokenize
:type string: str or unicode
:return: words
:rtype: list of strings
"""
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) |
def DbDeleteClassAttribute(self, argin):
""" delete a class attribute and all its properties from database
:param argin: Str[0] = Tango class name
Str[1] = Attribute name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug("In DbDele... | def function[DbDeleteClassAttribute, parameter[self, argin]]:
constant[ delete a class attribute and all its properties from database
:param argin: Str[0] = Tango class name
Str[1] = Attribute name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid ]
c... | keyword[def] identifier[DbDeleteClassAttribute] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
keyword[if] identifier[len] ( identifier[argin] )< literal[int] :
identifier[self] . identifi... | def DbDeleteClassAttribute(self, argin):
""" delete a class attribute and all its properties from database
:param argin: Str[0] = Tango class name
Str[1] = Attribute name
:type: tango.DevVarStringArray
:return:
:rtype: tango.DevVoid """
self._log.debug('In DbDeleteClassA... |
def is_contains(self, data):
"""
Judge the data whether is already exist if each bit of hash code is 1 then data exist.
"""
if not data:
return False
data = self._compress_by_md5(data)
result = True
# cut the first two place,route to different bloc... | def function[is_contains, parameter[self, data]]:
constant[
Judge the data whether is already exist if each bit of hash code is 1 then data exist.
]
if <ast.UnaryOp object at 0x7da18ede4190> begin[:]
return[constant[False]]
variable[data] assign[=] call[name[self]._co... | keyword[def] identifier[is_contains] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] keyword[not] identifier[data] :
keyword[return] keyword[False]
identifier[data] = identifier[self] . identifier[_compress_by_md5] ( identifier[data] )
identif... | def is_contains(self, data):
"""
Judge the data whether is already exist if each bit of hash code is 1 then data exist.
"""
if not data:
return False # depends on [control=['if'], data=[]]
data = self._compress_by_md5(data)
result = True
# cut the first two place,route t... |
def sort_by(self, attr_or_key, direction='asc'):
"""Sort the view by an attribute or key
:param attr_or_key: The attribute or key to sort by
:param direction: Either `asc` or `desc` indicating the direction of
sorting
"""
# work out the direction
... | def function[sort_by, parameter[self, attr_or_key, direction]]:
constant[Sort the view by an attribute or key
:param attr_or_key: The attribute or key to sort by
:param direction: Either `asc` or `desc` indicating the direction of
sorting
]
if compare[n... | keyword[def] identifier[sort_by] ( identifier[self] , identifier[attr_or_key] , identifier[direction] = literal[string] ):
literal[string]
keyword[if] identifier[direction] keyword[in] ( literal[string] , literal[string] , identifier[gtk] . identifier[SORT_ASCENDING] ):
iden... | def sort_by(self, attr_or_key, direction='asc'):
"""Sort the view by an attribute or key
:param attr_or_key: The attribute or key to sort by
:param direction: Either `asc` or `desc` indicating the direction of
sorting
"""
# work out the direction
if directi... |
def visit_call(self, node):
"""visit a Call node -> check if this is not a blacklisted builtin
call and check for * or ** use
"""
self._check_misplaced_format_function(node)
if isinstance(node.func, astroid.Name):
name = node.func.name
# ignore the name if... | def function[visit_call, parameter[self, node]]:
constant[visit a Call node -> check if this is not a blacklisted builtin
call and check for * or ** use
]
call[name[self]._check_misplaced_format_function, parameter[name[node]]]
if call[name[isinstance], parameter[name[node].func,... | keyword[def] identifier[visit_call] ( identifier[self] , identifier[node] ):
literal[string]
identifier[self] . identifier[_check_misplaced_format_function] ( identifier[node] )
keyword[if] identifier[isinstance] ( identifier[node] . identifier[func] , identifier[astroid] . identifier[Nam... | def visit_call(self, node):
"""visit a Call node -> check if this is not a blacklisted builtin
call and check for * or ** use
"""
self._check_misplaced_format_function(node)
if isinstance(node.func, astroid.Name):
name = node.func.name
# ignore the name if it's not a builtin ... |
def get_valid_residue(residue):
"""Check if the given string represents a valid amino acid residue."""
if residue is not None and amino_acids.get(residue) is None:
res = amino_acids_reverse.get(residue.lower())
if res is None:
raise InvalidResidueError(residue)
else:
... | def function[get_valid_residue, parameter[residue]]:
constant[Check if the given string represents a valid amino acid residue.]
if <ast.BoolOp object at 0x7da2041d94e0> begin[:]
variable[res] assign[=] call[name[amino_acids_reverse].get, parameter[call[name[residue].lower, parameter[]]]]... | keyword[def] identifier[get_valid_residue] ( identifier[residue] ):
literal[string]
keyword[if] identifier[residue] keyword[is] keyword[not] keyword[None] keyword[and] identifier[amino_acids] . identifier[get] ( identifier[residue] ) keyword[is] keyword[None] :
identifier[res] = identifier[... | def get_valid_residue(residue):
"""Check if the given string represents a valid amino acid residue."""
if residue is not None and amino_acids.get(residue) is None:
res = amino_acids_reverse.get(residue.lower())
if res is None:
raise InvalidResidueError(residue) # depends on [control... |
def _set_reserved_vlan(self, v, load=False):
"""
Setter method for reserved_vlan, mapped from YANG variable /reserved_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reserved_vlan is considered as a private
method. Backends looking to populate this v... | def function[_set_reserved_vlan, parameter[self, v, load]]:
constant[
Setter method for reserved_vlan, mapped from YANG variable /reserved_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reserved_vlan is considered as a private
method. Backends l... | keyword[def] identifier[_set_reserved_vlan] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_reserved_vlan(self, v, load=False):
"""
Setter method for reserved_vlan, mapped from YANG variable /reserved_vlan (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_reserved_vlan is considered as a private
method. Backends looking to populate this v... |
def settimeout(self, key, value, timeout):
"""Set a key with a timeout value (in seconds).
:meth:`settimeout` is used to override the shelf's timeout value.
:param timeout: The timeout value in seconds for the given key.
``0`` means that the key will never expire.
:type tim... | def function[settimeout, parameter[self, key, value, timeout]]:
constant[Set a key with a timeout value (in seconds).
:meth:`settimeout` is used to override the shelf's timeout value.
:param timeout: The timeout value in seconds for the given key.
``0`` means that the key will neve... | keyword[def] identifier[settimeout] ( identifier[self] , identifier[key] , identifier[value] , identifier[timeout] ):
literal[string]
identifier[self] [ identifier[key] ]= identifier[value]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
... | def settimeout(self, key, value, timeout):
"""Set a key with a timeout value (in seconds).
:meth:`settimeout` is used to override the shelf's timeout value.
:param timeout: The timeout value in seconds for the given key.
``0`` means that the key will never expire.
:type timeout... |
def _str_member_list(self, name):
"""
Generate a member listing, autosummary:: table where possible,
and a table where not.
"""
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix... | def function[_str_member_list, parameter[self, name]]:
constant[
Generate a member listing, autosummary:: table where possible,
and a table where not.
]
variable[out] assign[=] list[[]]
if call[name[self]][name[name]] begin[:]
<ast.AugAssign object at 0x7da1b0807... | keyword[def] identifier[_str_member_list] ( identifier[self] , identifier[name] ):
literal[string]
identifier[out] =[]
keyword[if] identifier[self] [ identifier[name] ]:
identifier[out] +=[ literal[string] % identifier[name] , literal[string] ]
identifier[prefix]... | def _str_member_list(self, name):
"""
Generate a member listing, autosummary:: table where possible,
and a table where not.
"""
out = []
if self[name]:
out += ['.. rubric:: %s' % name, '']
prefix = getattr(self, '_name', '')
if prefix:
prefix = '~... |
def outbound_message_filter(f):
"""
Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters.
"""
... | def function[outbound_message_filter, parameter[f]]:
constant[
Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use ... | keyword[def] identifier[outbound_message_filter] ( identifier[f] ):
literal[string]
keyword[if] identifier[asyncio] . identifier[iscoroutinefunction] ( identifier[f] ):
keyword[raise] identifier[TypeError] (
literal[string]
)
identifier[add_handler_spec] (
identifie... | def outbound_message_filter(f):
"""
Register the decorated function as a service-level outbound message filter.
:raise TypeError: if the decorated object is a coroutine function
.. seealso::
:class:`StanzaStream`
for important remarks regarding the use of stanza filters.
"""
... |
def parse_title(self, docname):
"""Parse a document title as the first line starting in [A-Za-z0-9<]
or fall back to the document basename if no such line exists.
The cmake --help-*-list commands also depend on this convention.
Return the title or False if the document file does... | def function[parse_title, parameter[self, docname]]:
constant[Parse a document title as the first line starting in [A-Za-z0-9<]
or fall back to the document basename if no such line exists.
The cmake --help-*-list commands also depend on this convention.
Return the title or Fals... | keyword[def] identifier[parse_title] ( identifier[self] , identifier[docname] ):
literal[string]
identifier[env] = identifier[self] . identifier[document] . identifier[settings] . identifier[env]
identifier[title] = identifier[self] . identifier[titles] . identifier[get] ( identifier[docn... | def parse_title(self, docname):
"""Parse a document title as the first line starting in [A-Za-z0-9<]
or fall back to the document basename if no such line exists.
The cmake --help-*-list commands also depend on this convention.
Return the title or False if the document file does not... |
def get_format(**kwargs):
"""
Returns a `QTextCharFormat <http://doc.qt.nokia.com/qtextcharformat.html>`_ format.
:param \*\*kwargs: Format settings.
:type \*\*kwargs: dict
:return: Format.
:rtype: QTextCharFormat
"""
settings = foundations.data_structures.Structure(**{"format": QTextC... | def function[get_format, parameter[]]:
constant[
Returns a `QTextCharFormat <http://doc.qt.nokia.com/qtextcharformat.html>`_ format.
:param \*\*kwargs: Format settings.
:type \*\*kwargs: dict
:return: Format.
:rtype: QTextCharFormat
]
variable[settings] assign[=] call[name[found... | keyword[def] identifier[get_format] (** identifier[kwargs] ):
literal[string]
identifier[settings] = identifier[foundations] . identifier[data_structures] . identifier[Structure] (**{ literal[string] : identifier[QTextCharFormat] (),
literal[string] : keyword[None] ,
literal[string] : keyword[No... | def get_format(**kwargs):
"""
Returns a `QTextCharFormat <http://doc.qt.nokia.com/qtextcharformat.html>`_ format.
:param \\*\\*kwargs: Format settings.
:type \\*\\*kwargs: dict
:return: Format.
:rtype: QTextCharFormat
"""
settings = foundations.data_structures.Structure(**{'format': QTe... |
def build_items(self):
u"""This method called by Executer.
/proc/net/tcp -> {host:host, key:key, value:value, clock:clock}
"""
protocols = ['tcp', 'tcp6']
for protocol in protocols:
procfile = open('/proc/net/{0}'.format(protocol), 'r')
stats = self.count(... | def function[build_items, parameter[self]]:
constant[This method called by Executer.
/proc/net/tcp -> {host:host, key:key, value:value, clock:clock}
]
variable[protocols] assign[=] list[[<ast.Constant object at 0x7da2046228f0>, <ast.Constant object at 0x7da204623550>]]
for taget[... | keyword[def] identifier[build_items] ( identifier[self] ):
literal[string]
identifier[protocols] =[ literal[string] , literal[string] ]
keyword[for] identifier[protocol] keyword[in] identifier[protocols] :
identifier[procfile] = identifier[open] ( literal[string] . identifi... | def build_items(self):
u"""This method called by Executer.
/proc/net/tcp -> {host:host, key:key, value:value, clock:clock}
"""
protocols = ['tcp', 'tcp6']
for protocol in protocols:
procfile = open('/proc/net/{0}'.format(protocol), 'r')
stats = self.count(procfile)
fo... |
def segmentAcceptable(RCV_NXT, RCV_WND, SEG_SEQ, SEG_LEN):
"""
An acceptable segment: RFC 793 page 26.
"""
if SEG_LEN == 0 and RCV_WND == 0:
return SEG_SEQ == RCV_NXT
if SEG_LEN == 0 and RCV_WND > 0:
return ((RCV_NXT <= SEG_SEQ) and (SEG_SEQ < RCV_NXT + RCV_WND))
if SEG_LEN > 0 a... | def function[segmentAcceptable, parameter[RCV_NXT, RCV_WND, SEG_SEQ, SEG_LEN]]:
constant[
An acceptable segment: RFC 793 page 26.
]
if <ast.BoolOp object at 0x7da20c6c59f0> begin[:]
return[compare[name[SEG_SEQ] equal[==] name[RCV_NXT]]]
if <ast.BoolOp object at 0x7da20c6c5060> be... | keyword[def] identifier[segmentAcceptable] ( identifier[RCV_NXT] , identifier[RCV_WND] , identifier[SEG_SEQ] , identifier[SEG_LEN] ):
literal[string]
keyword[if] identifier[SEG_LEN] == literal[int] keyword[and] identifier[RCV_WND] == literal[int] :
keyword[return] identifier[SEG_SEQ] == identi... | def segmentAcceptable(RCV_NXT, RCV_WND, SEG_SEQ, SEG_LEN):
"""
An acceptable segment: RFC 793 page 26.
"""
if SEG_LEN == 0 and RCV_WND == 0:
return SEG_SEQ == RCV_NXT # depends on [control=['if'], data=[]]
if SEG_LEN == 0 and RCV_WND > 0:
return RCV_NXT <= SEG_SEQ and SEG_SEQ < RCV_... |
def to_dict(self) -> Dict:
""" Export the CAG to a dict that can be serialized to JSON. """
return {
"name": self.name,
"dateCreated": str(self.dateCreated),
"variables": lmap(
lambda n: self.export_node(n), self.nodes(data=True)
),
... | def function[to_dict, parameter[self]]:
constant[ Export the CAG to a dict that can be serialized to JSON. ]
return[dictionary[[<ast.Constant object at 0x7da18f58c070>, <ast.Constant object at 0x7da18f58c6a0>, <ast.Constant object at 0x7da18f58e2f0>, <ast.Constant object at 0x7da18f58f250>, <ast.Constant ob... | keyword[def] identifier[to_dict] ( identifier[self] )-> identifier[Dict] :
literal[string]
keyword[return] {
literal[string] : identifier[self] . identifier[name] ,
literal[string] : identifier[str] ( identifier[self] . identifier[dateCreated] ),
literal[string] : identif... | def to_dict(self) -> Dict:
""" Export the CAG to a dict that can be serialized to JSON. """
return {'name': self.name, 'dateCreated': str(self.dateCreated), 'variables': lmap(lambda n: self.export_node(n), self.nodes(data=True)), 'timeStep': str(self.Δt), 'edge_data': lmap(export_edge, self.edges(data=True))} |
def fromgroups(args):
"""
%prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into different piles (e.g.
pairs ... | def function[fromgroups, parameter[args]]:
constant[
%prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into d... | keyword[def] identifier[fromgroups] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[bed] keyword[import] identifier[Bed]
identifier[p] = identifier[OptionParser] ( identifier[fromgroups] . identifier[__doc__] )
identifier[opts] , identi... | def fromgroups(args):
"""
%prog fromgroups groupsfile a.bed b.bed ...
Flatten the gene familes into pairs, the groupsfile is a file with each line
containing the members, separated by comma. The commands also require
several bed files in order to sort the pairs into different piles (e.g.
pairs ... |
def _strvar(a, prec='{:G}'):
r"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) | def function[_strvar, parameter[a, prec]]:
constant[Return variable as a string to print, with given precision.]
return[call[constant[ ].join, parameter[<ast.ListComp object at 0x7da18ede5210>]]] | keyword[def] identifier[_strvar] ( identifier[a] , identifier[prec] = literal[string] ):
literal[string]
keyword[return] literal[string] . identifier[join] ([ identifier[prec] . identifier[format] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[np] . identifier[atleast_1d] ( identif... | def _strvar(a, prec='{:G}'):
"""Return variable as a string to print, with given precision."""
return ' '.join([prec.format(i) for i in np.atleast_1d(a)]) |
def p_iteration_statement_1(self, p):
"""
iteration_statement \
: DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI
"""
p[0] = self.asttypes.DoWhile(predicate=p[5], statement=p[2])
p[0].setpos(p) | def function[p_iteration_statement_1, parameter[self, p]]:
constant[
iteration_statement : DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI
]
call[name[p]][constant[0]] assign[=] call[name[self].asttypes.DoWhile, paramete... | keyword[def] identifier[p_iteration_statement_1] ( identifier[self] , identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[self] . identifier[asttypes] . identifier[DoWhile] ( identifier[predicate] = identifier[p] [ literal[int] ], identifier[statement] = identifier[p] [ lite... | def p_iteration_statement_1(self, p):
"""
iteration_statement : DO statement WHILE LPAREN expr RPAREN SEMI
| DO statement WHILE LPAREN expr RPAREN AUTOSEMI
"""
p[0] = self.asttypes.DoWhile(predicate=p[5], statement=p[2])
p[0].setpos(p) |
def decode_response(client_message, to_object=None):
""" Decode response from client message"""
parameters = dict(response=None)
response_size = client_message.read_int()
response = []
for _ in range(0, response_size):
response_item = client_message.read_data()
response.append(respon... | def function[decode_response, parameter[client_message, to_object]]:
constant[ Decode response from client message]
variable[parameters] assign[=] call[name[dict], parameter[]]
variable[response_size] assign[=] call[name[client_message].read_int, parameter[]]
variable[response] assign[=]... | keyword[def] identifier[decode_response] ( identifier[client_message] , identifier[to_object] = keyword[None] ):
literal[string]
identifier[parameters] = identifier[dict] ( identifier[response] = keyword[None] )
identifier[response_size] = identifier[client_message] . identifier[read_int] ()
iden... | def decode_response(client_message, to_object=None):
""" Decode response from client message"""
parameters = dict(response=None)
response_size = client_message.read_int()
response = []
for _ in range(0, response_size):
response_item = client_message.read_data()
response.append(respon... |
def modify_site(name, sourcepath=None, apppool=None, preload=None):
'''
Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
... | def function[modify_site, parameter[name, sourcepath, apppool, preload]]:
constant[
Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS applica... | keyword[def] identifier[modify_site] ( identifier[name] , identifier[sourcepath] = keyword[None] , identifier[apppool] = keyword[None] , identifier[preload] = keyword[None] ):
literal[string]
identifier[site_path] = literal[string] . identifier[format] ( identifier[name] )
identifier[current_sites] = ... | def modify_site(name, sourcepath=None, apppool=None, preload=None):
"""
Modify a basic website in IIS.
.. versionadded:: 2017.7.0
Args:
name (str): The IIS site name.
sourcepath (str): The physical path of the IIS site.
apppool (str): The name of the IIS application pool.
... |
def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True
else:
# py3
fn.__dict__['is_transform_generator'] = True
return fn | def function[transform_generator, parameter[fn]]:
constant[A decorator that marks transform pipes that should be called to create the real transform]
if name[six].PY2 begin[:]
call[name[fn].func_dict][constant[is_transform_generator]] assign[=] constant[True]
return[name[fn]] | keyword[def] identifier[transform_generator] ( identifier[fn] ):
literal[string]
keyword[if] identifier[six] . identifier[PY2] :
identifier[fn] . identifier[func_dict] [ literal[string] ]= keyword[True]
keyword[else] :
identifier[fn] . identifier[__dict__] [ literal[string] ]=... | def transform_generator(fn):
"""A decorator that marks transform pipes that should be called to create the real transform"""
if six.PY2:
fn.func_dict['is_transform_generator'] = True # depends on [control=['if'], data=[]]
else:
# py3
fn.__dict__['is_transform_generator'] = True
... |
def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):
"""
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
... | def function[getComponentExceptionSummary, parameter[self, tmaster, component_name, instances, callback]]:
constant[
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
]
if <ast.BoolOp object at 0x7da2054a4160> begin[:]
... | keyword[def] identifier[getComponentExceptionSummary] ( identifier[self] , identifier[tmaster] , identifier[component_name] , identifier[instances] =[], identifier[callback] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[tmaster] keyword[or] keyword[not] identifier[tmaster] . i... | def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):
"""
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
"""
if not tmaster or not tmaster.host or (not tmaster.stats_port):
return ... |
def create(cls, options, session, build_root=None, exclude_patterns=None, tags=None):
"""
:param Options options: An `Options` instance to use.
:param session: The Scheduler session
:param string build_root: The build root.
"""
# Determine the literal target roots.
spec_roots = cls.parse_spe... | def function[create, parameter[cls, options, session, build_root, exclude_patterns, tags]]:
constant[
:param Options options: An `Options` instance to use.
:param session: The Scheduler session
:param string build_root: The build root.
]
variable[spec_roots] assign[=] call[name[cls].pars... | keyword[def] identifier[create] ( identifier[cls] , identifier[options] , identifier[session] , identifier[build_root] = keyword[None] , identifier[exclude_patterns] = keyword[None] , identifier[tags] = keyword[None] ):
literal[string]
identifier[spec_roots] = identifier[cls] . identifier[parse_specs]... | def create(cls, options, session, build_root=None, exclude_patterns=None, tags=None):
"""
:param Options options: An `Options` instance to use.
:param session: The Scheduler session
:param string build_root: The build root.
"""
# Determine the literal target roots.
spec_roots = cls.parse_spe... |
def check_output(args):
"""Pipe-safe (and 2.6 compatible) version of subprocess.check_output
"""
proc = Popen(args, stdout=PIPE)
out = proc.communicate()[0]
if proc.returncode:
raise CalledProcessError(proc.returncode, args, output=out)
return out | def function[check_output, parameter[args]]:
constant[Pipe-safe (and 2.6 compatible) version of subprocess.check_output
]
variable[proc] assign[=] call[name[Popen], parameter[name[args]]]
variable[out] assign[=] call[call[name[proc].communicate, parameter[]]][constant[0]]
if name[pro... | keyword[def] identifier[check_output] ( identifier[args] ):
literal[string]
identifier[proc] = identifier[Popen] ( identifier[args] , identifier[stdout] = identifier[PIPE] )
identifier[out] = identifier[proc] . identifier[communicate] ()[ literal[int] ]
keyword[if] identifier[proc] . identifier[... | def check_output(args):
"""Pipe-safe (and 2.6 compatible) version of subprocess.check_output
"""
proc = Popen(args, stdout=PIPE)
out = proc.communicate()[0]
if proc.returncode:
raise CalledProcessError(proc.returncode, args, output=out) # depends on [control=['if'], data=[]]
return out |
def _parseStylesheet(self, src):
"""stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
"""
# FIXME: BYTES to STR
if type(src) == six.binary_type:
... | def function[_parseStylesheet, parameter[self, src]]:
constant[stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
]
if compare[call[name[type], parameter[name[src]... | keyword[def] identifier[_parseStylesheet] ( identifier[self] , identifier[src] ):
literal[string]
keyword[if] identifier[type] ( identifier[src] )== identifier[six] . identifier[binary_type] :
identifier[src] = identifier[six] . identifier[text_type] ( identifier[src] )
... | def _parseStylesheet(self, src):
"""stylesheet
: [ CHARSET_SYM S* STRING S* ';' ]?
[S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
[ [ ruleset | media | page | font_face ] [S|CDO|CDC]* ]*
;
""" # FIXME: BYTES to STR
if type(src) == six.binary_type:
src = six.text_... |
def make_op_return_output(data):
'''Generates OP_RETURN output for data less than 78 bytes.
If data is 76 or 77 bytes, OP_PUSHDATA1 is included:
<OP_RETURN><OP_PUSHDATA1><data len><data>
If data is less than 76 bytes, OP_PUSHDATA1 is not included:
<OP_RETURN><data len><data>
80 bytes is the defa... | def function[make_op_return_output, parameter[data]]:
constant[Generates OP_RETURN output for data less than 78 bytes.
If data is 76 or 77 bytes, OP_PUSHDATA1 is included:
<OP_RETURN><OP_PUSHDATA1><data len><data>
If data is less than 76 bytes, OP_PUSHDATA1 is not included:
<OP_RETURN><data len>... | keyword[def] identifier[make_op_return_output] ( identifier[data] ):
literal[string]
keyword[if] identifier[len] ( identifier[data] )> literal[int] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[pk_script] = identifier[bytearray] ()
identifier[pk_script] . iden... | def make_op_return_output(data):
"""Generates OP_RETURN output for data less than 78 bytes.
If data is 76 or 77 bytes, OP_PUSHDATA1 is included:
<OP_RETURN><OP_PUSHDATA1><data len><data>
If data is less than 76 bytes, OP_PUSHDATA1 is not included:
<OP_RETURN><data len><data>
80 bytes is the defa... |
def _write_input(self, input_dir="."):
"""
Write the packmol input file to the input directory.
Args:
input_dir (string): path to the input directory
"""
with open(os.path.join(input_dir, self.input_file), 'wt', encoding="utf-8") as inp:
for k, v in self.... | def function[_write_input, parameter[self, input_dir]]:
constant[
Write the packmol input file to the input directory.
Args:
input_dir (string): path to the input directory
]
with call[name[open], parameter[call[name[os].path.join, parameter[name[input_dir], name[sel... | keyword[def] identifier[_write_input] ( identifier[self] , identifier[input_dir] = literal[string] ):
literal[string]
keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[input_dir] , identifier[self] . identifier[input_file] ), literal[string] , ident... | def _write_input(self, input_dir='.'):
"""
Write the packmol input file to the input directory.
Args:
input_dir (string): path to the input directory
"""
with open(os.path.join(input_dir, self.input_file), 'wt', encoding='utf-8') as inp:
for (k, v) in self.control_pa... |
def _init_metadata(self):
"""stub"""
MultiChoiceAnswerFormRecord._init_metadata(self)
FilesAnswerFormRecord._init_metadata(self)
FeedbackAnswerFormRecord._init_metadata(self)
super(MultiChoiceFeedbackAndFilesAnswerFormRecord, self)._init_metadata() | def function[_init_metadata, parameter[self]]:
constant[stub]
call[name[MultiChoiceAnswerFormRecord]._init_metadata, parameter[name[self]]]
call[name[FilesAnswerFormRecord]._init_metadata, parameter[name[self]]]
call[name[FeedbackAnswerFormRecord]._init_metadata, parameter[name[self]]]
... | keyword[def] identifier[_init_metadata] ( identifier[self] ):
literal[string]
identifier[MultiChoiceAnswerFormRecord] . identifier[_init_metadata] ( identifier[self] )
identifier[FilesAnswerFormRecord] . identifier[_init_metadata] ( identifier[self] )
identifier[FeedbackAnswerForm... | def _init_metadata(self):
"""stub"""
MultiChoiceAnswerFormRecord._init_metadata(self)
FilesAnswerFormRecord._init_metadata(self)
FeedbackAnswerFormRecord._init_metadata(self)
super(MultiChoiceFeedbackAndFilesAnswerFormRecord, self)._init_metadata() |
def source(source_id=None, **kwargs):
"""Get a source of economic data."""
if source_id is not None:
kwargs['source_id'] = source_id
elif 'id' in kwargs:
source_id = kwargs.pop('id')
kwargs['source_id'] = source_id
if 'releases' in kwargs:
kwargs.pop('releases')
p... | def function[source, parameter[source_id]]:
constant[Get a source of economic data.]
if compare[name[source_id] is_not constant[None]] begin[:]
call[name[kwargs]][constant[source_id]] assign[=] name[source_id]
if compare[constant[releases] in name[kwargs]] begin[:]
... | keyword[def] identifier[source] ( identifier[source_id] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[source_id] keyword[is] keyword[not] keyword[None] :
identifier[kwargs] [ literal[string] ]= identifier[source_id]
keyword[elif] literal[string] keywo... | def source(source_id=None, **kwargs):
"""Get a source of economic data."""
if source_id is not None:
kwargs['source_id'] = source_id # depends on [control=['if'], data=['source_id']]
elif 'id' in kwargs:
source_id = kwargs.pop('id')
kwargs['source_id'] = source_id # depends on [con... |
def full_size(self):
'''show image at full size'''
self.dragpos = wx.Point(0, 0)
self.zoom = 1.0
self.need_redraw = True | def function[full_size, parameter[self]]:
constant[show image at full size]
name[self].dragpos assign[=] call[name[wx].Point, parameter[constant[0], constant[0]]]
name[self].zoom assign[=] constant[1.0]
name[self].need_redraw assign[=] constant[True] | keyword[def] identifier[full_size] ( identifier[self] ):
literal[string]
identifier[self] . identifier[dragpos] = identifier[wx] . identifier[Point] ( literal[int] , literal[int] )
identifier[self] . identifier[zoom] = literal[int]
identifier[self] . identifier[need_redraw] = key... | def full_size(self):
"""show image at full size"""
self.dragpos = wx.Point(0, 0)
self.zoom = 1.0
self.need_redraw = True |
def on_shared_folder_change(self, global_p):
"""Triggered when a permanent (global or machine) shared folder has been
created or removed.
We don't pass shared folder parameters in this notification because
the order in which parallel notifications are delivered is not defined,
... | def function[on_shared_folder_change, parameter[self, global_p]]:
constant[Triggered when a permanent (global or machine) shared folder has been
created or removed.
We don't pass shared folder parameters in this notification because
the order in which parallel notifications are ... | keyword[def] identifier[on_shared_folder_change] ( identifier[self] , identifier[global_p] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[global_p] , identifier[bool] ):
keyword[raise] identifier[TypeError] ( literal[string] )
identifier[sel... | def on_shared_folder_change(self, global_p):
"""Triggered when a permanent (global or machine) shared folder has been
created or removed.
We don't pass shared folder parameters in this notification because
the order in which parallel notifications are delivered is not defined,
... |
def get_country_from_request(request):
"""
Analyzes the request to find which country the user wants
the system to recognize. It checks the following sources
in the given order:
* session,
* cookie,
* HTTP_ACCEPT_LANGUAGE HTTP header, and
* IP address if USE_GEOIP is True.
It return... | def function[get_country_from_request, parameter[request]]:
constant[
Analyzes the request to find which country the user wants
the system to recognize. It checks the following sources
in the given order:
* session,
* cookie,
* HTTP_ACCEPT_LANGUAGE HTTP header, and
* IP address if US... | keyword[def] identifier[get_country_from_request] ( identifier[request] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[request] , literal[string] ):
identifier[country_code] = identifier[request] . identifier[session] . identifier[get] ( identifier[COUNTRY_SESSION_KEY] )
... | def get_country_from_request(request):
"""
Analyzes the request to find which country the user wants
the system to recognize. It checks the following sources
in the given order:
* session,
* cookie,
* HTTP_ACCEPT_LANGUAGE HTTP header, and
* IP address if USE_GEOIP is True.
It return... |
def get_by_page(query, page, page_size):
"""
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
"""
pager = Paginator(query, page_size)
try:
models = pager.page(page)
except PageNotAnInteger:... | def function[get_by_page, parameter[query, page, page_size]]:
constant[
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
]
variable[pager] assign[=] call[name[Paginator], parameter[name[query], name... | keyword[def] identifier[get_by_page] ( identifier[query] , identifier[page] , identifier[page_size] ):
literal[string]
identifier[pager] = identifier[Paginator] ( identifier[query] , identifier[page_size] )
keyword[try] :
identifier[models] = identifier[pager] . identifier[page] ( identifier... | def get_by_page(query, page, page_size):
"""
Осуществляет пагинацию
:param query: запрос
:param page: номер страницы
:param page_size: количество объектов на странице
:return:
"""
pager = Paginator(query, page_size)
try:
models = pager.page(page) # depends on [control=['try'... |
def scatterplot(self, x, y, **kw):
"""plot after clearing current plot """
self.panel.scatterplot(x, y, **kw) | def function[scatterplot, parameter[self, x, y]]:
constant[plot after clearing current plot ]
call[name[self].panel.scatterplot, parameter[name[x], name[y]]] | keyword[def] identifier[scatterplot] ( identifier[self] , identifier[x] , identifier[y] ,** identifier[kw] ):
literal[string]
identifier[self] . identifier[panel] . identifier[scatterplot] ( identifier[x] , identifier[y] ,** identifier[kw] ) | def scatterplot(self, x, y, **kw):
"""plot after clearing current plot """
self.panel.scatterplot(x, y, **kw) |
def _enforceDataType(self, data):
""" Converts to str so that this CTI always stores that type.
"""
qColor = QtGui.QColor(data) # TODO: store a RGB string?
if not qColor.isValid():
raise ValueError("Invalid color specification: {!r}".format(data))
return qColor | def function[_enforceDataType, parameter[self, data]]:
constant[ Converts to str so that this CTI always stores that type.
]
variable[qColor] assign[=] call[name[QtGui].QColor, parameter[name[data]]]
if <ast.UnaryOp object at 0x7da1b04f9cf0> begin[:]
<ast.Raise object at 0x7da1b0... | keyword[def] identifier[_enforceDataType] ( identifier[self] , identifier[data] ):
literal[string]
identifier[qColor] = identifier[QtGui] . identifier[QColor] ( identifier[data] )
keyword[if] keyword[not] identifier[qColor] . identifier[isValid] ():
keyword[raise] identifie... | def _enforceDataType(self, data):
""" Converts to str so that this CTI always stores that type.
"""
qColor = QtGui.QColor(data) # TODO: store a RGB string?
if not qColor.isValid():
raise ValueError('Invalid color specification: {!r}'.format(data)) # depends on [control=['if'], data=[]]
... |
def clearParameters(self):
"""Removes all parameters from model"""
self.beginRemoveRows(QtCore.QModelIndex(), 0, self.rowCount())
self.model.clear_parameters()
self.endRemoveRows() | def function[clearParameters, parameter[self]]:
constant[Removes all parameters from model]
call[name[self].beginRemoveRows, parameter[call[name[QtCore].QModelIndex, parameter[]], constant[0], call[name[self].rowCount, parameter[]]]]
call[name[self].model.clear_parameters, parameter[]]
c... | keyword[def] identifier[clearParameters] ( identifier[self] ):
literal[string]
identifier[self] . identifier[beginRemoveRows] ( identifier[QtCore] . identifier[QModelIndex] (), literal[int] , identifier[self] . identifier[rowCount] ())
identifier[self] . identifier[model] . identifier[clea... | def clearParameters(self):
"""Removes all parameters from model"""
self.beginRemoveRows(QtCore.QModelIndex(), 0, self.rowCount())
self.model.clear_parameters()
self.endRemoveRows() |
def set_executable(filename):
"""Set the exectuable bit on the given filename"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC) | def function[set_executable, parameter[filename]]:
constant[Set the exectuable bit on the given filename]
variable[st] assign[=] call[name[os].stat, parameter[name[filename]]]
call[name[os].chmod, parameter[name[filename], binary_operation[name[st].st_mode <ast.BitOr object at 0x7da2590d6aa0> na... | keyword[def] identifier[set_executable] ( identifier[filename] ):
literal[string]
identifier[st] = identifier[os] . identifier[stat] ( identifier[filename] )
identifier[os] . identifier[chmod] ( identifier[filename] , identifier[st] . identifier[st_mode] | identifier[stat] . identifier[S_IEXEC] ) | def set_executable(filename):
"""Set the exectuable bit on the given filename"""
st = os.stat(filename)
os.chmod(filename, st.st_mode | stat.S_IEXEC) |
def parse_abstract(xml_dict):
"""
Parse PubMed XML dictionary to retrieve abstract.
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation',
'Article', 'Abstract', 'AbstractText']
abstract_xml = reduce(dict.get, key_path, xml_dict)
abst... | def function[parse_abstract, parameter[xml_dict]]:
constant[
Parse PubMed XML dictionary to retrieve abstract.
]
variable[key_path] assign[=] list[[<ast.Constant object at 0x7da18f722f50>, <ast.Constant object at 0x7da18f7216f0>, <ast.Constant object at 0x7da18f721780>, <ast.Constant obj... | keyword[def] identifier[parse_abstract] ( identifier[xml_dict] ):
literal[string]
identifier[key_path] =[ literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal[string] ]
identifier[abstract_xml] = identifier[reduce] ( identifier[dict] . ... | def parse_abstract(xml_dict):
"""
Parse PubMed XML dictionary to retrieve abstract.
"""
key_path = ['PubmedArticleSet', 'PubmedArticle', 'MedlineCitation', 'Article', 'Abstract', 'AbstractText']
abstract_xml = reduce(dict.get, key_path, xml_dict)
abstract_paragraphs = []
if isinstanc... |
def update_group(self, group_id, group, force=False, minimal=True):
"""Update a group.
Applies writable settings in `group` to `group_id`
Note: this method can not be used to rename groups.
:param str group_id: target group ID
:param group: group settings
:type group: :... | def function[update_group, parameter[self, group_id, group, force, minimal]]:
constant[Update a group.
Applies writable settings in `group` to `group_id`
Note: this method can not be used to rename groups.
:param str group_id: target group ID
:param group: group settings
... | keyword[def] identifier[update_group] ( identifier[self] , identifier[group_id] , identifier[group] , identifier[force] = keyword[False] , identifier[minimal] = keyword[True] ):
literal[string]
identifier[group] . identifier[version] = keyword[None]
identifier[params] ={ literal... | def update_group(self, group_id, group, force=False, minimal=True):
"""Update a group.
Applies writable settings in `group` to `group_id`
Note: this method can not be used to rename groups.
:param str group_id: target group ID
:param group: group settings
:type group: :clas... |
def is_dark_terminal_background(cls):
"""
:return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
and if <background-color> ... | def function[is_dark_terminal_background, parameter[cls]]:
constant[
:return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
... | keyword[def] identifier[is_dark_terminal_background] ( identifier[cls] ):
literal[string]
keyword[if] identifier[os] . identifier[environ] . identifier[get] ( literal[string] , keyword[None] ):
identifier[parts] = identifier[os] . identifier[environ] [ literal[string] ]. identifier[sp... | def is_dark_terminal_background(cls):
"""
:return: Whether we have a dark Terminal background color, or None if unknown.
We currently just check the env var COLORFGBG,
which some terminals define like "<foreground-color>:<background-color>",
and if <background-color> in {... |
def write_batch_json(self, content):
"""Write batch json data to a file."""
timestamp = str(time.time()).replace('.', '')
batch_json_file = os.path.join(
self.tcex.args.tc_temp_path, 'batch-{}.json'.format(timestamp)
)
with open(batch_json_file, 'w') as fh:
... | def function[write_batch_json, parameter[self, content]]:
constant[Write batch json data to a file.]
variable[timestamp] assign[=] call[call[name[str], parameter[call[name[time].time, parameter[]]]].replace, parameter[constant[.], constant[]]]
variable[batch_json_file] assign[=] call[name[os].pa... | keyword[def] identifier[write_batch_json] ( identifier[self] , identifier[content] ):
literal[string]
identifier[timestamp] = identifier[str] ( identifier[time] . identifier[time] ()). identifier[replace] ( literal[string] , literal[string] )
identifier[batch_json_file] = identifier[os] . ... | def write_batch_json(self, content):
"""Write batch json data to a file."""
timestamp = str(time.time()).replace('.', '')
batch_json_file = os.path.join(self.tcex.args.tc_temp_path, 'batch-{}.json'.format(timestamp))
with open(batch_json_file, 'w') as fh:
json.dump(content, fh, indent=2) # depe... |
def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(
set(self.source.get_domains() + self.target.get_domains()))
return self.domains | def function[get_domains, parameter[self]]:
constant[
Returns domains affected by operation.
@rtype: list
]
if compare[name[self].domains is constant[None]] begin[:]
name[self].domains assign[=] call[name[list], parameter[call[name[set], parameter[binary_operation... | keyword[def] identifier[get_domains] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[domains] keyword[is] keyword[None] :
identifier[self] . identifier[domains] = identifier[list] (
identifier[set] ( identifier[self] . identifier[source] ... | def get_domains(self):
"""
Returns domains affected by operation.
@rtype: list
"""
if self.domains is None:
self.domains = list(set(self.source.get_domains() + self.target.get_domains())) # depends on [control=['if'], data=[]]
return self.domains |
def transform_to_mods_mono(marc_xml, uuid, url):
"""
Convert `marc_xml` to MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url (str): URL of the publication ... | def function[transform_to_mods_mono, parameter[marc_xml, uuid, url]]:
constant[
Convert `marc_xml` to MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url ... | keyword[def] identifier[transform_to_mods_mono] ( identifier[marc_xml] , identifier[uuid] , identifier[url] ):
literal[string]
identifier[marc_xml] = identifier[_read_content_or_path] ( identifier[marc_xml] )
identifier[transformed] = identifier[xslt_transformation] (
identifier[marc_xml] ,
... | def transform_to_mods_mono(marc_xml, uuid, url):
"""
Convert `marc_xml` to MODS data format.
Args:
marc_xml (str): Filename or XML string. Don't use ``\\n`` in case of
filename.
uuid (str): UUID string giving the package ID.
url (str): URL of the publication ... |
def _nested_transactional(fn):
# type: (Callable) -> Callable
"""In a transactional method create a nested transaction."""
@wraps(fn)
def wrapped(self, *args, **kwargs):
# type: (SessionFactory) -> Any
try:
rv = fn(self, *args, **kwargs)
except _TransactionalPolicyVi... | def function[_nested_transactional, parameter[fn]]:
constant[In a transactional method create a nested transaction.]
def function[wrapped, parameter[self]]:
<ast.Try object at 0x7da207f00370>
return[name[rv]]
return[name[wrapped]] | keyword[def] identifier[_nested_transactional] ( identifier[fn] ):
literal[string]
@ identifier[wraps] ( identifier[fn] )
keyword[def] identifier[wrapped] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
keyword[try] :
identifier[rv] = identifier[fn] ( iden... | def _nested_transactional(fn):
# type: (Callable) -> Callable
'In a transactional method create a nested transaction.'
@wraps(fn)
def wrapped(self, *args, **kwargs):
# type: (SessionFactory) -> Any
try:
rv = fn(self, *args, **kwargs) # depends on [control=['try'], data=[]]
... |
def page_menu(context, token):
"""
Return a list of child pages for the given parent, storing all
pages in a dict in the context when first called using parents as keys
for retrieval on subsequent recursive calls from the menu template.
"""
# First arg could be the menu template file name, or th... | def function[page_menu, parameter[context, token]]:
constant[
Return a list of child pages for the given parent, storing all
pages in a dict in the context when first called using parents as keys
for retrieval on subsequent recursive calls from the menu template.
]
variable[template_name... | keyword[def] identifier[page_menu] ( identifier[context] , identifier[token] ):
literal[string]
identifier[template_name] = keyword[None]
identifier[parent_page] = keyword[None]
identifier[parts] = identifier[token] . identifier[split_contents] ()[ literal[int] :]
keyword[for] i... | def page_menu(context, token):
"""
Return a list of child pages for the given parent, storing all
pages in a dict in the context when first called using parents as keys
for retrieval on subsequent recursive calls from the menu template.
"""
# First arg could be the menu template file name, or th... |
def kmean_clustering(network, n_clusters=10, load_cluster=False,
line_length_factor=1.25,
remove_stubs=False, use_reduced_coordinates=False,
bus_weight_tocsv=None, bus_weight_fromcsv=None,
n_init=10, max_iter=300, tol=1e-4,
... | def function[kmean_clustering, parameter[network, n_clusters, load_cluster, line_length_factor, remove_stubs, use_reduced_coordinates, bus_weight_tocsv, bus_weight_fromcsv, n_init, max_iter, tol, n_jobs]]:
constant[ Main function of the k-mean clustering approach. Maps an original
network to a new one with ... | keyword[def] identifier[kmean_clustering] ( identifier[network] , identifier[n_clusters] = literal[int] , identifier[load_cluster] = keyword[False] ,
identifier[line_length_factor] = literal[int] ,
identifier[remove_stubs] = keyword[False] , identifier[use_reduced_coordinates] = keyword[False] ,
identifier[bus_wei... | def kmean_clustering(network, n_clusters=10, load_cluster=False, line_length_factor=1.25, remove_stubs=False, use_reduced_coordinates=False, bus_weight_tocsv=None, bus_weight_fromcsv=None, n_init=10, max_iter=300, tol=0.0001, n_jobs=1):
""" Main function of the k-mean clustering approach. Maps an original
netwo... |
def _send(self, data):
"""
Insert the data
"""
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute("INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)"
% (self.table, self.col_metric,
... | def function[_send, parameter[self, data]]:
constant[
Insert the data
]
variable[data] assign[=] call[call[name[data].strip, parameter[]].split, parameter[constant[ ]]]
<ast.Try object at 0x7da207f9add0> | keyword[def] identifier[_send] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[data] . identifier[strip] (). identifier[split] ( literal[string] )
keyword[try] :
identifier[cursor] = identifier[self] . identifier[conn] . identifier[cursor... | def _send(self, data):
"""
Insert the data
"""
data = data.strip().split(' ')
try:
cursor = self.conn.cursor()
cursor.execute('INSERT INTO %s (%s, %s, %s) VALUES(%%s, %%s, %%s)' % (self.table, self.col_metric, self.col_time, self.col_value), (data[0], data[2], data[1]))
... |
def _fromJSON(cls, jsonobject):
"""Generates a new instance of :class:`maspy.core.Smi` from a decoded
JSON object (as generated by :func:`maspy.core.Smi._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Smi`
"""
newInstance = cls(... | def function[_fromJSON, parameter[cls, jsonobject]]:
constant[Generates a new instance of :class:`maspy.core.Smi` from a decoded
JSON object (as generated by :func:`maspy.core.Smi._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Smi`
]
... | keyword[def] identifier[_fromJSON] ( identifier[cls] , identifier[jsonobject] ):
literal[string]
identifier[newInstance] = identifier[cls] ( keyword[None] , keyword[None] )
identifier[attribDict] ={}
identifier[attribDict] [ literal[string] ]= identifier[jsonobject] [ literal[int]... | def _fromJSON(cls, jsonobject):
"""Generates a new instance of :class:`maspy.core.Smi` from a decoded
JSON object (as generated by :func:`maspy.core.Smi._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Smi`
"""
newInstance = cls(None, No... |
def create_callback(self):
"""
create a callback, suitable to be passed to SenateCounter
"""
def __callback(question_posed):
logger.debug("%s: asked to choose between: %s" % (self._name, self._qstr(question_posed)))
if self._upto == len(self._data):
... | def function[create_callback, parameter[self]]:
constant[
create a callback, suitable to be passed to SenateCounter
]
def function[__callback, parameter[question_posed]]:
call[name[logger].debug, parameter[binary_operation[constant[%s: asked to choose between: %s] <ast.Mo... | keyword[def] identifier[create_callback] ( identifier[self] ):
literal[string]
keyword[def] identifier[__callback] ( identifier[question_posed] ):
identifier[logger] . identifier[debug] ( literal[string] %( identifier[self] . identifier[_name] , identifier[self] . identifier[_qstr] ( ... | def create_callback(self):
"""
create a callback, suitable to be passed to SenateCounter
"""
def __callback(question_posed):
logger.debug('%s: asked to choose between: %s' % (self._name, self._qstr(question_posed)))
if self._upto == len(self._data):
logger.error('%s:... |
def read_array(fo, writer_schema, reader_schema=None):
"""Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's... | def function[read_array, parameter[fo, writer_schema, reader_schema]]:
constant[Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item... | keyword[def] identifier[read_array] ( identifier[fo] , identifier[writer_schema] , identifier[reader_schema] = keyword[None] ):
literal[string]
keyword[if] identifier[reader_schema] :
keyword[def] identifier[item_reader] ( identifier[fo] , identifier[w_schema] , identifier[r_schema] ):
... | def read_array(fo, writer_schema, reader_schema=None):
"""Arrays are encoded as a series of blocks.
Each block consists of a long count value, followed by that many array
items. A block with count zero indicates the end of the array. Each item
is encoded per the array's item schema.
If a block's... |
def generateNamespaceNodeDocuments(self):
'''
Generates the reStructuredText document for every namespace, including nested
namespaces that were removed from ``self.namespaces`` (but added as children
to one of the namespaces in ``self.namespaces``).
The documents generated do n... | def function[generateNamespaceNodeDocuments, parameter[self]]:
constant[
Generates the reStructuredText document for every namespace, including nested
namespaces that were removed from ``self.namespaces`` (but added as children
to one of the namespaces in ``self.namespaces``).
T... | keyword[def] identifier[generateNamespaceNodeDocuments] ( identifier[self] ):
literal[string]
keyword[for] identifier[n] keyword[in] identifier[self] . identifier[namespaces] :
identifier[nested_namespaces] =[]
keyword[for] identifier[child] keyword[... | def generateNamespaceNodeDocuments(self):
"""
Generates the reStructuredText document for every namespace, including nested
namespaces that were removed from ``self.namespaces`` (but added as children
to one of the namespaces in ``self.namespaces``).
The documents generated do not u... |
def assert_regex(text, regex, msg_fmt="{msg}"):
"""Fail if text does not match the regular expression.
regex can be either a regular expression string or a compiled regular
expression object.
>>> assert_regex("Hello World!", r"llo.*rld!$")
>>> assert_regex("Hello World!", r"\\d")
Traceback (mo... | def function[assert_regex, parameter[text, regex, msg_fmt]]:
constant[Fail if text does not match the regular expression.
regex can be either a regular expression string or a compiled regular
expression object.
>>> assert_regex("Hello World!", r"llo.*rld!$")
>>> assert_regex("Hello World!", r"... | keyword[def] identifier[assert_regex] ( identifier[text] , identifier[regex] , identifier[msg_fmt] = literal[string] ):
literal[string]
identifier[compiled] = identifier[re] . identifier[compile] ( identifier[regex] )
keyword[if] keyword[not] identifier[compiled] . identifier[search] ( identifier[t... | def assert_regex(text, regex, msg_fmt='{msg}'):
"""Fail if text does not match the regular expression.
regex can be either a regular expression string or a compiled regular
expression object.
>>> assert_regex("Hello World!", r"llo.*rld!$")
>>> assert_regex("Hello World!", r"\\d")
Traceback (mo... |
def dbgr(self, string):
'''Invoke a debugger command from inside a python shell called inside
the debugger.
'''
print('')
self.proc.cmd_queue.append(string)
self.proc.process_command()
return | def function[dbgr, parameter[self, string]]:
constant[Invoke a debugger command from inside a python shell called inside
the debugger.
]
call[name[print], parameter[constant[]]]
call[name[self].proc.cmd_queue.append, parameter[name[string]]]
call[name[self].proc.process_c... | keyword[def] identifier[dbgr] ( identifier[self] , identifier[string] ):
literal[string]
identifier[print] ( literal[string] )
identifier[self] . identifier[proc] . identifier[cmd_queue] . identifier[append] ( identifier[string] )
identifier[self] . identifier[proc] . identifier[p... | def dbgr(self, string):
"""Invoke a debugger command from inside a python shell called inside
the debugger.
"""
print('')
self.proc.cmd_queue.append(string)
self.proc.process_command()
return |
def redirect_to_handler(error, location):
"""
Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, e.g.::
@expose()
... | def function[redirect_to_handler, parameter[error, location]]:
constant[
Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, ... | keyword[def] identifier[redirect_to_handler] ( identifier[error] , identifier[location] ):
literal[string]
keyword[if] identifier[callable] ( identifier[location] ):
identifier[location] = identifier[location] ()
identifier[request] . identifier[environ] [ literal[string] ]= literal[string] ... | def redirect_to_handler(error, location):
"""
Cause a requset with an error to internally redirect to a URI path.
This is generally for internal use, but can be called from within a Pecan
controller to trigger a validation failure from *within* the controller
itself, e.g.::
@expose()
... |
def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name)
return member | def function[spop, parameter[self, name]]:
constant[Emulate spop.]
variable[redis_set] assign[=] call[name[self]._get_set, parameter[name[name], constant[SPOP]]]
if <ast.UnaryOp object at 0x7da18ede7700> begin[:]
return[constant[None]]
variable[member] assign[=] call[name[choice]... | keyword[def] identifier[spop] ( identifier[self] , identifier[name] ):
literal[string]
identifier[redis_set] = identifier[self] . identifier[_get_set] ( identifier[name] , literal[string] )
keyword[if] keyword[not] identifier[redis_set] :
keyword[return] keyword[None]
... | def spop(self, name):
"""Emulate spop."""
redis_set = self._get_set(name, 'SPOP')
if not redis_set:
return None # depends on [control=['if'], data=[]]
member = choice(list(redis_set))
redis_set.remove(member)
if len(redis_set) == 0:
self.delete(name) # depends on [control=['if'... |
def _AddPropertiesForField(field, cls):
"""Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we're ... | def function[_AddPropertiesForField, parameter[field, cls]]:
constant[Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this... | keyword[def] identifier[_AddPropertiesForField] ( identifier[field] , identifier[cls] ):
literal[string]
keyword[assert] identifier[_FieldDescriptor] . identifier[MAX_CPPTYPE] == literal[int]
identifier[constant_name] = identifier[field] . identifier[name] . identifier[upper] ()+ literal[string]
... | def _AddPropertiesForField(field, cls):
"""Adds a public property for a protocol message field.
Clients can use this property to get and (in the case
of non-repeated scalar fields) directly set the value
of a protocol message field.
Args:
field: A FieldDescriptor for this field.
cls: The class we'r... |
def quadKeyToTileXYZ(self, quadKey):
'''
Computes tile x, y and z values based on quadKey.
'''
tileX = 0
tileY = 0
tileZ = len(quadKey)
for i in range(tileZ, 0, -1):
mask = 1 << (i - 1)
value = quadKey[tileZ - i]
if value == '... | def function[quadKeyToTileXYZ, parameter[self, quadKey]]:
constant[
Computes tile x, y and z values based on quadKey.
]
variable[tileX] assign[=] constant[0]
variable[tileY] assign[=] constant[0]
variable[tileZ] assign[=] call[name[len], parameter[name[quadKey]]]
... | keyword[def] identifier[quadKeyToTileXYZ] ( identifier[self] , identifier[quadKey] ):
literal[string]
identifier[tileX] = literal[int]
identifier[tileY] = literal[int]
identifier[tileZ] = identifier[len] ( identifier[quadKey] )
keyword[for] identifier[i] keyword[in] ... | def quadKeyToTileXYZ(self, quadKey):
"""
Computes tile x, y and z values based on quadKey.
"""
tileX = 0
tileY = 0
tileZ = len(quadKey)
for i in range(tileZ, 0, -1):
mask = 1 << i - 1
value = quadKey[tileZ - i]
if value == '0':
continue # depends ... |
def similarity_graph(self, k=5, radius=None, include_self_edges=False,
output_type='SGraph', verbose=True):
"""
Construct the similarity graph on the reference dataset, which is
already stored in the model. This is conceptually very similar to
running `query` wit... | def function[similarity_graph, parameter[self, k, radius, include_self_edges, output_type, verbose]]:
constant[
Construct the similarity graph on the reference dataset, which is
already stored in the model. This is conceptually very similar to
running `query` with the reference set, but ... | keyword[def] identifier[similarity_graph] ( identifier[self] , identifier[k] = literal[int] , identifier[radius] = keyword[None] , identifier[include_self_edges] = keyword[False] ,
identifier[output_type] = literal[string] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[i... | def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True):
"""
Construct the similarity graph on the reference dataset, which is
already stored in the model. This is conceptually very similar to
running `query` with the reference set, but this... |
def deploy_knowledge(filename, module_name, auth=None):
"""Deploy a file to the Artifactory BEL knowledge cache.
:param str filename: The physical file path
:param str module_name: The name of the module to deploy to
:param tuple[str] auth: A pair of (str username, str password) to give to the auth key... | def function[deploy_knowledge, parameter[filename, module_name, auth]]:
constant[Deploy a file to the Artifactory BEL knowledge cache.
:param str filename: The physical file path
:param str module_name: The name of the module to deploy to
:param tuple[str] auth: A pair of (str username, str passwor... | keyword[def] identifier[deploy_knowledge] ( identifier[filename] , identifier[module_name] , identifier[auth] = keyword[None] ):
literal[string]
keyword[return] identifier[_deploy_helper] (
identifier[filename] ,
identifier[module_name] ,
identifier[get_knowledge_module_url] ,
identifi... | def deploy_knowledge(filename, module_name, auth=None):
"""Deploy a file to the Artifactory BEL knowledge cache.
:param str filename: The physical file path
:param str module_name: The name of the module to deploy to
:param tuple[str] auth: A pair of (str username, str password) to give to the auth key... |
def loadd(self, ava, base64encode=False):
"""
Sets attributes, children, extension elements and extension
attributes of this element instance depending on what is in
the given dictionary. If there are already values on properties
those will be overwritten. If the keys in the dict... | def function[loadd, parameter[self, ava, base64encode]]:
constant[
Sets attributes, children, extension elements and extension
attributes of this element instance depending on what is in
the given dictionary. If there are already values on properties
those will be overwritten. If... | keyword[def] identifier[loadd] ( identifier[self] , identifier[ava] , identifier[base64encode] = keyword[False] ):
literal[string]
keyword[for] identifier[prop] , identifier[_typ] , identifier[_req] keyword[in] identifier[self] . identifier[c_attributes] . identifier[values] ():
ke... | def loadd(self, ava, base64encode=False):
"""
Sets attributes, children, extension elements and extension
attributes of this element instance depending on what is in
the given dictionary. If there are already values on properties
those will be overwritten. If the keys in the dictiona... |
def parse_value(self):
"""Parse a single literal value.
Returns:
The parsed value.
"""
parsers = [
self._maybe_parse_container, self._maybe_parse_basic_type,
self._maybe_parse_configurable_reference, self._maybe_parse_macro
]
for parser in parsers:
success, value = p... | def function[parse_value, parameter[self]]:
constant[Parse a single literal value.
Returns:
The parsed value.
]
variable[parsers] assign[=] list[[<ast.Attribute object at 0x7da1b0317a60>, <ast.Attribute object at 0x7da1b0314eb0>, <ast.Attribute object at 0x7da1b0316230>, <ast.Attribute ob... | keyword[def] identifier[parse_value] ( identifier[self] ):
literal[string]
identifier[parsers] =[
identifier[self] . identifier[_maybe_parse_container] , identifier[self] . identifier[_maybe_parse_basic_type] ,
identifier[self] . identifier[_maybe_parse_configurable_reference] , identifier[self] ... | def parse_value(self):
"""Parse a single literal value.
Returns:
The parsed value.
"""
parsers = [self._maybe_parse_container, self._maybe_parse_basic_type, self._maybe_parse_configurable_reference, self._maybe_parse_macro]
for parser in parsers:
(success, value) = parser()
if... |
def authenticate(self, req_data, identifier: Optional[str]=None,
signature: Optional[str]=None, threshold: Optional[int] = None,
verifier: Verifier=DidVerifier):
"""
Prepares the data to be serialised for signing and then verifies the
signature
:... | def function[authenticate, parameter[self, req_data, identifier, signature, threshold, verifier]]:
constant[
Prepares the data to be serialised for signing and then verifies the
signature
:param req_data:
:param identifier:
:param signature:
:param verifier:
... | keyword[def] identifier[authenticate] ( identifier[self] , identifier[req_data] , identifier[identifier] : identifier[Optional] [ identifier[str] ]= keyword[None] ,
identifier[signature] : identifier[Optional] [ identifier[str] ]= keyword[None] , identifier[threshold] : identifier[Optional] [ identifier[int] ]= keyw... | def authenticate(self, req_data, identifier: Optional[str]=None, signature: Optional[str]=None, threshold: Optional[int]=None, verifier: Verifier=DidVerifier):
"""
Prepares the data to be serialised for signing and then verifies the
signature
:param req_data:
:param identifier:
... |
def mdl(ll, k, data):
"""
Returns the minimum description length score of the model given its
log-likelihood and k, the number of cell types.
a lower cost is better...
"""
"""
N - no. of genes
n - no. of cells
k - no. of cell types
R - sum(Dataset) i.e. total no. of reads
... | def function[mdl, parameter[ll, k, data]]:
constant[
Returns the minimum description length score of the model given its
log-likelihood and k, the number of cell types.
a lower cost is better...
]
constant[
N - no. of genes
n - no. of cells
k - no. of cell types
R - sum... | keyword[def] identifier[mdl] ( identifier[ll] , identifier[k] , identifier[data] ):
literal[string]
literal[string]
identifier[N] , identifier[m] = identifier[data] . identifier[shape]
identifier[cost] = identifier[ll] +( identifier[N] * identifier[m] + identifier[m] * identifier[k] )*( identi... | def mdl(ll, k, data):
"""
Returns the minimum description length score of the model given its
log-likelihood and k, the number of cell types.
a lower cost is better...
"""
'\n N - no. of genes\n n - no. of cells \n k - no. of cell types\n R - sum(Dataset) i.e. total no. of reads\n\n... |
async def on_raw_730(self, message):
""" Someone we are monitoring just came online. """
for nick in message.params[1].split(','):
self._create_user(nick)
await self.on_user_online(nickname) | <ast.AsyncFunctionDef object at 0x7da20c6e6560> | keyword[async] keyword[def] identifier[on_raw_730] ( identifier[self] , identifier[message] ):
literal[string]
keyword[for] identifier[nick] keyword[in] identifier[message] . identifier[params] [ literal[int] ]. identifier[split] ( literal[string] ):
identifier[self] . identifier[_... | async def on_raw_730(self, message):
""" Someone we are monitoring just came online. """
for nick in message.params[1].split(','):
self._create_user(nick)
await self.on_user_online(nickname) # depends on [control=['for'], data=['nick']] |
def read(self):
"""Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode()
else:
... | def function[read, parameter[self]]:
constant[Read stdout and stdout pipes if process is no longer running.]
if <ast.BoolOp object at 0x7da1b14c5e10> begin[:]
variable[ip] assign[=] call[name[get_ipython], parameter[]]
variable[err] assign[=] call[call[call[name[ip].user_... | keyword[def] identifier[read] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_process] keyword[and] identifier[self] . identifier[_process] . identifier[poll] () keyword[is] keyword[not] keyword[None] :
identifier[ip] = identifier[get_ipython] ()
... | def read(self):
"""Read stdout and stdout pipes if process is no longer running."""
if self._process and self._process.poll() is not None:
ip = get_ipython()
err = ip.user_ns['error'].read().decode()
out = ip.user_ns['output'].read().decode() # depends on [control=['if'], data=[]]
e... |
def get_kwargs(self, args):
"""
Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain the entire
content... | def function[get_kwargs, parameter[self, args]]:
constant[
Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain... | keyword[def] identifier[get_kwargs] ( identifier[self] , identifier[args] ):
literal[string]
identifier[kwargs] ={}
identifier[argspec] = identifier[inspect] . identifier[getargspec] ( identifier[self] . identifier[_func] )
identifier[required] = identifier[set]... | def get_kwargs(self, args):
"""
Given a Namespace object drawn from argparse, determines the
keyword arguments to pass to the underlying function. Note
that, if the underlying function accepts all keyword
arguments, the dictionary returned will contain the entire
contents of... |
def histogram2D(xvalues, yvalues, bins=12, norm=1, c="g", alpha=1, fill=False):
"""
Build a 2D hexagonal histogram from a list of x and y values.
:param bool bins: nr of bins for the smaller range in x or y.
:param float norm: sets a scaling factor for the z axis.
:param bool fill: draw solid hexag... | def function[histogram2D, parameter[xvalues, yvalues, bins, norm, c, alpha, fill]]:
constant[
Build a 2D hexagonal histogram from a list of x and y values.
:param bool bins: nr of bins for the smaller range in x or y.
:param float norm: sets a scaling factor for the z axis.
:param bool fill: dr... | keyword[def] identifier[histogram2D] ( identifier[xvalues] , identifier[yvalues] , identifier[bins] = literal[int] , identifier[norm] = literal[int] , identifier[c] = literal[string] , identifier[alpha] = literal[int] , identifier[fill] = keyword[False] ):
literal[string]
identifier[xmin] , identifier[xmax... | def histogram2D(xvalues, yvalues, bins=12, norm=1, c='g', alpha=1, fill=False):
"""
Build a 2D hexagonal histogram from a list of x and y values.
:param bool bins: nr of bins for the smaller range in x or y.
:param float norm: sets a scaling factor for the z axis.
:param bool fill: draw solid hexag... |
def plexp_inv(P,xm,a):
"""
Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.
"""
C = 1/(-xm/(1 - a) - xm/a + math.exp(a)*xm/a)
Pxm = 1+C*(xm/(1-a))
pp = P
x = xm*(pp-1)*(1-a)/(C*xm)**(1/(1-a)) if pp >= Pxm else (math.log( ((C*xm/a)*math.exp(a)-pp)/(C*xm/a)) - a... | def function[plexp_inv, parameter[P, xm, a]]:
constant[
Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.
]
variable[C] assign[=] binary_operation[constant[1] / binary_operation[binary_operation[binary_operation[<ast.UnaryOp object at 0x7da1b26af910> / binary_operat... | keyword[def] identifier[plexp_inv] ( identifier[P] , identifier[xm] , identifier[a] ):
literal[string]
identifier[C] = literal[int] /(- identifier[xm] /( literal[int] - identifier[a] )- identifier[xm] / identifier[a] + identifier[math] . identifier[exp] ( identifier[a] )* identifier[xm] / identifier[a] )
... | def plexp_inv(P, xm, a):
"""
Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.
"""
C = 1 / (-xm / (1 - a) - xm / a + math.exp(a) * xm / a)
Pxm = 1 + C * (xm / (1 - a))
pp = P
x = xm * (pp - 1) * (1 - a) / (C * xm) ** (1 / (1 - a)) if pp >= Pxm else (math.log((C ... |
def join(args):
"""
%prog join fastafile [phasefile]
Make AGP file for a bunch of sequences, and add gaps between, and then build
the joined fastafile. This is useful by itself, but with --oo option this
can convert the .oo (BAMBUS output) into AGP and a joined fasta.
Phasefile is optional, bu... | def function[join, parameter[args]]:
constant[
%prog join fastafile [phasefile]
Make AGP file for a bunch of sequences, and add gaps between, and then build
the joined fastafile. This is useful by itself, but with --oo option this
can convert the .oo (BAMBUS output) into AGP and a joined fasta.... | keyword[def] identifier[join] ( identifier[args] ):
literal[string]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[agp] keyword[import] identifier[OO] , identifier[Phases] , identifier[build]
keyword[from] identifier[jcvi] . identifier[formats] . identifier[sizes] keyword[impo... | def join(args):
"""
%prog join fastafile [phasefile]
Make AGP file for a bunch of sequences, and add gaps between, and then build
the joined fastafile. This is useful by itself, but with --oo option this
can convert the .oo (BAMBUS output) into AGP and a joined fasta.
Phasefile is optional, bu... |
def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imp... | def function[_find_frame_imports, parameter[name, frame]]:
constant[
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
]
variable[imports] assign[=] call[name[frame].nodes_of_class, p... | keyword[def] identifier[_find_frame_imports] ( identifier[name] , identifier[frame] ):
literal[string]
identifier[imports] = identifier[frame] . identifier[nodes_of_class] (( identifier[astroid] . identifier[Import] , identifier[astroid] . identifier[ImportFrom] ))
keyword[for] identifier[import_node... | def _find_frame_imports(name, frame):
"""
Detect imports in the frame, with the required
*name*. Such imports can be considered assignments.
Returns True if an import for the given name was found.
"""
imports = frame.nodes_of_class((astroid.Import, astroid.ImportFrom))
for import_node in imp... |
def img2img_transformer_base_tpu():
"""Hparams for training img2img_transformer on tpu."""
hparams = img2img_transformer_base()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 8
hparams.num_encoder_layers = 4
hparam... | def function[img2img_transformer_base_tpu, parameter[]]:
constant[Hparams for training img2img_transformer on tpu.]
variable[hparams] assign[=] call[name[img2img_transformer_base], parameter[]]
call[name[update_hparams_for_tpu], parameter[name[hparams]]]
name[hparams].batch_size assign[=... | keyword[def] identifier[img2img_transformer_base_tpu] ():
literal[string]
identifier[hparams] = identifier[img2img_transformer_base] ()
identifier[update_hparams_for_tpu] ( identifier[hparams] )
identifier[hparams] . identifier[batch_size] = literal[int]
identifier[hparams] . identifier[num_heads] = ... | def img2img_transformer_base_tpu():
"""Hparams for training img2img_transformer on tpu."""
hparams = img2img_transformer_base()
update_hparams_for_tpu(hparams)
hparams.batch_size = 2
hparams.num_heads = 4 # heads are expensive on tpu
hparams.num_decoder_layers = 8
hparams.num_encoder_layers... |
def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None,
basis_set="6-31g", basis_set_option="cartesian",
title=None, operation="optimize", theory_directives=None,
alternate_directives=None):
"""
Very flexible arguments to... | def function[from_molecule, parameter[cls, mol, theory, charge, spin_multiplicity, basis_set, basis_set_option, title, operation, theory_directives, alternate_directives]]:
constant[
Very flexible arguments to support many types of potential setups.
Users should use more friendly static methods ... | keyword[def] identifier[from_molecule] ( identifier[cls] , identifier[mol] , identifier[theory] , identifier[charge] = keyword[None] , identifier[spin_multiplicity] = keyword[None] ,
identifier[basis_set] = literal[string] , identifier[basis_set_option] = literal[string] ,
identifier[title] = keyword[None] , identi... | def from_molecule(cls, mol, theory, charge=None, spin_multiplicity=None, basis_set='6-31g', basis_set_option='cartesian', title=None, operation='optimize', theory_directives=None, alternate_directives=None):
"""
Very flexible arguments to support many types of potential setups.
Users should use more... |
def parse(self, xmltext):
"""
Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str
"""
xml = LEMSXMLNode(xe.XML(xmltext))
if xml.ltag != 'lems' and xml.ltag != 'neuroml':
rais... | def function[parse, parameter[self, xmltext]]:
constant[
Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str
]
variable[xml] assign[=] call[name[LEMSXMLNode], parameter[call[name[xe].XML, parameter[name[x... | keyword[def] identifier[parse] ( identifier[self] , identifier[xmltext] ):
literal[string]
identifier[xml] = identifier[LEMSXMLNode] ( identifier[xe] . identifier[XML] ( identifier[xmltext] ))
keyword[if] identifier[xml] . identifier[ltag] != literal[string] keyword[and] identifier[xm... | def parse(self, xmltext):
"""
Parse a string containing LEMS XML text.
@param xmltext: String containing LEMS XML formatted text.
@type xmltext: str
"""
xml = LEMSXMLNode(xe.XML(xmltext))
if xml.ltag != 'lems' and xml.ltag != 'neuroml':
raise ParseError('<Lems> expec... |
def to_bytes(self, transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype',
format="png"):
"""
Convert to selected format (discarding geo).
Optionally also resizes.
Note: for color images returns interlaced.
:param transparent... | def function[to_bytes, parameter[self, transparent, thumbnail_size, resampling, in_range, out_range, format]]:
constant[
Convert to selected format (discarding geo).
Optionally also resizes.
Note: for color images returns interlaced.
:param transparent: if True - sets alpha chan... | keyword[def] identifier[to_bytes] ( identifier[self] , identifier[transparent] = keyword[True] , identifier[thumbnail_size] = keyword[None] , identifier[resampling] = keyword[None] , identifier[in_range] = literal[string] , identifier[out_range] = literal[string] ,
identifier[format] = literal[string] ):
li... | def to_bytes(self, transparent=True, thumbnail_size=None, resampling=None, in_range='dtype', out_range='dtype', format='png'):
"""
Convert to selected format (discarding geo).
Optionally also resizes.
Note: for color images returns interlaced.
:param transparent: if True - sets alph... |
def _check_cache_minions(self,
expr,
delimiter,
greedy,
search_type,
regex_match=False,
exact_match=False):
'''
Helper function to... | def function[_check_cache_minions, parameter[self, expr, delimiter, greedy, search_type, regex_match, exact_match]]:
constant[
Helper function to search for minions in master caches If 'greedy',
then return accepted minions matched by the condition or those absent
from the cache. If not... | keyword[def] identifier[_check_cache_minions] ( identifier[self] ,
identifier[expr] ,
identifier[delimiter] ,
identifier[greedy] ,
identifier[search_type] ,
identifier[regex_match] = keyword[False] ,
identifier[exact_match] = keyword[False] ):
literal[string]
identifier[cache_enabled] = ident... | def _check_cache_minions(self, expr, delimiter, greedy, search_type, regex_match=False, exact_match=False):
"""
Helper function to search for minions in master caches If 'greedy',
then return accepted minions matched by the condition or those absent
from the cache. If not 'greedy' return th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.