code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def convert_rgb_to_rgba(self, row, result):
"""
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[(4 * i) + j] = row[(3 ... | def function[convert_rgb_to_rgba, parameter[self, row, result]]:
constant[
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
]
for taget[name[i]] in starred[call[name[range], parameter[binary_operation[call[na... | keyword[def] identifier[convert_rgb_to_rgba] ( identifier[self] , identifier[row] , identifier[result] ):
literal[string]
keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[row] )// literal[int] ):
keyword[for] identifier[j] keyword[in] identi... | def convert_rgb_to_rgba(self, row, result):
"""
Convert an RGB image to RGBA.
This method assumes the alpha channel in result is already
correctly initialized.
"""
for i in range(len(row) // 3):
for j in range(3):
result[4 * i + j] = row[3 * i + j] # depends... |
def combine_sj_out(
fns,
external_db,
total_jxn_cov_cutoff=20,
define_sample_name=None,
verbose=False,
):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list... | def function[combine_sj_out, parameter[fns, external_db, total_jxn_cov_cutoff, define_sample_name, verbose]]:
constant[Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strin... | keyword[def] identifier[combine_sj_out] (
identifier[fns] ,
identifier[external_db] ,
identifier[total_jxn_cov_cutoff] = literal[int] ,
identifier[define_sample_name] = keyword[None] ,
identifier[verbose] = keyword[False] ,
):
literal[string]
keyword[if] identifier[verbose] :
keyword[import]... | def combine_sj_out(fns, external_db, total_jxn_cov_cutoff=20, define_sample_name=None, verbose=False):
"""Combine SJ.out.tab files from STAR by filtering based on coverage and
comparing to an external annotation to discover novel junctions.
Parameters
----------
fns : list of strings
Filen... |
def ren(i):
"""
Input: {
data_uoa - repo UOA
(new_data_uoa)
or
xcids[0] - {'data_uoa'} - new data UOA
}
Output: {
return - return code = 0, if successful
> 0, i... | def function[ren, parameter[i]]:
constant[
Input: {
data_uoa - repo UOA
(new_data_uoa)
or
xcids[0] - {'data_uoa'} - new data UOA
}
Output: {
return - return code = 0, if successful
... | keyword[def] identifier[ren] ( identifier[i] ):
literal[string]
identifier[o] = identifier[i] . identifier[get] ( literal[string] , literal[string] )
identifier[duoa] = identifier[i] . identifier[get] ( literal[string] , literal[string] )
keyword[if] identifier[duoa] == literal[string] :
... | def ren(i):
"""
Input: {
data_uoa - repo UOA
(new_data_uoa)
or
xcids[0] - {'data_uoa'} - new data UOA
}
Output: {
return - return code = 0, if successful
> 0, i... |
def parse(self, argument):
"""Determine validity of argument and return the correct element of enum.
If self.enum_values is empty, then all arguments are valid and argument
will be returned.
Otherwise, if argument matches an element in enum, then the first
matching element will be returned.
A... | def function[parse, parameter[self, argument]]:
constant[Determine validity of argument and return the correct element of enum.
If self.enum_values is empty, then all arguments are valid and argument
will be returned.
Otherwise, if argument matches an element in enum, then the first
matching e... | keyword[def] identifier[parse] ( identifier[self] , identifier[argument] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[enum_values] :
keyword[return] identifier[argument]
keyword[elif] identifier[self] . identifier[case_sensitive] :
keyword[if] identifie... | def parse(self, argument):
"""Determine validity of argument and return the correct element of enum.
If self.enum_values is empty, then all arguments are valid and argument
will be returned.
Otherwise, if argument matches an element in enum, then the first
matching element will be returned.
A... |
def run(self):
"""
loops until exit command given
"""
while self.status != 'EXIT':
print(self.process_input(self.get_input()))
print('Bye') | def function[run, parameter[self]]:
constant[
loops until exit command given
]
while compare[name[self].status not_equal[!=] constant[EXIT]] begin[:]
call[name[print], parameter[call[name[self].process_input, parameter[call[name[self].get_input, parameter[]]]]]]
c... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
keyword[while] identifier[self] . identifier[status] != literal[string] :
identifier[print] ( identifier[self] . identifier[process_input] ( identifier[self] . identifier[get_input] ()))
identifier[print] ( l... | def run(self):
"""
loops until exit command given
"""
while self.status != 'EXIT':
print(self.process_input(self.get_input())) # depends on [control=['while'], data=[]]
print('Bye') |
def leaders(self, current_page, **options):
'''
Retrieve a page of leaders from the leaderboard.
@param current_page [int] Page to retrieve from the leaderboard.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a page of leaders fro... | def function[leaders, parameter[self, current_page]]:
constant[
Retrieve a page of leaders from the leaderboard.
@param current_page [int] Page to retrieve from the leaderboard.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a pag... | keyword[def] identifier[leaders] ( identifier[self] , identifier[current_page] ,** identifier[options] ):
literal[string]
keyword[return] identifier[self] . identifier[leaders_in] ( identifier[self] . identifier[leaderboard_name] , identifier[current_page] ,** identifier[options] ) | def leaders(self, current_page, **options):
"""
Retrieve a page of leaders from the leaderboard.
@param current_page [int] Page to retrieve from the leaderboard.
@param options [Hash] Options to be used when retrieving the page from the leaderboard.
@return a page of leaders from th... |
def _set_lsp_secpath_autobw_template(self, v, load=False):
"""
Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is read-only (config: false) ... | def function[_set_lsp_secpath_autobw_template, parameter[self, v, load]]:
constant[
Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is r... | keyword[def] identifier[_set_lsp_secpath_autobw_template] ( 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[... | def _set_lsp_secpath_autobw_template(self, v, load=False):
"""
Setter method for lsp_secpath_autobw_template, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/lsp/secondary_path/lsp_secpath_auto_bandwidth/lsp_secpath_autobw_template (leafref)
If this variable is read-only (config: false) ... |
def copy_shell(self):
"""
Copy the group properties EXCEPT the members.
Members need to be filled after manually
:return: Itemgroup object
:rtype: alignak.objects.itemgroup.Itemgroup
:return: None
"""
cls = self.__class__
new_i = cls() # create a... | def function[copy_shell, parameter[self]]:
constant[
Copy the group properties EXCEPT the members.
Members need to be filled after manually
:return: Itemgroup object
:rtype: alignak.objects.itemgroup.Itemgroup
:return: None
]
variable[cls] assign[=] name[... | keyword[def] identifier[copy_shell] ( identifier[self] ):
literal[string]
identifier[cls] = identifier[self] . identifier[__class__]
identifier[new_i] = identifier[cls] ()
identifier[new_i] . identifier[uuid] = identifier[self] . identifier[uuid]
keyword[for] ... | def copy_shell(self):
"""
Copy the group properties EXCEPT the members.
Members need to be filled after manually
:return: Itemgroup object
:rtype: alignak.objects.itemgroup.Itemgroup
:return: None
"""
cls = self.__class__
new_i = cls() # create a new group
... |
def get_git_postversion(addon_dir):
""" return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is used as is for the python pack... | def function[get_git_postversion, parameter[addon_dir]]:
constant[ return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is... | keyword[def] identifier[get_git_postversion] ( identifier[addon_dir] ):
literal[string]
identifier[addon_dir] = identifier[os] . identifier[path] . identifier[realpath] ( identifier[addon_dir] )
identifier[last_version] = identifier[read_manifest] ( identifier[addon_dir] ). identifier[get] ( literal[s... | def get_git_postversion(addon_dir):
""" return the addon version number, with a developmental version increment
if there were git commits in the addon_dir after the last version change.
If the last change to the addon correspond to the version number in the
manifest it is used as is for the python pack... |
def tilequeue_load_tiles_of_interest(cfg, peripherals):
"""
Given a newline-delimited file containing tile coordinates in
`zoom/column/row` format, load those tiles into the tiles of interest.
"""
logger = make_logger(cfg, 'load_tiles_of_interest')
toi_filename = "toi.txt"
logger.info('Load... | def function[tilequeue_load_tiles_of_interest, parameter[cfg, peripherals]]:
constant[
Given a newline-delimited file containing tile coordinates in
`zoom/column/row` format, load those tiles into the tiles of interest.
]
variable[logger] assign[=] call[name[make_logger], parameter[name[cfg]... | keyword[def] identifier[tilequeue_load_tiles_of_interest] ( identifier[cfg] , identifier[peripherals] ):
literal[string]
identifier[logger] = identifier[make_logger] ( identifier[cfg] , literal[string] )
identifier[toi_filename] = literal[string]
identifier[logger] . identifier[info] ( literal[... | def tilequeue_load_tiles_of_interest(cfg, peripherals):
"""
Given a newline-delimited file containing tile coordinates in
`zoom/column/row` format, load those tiles into the tiles of interest.
"""
logger = make_logger(cfg, 'load_tiles_of_interest')
toi_filename = 'toi.txt'
logger.info('Loadi... |
def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument(
'-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV') | def function[add_env, parameter[parser]]:
constant[Add an `env` flag to the _parser_.]
call[name[parser].add_argument, parameter[constant[-e], constant[--env]]] | keyword[def] identifier[add_env] ( identifier[parser] ):
literal[string]
identifier[parser] . identifier[add_argument] (
literal[string] , literal[string] , identifier[choices] = identifier[ENVS] , identifier[default] = identifier[os] . identifier[getenv] ( literal[string] , identifier[default] = lite... | def add_env(parser):
"""Add an `env` flag to the _parser_."""
parser.add_argument('-e', '--env', choices=ENVS, default=os.getenv('ENV', default='dev'), help='Deploy environment, overrides $ENV') |
def initdict2(self, dictfile):
"""initdict2"""
dt = {}
dtls = []
adict = dictfile
for element in adict:
dt[element[0].upper()] = [] # dict keys for objects always in caps
dtls.append(element[0].upper())
return dt, dtls | def function[initdict2, parameter[self, dictfile]]:
constant[initdict2]
variable[dt] assign[=] dictionary[[], []]
variable[dtls] assign[=] list[[]]
variable[adict] assign[=] name[dictfile]
for taget[name[element]] in starred[name[adict]] begin[:]
call[name[dt]][ca... | keyword[def] identifier[initdict2] ( identifier[self] , identifier[dictfile] ):
literal[string]
identifier[dt] ={}
identifier[dtls] =[]
identifier[adict] = identifier[dictfile]
keyword[for] identifier[element] keyword[in] identifier[adict] :
identifier[dt... | def initdict2(self, dictfile):
"""initdict2"""
dt = {}
dtls = []
adict = dictfile
for element in adict:
dt[element[0].upper()] = [] # dict keys for objects always in caps
dtls.append(element[0].upper()) # depends on [control=['for'], data=['element']]
return (dt, dtls) |
def is_bridge(self):
"""bool: Is this zone a bridge?"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._is_bridge is not None:
return self._is_bridge
# if not, we have to get it from... | def function[is_bridge, parameter[self]]:
constant[bool: Is this zone a bridge?]
if compare[name[self]._is_bridge is_not constant[None]] begin[:]
return[name[self]._is_bridge]
call[name[self]._parse_zone_group_state, parameter[]]
return[name[self]._is_bridge] | keyword[def] identifier[is_bridge] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_is_bridge] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[self] . identifier[_is_bridge]
... | def is_bridge(self):
"""bool: Is this zone a bridge?"""
# Since this does not change over time (?) check whether we already
# know the answer. If so, there is no need to go further
if self._is_bridge is not None:
return self._is_bridge # depends on [control=['if'], data=[]]
# if not, we hav... |
def bind(cls, ns, location=None):
"""
Bind a namespace to a schema location (URI).
This is used for imports that don't specify a schemaLocation.
@param ns: A namespace-uri.
@type ns: str
@param location: The (optional) schema location for the
namespace. (defa... | def function[bind, parameter[cls, ns, location]]:
constant[
Bind a namespace to a schema location (URI).
This is used for imports that don't specify a schemaLocation.
@param ns: A namespace-uri.
@type ns: str
@param location: The (optional) schema location for the
... | keyword[def] identifier[bind] ( identifier[cls] , identifier[ns] , identifier[location] = keyword[None] ):
literal[string]
keyword[if] identifier[location] keyword[is] keyword[None] :
identifier[location] = identifier[ns]
identifier[cls] . identifier[locations] [ identifie... | def bind(cls, ns, location=None):
"""
Bind a namespace to a schema location (URI).
This is used for imports that don't specify a schemaLocation.
@param ns: A namespace-uri.
@type ns: str
@param location: The (optional) schema location for the
namespace. (default=... |
def add_trial(self, trial):
"""Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue.
"""
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow("scheduler.on_trial_add"):
... | def function[add_trial, parameter[self, trial]]:
constant[Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue.
]
call[name[trial].set_verbose, parameter[name[self]._verbose]]
call[name[self]._trials.appe... | keyword[def] identifier[add_trial] ( identifier[self] , identifier[trial] ):
literal[string]
identifier[trial] . identifier[set_verbose] ( identifier[self] . identifier[_verbose] )
identifier[self] . identifier[_trials] . identifier[append] ( identifier[trial] )
keyword[with] ide... | def add_trial(self, trial):
"""Adds a new trial to this TrialRunner.
Trials may be added at any time.
Args:
trial (Trial): Trial to queue.
"""
trial.set_verbose(self._verbose)
self._trials.append(trial)
with warn_if_slow('scheduler.on_trial_add'):
self._sche... |
def infer_location(
self,
location_query,
max_distance,
google_key,
foursquare_client_id,
foursquare_client_secret,
limit
):
"""In-place location inferring of segments
Returns:
This track
"""... | def function[infer_location, parameter[self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit]]:
constant[In-place location inferring of segments
Returns:
This track
]
name[self].segments assign[=] <ast.ListComp object at 0x7da1... | keyword[def] identifier[infer_location] (
identifier[self] ,
identifier[location_query] ,
identifier[max_distance] ,
identifier[google_key] ,
identifier[foursquare_client_id] ,
identifier[foursquare_client_secret] ,
identifier[limit]
):
literal[string]
identifier[self] . identifier[segments... | def infer_location(self, location_query, max_distance, google_key, foursquare_client_id, foursquare_client_secret, limit):
"""In-place location inferring of segments
Returns:
This track
"""
self.segments = [segment.infer_location(location_query, max_distance, google_key, foursquare_... |
def fromxml(node):
"""Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(Stri... | def function[fromxml, parameter[node]]:
constant[Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element]
if <ast.UnaryOp object at 0x7da20e9b1d20> begin[:]
variable[node] assign[=] call... | keyword[def] identifier[fromxml] ( identifier[node] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[node] , identifier[ElementTree] . identifier[_Element] ):
identifier[node] = identifier[ElementTree] . identifier[parse] ( identifier[StringIO] ( identi... | def fromxml(node):
"""Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element"""
if not isinstance(node, ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(StringIO(node)... |
def getPriorities(self, projectarea_id=None, projectarea_name=None):
"""Get all :class:`rtcclient.models.Priority` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given.
If no :class:`rtcclient.models.Priority` is retrieved,
`Non... | def function[getPriorities, parameter[self, projectarea_id, projectarea_name]]:
constant[Get all :class:`rtcclient.models.Priority` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given.
If no :class:`rtcclient.models.Priority` is retrie... | keyword[def] identifier[getPriorities] ( identifier[self] , identifier[projectarea_id] = keyword[None] , identifier[projectarea_name] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_getPriorities] ( identifier[projectarea_id] = identifier[projectarea_id] ,
... | def getPriorities(self, projectarea_id=None, projectarea_name=None):
"""Get all :class:`rtcclient.models.Priority` objects by
project area id or name
At least either of `projectarea_id` and `projectarea_name` is given.
If no :class:`rtcclient.models.Priority` is retrieved,
`None` i... |
def created(self):
"""Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
"""
if 'id_perms' not in self:
self.fetch()
created = self['id_perms']['created']
return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.... | def function[created, parameter[self]]:
constant[Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
]
if compare[constant[id_perms] <ast.NotIn object at 0x7da2590d7190> name[self]] begin[:]
call[name[self].fetch, paramet... | keyword[def] identifier[created] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[self] :
identifier[self] . identifier[fetch] ()
identifier[created] = identifier[self] [ literal[string] ][ literal[string] ]
key... | def created(self):
"""Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
"""
if 'id_perms' not in self:
self.fetch() # depends on [control=['if'], data=['self']]
created = self['id_perms']['created']
return datetime.strptime(cr... |
def _first(self, **spec):
""" Get the earliest entry in this category, optionally including subcategories """
for record in self._entries(spec).order_by(model.Entry.local_date,
model.Entry.id)[:1]:
return entry.Entry(record)
return N... | def function[_first, parameter[self]]:
constant[ Get the earliest entry in this category, optionally including subcategories ]
for taget[name[record]] in starred[call[call[call[name[self]._entries, parameter[name[spec]]].order_by, parameter[name[model].Entry.local_date, name[model].Entry.id]]][<ast.Slic... | keyword[def] identifier[_first] ( identifier[self] ,** identifier[spec] ):
literal[string]
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[_entries] ( identifier[spec] ). identifier[order_by] ( identifier[model] . identifier[Entry] . identifier[local_date] ,
id... | def _first(self, **spec):
""" Get the earliest entry in this category, optionally including subcategories """
for record in self._entries(spec).order_by(model.Entry.local_date, model.Entry.id)[:1]:
return entry.Entry(record) # depends on [control=['for'], data=['record']]
return None |
def _platform_name():
"""
Returns information about the current operating system and version
:return:
A unicode string containing the OS name and version
"""
if sys.platform == 'darwin':
version = _plat.mac_ver()[0]
_plat_ver_info = tuple(map(int, version.split('.')))
... | def function[_platform_name, parameter[]]:
constant[
Returns information about the current operating system and version
:return:
A unicode string containing the OS name and version
]
if compare[name[sys].platform equal[==] constant[darwin]] begin[:]
variable[version]... | keyword[def] identifier[_platform_name] ():
literal[string]
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[version] = identifier[_plat] . identifier[mac_ver] ()[ literal[int] ]
identifier[_plat_ver_info] = identifier[tuple] ( identifier[map] ( identif... | def _platform_name():
"""
Returns information about the current operating system and version
:return:
A unicode string containing the OS name and version
"""
if sys.platform == 'darwin':
version = _plat.mac_ver()[0]
_plat_ver_info = tuple(map(int, version.split('.')))
... |
def generate_password():
"""Returns a 23 character random string, with 3 special characters at the end"""
if sys.version_info > (3, 6):
import secrets # pylint: disable=import-error
alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for i in rang... | def function[generate_password, parameter[]]:
constant[Returns a 23 character random string, with 3 special characters at the end]
if compare[name[sys].version_info greater[>] tuple[[<ast.Constant object at 0x7da204621510>, <ast.Constant object at 0x7da204620e50>]]] begin[:]
import module[secret... | keyword[def] identifier[generate_password] ():
literal[string]
keyword[if] identifier[sys] . identifier[version_info] >( literal[int] , literal[int] ):
keyword[import] identifier[secrets]
identifier[alphabet] = identifier[string] . identifier[ascii_letters] + identifier[string] . ident... | def generate_password():
"""Returns a 23 character random string, with 3 special characters at the end"""
if sys.version_info > (3, 6):
import secrets # pylint: disable=import-error
alphabet = string.ascii_letters + string.digits
password = ''.join((secrets.choice(alphabet) for i in ran... |
def _parseBoundImportDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.... | def function[_parseBoundImportDirectory, parameter[self, rva, size, magic]]:
constant[
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound impo... | keyword[def] identifier[_parseBoundImportDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ):
literal[string]
identifier[data] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] )
i... | def _parseBoundImportDirectory(self, rva, size, magic=consts.PE32):
"""
Parses the bound import directory.
@type rva: int
@param rva: The RVA where the bound import directory starts.
@type size: int
@param size: The size of the bound import directory.
... |
def preferred_jvm_distribution(cls, platforms, strict=False):
"""Returns a jvm Distribution with a version that should work for all the platforms.
Any one of those distributions whose version is >= all requested platforms' versions
can be returned unless strict flag is set.
:param iterable platforms: ... | def function[preferred_jvm_distribution, parameter[cls, platforms, strict]]:
constant[Returns a jvm Distribution with a version that should work for all the platforms.
Any one of those distributions whose version is >= all requested platforms' versions
can be returned unless strict flag is set.
:p... | keyword[def] identifier[preferred_jvm_distribution] ( identifier[cls] , identifier[platforms] , identifier[strict] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[platforms] :
keyword[return] identifier[DistributionLocator] . identifier[cached] ()
identifier[min_versi... | def preferred_jvm_distribution(cls, platforms, strict=False):
"""Returns a jvm Distribution with a version that should work for all the platforms.
Any one of those distributions whose version is >= all requested platforms' versions
can be returned unless strict flag is set.
:param iterable platforms: ... |
def end_episode(self, agent_indices):
"""Add episodes to the memory and perform update steps if memory is full.
During training, add the collected episodes of the batch indices that
finished their episode to the memory. If the memory is full, train on it,
and then clear the memory. A summary string is ... | def function[end_episode, parameter[self, agent_indices]]:
constant[Add episodes to the memory and perform update steps if memory is full.
During training, add the collected episodes of the batch indices that
finished their episode to the memory. If the memory is full, train on it,
and then clear t... | keyword[def] identifier[end_episode] ( identifier[self] , identifier[agent_indices] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( literal[string] ):
keyword[return] identifier[tf] . identifier[cond] (
identifier[self] . identifier[_is_training] ,
keyword[... | def end_episode(self, agent_indices):
"""Add episodes to the memory and perform update steps if memory is full.
During training, add the collected episodes of the batch indices that
finished their episode to the memory. If the memory is full, train on it,
and then clear the memory. A summary string is ... |
def _distance_squared(self, p2: "Point2") -> Union[int, float]:
""" Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """
return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2 | def function[_distance_squared, parameter[self, p2]]:
constant[ Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. ]
return[binary_operation[binary_operation[binary_operation[call[name[self]][constant[0]] - call[name[p2]][co... | keyword[def] identifier[_distance_squared] ( identifier[self] , identifier[p2] : literal[string] )-> identifier[Union] [ identifier[int] , identifier[float] ]:
literal[string]
keyword[return] ( identifier[self] [ literal[int] ]- identifier[p2] [ literal[int] ])** literal[int] +( identifier[self] [ ... | def _distance_squared(self, p2: 'Point2') -> Union[int, float]:
""" Function used to not take the square root as the distances will stay proportionally the same. This is to speed up the sorting process. """
return (self[0] - p2[0]) ** 2 + (self[1] - p2[1]) ** 2 |
def set_attribute_xsi_type(self, el, **kw):
'''if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
'''
if kw.get('typed', self.typed):
namespaceURI,typeName = kw.get('type', _get_xsitype(self))
if namespaceU... | def function[set_attribute_xsi_type, parameter[self, el]]:
constant[if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
]
if call[name[kw].get, parameter[constant[typed], name[self].typed]] begin[:]
<ast.Tuple objec... | keyword[def] identifier[set_attribute_xsi_type] ( identifier[self] , identifier[el] ,** identifier[kw] ):
literal[string]
keyword[if] identifier[kw] . identifier[get] ( literal[string] , identifier[self] . identifier[typed] ):
identifier[namespaceURI] , identifier[typeName] = identifi... | def set_attribute_xsi_type(self, el, **kw):
"""if typed, set the xsi:type attribute
Paramters:
el -- MessageInterface representing the element
"""
if kw.get('typed', self.typed):
(namespaceURI, typeName) = kw.get('type', _get_xsitype(self))
if namespaceURI and typeNa... |
def _parseRelocsDirectory(self, rva, size, magic = consts.PE32):
"""
Parses the relocation directory.
@type rva: int
@param rva: The RVA where the relocation directory starts.
@type size: int
@param size: The size of the relocation directory.
... | def function[_parseRelocsDirectory, parameter[self, rva, size, magic]]:
constant[
Parses the relocation directory.
@type rva: int
@param rva: The RVA where the relocation directory starts.
@type size: int
@param size: The size of the relocation director... | keyword[def] identifier[_parseRelocsDirectory] ( identifier[self] , identifier[rva] , identifier[size] , identifier[magic] = identifier[consts] . identifier[PE32] ):
literal[string]
identifier[data] = identifier[self] . identifier[getDataAtRva] ( identifier[rva] , identifier[size] )
... | def _parseRelocsDirectory(self, rva, size, magic=consts.PE32):
"""
Parses the relocation directory.
@type rva: int
@param rva: The RVA where the relocation directory starts.
@type size: int
@param size: The size of the relocation directory.
... |
def nextversion(current_version):
"""Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
... | def function[nextversion, parameter[current_version]]:
constant[Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version`... | keyword[def] identifier[nextversion] ( identifier[current_version] ):
literal[string]
identifier[norm_ver] = identifier[verlib] . identifier[suggest_normalized_version] ( identifier[current_version] )
keyword[if] identifier[norm_ver] keyword[is] keyword[None] :
keyword[return] keyword[Non... | def nextversion(current_version):
"""Returns incremented module version number.
:param current_version: version string to increment
:returns: Next version string (PEP 386 compatible) if possible.
If impossible (since `current_version` is too far from PEP 386),
... |
def rational_limit(f, g, t0):
"""Computes the limit of the rational function (f/g)(t)
as t approaches t0."""
assert isinstance(f, np.poly1d) and isinstance(g, np.poly1d)
assert g != np.poly1d([0])
if g(t0) != 0:
return f(t0)/g(t0)
elif f(t0) == 0:
return rational_limit(f.deriv(),... | def function[rational_limit, parameter[f, g, t0]]:
constant[Computes the limit of the rational function (f/g)(t)
as t approaches t0.]
assert[<ast.BoolOp object at 0x7da1b2344a00>]
assert[compare[name[g] not_equal[!=] call[name[np].poly1d, parameter[list[[<ast.Constant object at 0x7da20cabf190>]]]]]]... | keyword[def] identifier[rational_limit] ( identifier[f] , identifier[g] , identifier[t0] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[f] , identifier[np] . identifier[poly1d] ) keyword[and] identifier[isinstance] ( identifier[g] , identifier[np] . identifier[poly1d] )
keywo... | def rational_limit(f, g, t0):
"""Computes the limit of the rational function (f/g)(t)
as t approaches t0."""
assert isinstance(f, np.poly1d) and isinstance(g, np.poly1d)
assert g != np.poly1d([0])
if g(t0) != 0:
return f(t0) / g(t0) # depends on [control=['if'], data=[]]
elif f(t0) == 0... |
def render(self, context, instance, placeholder):
''' Add the cart-specific context to this form '''
context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder)
context.update({
'squareApplicationId': getattr(settings,'SQUARE_APPLICATION_ID',''),
... | def function[render, parameter[self, context, instance, placeholder]]:
constant[ Add the cart-specific context to this form ]
variable[context] assign[=] call[call[name[super], parameter[name[SquareCheckoutFormPlugin], name[self]]].render, parameter[name[context], name[instance], name[placeholder]]]
... | keyword[def] identifier[render] ( identifier[self] , identifier[context] , identifier[instance] , identifier[placeholder] ):
literal[string]
identifier[context] = identifier[super] ( identifier[SquareCheckoutFormPlugin] , identifier[self] ). identifier[render] ( identifier[context] , identifier[i... | def render(self, context, instance, placeholder):
""" Add the cart-specific context to this form """
context = super(SquareCheckoutFormPlugin, self).render(context, instance, placeholder)
context.update({'squareApplicationId': getattr(settings, 'SQUARE_APPLICATION_ID', '')})
return context |
def fetch_events(cursor, config, account_name):
"""Generator that returns the events"""
query = config['indexer'].get('query',
'select * from events where user_agent glob \'*CloudCustodian*\'')
for event in cursor.execute(query):
event['account'] = account_name
event['_index'] = con... | def function[fetch_events, parameter[cursor, config, account_name]]:
constant[Generator that returns the events]
variable[query] assign[=] call[call[name[config]][constant[indexer]].get, parameter[constant[query], constant[select * from events where user_agent glob '*CloudCustodian*']]]
for tage... | keyword[def] identifier[fetch_events] ( identifier[cursor] , identifier[config] , identifier[account_name] ):
literal[string]
identifier[query] = identifier[config] [ literal[string] ]. identifier[get] ( literal[string] ,
literal[string] )
keyword[for] identifier[event] keyword[in] identifier... | def fetch_events(cursor, config, account_name):
"""Generator that returns the events"""
query = config['indexer'].get('query', "select * from events where user_agent glob '*CloudCustodian*'")
for event in cursor.execute(query):
event['account'] = account_name
event['_index'] = config['indexe... |
def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k))
host_setting = app.config['JSONSCHEMAS_HOST']
if not host_setting or host_setting == 'localhost':
... | def function[init_config, parameter[self, app]]:
constant[Initialize configuration.]
for taget[name[k]] in starred[call[name[dir], parameter[name[config]]]] begin[:]
if call[name[k].startswith, parameter[constant[JSONSCHEMAS_]]] begin[:]
call[name[app].config.setd... | keyword[def] identifier[init_config] ( identifier[self] , identifier[app] ):
literal[string]
keyword[for] identifier[k] keyword[in] identifier[dir] ( identifier[config] ):
keyword[if] identifier[k] . identifier[startswith] ( literal[string] ):
identifier[app] . ide... | def init_config(self, app):
"""Initialize configuration."""
for k in dir(config):
if k.startswith('JSONSCHEMAS_'):
app.config.setdefault(k, getattr(config, k)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['k']]
host_setting = app.config['JSONSCHEMAS_HOST'... |
def add_custom_fields(cls, *args, **kw):
""" Add any custom fields defined in the configuration.
"""
for factory in config.custom_field_factories:
for field in factory():
setattr(cls, field.name, field) | def function[add_custom_fields, parameter[cls]]:
constant[ Add any custom fields defined in the configuration.
]
for taget[name[factory]] in starred[name[config].custom_field_factories] begin[:]
for taget[name[field]] in starred[call[name[factory], parameter[]]] begin[:]
... | keyword[def] identifier[add_custom_fields] ( identifier[cls] ,* identifier[args] ,** identifier[kw] ):
literal[string]
keyword[for] identifier[factory] keyword[in] identifier[config] . identifier[custom_field_factories] :
keyword[for] identifier[field] keyword[in] identifier[fact... | def add_custom_fields(cls, *args, **kw):
""" Add any custom fields defined in the configuration.
"""
for factory in config.custom_field_factories:
for field in factory():
setattr(cls, field.name, field) # depends on [control=['for'], data=['field']] # depends on [control=['for'], d... |
def extract_url_query_parameter(url, parameter):
"""Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the gi... | def function[extract_url_query_parameter, parameter[url, parameter]]:
constant[Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for... | keyword[def] identifier[extract_url_query_parameter] ( identifier[url] , identifier[parameter] ):
literal[string]
identifier[query_string] = identifier[urlparse] ( identifier[url] ). identifier[query]
keyword[return] identifier[parse_qs] ( identifier[query_string] ). identifier[get] ( identifier[par... | def extract_url_query_parameter(url, parameter):
"""Given a URL (ex: "http://www.test.com/path?query=3") and a parameter
(ex: "query"), return the value as a list
:param url: a `str` URL
:param parameter: the URL query we went to extract
:return: a `list` of values for the given query name in the gi... |
def parse_prototype(prototype):
'''Returns a :attr:`FunctionSpec` instance from the input.
'''
val = ' '.join(prototype.splitlines())
f = match(func_pat, val) # match the whole function
if f is None:
raise Exception('Cannot parse function prototype "{}"'.format(val))
ftp, pointer... | def function[parse_prototype, parameter[prototype]]:
constant[Returns a :attr:`FunctionSpec` instance from the input.
]
variable[val] assign[=] call[constant[ ].join, parameter[call[name[prototype].splitlines, parameter[]]]]
variable[f] assign[=] call[name[match], parameter[name[func_pat], n... | keyword[def] identifier[parse_prototype] ( identifier[prototype] ):
literal[string]
identifier[val] = literal[string] . identifier[join] ( identifier[prototype] . identifier[splitlines] ())
identifier[f] = identifier[match] ( identifier[func_pat] , identifier[val] )
keyword[if] identifier[f]... | def parse_prototype(prototype):
"""Returns a :attr:`FunctionSpec` instance from the input.
"""
val = ' '.join(prototype.splitlines())
f = match(func_pat, val) # match the whole function
if f is None:
raise Exception('Cannot parse function prototype "{}"'.format(val)) # depends on [control=... |
def set_nested(self, klist, value):
"""D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v"""
keys = list(klist)
if len(keys) > 0:
curr_dict = self
last_key = keys.pop()
for key in keys:
if not curr_dict.has_key(key) or not isinstance(cu... | def function[set_nested, parameter[self, klist, value]]:
constant[D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v]
variable[keys] assign[=] call[name[list], parameter[name[klist]]]
if compare[call[name[len], parameter[name[keys]]] greater[>] constant[0]] begin[:]
varia... | keyword[def] identifier[set_nested] ( identifier[self] , identifier[klist] , identifier[value] ):
literal[string]
identifier[keys] = identifier[list] ( identifier[klist] )
keyword[if] identifier[len] ( identifier[keys] )> literal[int] :
identifier[curr_dict] = identifier[self... | def set_nested(self, klist, value):
"""D.set_nested((k1, k2,k3, ...), v) -> D[k1][k2][k3] ... = v"""
keys = list(klist)
if len(keys) > 0:
curr_dict = self
last_key = keys.pop()
for key in keys:
if not curr_dict.has_key(key) or not isinstance(curr_dict[key], NestedDict):
... |
def _run_dir(self, run):
"""Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's "run" concept (which is a subdi... | def function[_run_dir, parameter[self, run]]:
constant[Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's ... | keyword[def] identifier[_run_dir] ( identifier[self] , identifier[run] ):
literal[string]
identifier[run] = identifier[run] . identifier[rstrip] ( literal[string] )
keyword[if] literal[string] keyword[not] keyword[in] identifier[run] :
identifier[run] = literal[string] + identifier[run]
... | def _run_dir(self, run):
"""Helper that maps a frontend run name to a profile "run" directory.
The frontend run name consists of the TensorBoard run name (aka the relative
path from the logdir root to the directory containing the data) path-joined
to the Profile plugin's "run" concept (which is a subdi... |
def array(self, name):
"""
Returns the array of tables with the given name.
"""
if name in self._navigable:
if isinstance(self._navigable[name], (list, tuple)):
return self[name]
else:
raise NoArrayFoundError
else:
... | def function[array, parameter[self, name]]:
constant[
Returns the array of tables with the given name.
]
if compare[name[name] in name[self]._navigable] begin[:]
if call[name[isinstance], parameter[call[name[self]._navigable][name[name]], tuple[[<ast.Name object at 0x7da2... | keyword[def] identifier[array] ( identifier[self] , identifier[name] ):
literal[string]
keyword[if] identifier[name] keyword[in] identifier[self] . identifier[_navigable] :
keyword[if] identifier[isinstance] ( identifier[self] . identifier[_navigable] [ identifier[name] ],( identif... | def array(self, name):
"""
Returns the array of tables with the given name.
"""
if name in self._navigable:
if isinstance(self._navigable[name], (list, tuple)):
return self[name] # depends on [control=['if'], data=[]]
else:
raise NoArrayFoundError # depe... |
def _get_limits_instances(self):
"""
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
# from: http://aws.amazon.com/ec2/faqs/
# (On-Demand, Reserved, Spot)
defau... | def function[_get_limits_instances, parameter[self]]:
constant[
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
]
variable[default_limits] assign[=] tuple[[<ast.Constant object at ... | keyword[def] identifier[_get_limits_instances] ( identifier[self] ):
literal[string]
identifier[default_limits] =( literal[int] , literal[int] , literal[int] )
identifier[special_limits] ={
literal[string] :( literal[int] , literal[int] , literal[int] ),
... | def _get_limits_instances(self):
"""
Return a dict of limits for EC2 instances only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
# from: http://aws.amazon.com/ec2/faqs/
# (On-Demand, Reserved, Spot)
default_limits = (20,... |
def add_attachment_viewer_widget(self, attachment_property, custom_title=False, height=None):
"""
Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization.
The widget will be saved to KE-chain.
:param attachment_property: The Attachment Property to which th... | def function[add_attachment_viewer_widget, parameter[self, attachment_property, custom_title, height]]:
constant[
Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization.
The widget will be saved to KE-chain.
:param attachment_property: The Attachment Prop... | keyword[def] identifier[add_attachment_viewer_widget] ( identifier[self] , identifier[attachment_property] , identifier[custom_title] = keyword[False] , identifier[height] = keyword[None] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[attachment_property] , identifier[... | def add_attachment_viewer_widget(self, attachment_property, custom_title=False, height=None):
"""
Add a KE-chain Attachment Viewer (e.g. attachment viewer widget) to the customization.
The widget will be saved to KE-chain.
:param attachment_property: The Attachment Property to which the Vi... |
def has_sources(self, extension=None):
"""Return `True` if this target owns sources; optionally of the given `extension`.
:API: public
:param string extension: Optional suffix of filenames to test for.
:return: `True` if the target contains sources that match the optional extension suffix.
:rtype:... | def function[has_sources, parameter[self, extension]]:
constant[Return `True` if this target owns sources; optionally of the given `extension`.
:API: public
:param string extension: Optional suffix of filenames to test for.
:return: `True` if the target contains sources that match the optional ext... | keyword[def] identifier[has_sources] ( identifier[self] , identifier[extension] = keyword[None] ):
literal[string]
identifier[source_paths] = identifier[self] . identifier[_sources_field] . identifier[source_paths]
keyword[if] keyword[not] identifier[source_paths] :
keyword[return] keyword[... | def has_sources(self, extension=None):
"""Return `True` if this target owns sources; optionally of the given `extension`.
:API: public
:param string extension: Optional suffix of filenames to test for.
:return: `True` if the target contains sources that match the optional extension suffix.
:rtype:... |
def binary(self):
"""Load and return the path to the native engine binary."""
lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE)
lib_path = os.path.join(safe_mkdtemp(), lib_name)
try:
with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp:
# NB: The header stripping code ... | def function[binary, parameter[self]]:
constant[Load and return the path to the native engine binary.]
variable[lib_name] assign[=] call[constant[{}.so].format, parameter[name[NATIVE_ENGINE_MODULE]]]
variable[lib_path] assign[=] call[name[os].path.join, parameter[call[name[safe_mkdtemp], paramet... | keyword[def] identifier[binary] ( identifier[self] ):
literal[string]
identifier[lib_name] = literal[string] . identifier[format] ( identifier[NATIVE_ENGINE_MODULE] )
identifier[lib_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[safe_mkdtemp] (), identifier[lib_name] )
... | def binary(self):
"""Load and return the path to the native engine binary."""
lib_name = '{}.so'.format(NATIVE_ENGINE_MODULE)
lib_path = os.path.join(safe_mkdtemp(), lib_name)
try:
with closing(pkg_resources.resource_stream(__name__, lib_name)) as input_fp:
# NB: The header stripping... |
def shippingaddress_update(self, tid, session, **kwargs):
'''taobao.trade.shippingaddress.update 更改交易的收货地址'''
request = TOPRequest('taobao.trade.shippingaddress.update')
request['tid'] = tid
for k, v in kwargs.iteritems():
if k not in ('receiver_name','receiver_phone','receiv... | def function[shippingaddress_update, parameter[self, tid, session]]:
constant[taobao.trade.shippingaddress.update 更改交易的收货地址]
variable[request] assign[=] call[name[TOPRequest], parameter[constant[taobao.trade.shippingaddress.update]]]
call[name[request]][constant[tid]] assign[=] name[tid]
... | keyword[def] identifier[shippingaddress_update] ( identifier[self] , identifier[tid] , identifier[session] ,** identifier[kwargs] ):
literal[string]
identifier[request] = identifier[TOPRequest] ( literal[string] )
identifier[request] [ literal[string] ]= identifier[tid]
keyword[f... | def shippingaddress_update(self, tid, session, **kwargs):
"""taobao.trade.shippingaddress.update 更改交易的收货地址"""
request = TOPRequest('taobao.trade.shippingaddress.update')
request['tid'] = tid
for (k, v) in kwargs.iteritems():
if k not in ('receiver_name', 'receiver_phone', 'receiver_mobile', 'rec... |
def read_line(self, line):
"""
Match a line of input according to the format specified and return a
tuple of the resulting values
"""
if not self._read_line_init:
self.init_read_line()
match = self._re.match(line)
assert match is not None, f"Format m... | def function[read_line, parameter[self, line]]:
constant[
Match a line of input according to the format specified and return a
tuple of the resulting values
]
if <ast.UnaryOp object at 0x7da18f721750> begin[:]
call[name[self].init_read_line, parameter[]]
v... | keyword[def] identifier[read_line] ( identifier[self] , identifier[line] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_read_line_init] :
identifier[self] . identifier[init_read_line] ()
identifier[match] = identifier[self] . identifier[_re] . i... | def read_line(self, line):
"""
Match a line of input according to the format specified and return a
tuple of the resulting values
"""
if not self._read_line_init:
self.init_read_line() # depends on [control=['if'], data=[]]
match = self._re.match(line)
assert match is no... |
def copy(self, name=None, prefix=None):
"""Copy this :class:`SettingBase`"""
setting = self.__class__.__new__(self.__class__)
setting.__dict__.update(self.__dict__)
# Keep the modified flag?
# setting.modified = False
if prefix and not setting.is_global:
flags... | def function[copy, parameter[self, name, prefix]]:
constant[Copy this :class:`SettingBase`]
variable[setting] assign[=] call[name[self].__class__.__new__, parameter[name[self].__class__]]
call[name[setting].__dict__.update, parameter[name[self].__dict__]]
if <ast.BoolOp object at 0x7da18... | keyword[def] identifier[copy] ( identifier[self] , identifier[name] = keyword[None] , identifier[prefix] = keyword[None] ):
literal[string]
identifier[setting] = identifier[self] . identifier[__class__] . identifier[__new__] ( identifier[self] . identifier[__class__] )
identifier[setting] ... | def copy(self, name=None, prefix=None):
"""Copy this :class:`SettingBase`"""
setting = self.__class__.__new__(self.__class__)
setting.__dict__.update(self.__dict__)
# Keep the modified flag?
# setting.modified = False
if prefix and (not setting.is_global):
flags = setting.flags
#... |
def SetHighlight( self, node, point=None, propagate=True ):
"""Set the currently-highlighted node"""
if node == self.highlightedNode:
return
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.UpdateDrawing()
... | def function[SetHighlight, parameter[self, node, point, propagate]]:
constant[Set the currently-highlighted node]
if compare[name[node] equal[==] name[self].highlightedNode] begin[:]
return[None]
name[self].highlightedNode assign[=] name[node]
call[name[self].UpdateDrawing, param... | keyword[def] identifier[SetHighlight] ( identifier[self] , identifier[node] , identifier[point] = keyword[None] , identifier[propagate] = keyword[True] ):
literal[string]
keyword[if] identifier[node] == identifier[self] . identifier[highlightedNode] :
keyword[return]
identif... | def SetHighlight(self, node, point=None, propagate=True):
"""Set the currently-highlighted node"""
if node == self.highlightedNode:
return # depends on [control=['if'], data=[]]
self.highlightedNode = node
# TODO: restrict refresh to the squares for previous node and new node...
self.Update... |
def display_html(*objs, **kwargs):
"""Display the HTML representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to
display.
raw : bool
Are the data objects raw data or Python objects that need to b... | def function[display_html, parameter[]]:
constant[Display the HTML representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to
display.
raw : bool
Are the data objects raw data or Python object... | keyword[def] identifier[display_html] (* identifier[objs] ,** identifier[kwargs] ):
literal[string]
identifier[raw] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[False] )
keyword[if] identifier[raw] :
keyword[for] identifier[obj] keyword[in] identifier[objs] :
... | def display_html(*objs, **kwargs):
"""Display the HTML representation of an object.
Parameters
----------
objs : tuple of objects
The Python objects to display, or if raw=True raw HTML data to
display.
raw : bool
Are the data objects raw data or Python objects that need to b... |
def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs):
"""Replace TaxClass
Replace all attributes of TaxClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_tax_class_by... | def function[replace_tax_class_by_id, parameter[cls, tax_class_id, tax_class]]:
constant[Replace TaxClass
Replace all attributes of TaxClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.rep... | keyword[def] identifier[replace_tax_class_by_id] ( identifier[cls] , identifier[tax_class_id] , identifier[tax_class] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs):
"""Replace TaxClass
Replace all attributes of TaxClass
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_tax_class_by_id(... |
def getExpressionLevelById(self, expressionId):
"""
:param expressionId: the ExpressionLevel ID
:return: dictionary representing an ExpressionLevel object,
or None if no match is found.
"""
sql = ("SELECT * FROM Expression WHERE id = ?")
query = self._dbconn.e... | def function[getExpressionLevelById, parameter[self, expressionId]]:
constant[
:param expressionId: the ExpressionLevel ID
:return: dictionary representing an ExpressionLevel object,
or None if no match is found.
]
variable[sql] assign[=] constant[SELECT * FROM Expres... | keyword[def] identifier[getExpressionLevelById] ( identifier[self] , identifier[expressionId] ):
literal[string]
identifier[sql] =( literal[string] )
identifier[query] = identifier[self] . identifier[_dbconn] . identifier[execute] ( identifier[sql] ,( identifier[expressionId] ,))
... | def getExpressionLevelById(self, expressionId):
"""
:param expressionId: the ExpressionLevel ID
:return: dictionary representing an ExpressionLevel object,
or None if no match is found.
"""
sql = 'SELECT * FROM Expression WHERE id = ?'
query = self._dbconn.execute(sql, (e... |
def combine_first(self, other):
"""
Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
The value(s) to be combined with the `Series`.
Returns
-------
Series
The result of combin... | def function[combine_first, parameter[self, other]]:
constant[
Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
The value(s) to be combined with the `Series`.
Returns
-------
Series
... | keyword[def] identifier[combine_first] ( identifier[self] , identifier[other] ):
literal[string]
identifier[new_index] = identifier[self] . identifier[index] . identifier[union] ( identifier[other] . identifier[index] )
identifier[this] = identifier[self] . identifier[reindex] ( identifier... | def combine_first(self, other):
"""
Combine Series values, choosing the calling Series's values first.
Parameters
----------
other : Series
The value(s) to be combined with the `Series`.
Returns
-------
Series
The result of combining ... |
def source_roots(self, document_path):
"""Return the source roots for the given document."""
files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or []
return [os.path.dirname(setup_py) for setup_py in files] | def function[source_roots, parameter[self, document_path]]:
constant[Return the source roots for the given document.]
variable[files] assign[=] <ast.BoolOp object at 0x7da18f723f40>
return[<ast.ListComp object at 0x7da18f721990>] | keyword[def] identifier[source_roots] ( identifier[self] , identifier[document_path] ):
literal[string]
identifier[files] = identifier[_utils] . identifier[find_parents] ( identifier[self] . identifier[_root_path] , identifier[document_path] ,[ literal[string] ]) keyword[or] []
keyword[ret... | def source_roots(self, document_path):
"""Return the source roots for the given document."""
files = _utils.find_parents(self._root_path, document_path, ['setup.py']) or []
return [os.path.dirname(setup_py) for setup_py in files] |
def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d | def function[sleep, parameter[self, delay]]:
constant[
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
]
variable[d] assign[=] call[name[Deferred], parameter[]]
call[call[name[self]._get_loop, parameter[]].callLater... | keyword[def] identifier[sleep] ( identifier[self] , identifier[delay] ):
literal[string]
identifier[d] = identifier[Deferred] ()
identifier[self] . identifier[_get_loop] (). identifier[callLater] ( identifier[delay] , identifier[d] . identifier[callback] , keyword[None] )
keyword[... | def sleep(self, delay):
"""
Inline sleep for use in co-routines.
:param delay: Time to sleep in seconds.
:type delay: float
"""
d = Deferred()
self._get_loop().callLater(delay, d.callback, None)
return d |
def angle_to_name(angle, segments=8, abbr=False):
"""Convert angle in to direction name.
Args:
angle (float): Angle in degrees to convert to direction name
segments (int): Number of segments to split compass in to
abbr (bool): Whether to return abbreviated direction string
Returns:... | def function[angle_to_name, parameter[angle, segments, abbr]]:
constant[Convert angle in to direction name.
Args:
angle (float): Angle in degrees to convert to direction name
segments (int): Number of segments to split compass in to
abbr (bool): Whether to return abbreviated directi... | keyword[def] identifier[angle_to_name] ( identifier[angle] , identifier[segments] = literal[int] , identifier[abbr] = keyword[False] ):
literal[string]
keyword[if] identifier[segments] == literal[int] :
identifier[string] = identifier[COMPASS_NAMES] [ identifier[int] (( identifier[angle] + litera... | def angle_to_name(angle, segments=8, abbr=False):
"""Convert angle in to direction name.
Args:
angle (float): Angle in degrees to convert to direction name
segments (int): Number of segments to split compass in to
abbr (bool): Whether to return abbreviated direction string
Returns:... |
def table_api_get(self, *paths, **kparams):
""" helper to make GET /api/now/v1/table requests """
url = self.flattened_params_url("/api/now/v1/table", *paths, **kparams)
rjson = self.req("get", url).text
return json.loads(rjson) | def function[table_api_get, parameter[self]]:
constant[ helper to make GET /api/now/v1/table requests ]
variable[url] assign[=] call[name[self].flattened_params_url, parameter[constant[/api/now/v1/table], <ast.Starred object at 0x7da18dc99300>]]
variable[rjson] assign[=] call[name[self].req, par... | keyword[def] identifier[table_api_get] ( identifier[self] ,* identifier[paths] ,** identifier[kparams] ):
literal[string]
identifier[url] = identifier[self] . identifier[flattened_params_url] ( literal[string] ,* identifier[paths] ,** identifier[kparams] )
identifier[rjson] = identifier[se... | def table_api_get(self, *paths, **kparams):
""" helper to make GET /api/now/v1/table requests """
url = self.flattened_params_url('/api/now/v1/table', *paths, **kparams)
rjson = self.req('get', url).text
return json.loads(rjson) |
def _evaluate(self,R,z,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z, phi
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(R,... | def function[_evaluate, parameter[self, R, z, phi, t]]:
constant[
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z, phi
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... | keyword[def] identifier[_evaluate] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
identifier[Rdist] = identifier[_cylR] ( identifier[R] , identifier[phi] , identifier[self] . identifier[_orb] . identifie... | def _evaluate(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,z, phi
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
Phi(... |
def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool:
"""Extract the variable substitution for the given pattern and subject.
This assumes that subject and pattern already match when being considered as linear.
Also, they both must be :ter... | def function[extract_substitution, parameter[self, subject, pattern]]:
constant[Extract the variable substitution for the given pattern and subject.
This assumes that subject and pattern already match when being considered as linear.
Also, they both must be :term:`syntactic`, as sequence variab... | keyword[def] identifier[extract_substitution] ( identifier[self] , identifier[subject] : literal[string] , identifier[pattern] : literal[string] )-> identifier[bool] :
literal[string]
keyword[if] identifier[getattr] ( identifier[pattern] , literal[string] , keyword[False] ):
keyword[t... | def extract_substitution(self, subject: 'expressions.Expression', pattern: 'expressions.Expression') -> bool:
"""Extract the variable substitution for the given pattern and subject.
This assumes that subject and pattern already match when being considered as linear.
Also, they both must be :term:`s... |
def encode(self, envelope, session, aes_cipher=None, **kwargs):
""" :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation.
:param envelope: original envelope
:param session: original session
:param aes_cipher: cipher to use
:param kwargs: additional arguments
:return: WMessengerBytesEnvelop... | def function[encode, parameter[self, envelope, session, aes_cipher]]:
constant[ :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation.
:param envelope: original envelope
:param session: original session
:param aes_cipher: cipher to use
:param kwargs: additional arguments
:return: WMes... | keyword[def] identifier[encode] ( identifier[self] , identifier[envelope] , identifier[session] , identifier[aes_cipher] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[WMessengerBytesEnvelope] ( identifier[aes_cipher] . identifier[encrypt] ( identifier[envelope] . identif... | def encode(self, envelope, session, aes_cipher=None, **kwargs):
""" :meth:`.WMessengerOnionCoderLayerProto.encode` method implementation.
:param envelope: original envelope
:param session: original session
:param aes_cipher: cipher to use
:param kwargs: additional arguments
:return: WMessengerBytesEnvel... |
def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
'''Return list N+1 points representing N line segments on bezier curve
defined by control points P.
'''
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
... | def function[pts_on_bezier_curve, parameter[P, n_seg]]:
constant[Return list N+1 points representing N line segments on bezier curve
defined by control points P.
]
assert[call[name[isinstance], parameter[name[P], name[list]]]]
assert[compare[call[name[len], parameter[name[P]]] greater[>] constant[... | keyword[def] identifier[pts_on_bezier_curve] ( identifier[P] =[( literal[int] , literal[int] )], identifier[n_seg] = literal[int] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[P] , identifier[list] )
keyword[assert] identifier[len] ( identifier[P] )> literal[int]
keywo... | def pts_on_bezier_curve(P=[(0.0, 0.0)], n_seg=0):
"""Return list N+1 points representing N line segments on bezier curve
defined by control points P.
"""
assert isinstance(P, list)
assert len(P) > 0
for p in P:
assert isinstance(p, tuple)
for i in p:
assert len(p) > 1
... |
def _normalize_date_SQL(self, field_name, field_kwargs, symbol):
"""
allow extracting information from date
http://www.sqlite.org/lang_datefunc.html
"""
fstrs = []
k_opts = {
'day': "CAST(strftime('%d', {}) AS integer)",
'hour': "CAST(strftime('%H... | def function[_normalize_date_SQL, parameter[self, field_name, field_kwargs, symbol]]:
constant[
allow extracting information from date
http://www.sqlite.org/lang_datefunc.html
]
variable[fstrs] assign[=] list[[]]
variable[k_opts] assign[=] dictionary[[<ast.Constant objec... | keyword[def] identifier[_normalize_date_SQL] ( identifier[self] , identifier[field_name] , identifier[field_kwargs] , identifier[symbol] ):
literal[string]
identifier[fstrs] =[]
identifier[k_opts] ={
literal[string] : literal[string] ,
literal[string] : literal[string] ,
... | def _normalize_date_SQL(self, field_name, field_kwargs, symbol):
"""
allow extracting information from date
http://www.sqlite.org/lang_datefunc.html
"""
fstrs = [] # day of year
# YYYY-MM-DD
# day of week 0 = sunday
k_opts = {'day': "CAST(strftime('%d', {}) AS integer)", 'h... |
def getcoordinates(self, tree, location):
"""Gets coordinates from a specific element in PLIP XML"""
return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location)) | def function[getcoordinates, parameter[self, tree, location]]:
constant[Gets coordinates from a specific element in PLIP XML]
return[call[name[tuple], parameter[<ast.GeneratorExp object at 0x7da18f09e0e0>]]] | keyword[def] identifier[getcoordinates] ( identifier[self] , identifier[tree] , identifier[location] ):
literal[string]
keyword[return] identifier[tuple] ( identifier[float] ( identifier[x] ) keyword[for] identifier[x] keyword[in] identifier[tree] . identifier[xpath] ( literal[string] % identif... | def getcoordinates(self, tree, location):
"""Gets coordinates from a specific element in PLIP XML"""
return tuple((float(x) for x in tree.xpath('.//%s/*/text()' % location))) |
def class_result(classname):
"""Errcheck function. Returns a function that creates the specified class.
"""
def wrap_errcheck(result, func, arguments):
if result is None:
return None
return classname(result)
return wrap_errcheck | def function[class_result, parameter[classname]]:
constant[Errcheck function. Returns a function that creates the specified class.
]
def function[wrap_errcheck, parameter[result, func, arguments]]:
if compare[name[result] is constant[None]] begin[:]
return[constant[None]]... | keyword[def] identifier[class_result] ( identifier[classname] ):
literal[string]
keyword[def] identifier[wrap_errcheck] ( identifier[result] , identifier[func] , identifier[arguments] ):
keyword[if] identifier[result] keyword[is] keyword[None] :
keyword[return] keyword[None]
... | def class_result(classname):
"""Errcheck function. Returns a function that creates the specified class.
"""
def wrap_errcheck(result, func, arguments):
if result is None:
return None # depends on [control=['if'], data=[]]
return classname(result)
return wrap_errcheck |
def clear_file(self, label):
"""stub"""
rm = self.my_osid_object_form._get_provider_manager('REPOSITORY')
catalog_id_str = ''
if 'assignedBankIds' in self.my_osid_object_form._my_map:
catalog_id_str = self.my_osid_object_form._my_map['assignedBankIds'][0]
elif 'assi... | def function[clear_file, parameter[self, label]]:
constant[stub]
variable[rm] assign[=] call[name[self].my_osid_object_form._get_provider_manager, parameter[constant[REPOSITORY]]]
variable[catalog_id_str] assign[=] constant[]
if compare[constant[assignedBankIds] in name[self].my_osid_obj... | keyword[def] identifier[clear_file] ( identifier[self] , identifier[label] ):
literal[string]
identifier[rm] = identifier[self] . identifier[my_osid_object_form] . identifier[_get_provider_manager] ( literal[string] )
identifier[catalog_id_str] = literal[string]
keyword[if] li... | def clear_file(self, label):
"""stub"""
rm = self.my_osid_object_form._get_provider_manager('REPOSITORY')
catalog_id_str = ''
if 'assignedBankIds' in self.my_osid_object_form._my_map:
catalog_id_str = self.my_osid_object_form._my_map['assignedBankIds'][0] # depends on [control=['if'], data=[]]
... |
def Reynolds_factor(FL, C, d, Rev, full_trim=True):
r'''Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534 calculations.
If f... | def function[Reynolds_factor, parameter[FL, C, d, Rev, full_trim]]:
constant[Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534... | keyword[def] identifier[Reynolds_factor] ( identifier[FL] , identifier[C] , identifier[d] , identifier[Rev] , identifier[full_trim] = keyword[True] ):
literal[string]
keyword[if] identifier[full_trim] :
identifier[n1] = identifier[N2] /( identifier[min] ( identifier[C] / identifier[d] ** literal[... | def Reynolds_factor(FL, C, d, Rev, full_trim=True):
"""Calculates the Reynolds number factor `FR` for a valve with a Reynolds
number `Rev`, diameter `d`, flow coefficient `C`, liquid pressure recovery
factor `FL`, and with either full or reduced trim, all according to
IEC 60534 calculations.
If fu... |
def _set_value(self, entity, value):
"""Internal helper to set a value in an entity for a Property.
This performs validation first. For a repeated Property the value
should be a list.
"""
if entity._projection:
raise ReadonlyPropertyError(
'You cannot set property values of a proje... | def function[_set_value, parameter[self, entity, value]]:
constant[Internal helper to set a value in an entity for a Property.
This performs validation first. For a repeated Property the value
should be a list.
]
if name[entity]._projection begin[:]
<ast.Raise object at 0x7da20c6a8... | keyword[def] identifier[_set_value] ( identifier[self] , identifier[entity] , identifier[value] ):
literal[string]
keyword[if] identifier[entity] . identifier[_projection] :
keyword[raise] identifier[ReadonlyPropertyError] (
literal[string] )
keyword[if] identifier[self] . identifier[... | def _set_value(self, entity, value):
"""Internal helper to set a value in an entity for a Property.
This performs validation first. For a repeated Property the value
should be a list.
"""
if entity._projection:
raise ReadonlyPropertyError('You cannot set property values of a projection ent... |
def generate_search_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams."""
parser = subparsers.add_parser(
'search', description=constants.SEARCH_DESCRIPTION,
epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter,
... | def function[generate_search_subparser, parameter[subparsers]]:
constant[Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams.]
variable[parser] assign[=] call[name[subparsers].add_parser, parameter[constant[search]]]
call[name[parser].set_defaults, param... | keyword[def] identifier[generate_search_subparser] ( identifier[subparsers] ):
literal[string]
identifier[parser] = identifier[subparsers] . identifier[add_parser] (
literal[string] , identifier[description] = identifier[constants] . identifier[SEARCH_DESCRIPTION] ,
identifier[epilog] = identifie... | def generate_search_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to generate search
results for a set of n-grams."""
parser = subparsers.add_parser('search', description=constants.SEARCH_DESCRIPTION, epilog=constants.SEARCH_EPILOG, formatter_class=ParagraphFormatter, help=constants.SE... |
def emitCurrentRecordEdited(self):
"""
Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time.
"""
if self._changedRecord == -1:
return
if self.signalsBlocke... | def function[emitCurrentRecordEdited, parameter[self]]:
constant[
Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time.
]
if compare[name[self]._changedRecord equal[==] <ast.UnaryOp object at ... | keyword[def] identifier[emitCurrentRecordEdited] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_changedRecord] ==- literal[int] :
keyword[return]
keyword[if] identifier[self] . identifier[signalsBlocked] ():
keyword[retu... | def emitCurrentRecordEdited(self):
"""
Emits the current record edited signal for this combobox, provided the
signals aren't blocked and the record has changed since the last time.
"""
if self._changedRecord == -1:
return # depends on [control=['if'], data=[]]
if self.signal... |
def fork(self, **args):
'''
fork any gist by providing gistID or gistname(for authenticated user)
'''
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name)
elif 'id' in args:
self.gist_id = args['id']
else:
raise Exception('Either provide authenticated user... | def function[fork, parameter[self]]:
constant[
fork any gist by providing gistID or gistname(for authenticated user)
]
if compare[constant[name] in name[args]] begin[:]
name[self].gist_name assign[=] call[name[args]][constant[name]]
name[self].gist_id assign[=] call[n... | keyword[def] identifier[fork] ( identifier[self] ,** identifier[args] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[args] :
identifier[self] . identifier[gist_name] = identifier[args] [ literal[string] ]
identifier[self] . identifier[gist_id] = identifier[self] . identifier[g... | def fork(self, **args):
"""
fork any gist by providing gistID or gistname(for authenticated user)
"""
if 'name' in args:
self.gist_name = args['name']
self.gist_id = self.getMyID(self.gist_name) # depends on [control=['if'], data=['args']]
elif 'id' in args:
self.gist_id = args[... |
def artist_to_qfont(artist):
"""Convert a :class:`matplotlib.text.Text` artist to a QFont object
Parameters
----------
artist: matplotlib.text.Text
The text artist, e.g. an axes title
Returns
-------
PyQt5.QtGui.QFont
The QFont object"""
... | def function[artist_to_qfont, parameter[artist]]:
constant[Convert a :class:`matplotlib.text.Text` artist to a QFont object
Parameters
----------
artist: matplotlib.text.Text
The text artist, e.g. an axes title
Returns
-------
PyQt5.QtGui.QFont
... | keyword[def] identifier[artist_to_qfont] ( identifier[artist] ):
literal[string]
identifier[size] = identifier[int] ( identifier[artist] . identifier[get_size] ())
identifier[weight] = identifier[mpl_weight2qt] ( identifier[artist] . identifier[get_weight] ())
identifier[italic] =... | def artist_to_qfont(artist):
"""Convert a :class:`matplotlib.text.Text` artist to a QFont object
Parameters
----------
artist: matplotlib.text.Text
The text artist, e.g. an axes title
Returns
-------
PyQt5.QtGui.QFont
The QFont object"""
... |
def update_access_key(self, access_key_id, status, user_name=None):
"""
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_name is not specified, t... | def function[update_access_key, parameter[self, access_key_id, status, user_name]]:
constant[
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_na... | keyword[def] identifier[update_access_key] ( identifier[self] , identifier[access_key_id] , identifier[status] , identifier[user_name] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : identifier[access_key_id] ,
literal[string] : identifier[status] }
keyw... | def update_access_key(self, access_key_id, status, user_name=None):
"""
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_name is not specified, the u... |
def _are_safety_checks_disabled(self, caller=u"unknown_function"):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False
self.log_warn([u"Saf... | def function[_are_safety_checks_disabled, parameter[self, caller]]:
constant[
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
]
if name[self].rconf.safety_checks begin[:]
return[constant[False]]
... | keyword[def] identifier[_are_safety_checks_disabled] ( identifier[self] , identifier[caller] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[rconf] . identifier[safety_checks] :
keyword[return] keyword[False]
identifier[self] . identifier[log_... | def _are_safety_checks_disabled(self, caller=u'unknown_function'):
"""
Return ``True`` if safety checks are disabled.
:param string caller: the name of the caller function
:rtype: bool
"""
if self.rconf.safety_checks:
return False # depends on [control=['if'], data=[]]
... |
def map(self, func):
"""
A lazy way to apply the given function to each element in the stream.
Useful for type casting, like:
>>> from audiolazy import count
>>> count().take(5)
[0, 1, 2, 3, 4]
>>> my_stream = count().map(float)
>>> my_stream.take(5) # A float counter
[0.0, 1.0, 2.0... | def function[map, parameter[self, func]]:
constant[
A lazy way to apply the given function to each element in the stream.
Useful for type casting, like:
>>> from audiolazy import count
>>> count().take(5)
[0, 1, 2, 3, 4]
>>> my_stream = count().map(float)
>>> my_stream.take(5) # A f... | keyword[def] identifier[map] ( identifier[self] , identifier[func] ):
literal[string]
identifier[self] . identifier[_data] = identifier[xmap] ( identifier[func] , identifier[self] . identifier[_data] )
keyword[return] identifier[self] | def map(self, func):
"""
A lazy way to apply the given function to each element in the stream.
Useful for type casting, like:
>>> from audiolazy import count
>>> count().take(5)
[0, 1, 2, 3, 4]
>>> my_stream = count().map(float)
>>> my_stream.take(5) # A float counter
[0.0, 1.0, 2.0... |
def custom_token(spacy_token) -> Token:
"""
Function for token attributes extension, methods extension
Use set_extension method.
Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes
"""
"""Add custom attributes"... | def function[custom_token, parameter[spacy_token]]:
constant[
Function for token attributes extension, methods extension
Use set_extension method.
Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes
]
constant[A... | keyword[def] identifier[custom_token] ( identifier[spacy_token] )-> identifier[Token] :
literal[string]
literal[string]
literal[string]
keyword[def] identifier[get_shape] ( identifier[token] ):
identifier[full_shape] = literal[string]
keyword[for] ... | def custom_token(spacy_token) -> Token:
"""
Function for token attributes extension, methods extension
Use set_extension method.
Reference: https://spacy.io/api/token, https://spacy.io/usage/processing-pipelines#custom-components-attributes
"""
'Add custom attributes'
'Add f... |
def new_media_status(self, media_status):
"""Handle reception of a new MediaStatus."""
casts = self._casts
group_members = self._mz.members
for member_uuid in group_members:
if member_uuid not in casts:
continue
for listener in list(casts[member_uu... | def function[new_media_status, parameter[self, media_status]]:
constant[Handle reception of a new MediaStatus.]
variable[casts] assign[=] name[self]._casts
variable[group_members] assign[=] name[self]._mz.members
for taget[name[member_uuid]] in starred[name[group_members]] begin[:]
... | keyword[def] identifier[new_media_status] ( identifier[self] , identifier[media_status] ):
literal[string]
identifier[casts] = identifier[self] . identifier[_casts]
identifier[group_members] = identifier[self] . identifier[_mz] . identifier[members]
keyword[for] identifier[memb... | def new_media_status(self, media_status):
"""Handle reception of a new MediaStatus."""
casts = self._casts
group_members = self._mz.members
for member_uuid in group_members:
if member_uuid not in casts:
continue # depends on [control=['if'], data=[]]
for listener in list(cas... |
def cli(ctx):
"""Saves a new command"""
cmd = click.prompt('Command')
desc = click.prompt('Description ')
alias = click.prompt('Alias (optional)', default='')
utils.save_command(cmd, desc, alias)
utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc)) | def function[cli, parameter[ctx]]:
constant[Saves a new command]
variable[cmd] assign[=] call[name[click].prompt, parameter[constant[Command]]]
variable[desc] assign[=] call[name[click].prompt, parameter[constant[Description ]]]
variable[alias] assign[=] call[name[click].prompt, paramete... | keyword[def] identifier[cli] ( identifier[ctx] ):
literal[string]
identifier[cmd] = identifier[click] . identifier[prompt] ( literal[string] )
identifier[desc] = identifier[click] . identifier[prompt] ( literal[string] )
identifier[alias] = identifier[click] . identifier[prompt] ( literal[string]... | def cli(ctx):
"""Saves a new command"""
cmd = click.prompt('Command')
desc = click.prompt('Description ')
alias = click.prompt('Alias (optional)', default='')
utils.save_command(cmd, desc, alias)
utils.log(ctx, 'Saved the new command - {} - with the description - {}.'.format(cmd, desc)) |
def hidden_basic_auth(user="user", passwd="passwd"):
"""Prompts the user for authorization using HTTP Basic Auth.
---
tags:
- Auth
parameters:
- in: path
name: user
type: string
- in: path
name: passwd
type: string
produces:
- application/json
... | def function[hidden_basic_auth, parameter[user, passwd]]:
constant[Prompts the user for authorization using HTTP Basic Auth.
---
tags:
- Auth
parameters:
- in: path
name: user
type: string
- in: path
name: passwd
type: string
produces:
- ap... | keyword[def] identifier[hidden_basic_auth] ( identifier[user] = literal[string] , identifier[passwd] = literal[string] ):
literal[string]
keyword[if] keyword[not] identifier[check_basic_auth] ( identifier[user] , identifier[passwd] ):
keyword[return] identifier[status_code] ( literal[int] )
... | def hidden_basic_auth(user='user', passwd='passwd'):
"""Prompts the user for authorization using HTTP Basic Auth.
---
tags:
- Auth
parameters:
- in: path
name: user
type: string
- in: path
name: passwd
type: string
produces:
- application/json
... |
def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_fo... | def function[get_field_name_for, parameter[cls, field_name, dynamic_part]]:
constant[
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
]
variable[field] assign[=] call[name[cls].... | keyword[def] identifier[get_field_name_for] ( identifier[cls] , identifier[field_name] , identifier[dynamic_part] ):
literal[string]
identifier[field] = identifier[cls] . identifier[get_field] ( identifier[field_name] )
keyword[return] identifier[field] . identifier[get_name_for] ( identi... | def get_field_name_for(cls, field_name, dynamic_part):
"""
Given the name of a dynamic field, and a dynamic part, return the
name of the final dynamic field to use. It will then be used with
get_field.
"""
field = cls.get_field(field_name)
return field.get_name_for(dynamic_pa... |
def add_line(self, moves: Iterable[chess.Move], *, comment: str = "", starting_comment: str = "", nags: Iterable[int] = ()) -> "GameNode":
"""
Creates a sequence of child nodes for the given list of moves.
Adds *comment* and *nags* to the last node of the line and returns it.
"""
... | def function[add_line, parameter[self, moves]]:
constant[
Creates a sequence of child nodes for the given list of moves.
Adds *comment* and *nags* to the last node of the line and returns it.
]
variable[node] assign[=] name[self]
for taget[name[move]] in starred[name[move... | keyword[def] identifier[add_line] ( identifier[self] , identifier[moves] : identifier[Iterable] [ identifier[chess] . identifier[Move] ],*, identifier[comment] : identifier[str] = literal[string] , identifier[starting_comment] : identifier[str] = literal[string] , identifier[nags] : identifier[Iterable] [ identifier[... | def add_line(self, moves: Iterable[chess.Move], *, comment: str='', starting_comment: str='', nags: Iterable[int]=()) -> 'GameNode':
"""
Creates a sequence of child nodes for the given list of moves.
Adds *comment* and *nags* to the last node of the line and returns it.
"""
node = self
... |
def read_fastas(input_files):
"""
Read the tumor and normal fastas into a joint dict.
:param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files.
:return: The read fastas in a dictionary of tuples
:rtype: dict
"""
tumor_file = [y for x, y in input_files.ite... | def function[read_fastas, parameter[input_files]]:
constant[
Read the tumor and normal fastas into a joint dict.
:param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files.
:return: The read fastas in a dictionary of tuples
:rtype: dict
]
variable[t... | keyword[def] identifier[read_fastas] ( identifier[input_files] ):
literal[string]
identifier[tumor_file] =[ identifier[y] keyword[for] identifier[x] , identifier[y] keyword[in] identifier[input_files] . identifier[items] () keyword[if] identifier[x] . identifier[startswith] ( literal[string] )][ liter... | def read_fastas(input_files):
"""
Read the tumor and normal fastas into a joint dict.
:param dict input_files: A dict containing filename: filepath for T_ and N_ transgened files.
:return: The read fastas in a dictionary of tuples
:rtype: dict
"""
tumor_file = [y for (x, y) in input_files.i... |
def GetCustomJsonFieldMapping(message_type, python_name=None, json_name=None):
"""Return the appropriate remapping for the given field, or None."""
return _FetchRemapping(message_type, 'field',
python_name=python_name, json_name=json_name,
mappings=_JSON_FIE... | def function[GetCustomJsonFieldMapping, parameter[message_type, python_name, json_name]]:
constant[Return the appropriate remapping for the given field, or None.]
return[call[name[_FetchRemapping], parameter[name[message_type], constant[field]]]] | keyword[def] identifier[GetCustomJsonFieldMapping] ( identifier[message_type] , identifier[python_name] = keyword[None] , identifier[json_name] = keyword[None] ):
literal[string]
keyword[return] identifier[_FetchRemapping] ( identifier[message_type] , literal[string] ,
identifier[python_name] = ident... | def GetCustomJsonFieldMapping(message_type, python_name=None, json_name=None):
"""Return the appropriate remapping for the given field, or None."""
return _FetchRemapping(message_type, 'field', python_name=python_name, json_name=json_name, mappings=_JSON_FIELD_MAPPINGS) |
def post_comment(self, message):
"""
Comments on an issue, not on a particular line.
"""
report_url = (
'https://api.github.com/repos/%s/issues/%s/comments'
% (self.repo_name, self.pr_number)
)
result = self.requester.post(report_url, {'body': mess... | def function[post_comment, parameter[self, message]]:
constant[
Comments on an issue, not on a particular line.
]
variable[report_url] assign[=] binary_operation[constant[https://api.github.com/repos/%s/issues/%s/comments] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object a... | keyword[def] identifier[post_comment] ( identifier[self] , identifier[message] ):
literal[string]
identifier[report_url] =(
literal[string]
%( identifier[self] . identifier[repo_name] , identifier[self] . identifier[pr_number] )
)
identifier[result] = identifier[s... | def post_comment(self, message):
"""
Comments on an issue, not on a particular line.
"""
report_url = 'https://api.github.com/repos/%s/issues/%s/comments' % (self.repo_name, self.pr_number)
result = self.requester.post(report_url, {'body': message})
if result.status_code >= 400:
... |
def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
array = tuple((self._clean_formula(v),) for v in formulas)
self._get_target... | def function[__set_formulas, parameter[self, formulas]]:
constant[
Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
]
variable[array] assign[=] call[name[tuple], parameter[<ast... | keyword[def] identifier[__set_formulas] ( identifier[self] , identifier[formulas] ):
literal[string]
identifier[array] = identifier[tuple] (( identifier[self] . identifier[_clean_formula] ( identifier[v] ),) keyword[for] identifier[v] keyword[in] identifier[formulas] )
identifier[self] ... | def __set_formulas(self, formulas):
"""
Sets formulas in this cell range from an iterable.
Any cell values can be set using this method. Actual formulas must
start with an equal sign.
"""
array = tuple(((self._clean_formula(v),) for v in formulas))
self._get_target().setForm... |
def _get_call_summary(self, call, index=0, inspect_packages=True):
'''
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -... | def function[_get_call_summary, parameter[self, call, index, inspect_packages]]:
constant[
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_in... | keyword[def] identifier[_get_call_summary] ( identifier[self] , identifier[call] , identifier[index] = literal[int] , identifier[inspect_packages] = keyword[True] ):
literal[string]
identifier[call_info] = identifier[call] . identifier[info]
identifier[inspect_regex] = identifier[re] . id... | def _get_call_summary(self, call, index=0, inspect_packages=True):
"""
get a call summary
a call summary is a nicely formatted string synopsis of the call
handy for backtraces
since -- 7-6-12
call_info -- dict -- the dict returned from _get_call_info()
index -- in... |
def covariance_lagged(data=None, c00=True, c0t=True, ctt=False, remove_constant_mean=None, remove_data_mean=False,
reversible=False, bessel=True, lag=0, weights="empirical", stride=1, skip=0, chunksize=None,
ncov_max=float('inf'), column_selection=None, diag_only=False):
... | def function[covariance_lagged, parameter[data, c00, c0t, ctt, remove_constant_mean, remove_data_mean, reversible, bessel, lag, weights, stride, skip, chunksize, ncov_max, column_selection, diag_only]]:
constant[Compute lagged covariances between time series. If data is available as an array of size (TxN), wher... | keyword[def] identifier[covariance_lagged] ( identifier[data] = keyword[None] , identifier[c00] = keyword[True] , identifier[c0t] = keyword[True] , identifier[ctt] = keyword[False] , identifier[remove_constant_mean] = keyword[None] , identifier[remove_data_mean] = keyword[False] ,
identifier[reversible] = keyword[Fa... | def covariance_lagged(data=None, c00=True, c0t=True, ctt=False, remove_constant_mean=None, remove_data_mean=False, reversible=False, bessel=True, lag=0, weights='empirical', stride=1, skip=0, chunksize=None, ncov_max=float('inf'), column_selection=None, diag_only=False):
"""Compute lagged covariances between time s... |
def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._d... | def function[remove_done_callback, parameter[self, func]]:
constant[Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
]
if <ast... | keyword[def] identifier[remove_done_callback] ( identifier[self] , identifier[func] ):
literal[string]
keyword[if] identifier[self] . identifier[_done] keyword[is] keyword[None] keyword[or] identifier[self] . identifier[_done] . identifier[is_set] ():
keyword[raise] identifier[Va... | def remove_done_callback(self, func):
"""Remove a callback from the long running operation.
:param callable func: The function to be removed from the callbacks.
:raises: ValueError if the long running operation has already
completed.
"""
if self._done is None or self._done.is_s... |
def render(self, context, instance, placeholder):
''' Allows this plugin to use templates designed for a list of locations. '''
context = super(StatsGraphPlugin,self).render(context,instance,placeholder)
# Javascript makes it difficult to calculate date/time differences, so instead
... | def function[render, parameter[self, context, instance, placeholder]]:
constant[ Allows this plugin to use templates designed for a list of locations. ]
variable[context] assign[=] call[call[name[super], parameter[name[StatsGraphPlugin], name[self]]].render, parameter[name[context], name[instance], name... | keyword[def] identifier[render] ( identifier[self] , identifier[context] , identifier[instance] , identifier[placeholder] ):
literal[string]
identifier[context] = identifier[super] ( identifier[StatsGraphPlugin] , identifier[self] ). identifier[render] ( identifier[context] , identifier[instance]... | def render(self, context, instance, placeholder):
""" Allows this plugin to use templates designed for a list of locations. """
context = super(StatsGraphPlugin, self).render(context, instance, placeholder) # Javascript makes it difficult to calculate date/time differences, so instead
# pass the most usefu... |
def identify_core(core):
"""Identify the polynomial argument."""
for datatype, identifier in {
int: _identify_scaler,
numpy.int8: _identify_scaler,
numpy.int16: _identify_scaler,
numpy.int32: _identify_scaler,
numpy.int64: _identify_scaler,
... | def function[identify_core, parameter[core]]:
constant[Identify the polynomial argument.]
for taget[tuple[[<ast.Name object at 0x7da18ede5960>, <ast.Name object at 0x7da18ede67a0>]]] in starred[call[dictionary[[<ast.Name object at 0x7da18ede5180>, <ast.Attribute object at 0x7da18ede5540>, <ast.Attribute... | keyword[def] identifier[identify_core] ( identifier[core] ):
literal[string]
keyword[for] identifier[datatype] , identifier[identifier] keyword[in] {
identifier[int] : identifier[_identify_scaler] ,
identifier[numpy] . identifier[int8] : identifier[_identify_scaler] ,
identifier[numpy] . i... | def identify_core(core):
"""Identify the polynomial argument."""
for (datatype, identifier) in {int: _identify_scaler, numpy.int8: _identify_scaler, numpy.int16: _identify_scaler, numpy.int32: _identify_scaler, numpy.int64: _identify_scaler, float: _identify_scaler, numpy.float16: _identify_scaler, numpy.float3... |
def create_sqs_policy(self, topic_name, topic_arn, topic_subs):
"""
This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than the ARN.
"""
... | def function[create_sqs_policy, parameter[self, topic_name, topic_arn, topic_subs]]:
constant[
This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than... | keyword[def] identifier[create_sqs_policy] ( identifier[self] , identifier[topic_name] , identifier[topic_arn] , identifier[topic_subs] ):
literal[string]
identifier[t] = identifier[self] . identifier[template]
identifier[arn_endpoints] =[]
identifier[url_endpoints] =[]
... | def create_sqs_policy(self, topic_name, topic_arn, topic_subs):
"""
This method creates the SQS policy needed for an SNS subscription. It
also takes the ARN of the SQS queue and converts it to the URL needed
for the subscription, as that takes a URL rather than the ARN.
"""
t = s... |
def publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, "media:content", mc_element) for
mc_element in self.media_content]
else:
PyRSS2Gen._opt_element(... | def function[publish_extensions, parameter[self, handler]]:
constant[Publish the Media RSS Feed elements as XML.]
if call[name[isinstance], parameter[name[self].media_content, name[list]]] begin[:]
<ast.ListComp object at 0x7da18fe92a10>
if call[name[hasattr], parameter[name[self... | keyword[def] identifier[publish_extensions] ( identifier[self] , identifier[handler] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[media_content] , identifier[list] ):
[ identifier[PyRSS2Gen] . identifier[_opt_element] ( identifier[handler] , lit... | def publish_extensions(self, handler):
"""Publish the Media RSS Feed elements as XML."""
if isinstance(self.media_content, list):
[PyRSS2Gen._opt_element(handler, 'media:content', mc_element) for mc_element in self.media_content] # depends on [control=['if'], data=[]]
else:
PyRSS2Gen._opt_e... |
def use_comparative_assessment_part_bank_view(self):
"""Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view"""
self._bank_view = COMPARATIVE
# self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked
for ses... | def function[use_comparative_assessment_part_bank_view, parameter[self]]:
constant[Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view]
name[self]._bank_view assign[=] name[COMPARATIVE]
for taget[name[session]] in starred[call[name[self]._get_provider_ses... | keyword[def] identifier[use_comparative_assessment_part_bank_view] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_bank_view] = identifier[COMPARATIVE]
keyword[for] identifier[session] keyword[in] identifier[self] . identifier[_get_provider_sessions] ():
... | def use_comparative_assessment_part_bank_view(self):
"""Pass through to provider AssessmentPartBankSession.use_comparative_assessment_part_bank_view"""
self._bank_view = COMPARATIVE
# self._get_provider_session('assessment_part_bank_session') # To make sure the session is tracked
for session in self._ge... |
def operations(nsteps):
'''Returns the number of operations needed for nsteps of GMRES'''
return {'A': 1 + nsteps,
'M': 2 + nsteps,
'Ml': 2 + nsteps,
'Mr': 1 + nsteps,
'ip_B': 2 + nsteps + nsteps*(nsteps+1)/2,
'axpy': 4 + 2*... | def function[operations, parameter[nsteps]]:
constant[Returns the number of operations needed for nsteps of GMRES]
return[dictionary[[<ast.Constant object at 0x7da1b26e3490>, <ast.Constant object at 0x7da1b26f0520>, <ast.Constant object at 0x7da1b26f0550>, <ast.Constant object at 0x7da1b26f0580>, <ast.Const... | keyword[def] identifier[operations] ( identifier[nsteps] ):
literal[string]
keyword[return] { literal[string] : literal[int] + identifier[nsteps] ,
literal[string] : literal[int] + identifier[nsteps] ,
literal[string] : literal[int] + identifier[nsteps] ,
literal[string] ... | def operations(nsteps):
"""Returns the number of operations needed for nsteps of GMRES"""
return {'A': 1 + nsteps, 'M': 2 + nsteps, 'Ml': 2 + nsteps, 'Mr': 1 + nsteps, 'ip_B': 2 + nsteps + nsteps * (nsteps + 1) / 2, 'axpy': 4 + 2 * nsteps + nsteps * (nsteps + 1) / 2} |
def compile_attribute(line, in_key, foreign_key_sql):
"""
Convert attribute definition from DataJoint format to SQL
:param line: attribution line
:param in_key: set to True if attribute is in primary key set
:param foreign_key_sql:
:returns: (name, sql, is_external) -- attribute name and sql co... | def function[compile_attribute, parameter[line, in_key, foreign_key_sql]]:
constant[
Convert attribute definition from DataJoint format to SQL
:param line: attribution line
:param in_key: set to True if attribute is in primary key set
:param foreign_key_sql:
:returns: (name, sql, is_externa... | keyword[def] identifier[compile_attribute] ( identifier[line] , identifier[in_key] , identifier[foreign_key_sql] ):
literal[string]
keyword[try] :
identifier[match] = identifier[attribute_parser] . identifier[parseString] ( identifier[line] + literal[string] , identifier[parseAll] = keyword[True] ... | def compile_attribute(line, in_key, foreign_key_sql):
"""
Convert attribute definition from DataJoint format to SQL
:param line: attribution line
:param in_key: set to True if attribute is in primary key set
:param foreign_key_sql:
:returns: (name, sql, is_external) -- attribute name and sql co... |
def show_tabulated(self, begin, middle, end):
"""Shows a tabulated message."""
internal_assert(len(begin) < info_tabulation, "info message too long", begin)
self.show(begin + " " * (info_tabulation - len(begin)) + middle + " " + end) | def function[show_tabulated, parameter[self, begin, middle, end]]:
constant[Shows a tabulated message.]
call[name[internal_assert], parameter[compare[call[name[len], parameter[name[begin]]] less[<] name[info_tabulation]], constant[info message too long], name[begin]]]
call[name[self].show, param... | keyword[def] identifier[show_tabulated] ( identifier[self] , identifier[begin] , identifier[middle] , identifier[end] ):
literal[string]
identifier[internal_assert] ( identifier[len] ( identifier[begin] )< identifier[info_tabulation] , literal[string] , identifier[begin] )
identifier[self]... | def show_tabulated(self, begin, middle, end):
"""Shows a tabulated message."""
internal_assert(len(begin) < info_tabulation, 'info message too long', begin)
self.show(begin + ' ' * (info_tabulation - len(begin)) + middle + ' ' + end) |
def create_stream(self, stream_id, sandbox=None):
"""
Must be overridden by deriving classes, must create the stream according to the tool and return its unique
identifier stream_id
"""
if stream_id in self.streams:
raise StreamAlreadyExistsError("Stream with id '{}' ... | def function[create_stream, parameter[self, stream_id, sandbox]]:
constant[
Must be overridden by deriving classes, must create the stream according to the tool and return its unique
identifier stream_id
]
if compare[name[stream_id] in name[self].streams] begin[:]
<ast.Ra... | keyword[def] identifier[create_stream] ( identifier[self] , identifier[stream_id] , identifier[sandbox] = keyword[None] ):
literal[string]
keyword[if] identifier[stream_id] keyword[in] identifier[self] . identifier[streams] :
keyword[raise] identifier[StreamAlreadyExistsError] ( li... | def create_stream(self, stream_id, sandbox=None):
"""
Must be overridden by deriving classes, must create the stream according to the tool and return its unique
identifier stream_id
"""
if stream_id in self.streams:
raise StreamAlreadyExistsError("Stream with id '{}' already exis... |
def iter(context, sequence, limit=10):
"""Iter to list all the jobs events."""
params = {'limit': limit,
'offset': 0}
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
while True:
j = context.session.get(uri, params=params).json()
if len(j['jobs_events']):
... | def function[iter, parameter[context, sequence, limit]]:
constant[Iter to list all the jobs events.]
variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da1b2429630>, <ast.Constant object at 0x7da1b242ab30>], [<ast.Name object at 0x7da1b242a9b0>, <ast.Constant object at 0x7da1b242b5e0>]]
... | keyword[def] identifier[iter] ( identifier[context] , identifier[sequence] , identifier[limit] = literal[int] ):
literal[string]
identifier[params] ={ literal[string] : identifier[limit] ,
literal[string] : literal[int] }
identifier[uri] = literal[string] %( identifier[context] . identifier[dci_c... | def iter(context, sequence, limit=10):
"""Iter to list all the jobs events."""
params = {'limit': limit, 'offset': 0}
uri = '%s/%s/%s' % (context.dci_cs_api, RESOURCE, sequence)
while True:
j = context.session.get(uri, params=params).json()
if len(j['jobs_events']):
for i in ... |
def make_related_protein_fasta_from_dataframe(self, input_df):
'''
DataFrame should have
'''
dirname = './group_fastas'
if not os.path.exists(dirname):
os.makedirs(dirname)
unique_hit_queries = set(input_df.hit_query)
for hq in unique_hit_queries... | def function[make_related_protein_fasta_from_dataframe, parameter[self, input_df]]:
constant[
DataFrame should have
]
variable[dirname] assign[=] constant[./group_fastas]
if <ast.UnaryOp object at 0x7da1b09d0280> begin[:]
call[name[os].makedirs, parameter[name[di... | keyword[def] identifier[make_related_protein_fasta_from_dataframe] ( identifier[self] , identifier[input_df] ):
literal[string]
identifier[dirname] = literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[dirname] ):
... | def make_related_protein_fasta_from_dataframe(self, input_df):
"""
DataFrame should have
"""
dirname = './group_fastas'
if not os.path.exists(dirname):
os.makedirs(dirname) # depends on [control=['if'], data=[]]
unique_hit_queries = set(input_df.hit_query)
for hq in unique_... |
def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
self._add... | def function[_add_install, parameter[self, context]]:
constant[
generates install.sh and adds it to included files
]
variable[contents] assign[=] call[name[self]._render_template, parameter[constant[install.sh], name[context]]]
call[name[self].config.setdefault, parameter[constan... | keyword[def] identifier[_add_install] ( identifier[self] , identifier[context] ):
literal[string]
identifier[contents] = identifier[self] . identifier[_render_template] ( literal[string] , identifier[context] )
identifier[self] . identifier[config] . identifier[setdefault] ( literal[string... | def _add_install(self, context):
"""
generates install.sh and adds it to included files
"""
contents = self._render_template('install.sh', context)
self.config.setdefault('files', []) # file list might be empty
# add install.sh to list of included files
self._add_unique_file({'path'... |
def boolean(_object):
"""
Validates a given input is of type boolean.
Example usage::
data = {'a' : True}
schema = ('a', boolean)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the... | def function[boolean, parameter[_object]]:
constant[
Validates a given input is of type boolean.
Example usage::
data = {'a' : True}
schema = ('a', boolean)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing... | keyword[def] identifier[boolean] ( identifier[_object] ):
literal[string]
keyword[if] identifier[is_callable] ( identifier[_object] ):
identifier[_validator] = identifier[_object]
@ identifier[wraps] ( identifier[_validator] )
keyword[def] identifier[decorated] ( identifier[va... | def boolean(_object):
"""
Validates a given input is of type boolean.
Example usage::
data = {'a' : True}
schema = ('a', boolean)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the... |
def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
'''These should also be in the config section, but some here for
overrides
'''
if self.config['api_key'] is None:
raise ValueError('config api_key is undefined')
if offset or self.config.get('o... | def function[poll, parameter[self, offset, poll_timeout, cooldown, debug]]:
constant[These should also be in the config section, but some here for
overrides
]
if compare[call[name[self].config][constant[api_key]] is constant[None]] begin[:]
<ast.Raise object at 0x7da18dc05480>
... | keyword[def] identifier[poll] ( identifier[self] , identifier[offset] = keyword[None] , identifier[poll_timeout] = literal[int] , identifier[cooldown] = literal[int] , identifier[debug] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[config] [ literal[string] ] keywor... | def poll(self, offset=None, poll_timeout=600, cooldown=60, debug=False):
"""These should also be in the config section, but some here for
overrides
"""
if self.config['api_key'] is None:
raise ValueError('config api_key is undefined') # depends on [control=['if'], data=[]]
if offse... |
def load(self):
"""(Re)Load config file."""
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile)
except TypeError:
# no config file (use environment variables)
pass
if self.config:
self.prefix ... | def function[load, parameter[self]]:
constant[(Re)Load config file.]
<ast.Try object at 0x7da1b1b6b400>
if name[self].config begin[:]
name[self].prefix assign[=] call[name[self].config.get, parameter[constant[config_prefix], constant[None]]]
if <ast.UnaryOp object at 0x7da18c... | keyword[def] identifier[load] ( identifier[self] ):
literal[string]
keyword[try] :
keyword[with] identifier[open] ( identifier[self] . identifier[config_file] ) keyword[as] identifier[configfile] :
identifier[self] . identifier[config] = identifier[yaml] . identifier... | def load(self):
"""(Re)Load config file."""
try:
with open(self.config_file) as configfile:
self.config = yaml.load(configfile) # depends on [control=['with'], data=['configfile']] # depends on [control=['try'], data=[]]
except TypeError:
# no config file (use environment varia... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.