code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def apply_clicked(self, button):
"""Triggered when the Apply-Shortcut in the editor is triggered.
"""
if isinstance(self.model.state, LibraryState):
return
self.set_script_text(self.view.get_text()) | def function[apply_clicked, parameter[self, button]]:
constant[Triggered when the Apply-Shortcut in the editor is triggered.
]
if call[name[isinstance], parameter[name[self].model.state, name[LibraryState]]] begin[:]
return[None]
call[name[self].set_script_text, parameter[call[n... | keyword[def] identifier[apply_clicked] ( identifier[self] , identifier[button] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[model] . identifier[state] , identifier[LibraryState] ):
keyword[return]
identifier[self] . identifier[set_sc... | def apply_clicked(self, button):
"""Triggered when the Apply-Shortcut in the editor is triggered.
"""
if isinstance(self.model.state, LibraryState):
return # depends on [control=['if'], data=[]]
self.set_script_text(self.view.get_text()) |
def randomize_es(es_queryset):
"""Randomize an elasticsearch queryset."""
return es_queryset.query(
query.FunctionScore(
functions=[function.RandomScore()]
)
).sort("-_score") | def function[randomize_es, parameter[es_queryset]]:
constant[Randomize an elasticsearch queryset.]
return[call[call[name[es_queryset].query, parameter[call[name[query].FunctionScore, parameter[]]]].sort, parameter[constant[-_score]]]] | keyword[def] identifier[randomize_es] ( identifier[es_queryset] ):
literal[string]
keyword[return] identifier[es_queryset] . identifier[query] (
identifier[query] . identifier[FunctionScore] (
identifier[functions] =[ identifier[function] . identifier[RandomScore] ()]
)
). identifier[sor... | def randomize_es(es_queryset):
"""Randomize an elasticsearch queryset."""
return es_queryset.query(query.FunctionScore(functions=[function.RandomScore()])).sort('-_score') |
def get_user(self, steam_id, fetch_persona_state=True):
"""Get :class:`.SteamUser` instance for ``steam id``
:param steam_id: steam id
:type steam_id: :class:`int`, :class:`.SteamID`
:param fetch_persona_state: whether to request person state when necessary
:type fetch_persona_s... | def function[get_user, parameter[self, steam_id, fetch_persona_state]]:
constant[Get :class:`.SteamUser` instance for ``steam id``
:param steam_id: steam id
:type steam_id: :class:`int`, :class:`.SteamID`
:param fetch_persona_state: whether to request person state when necessary
... | keyword[def] identifier[get_user] ( identifier[self] , identifier[steam_id] , identifier[fetch_persona_state] = keyword[True] ):
literal[string]
identifier[steam_id] = identifier[int] ( identifier[steam_id] )
identifier[suser] = identifier[self] . identifier[_user_cache] . identifier[get] ... | def get_user(self, steam_id, fetch_persona_state=True):
"""Get :class:`.SteamUser` instance for ``steam id``
:param steam_id: steam id
:type steam_id: :class:`int`, :class:`.SteamID`
:param fetch_persona_state: whether to request person state when necessary
:type fetch_persona_state... |
def _prepare_headers(
self,
headers: Optional[LooseHeaders]) -> 'CIMultiDict[str]':
""" Add default headers and transform it to CIMultiDict
"""
# Convert headers to MultiDict
result = CIMultiDict(self._default_headers)
if headers:
if not isinst... | def function[_prepare_headers, parameter[self, headers]]:
constant[ Add default headers and transform it to CIMultiDict
]
variable[result] assign[=] call[name[CIMultiDict], parameter[name[self]._default_headers]]
if name[headers] begin[:]
if <ast.UnaryOp object at 0x7da1b... | keyword[def] identifier[_prepare_headers] (
identifier[self] ,
identifier[headers] : identifier[Optional] [ identifier[LooseHeaders] ])-> literal[string] :
literal[string]
identifier[result] = identifier[CIMultiDict] ( identifier[self] . identifier[_default_headers] )
keyword[if... | def _prepare_headers(self, headers: Optional[LooseHeaders]) -> 'CIMultiDict[str]':
""" Add default headers and transform it to CIMultiDict
"""
# Convert headers to MultiDict
result = CIMultiDict(self._default_headers)
if headers:
if not isinstance(headers, (MultiDictProxy, MultiDict)):
... |
def check_path(path):
"""Check that a path is legal.
:return: the path if all is OK
:raise ValueError: if the path is illegal
"""
if path is None or path == b'' or path.startswith(b'/'):
raise ValueError("illegal path '%s'" % path)
if (
(sys.version_info[0] >= 3 and not isinsta... | def function[check_path, parameter[path]]:
constant[Check that a path is legal.
:return: the path if all is OK
:raise ValueError: if the path is illegal
]
if <ast.BoolOp object at 0x7da1b0aeead0> begin[:]
<ast.Raise object at 0x7da1b0911870>
if <ast.BoolOp object at 0x7da1b0... | keyword[def] identifier[check_path] ( identifier[path] ):
literal[string]
keyword[if] identifier[path] keyword[is] keyword[None] keyword[or] identifier[path] == literal[string] keyword[or] identifier[path] . identifier[startswith] ( literal[string] ):
keyword[raise] identifier[ValueError] ... | def check_path(path):
"""Check that a path is legal.
:return: the path if all is OK
:raise ValueError: if the path is illegal
"""
if path is None or path == b'' or path.startswith(b'/'):
raise ValueError("illegal path '%s'" % path) # depends on [control=['if'], data=[]]
if (sys.version... |
def GetValue(self, ignore_error=True):
"""Extracts and returns a single value from a DataBlob."""
if self.HasField("none"):
return None
field_names = [
"integer", "string", "data", "boolean", "list", "dict", "rdf_value",
"float", "set"
]
values = [getattr(self, x) for x in fi... | def function[GetValue, parameter[self, ignore_error]]:
constant[Extracts and returns a single value from a DataBlob.]
if call[name[self].HasField, parameter[constant[none]]] begin[:]
return[constant[None]]
variable[field_names] assign[=] list[[<ast.Constant object at 0x7da1b1b44d60>, <as... | keyword[def] identifier[GetValue] ( identifier[self] , identifier[ignore_error] = keyword[True] ):
literal[string]
keyword[if] identifier[self] . identifier[HasField] ( literal[string] ):
keyword[return] keyword[None]
identifier[field_names] =[
literal[string] , literal[string] , liter... | def GetValue(self, ignore_error=True):
"""Extracts and returns a single value from a DataBlob."""
if self.HasField('none'):
return None # depends on [control=['if'], data=[]]
field_names = ['integer', 'string', 'data', 'boolean', 'list', 'dict', 'rdf_value', 'float', 'set']
values = [getattr(se... |
def sexec(context, command, error_on_nonzero=True):
"""Executes a command within a particular Idiap SETSHELL context"""
import six
if isinstance(context, six.string_types): E = environ(context)
else: E = context
try:
logger.debug("Executing: '%s'", ' '.join(command))
p = subprocess.Popen(command, st... | def function[sexec, parameter[context, command, error_on_nonzero]]:
constant[Executes a command within a particular Idiap SETSHELL context]
import module[six]
if call[name[isinstance], parameter[name[context], name[six].string_types]] begin[:]
variable[E] assign[=] call[name[environ]... | keyword[def] identifier[sexec] ( identifier[context] , identifier[command] , identifier[error_on_nonzero] = keyword[True] ):
literal[string]
keyword[import] identifier[six]
keyword[if] identifier[isinstance] ( identifier[context] , identifier[six] . identifier[string_types] ): identifier[E] = identifier... | def sexec(context, command, error_on_nonzero=True):
"""Executes a command within a particular Idiap SETSHELL context"""
import six
if isinstance(context, six.string_types):
E = environ(context) # depends on [control=['if'], data=[]]
else:
E = context
try:
logger.debug("Execu... |
def add_file(self, **args):
'''
Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:pa... | def function[add_file, parameter[self]]:
constant[
Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for any... | keyword[def] identifier[add_file] ( identifier[self] ,** identifier[args] ):
literal[string]
identifier[self] . identifier[__check_if_adding_files_allowed_right_now] ()
identifier[mandatory_args] =[ literal[string] , literal[string] , literal[string] ,
literal[... | def add_file(self, **args):
"""
Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:param ... |
def configure_modevasive(self):
"""
Installs the mod-evasive Apache module for combating DDOS attacks.
https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache
"""
r = self.local_renderer
if r.env.modevasive_enabled:
self.install_packa... | def function[configure_modevasive, parameter[self]]:
constant[
Installs the mod-evasive Apache module for combating DDOS attacks.
https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache
]
variable[r] assign[=] name[self].local_renderer
if name[r]... | keyword[def] identifier[configure_modevasive] ( identifier[self] ):
literal[string]
identifier[r] = identifier[self] . identifier[local_renderer]
keyword[if] identifier[r] . identifier[env] . identifier[modevasive_enabled] :
identifier[self] . identifier[install_packages] ()... | def configure_modevasive(self):
"""
Installs the mod-evasive Apache module for combating DDOS attacks.
https://www.linode.com/docs/websites/apache-tips-and-tricks/modevasive-on-apache
"""
r = self.local_renderer
if r.env.modevasive_enabled:
self.install_packages()
# ... |
def deployment_plans(self):
"""
Gets the Deployment Plans API client.
Returns:
DeploymentPlans:
"""
if not self.__deployment_plans:
self.__deployment_plans = DeploymentPlans(self.__connection)
return self.__deployment_plans | def function[deployment_plans, parameter[self]]:
constant[
Gets the Deployment Plans API client.
Returns:
DeploymentPlans:
]
if <ast.UnaryOp object at 0x7da18bcc9330> begin[:]
name[self].__deployment_plans assign[=] call[name[DeploymentPlans], paramet... | keyword[def] identifier[deployment_plans] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__deployment_plans] :
identifier[self] . identifier[__deployment_plans] = identifier[DeploymentPlans] ( identifier[self] . identifier[__connection] )... | def deployment_plans(self):
"""
Gets the Deployment Plans API client.
Returns:
DeploymentPlans:
"""
if not self.__deployment_plans:
self.__deployment_plans = DeploymentPlans(self.__connection) # depends on [control=['if'], data=[]]
return self.__deployment_plans |
def BuildChecks(self, request):
"""Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return ... | def function[BuildChecks, parameter[self, request]]:
constant[Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a ... | keyword[def] identifier[BuildChecks] ( identifier[self] , identifier[request] ):
literal[string]
identifier[result] =[]
keyword[if] identifier[request] . identifier[HasField] ( literal[string] ) keyword[or] identifier[request] . identifier[HasField] ( literal[string] ):
keyword[def] identif... | def BuildChecks(self, request):
"""Parses request and returns a list of filter callables.
Each callable will be called with the StatEntry and returns True if the
entry should be suppressed.
Args:
request: A FindSpec that describes the search.
Returns:
a list of callables which return ... |
def do_auto_save(self):
"""
Delete current fit if auto_save==False,
unless current fit has explicitly been saved.
"""
if not self.auto_save.GetValue():
if self.current_fit:
if not self.current_fit.saved:
self.delete_fit(self.current... | def function[do_auto_save, parameter[self]]:
constant[
Delete current fit if auto_save==False,
unless current fit has explicitly been saved.
]
if <ast.UnaryOp object at 0x7da2041da9e0> begin[:]
if name[self].current_fit begin[:]
if <ast.Una... | keyword[def] identifier[do_auto_save] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[auto_save] . identifier[GetValue] ():
keyword[if] identifier[self] . identifier[current_fit] :
keyword[if] keyword[not] identifier[se... | def do_auto_save(self):
"""
Delete current fit if auto_save==False,
unless current fit has explicitly been saved.
"""
if not self.auto_save.GetValue():
if self.current_fit:
if not self.current_fit.saved:
self.delete_fit(self.current_fit, specimen=self.... |
def get_thumbnail_paths(self):
"""
Helper function used to avoid processing thumbnail files during `os.walk`.
"""
thumbnail_path_tuples = []
# channel thumbnail
channel_info = self.get_channel_info()
chthumbnail_path = channel_info.get('thumbnail_chan_path', None)... | def function[get_thumbnail_paths, parameter[self]]:
constant[
Helper function used to avoid processing thumbnail files during `os.walk`.
]
variable[thumbnail_path_tuples] assign[=] list[[]]
variable[channel_info] assign[=] call[name[self].get_channel_info, parameter[]]
va... | keyword[def] identifier[get_thumbnail_paths] ( identifier[self] ):
literal[string]
identifier[thumbnail_path_tuples] =[]
identifier[channel_info] = identifier[self] . identifier[get_channel_info] ()
identifier[chthumbnail_path] = identifier[channel_info] . identifier[get]... | def get_thumbnail_paths(self):
"""
Helper function used to avoid processing thumbnail files during `os.walk`.
"""
thumbnail_path_tuples = []
# channel thumbnail
channel_info = self.get_channel_info()
chthumbnail_path = channel_info.get('thumbnail_chan_path', None)
if chthumbnail_... |
def rewrite_elife_authors_json(json_content, doi):
""" this does the work of rewriting elife authors json """
# Convert doi from testing doi if applicable
article_doi = elifetools.utils.convert_testing_doi(doi)
# Edge case fix an affiliation name
if article_doi == "10.7554/eLife.06956":
fo... | def function[rewrite_elife_authors_json, parameter[json_content, doi]]:
constant[ this does the work of rewriting elife authors json ]
variable[article_doi] assign[=] call[name[elifetools].utils.convert_testing_doi, parameter[name[doi]]]
if compare[name[article_doi] equal[==] constant[10.7554/eL... | keyword[def] identifier[rewrite_elife_authors_json] ( identifier[json_content] , identifier[doi] ):
literal[string]
identifier[article_doi] = identifier[elifetools] . identifier[utils] . identifier[convert_testing_doi] ( identifier[doi] )
keyword[if] identifier[article_doi] == literal[str... | def rewrite_elife_authors_json(json_content, doi):
""" this does the work of rewriting elife authors json """
# Convert doi from testing doi if applicable
article_doi = elifetools.utils.convert_testing_doi(doi)
# Edge case fix an affiliation name
if article_doi == '10.7554/eLife.06956':
for ... |
def __get_stat_display(self, stats, layer):
"""Return a dict of dict with all the stats display.
stats: Global stats dict
layer: ~ cs_status
"None": standalone or server mode
"Connected": Client is connected to a Glances server
"SNMP": Client is connected to a... | def function[__get_stat_display, parameter[self, stats, layer]]:
constant[Return a dict of dict with all the stats display.
stats: Global stats dict
layer: ~ cs_status
"None": standalone or server mode
"Connected": Client is connected to a Glances server
"SNMP... | keyword[def] identifier[__get_stat_display] ( identifier[self] , identifier[stats] , identifier[layer] ):
literal[string]
identifier[ret] ={}
keyword[for] identifier[p] keyword[in] identifier[stats] . identifier[getPluginsList] ( identifier[enable] = keyword[False] ):
keyw... | def __get_stat_display(self, stats, layer):
"""Return a dict of dict with all the stats display.
stats: Global stats dict
layer: ~ cs_status
"None": standalone or server mode
"Connected": Client is connected to a Glances server
"SNMP": Client is connected to a SNM... |
def dof(self):
"""Returns the DoF of the robot (with grippers)."""
dof = self.mujoco_robot.dof
if self.has_gripper_left:
dof += self.gripper_left.dof
if self.has_gripper_right:
dof += self.gripper_right.dof
return dof | def function[dof, parameter[self]]:
constant[Returns the DoF of the robot (with grippers).]
variable[dof] assign[=] name[self].mujoco_robot.dof
if name[self].has_gripper_left begin[:]
<ast.AugAssign object at 0x7da20c6a8eb0>
if name[self].has_gripper_right begin[:]
<ast.A... | keyword[def] identifier[dof] ( identifier[self] ):
literal[string]
identifier[dof] = identifier[self] . identifier[mujoco_robot] . identifier[dof]
keyword[if] identifier[self] . identifier[has_gripper_left] :
identifier[dof] += identifier[self] . identifier[gripper_left] . i... | def dof(self):
"""Returns the DoF of the robot (with grippers)."""
dof = self.mujoco_robot.dof
if self.has_gripper_left:
dof += self.gripper_left.dof # depends on [control=['if'], data=[]]
if self.has_gripper_right:
dof += self.gripper_right.dof # depends on [control=['if'], data=[]]
... |
def _language_in_list(language, targets, min_score=80):
"""
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iter... | def function[_language_in_list, parameter[language, targets, min_score]]:
constant[
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
object... | keyword[def] identifier[_language_in_list] ( identifier[language] , identifier[targets] , identifier[min_score] = literal[int] ):
literal[string]
identifier[matched] = identifier[best_match] ( identifier[language] , identifier[targets] , identifier[min_score] = identifier[min_score] )
keyword[return] ... | def _language_in_list(language, targets, min_score=80):
"""
A helper function to determine whether this language matches one of the
target languages, with a match score above a certain threshold.
The languages can be given as strings (language tags) or as Language
objects. `targets` can be any iter... |
def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs):
"""Given a mod and a set of opts return an instantiated
Backend class.
"""
kw = dict(encoding=encoding, encoding_errors=encoding_errors,
kwargs=kwargs)
try:
klass = getattr(mod, "Backend")
except AttributeEr... | def function[backend_inst_from_mod, parameter[mod, encoding, encoding_errors, kwargs]]:
constant[Given a mod and a set of opts return an instantiated
Backend class.
]
variable[kw] assign[=] call[name[dict], parameter[]]
<ast.Try object at 0x7da2041d9e10>
variable[inst] assign[=] call... | keyword[def] identifier[backend_inst_from_mod] ( identifier[mod] , identifier[encoding] , identifier[encoding_errors] , identifier[kwargs] ):
literal[string]
identifier[kw] = identifier[dict] ( identifier[encoding] = identifier[encoding] , identifier[encoding_errors] = identifier[encoding_errors] ,
id... | def backend_inst_from_mod(mod, encoding, encoding_errors, kwargs):
"""Given a mod and a set of opts return an instantiated
Backend class.
"""
kw = dict(encoding=encoding, encoding_errors=encoding_errors, kwargs=kwargs)
try:
klass = getattr(mod, 'Backend') # depends on [control=['try'], data... |
def all_points_membership_vectors(clusterer):
"""Predict soft cluster membership vectors for all points in the
original dataset the clusterer was trained on. This function is more
efficient by making use of the fact that all points are already in the
condensed tree, and processing in bulk.
Paramete... | def function[all_points_membership_vectors, parameter[clusterer]]:
constant[Predict soft cluster membership vectors for all points in the
original dataset the clusterer was trained on. This function is more
efficient by making use of the fact that all points are already in the
condensed tree, and pr... | keyword[def] identifier[all_points_membership_vectors] ( identifier[clusterer] ):
literal[string]
identifier[clusters] = identifier[np] . identifier[array] ( identifier[sorted] ( identifier[list] ( identifier[clusterer] . identifier[condensed_tree_] . identifier[_select_clusters] ()))). identifier[astype] ... | def all_points_membership_vectors(clusterer):
"""Predict soft cluster membership vectors for all points in the
original dataset the clusterer was trained on. This function is more
efficient by making use of the fact that all points are already in the
condensed tree, and processing in bulk.
Paramete... |
def create_developer_certificate(self, authorization, body, **kwargs): # noqa: E501
"""Create a new developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multiple ... | def function[create_developer_certificate, parameter[self, authorization, body]]:
constant[Create a new developer certificate to connect to the bootstrap server. # noqa: E501
This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multip... | keyword[def] identifier[create_developer_certificate] ( identifier[self] , identifier[authorization] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def create_developer_certificate(self, authorization, body, **kwargs): # noqa: E501
'Create a new developer certificate to connect to the bootstrap server. # noqa: E501\n\n This REST API is intended to be used by customers to get a developer certificate (a certificate that can be flashed into multiple devi... |
def list_offers(access_token, subscription_id, location, publisher):
'''List available VM image offers from a publisher.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data center location. E.g. westus.
... | def function[list_offers, parameter[access_token, subscription_id, location, publisher]]:
constant[List available VM image offers from a publisher.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data ... | keyword[def] identifier[list_offers] ( identifier[access_token] , identifier[subscription_id] , identifier[location] , identifier[publisher] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] , identifier[subscription_id] ,
... | def list_offers(access_token, subscription_id, location, publisher):
"""List available VM image offers from a publisher.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data center location. E.g. westus.
... |
def sanity_check_subsections(self):
"""
This function goes through the ConfigParset and checks that any options
given in the [SECTION_NAME] section are not also given in any
[SECTION_NAME-SUBSECTION] sections.
"""
# Loop over the sections in the ini file
for sect... | def function[sanity_check_subsections, parameter[self]]:
constant[
This function goes through the ConfigParset and checks that any options
given in the [SECTION_NAME] section are not also given in any
[SECTION_NAME-SUBSECTION] sections.
]
for taget[name[section]] in star... | keyword[def] identifier[sanity_check_subsections] ( identifier[self] ):
literal[string]
keyword[for] identifier[section] keyword[in] identifier[self] . identifier[sections] ():
keyword[if] identifier[section] == literal[string] :
keyword[... | def sanity_check_subsections(self):
"""
This function goes through the ConfigParset and checks that any options
given in the [SECTION_NAME] section are not also given in any
[SECTION_NAME-SUBSECTION] sections.
"""
# Loop over the sections in the ini file
for section in self.... |
def insert_entity(self, table_name, entity, timeout=None):
'''
Inserts a new entity into the table. Throws if an entity with the same
PartitionKey and RowKey already exists.
When inserting an entity into a table, you must specify values for the
PartitionKey and RowKey system p... | def function[insert_entity, parameter[self, table_name, entity, timeout]]:
constant[
Inserts a new entity into the table. Throws if an entity with the same
PartitionKey and RowKey already exists.
When inserting an entity into a table, you must specify values for the
PartitionK... | keyword[def] identifier[insert_entity] ( identifier[self] , identifier[table_name] , identifier[entity] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[_validate_not_none] ( literal[string] , identifier[table_name] )
identifier[request] = identifier[_insert_entity] ( id... | def insert_entity(self, table_name, entity, timeout=None):
"""
Inserts a new entity into the table. Throws if an entity with the same
PartitionKey and RowKey already exists.
When inserting an entity into a table, you must specify values for the
PartitionKey and RowKey system prope... |
def _parse(self, chord):
""" parse a chord
:param str chord: Name of chord.
"""
root, quality, appended, on = parse(chord)
self._root = root
self._quality = quality
self._appended = appended
self._on = on | def function[_parse, parameter[self, chord]]:
constant[ parse a chord
:param str chord: Name of chord.
]
<ast.Tuple object at 0x7da1b0c60cd0> assign[=] call[name[parse], parameter[name[chord]]]
name[self]._root assign[=] name[root]
name[self]._quality assign[=] name[qual... | keyword[def] identifier[_parse] ( identifier[self] , identifier[chord] ):
literal[string]
identifier[root] , identifier[quality] , identifier[appended] , identifier[on] = identifier[parse] ( identifier[chord] )
identifier[self] . identifier[_root] = identifier[root]
identifier[se... | def _parse(self, chord):
""" parse a chord
:param str chord: Name of chord.
"""
(root, quality, appended, on) = parse(chord)
self._root = root
self._quality = quality
self._appended = appended
self._on = on |
def debug_show_reconstructed_similarity(
self,
data3d=None,
voxelsize=None,
seeds=None,
area_weight=1,
hard_constraints=True,
show=True,
bins=20,
slice_number=None,
):
"""
Show tlinks.
:param data3d: ndarray with input d... | def function[debug_show_reconstructed_similarity, parameter[self, data3d, voxelsize, seeds, area_weight, hard_constraints, show, bins, slice_number]]:
constant[
Show tlinks.
:param data3d: ndarray with input data
:param voxelsize:
:param seeds:
:param area_weight:
... | keyword[def] identifier[debug_show_reconstructed_similarity] (
identifier[self] ,
identifier[data3d] = keyword[None] ,
identifier[voxelsize] = keyword[None] ,
identifier[seeds] = keyword[None] ,
identifier[area_weight] = literal[int] ,
identifier[hard_constraints] = keyword[True] ,
identifier[show] = keyword[T... | def debug_show_reconstructed_similarity(self, data3d=None, voxelsize=None, seeds=None, area_weight=1, hard_constraints=True, show=True, bins=20, slice_number=None):
"""
Show tlinks.
:param data3d: ndarray with input data
:param voxelsize:
:param seeds:
:param area_weight:
... |
def get_or_add(self, reltype, target_part):
"""
Return relationship of *reltype* to *target_part*, newly added if not
already present in collection.
"""
rel = self._get_matching(reltype, target_part)
if rel is None:
rId = self._next_rId
rel = self.... | def function[get_or_add, parameter[self, reltype, target_part]]:
constant[
Return relationship of *reltype* to *target_part*, newly added if not
already present in collection.
]
variable[rel] assign[=] call[name[self]._get_matching, parameter[name[reltype], name[target_part]]]
... | keyword[def] identifier[get_or_add] ( identifier[self] , identifier[reltype] , identifier[target_part] ):
literal[string]
identifier[rel] = identifier[self] . identifier[_get_matching] ( identifier[reltype] , identifier[target_part] )
keyword[if] identifier[rel] keyword[is] keyword[None... | def get_or_add(self, reltype, target_part):
"""
Return relationship of *reltype* to *target_part*, newly added if not
already present in collection.
"""
rel = self._get_matching(reltype, target_part)
if rel is None:
rId = self._next_rId
rel = self.add_relationship(rel... |
def avail_locations(call=None):
'''
Return available Packet datacenter locations.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations packet-provider
salt-cloud -f avail_locations packet-provider
'''
if call == 'action':
raise SaltCloudException(
... | def function[avail_locations, parameter[call]]:
constant[
Return available Packet datacenter locations.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations packet-provider
salt-cloud -f avail_locations packet-provider
]
if compare[name[call] equal[==] constan... | keyword[def] identifier[avail_locations] ( identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] == literal[string] :
keyword[raise] identifier[SaltCloudException] (
literal[string]
)
identifier[vm_] = identifier[get_configured_provider] ()
... | def avail_locations(call=None):
"""
Return available Packet datacenter locations.
CLI Example:
.. code-block:: bash
salt-cloud --list-locations packet-provider
salt-cloud -f avail_locations packet-provider
"""
if call == 'action':
raise SaltCloudException('The avail_lo... |
def move(self, d, add_tile=True):
"""
move and return the move score
"""
if d == Board.LEFT or d == Board.RIGHT:
chg, get = self.setLine, self.getLine
elif d == Board.UP or d == Board.DOWN:
chg, get = self.setCol, self.getCol
else:
retu... | def function[move, parameter[self, d, add_tile]]:
constant[
move and return the move score
]
if <ast.BoolOp object at 0x7da1b07af4f0> begin[:]
<ast.Tuple object at 0x7da1b07ad210> assign[=] tuple[[<ast.Attribute object at 0x7da1b07acd30>, <ast.Attribute object at 0x7da1b0... | keyword[def] identifier[move] ( identifier[self] , identifier[d] , identifier[add_tile] = keyword[True] ):
literal[string]
keyword[if] identifier[d] == identifier[Board] . identifier[LEFT] keyword[or] identifier[d] == identifier[Board] . identifier[RIGHT] :
identifier[chg] , identif... | def move(self, d, add_tile=True):
"""
move and return the move score
"""
if d == Board.LEFT or d == Board.RIGHT:
(chg, get) = (self.setLine, self.getLine) # depends on [control=['if'], data=[]]
elif d == Board.UP or d == Board.DOWN:
(chg, get) = (self.setCol, self.getCol) #... |
def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' ... | def function[_parse_metadata, parameter[self, message]]:
constant[
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
]
variable[metadata] assign[=] call[name[Metadata]... | keyword[def] identifier[_parse_metadata] ( identifier[self] , identifier[message] ):
literal[string]
identifier[metadata] = identifier[Metadata] ( identifier[source] = identifier[self] . identifier[actor_urn] ). identifier[__dict__]
keyword[if] literal[string] keyword[in] identifier[m... | def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' in message['d... |
def rgb_to_hex(rgb):
"""
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
"""
r, g, b = rgb[:3]
if (r < 0) or (g < 0) or (b < 0)... | def function[rgb_to_hex, parameter[rgb]]:
constant[
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
]
<ast.Tuple object at ... | keyword[def] identifier[rgb_to_hex] ( identifier[rgb] ):
literal[string]
identifier[r] , identifier[g] , identifier[b] = identifier[rgb] [: literal[int] ]
keyword[if] ( identifier[r] < literal[int] ) keyword[or] ( identifier[g] < literal[int] ) keyword[or] ( identifier[b] < literal[int] ):
... | def rgb_to_hex(rgb):
"""
Utility function to convert (r,g,b) triples to hex.
http://ageo.co/1CFxXpO
Args:
rgb (tuple): A sequence of RGB values in the
range 0-255 or 0-1.
Returns:
str: The hex code for the colour.
"""
(r, g, b) = rgb[:3]
if r < 0 or g < 0 or b < 0:
... |
def update_server_cert(self, cert_name, new_cert_name=None,
new_path=None):
"""
Updates the name and/or the path of the specified server certificate.
:type cert_name: string
:param cert_name: The name of the server certificate that you want
... | def function[update_server_cert, parameter[self, cert_name, new_cert_name, new_path]]:
constant[
Updates the name and/or the path of the specified server certificate.
:type cert_name: string
:param cert_name: The name of the server certificate that you want
to ... | keyword[def] identifier[update_server_cert] ( identifier[self] , identifier[cert_name] , identifier[new_cert_name] = keyword[None] ,
identifier[new_path] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : identifier[cert_name] }
keyword[if] identifier[new_cert_nam... | def update_server_cert(self, cert_name, new_cert_name=None, new_path=None):
"""
Updates the name and/or the path of the specified server certificate.
:type cert_name: string
:param cert_name: The name of the server certificate that you want
to update.
:typ... |
def get_SZ(self):
"""Get the S and Z matrices using the current parameters.
"""
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient()
else:
scatter_outdated = self._scatter_signature != (self.thet0,
self.thet, self.phi0, self.p... | def function[get_SZ, parameter[self]]:
constant[Get the S and Z matrices using the current parameters.
]
if compare[name[self].psd_integrator is constant[None]] begin[:]
<ast.Tuple object at 0x7da2044c1f90> assign[=] call[name[self].get_SZ_orient, parameter[]]
return[tuple[[<... | keyword[def] identifier[get_SZ] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[psd_integrator] keyword[is] keyword[None] :
( identifier[self] . identifier[_S] , identifier[self] . identifier[_Z] )= identifier[self] . identifier[get_SZ_orient] ()
... | def get_SZ(self):
"""Get the S and Z matrices using the current parameters.
"""
if self.psd_integrator is None:
(self._S, self._Z) = self.get_SZ_orient() # depends on [control=['if'], data=[]]
else:
scatter_outdated = self._scatter_signature != (self.thet0, self.thet, self.phi0, sel... |
def m2m_changed(sender, instance, action, reverse, model, pk_set, using, **kwargs):
"""https://docs.djangoproject.com/es/1.10/ref/signals/#m2m-changed"""
try:
with transaction.atomic():
if not should_audit(instance):
return False
if action not in ("post_add", "po... | def function[m2m_changed, parameter[sender, instance, action, reverse, model, pk_set, using]]:
constant[https://docs.djangoproject.com/es/1.10/ref/signals/#m2m-changed]
<ast.Try object at 0x7da1b1679960> | keyword[def] identifier[m2m_changed] ( identifier[sender] , identifier[instance] , identifier[action] , identifier[reverse] , identifier[model] , identifier[pk_set] , identifier[using] ,** identifier[kwargs] ):
literal[string]
keyword[try] :
keyword[with] identifier[transaction] . identifier[atom... | def m2m_changed(sender, instance, action, reverse, model, pk_set, using, **kwargs):
"""https://docs.djangoproject.com/es/1.10/ref/signals/#m2m-changed"""
try:
with transaction.atomic():
if not should_audit(instance):
return False # depends on [control=['if'], data=[]]
... |
def must_exist(*components):
"""
Ensure path exists.
Arguments:
*components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
"""
_path = path(*components)
if not exists(_path):
raise File404(_path)
return _... | def function[must_exist, parameter[]]:
constant[
Ensure path exists.
Arguments:
*components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
]
variable[_path] assign[=] call[name[path], parameter[<ast.Starred objec... | keyword[def] identifier[must_exist] (* identifier[components] ):
literal[string]
identifier[_path] = identifier[path] (* identifier[components] )
keyword[if] keyword[not] identifier[exists] ( identifier[_path] ):
keyword[raise] identifier[File404] ( identifier[_path] )
keyword[return]... | def must_exist(*components):
"""
Ensure path exists.
Arguments:
*components (str[]): Path components.
Returns:
str: File path.
Raises:
File404: If path does not exist.
"""
_path = path(*components)
if not exists(_path):
raise File404(_path) # depends o... |
def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None,
score_end_callback=None,
reset=True, epoch=0, sparse_row_id_fn=None):
"""Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `... | def function[score, parameter[self, eval_data, eval_metric, num_batch, batch_end_callback, score_end_callback, reset, epoch, sparse_row_id_fn]]:
constant[Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `Module Tutorial <http://mxne... | keyword[def] identifier[score] ( identifier[self] , identifier[eval_data] , identifier[eval_metric] , identifier[num_batch] = keyword[None] , identifier[batch_end_callback] = keyword[None] ,
identifier[score_end_callback] = keyword[None] ,
identifier[reset] = keyword[True] , identifier[epoch] = literal[int] , ident... | def score(self, eval_data, eval_metric, num_batch=None, batch_end_callback=None, score_end_callback=None, reset=True, epoch=0, sparse_row_id_fn=None):
"""Runs prediction on ``eval_data`` and evaluates the performance according to
the given ``eval_metric``.
Checkout `Module Tutorial <http://mxnet.io... |
def _preprocess(self, x, out=None):
"""Return the pre-processed version of ``x``.
C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation)
R2C: use ``tmp_f`` (R2C operation)
HALFC: use ``tmp_r`` (R2R operation)
The result is stored in ``out`` if given, otherwise in
a temporary o... | def function[_preprocess, parameter[self, x, out]]:
constant[Return the pre-processed version of ``x``.
C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation)
R2C: use ``tmp_f`` (R2C operation)
HALFC: use ``tmp_r`` (R2R operation)
The result is stored in ``out`` if given, otherwise in... | keyword[def] identifier[_preprocess] ( identifier[self] , identifier[x] , identifier[out] = keyword[None] ):
literal[string]
keyword[if] identifier[out] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[domain] . identifier[field] == identifier[ComplexNumbers] (... | def _preprocess(self, x, out=None):
"""Return the pre-processed version of ``x``.
C2C: use ``tmp_r`` or ``tmp_f`` (C2C operation)
R2C: use ``tmp_f`` (R2C operation)
HALFC: use ``tmp_r`` (R2R operation)
The result is stored in ``out`` if given, otherwise in
a temporary or a ... |
def get_column(self, column_name, column_type, index, verbose=True):
"""Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
"""
return LazyOpResult(
... | def function[get_column, parameter[self, column_name, column_type, index, verbose]]:
constant[Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
]
return[... | keyword[def] identifier[get_column] ( identifier[self] , identifier[column_name] , identifier[column_type] , identifier[index] , identifier[verbose] = keyword[True] ):
literal[string]
keyword[return] identifier[LazyOpResult] (
identifier[grizzly_impl] . identifier[get_column] (
i... | def get_column(self, column_name, column_type, index, verbose=True):
"""Summary
Args:
column_name (TYPE): Description
column_type (TYPE): Description
index (TYPE): Description
Returns:
TYPE: Description
"""
return LazyOpResult(grizzly_imp... |
def find_file(folder, filename):
"""
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder.
"""
matches = []
if os.path.isabs(filename) and os.path.isfile(filename):
return filename
for root, _, filenames in os.wal... | def function[find_file, parameter[folder, filename]]:
constant[
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder.
]
variable[matches] assign[=] list[[]]
if <ast.BoolOp object at 0x7da20c993310> begin[:]
... | keyword[def] identifier[find_file] ( identifier[folder] , identifier[filename] ):
literal[string]
identifier[matches] =[]
keyword[if] identifier[os] . identifier[path] . identifier[isabs] ( identifier[filename] ) keyword[and] identifier[os] . identifier[path] . identifier[isfile] ( identifier[filena... | def find_file(folder, filename):
"""
Find a file given folder and filename. If the filename can be
resolved directly returns otherwise walks the supplied folder.
"""
matches = []
if os.path.isabs(filename) and os.path.isfile(filename):
return filename # depends on [control=['if'], data=... |
def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... | def function[makeService, parameter[opt]]:
constant[Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart ... | keyword[def] identifier[makeService] ( identifier[opt] ):
literal[string]
identifier[restarter] , identifier[path] = identifier[beatcheck] . identifier[parseConfig] ( identifier[opt] )
identifier[pool] = identifier[client] . identifier[HTTPConnectionPool] ( identifier[reactor] )
identifier[agent]... | def makeService(opt):
"""Make a service
:params opt: dictionary-like object with 'freq', 'config' and 'messages'
:returns: twisted.application.internet.TimerService that at opt['freq']
checks for stale processes in opt['config'], and sends
restart messages through opt['messages'... |
def match_prefix(self, string):
"""
Do a partial match of the string with the grammar. The returned
:class:`Match` instance can contain multiple representations of the
match. This will never return `None`. If it doesn't match at all, the "trailing input"
part will capture all of ... | def function[match_prefix, parameter[self, string]]:
constant[
Do a partial match of the string with the grammar. The returned
:class:`Match` instance can contain multiple representations of the
match. This will never return `None`. If it doesn't match at all, the "trailing input"
... | keyword[def] identifier[match_prefix] ( identifier[self] , identifier[string] ):
literal[string]
keyword[for] identifier[patterns] keyword[in] [ identifier[self] . identifier[_re_prefix] , identifier[self] . identifier[_re_prefix_with_trailing_input] ]:
identifier[m... | def match_prefix(self, string):
"""
Do a partial match of the string with the grammar. The returned
:class:`Match` instance can contain multiple representations of the
match. This will never return `None`. If it doesn't match at all, the "trailing input"
part will capture all of the ... |
def get_badge(self, kind):
''' Get a badge given its kind if present'''
candidates = [b for b in self.badges if b.kind == kind]
return candidates[0] if candidates else None | def function[get_badge, parameter[self, kind]]:
constant[ Get a badge given its kind if present]
variable[candidates] assign[=] <ast.ListComp object at 0x7da20c76e500>
return[<ast.IfExp object at 0x7da20c76d360>] | keyword[def] identifier[get_badge] ( identifier[self] , identifier[kind] ):
literal[string]
identifier[candidates] =[ identifier[b] keyword[for] identifier[b] keyword[in] identifier[self] . identifier[badges] keyword[if] identifier[b] . identifier[kind] == identifier[kind] ]
keyword[... | def get_badge(self, kind):
""" Get a badge given its kind if present"""
candidates = [b for b in self.badges if b.kind == kind]
return candidates[0] if candidates else None |
def prepare(self):
"""No percolator XML for protein tables"""
self.target = self.fn
self.targetheader = reader.get_tsv_header(self.target)
self.decoyheader = reader.get_tsv_header(self.decoyfn) | def function[prepare, parameter[self]]:
constant[No percolator XML for protein tables]
name[self].target assign[=] name[self].fn
name[self].targetheader assign[=] call[name[reader].get_tsv_header, parameter[name[self].target]]
name[self].decoyheader assign[=] call[name[reader].get_tsv_he... | keyword[def] identifier[prepare] ( identifier[self] ):
literal[string]
identifier[self] . identifier[target] = identifier[self] . identifier[fn]
identifier[self] . identifier[targetheader] = identifier[reader] . identifier[get_tsv_header] ( identifier[self] . identifier[target] )
... | def prepare(self):
"""No percolator XML for protein tables"""
self.target = self.fn
self.targetheader = reader.get_tsv_header(self.target)
self.decoyheader = reader.get_tsv_header(self.decoyfn) |
def connect_telnet(name, ip_address=None, user='micro', password='python'):
"""Connect to a MicroPython board via telnet."""
if ip_address is None:
try:
ip_address = socket.gethostbyname(name)
except socket.gaierror:
ip_address = name
if not QUIET:
if name == ... | def function[connect_telnet, parameter[name, ip_address, user, password]]:
constant[Connect to a MicroPython board via telnet.]
if compare[name[ip_address] is constant[None]] begin[:]
<ast.Try object at 0x7da20c6c66b0>
if <ast.UnaryOp object at 0x7da20c6c51e0> begin[:]
if... | keyword[def] identifier[connect_telnet] ( identifier[name] , identifier[ip_address] = keyword[None] , identifier[user] = literal[string] , identifier[password] = literal[string] ):
literal[string]
keyword[if] identifier[ip_address] keyword[is] keyword[None] :
keyword[try] :
identif... | def connect_telnet(name, ip_address=None, user='micro', password='python'):
"""Connect to a MicroPython board via telnet."""
if ip_address is None:
try:
ip_address = socket.gethostbyname(name) # depends on [control=['try'], data=[]]
except socket.gaierror:
ip_address = n... |
def format_dimension(dimension):
"""Formats the specified <dimension> XML tag for string output."""
result = ""
if "type" in dimension.attrib:
result += "[R" if dimension.attrib["type"] == "row" else "[C"
else:
result += "[C"
if "index" in dimension.attrib... | def function[format_dimension, parameter[dimension]]:
constant[Formats the specified <dimension> XML tag for string output.]
variable[result] assign[=] constant[]
if compare[constant[type] in name[dimension].attrib] begin[:]
<ast.AugAssign object at 0x7da1b26ac8b0>
if compare[con... | keyword[def] identifier[format_dimension] ( identifier[dimension] ):
literal[string]
identifier[result] = literal[string]
keyword[if] literal[string] keyword[in] identifier[dimension] . identifier[attrib] :
identifier[result] += literal[string] keyword[if] identifier[dim... | def format_dimension(dimension):
"""Formats the specified <dimension> XML tag for string output."""
result = ''
if 'type' in dimension.attrib:
result += '[R' if dimension.attrib['type'] == 'row' else '[C' # depends on [control=['if'], data=[]]
else:
result += '[C'
if 'index' in dime... |
def load(filters="*.*", text='Select a file, FACEFACE!', default_directory='default_directory'):
"""
Pops up a dialog for opening a single file. Returns a string path or None.
"""
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'): filters = filters + ";;All files ... | def function[load, parameter[filters, text, default_directory]]:
constant[
Pops up a dialog for opening a single file. Returns a string path or None.
]
if <ast.UnaryOp object at 0x7da18ede61d0> begin[:]
variable[filters] assign[=] binary_operation[name[filters] + constant[;;All f... | keyword[def] identifier[load] ( identifier[filters] = literal[string] , identifier[text] = literal[string] , identifier[default_directory] = literal[string] ):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[filters] . identifier[split] ( literal[string] ): identifi... | def load(filters='*.*', text='Select a file, FACEFACE!', default_directory='default_directory'):
"""
Pops up a dialog for opening a single file. Returns a string path or None.
"""
# make sure the filters contains "*.*" as an option!
if not '*' in filters.split(';'):
filters = filters + ';;Al... |
def verify_dir_structure(full_path):
'''Check if given directory to see if it is usable by s2.
Checks that all required directories exist under the given
directory, and also checks that they are writable.
'''
if full_path == None:
return False
r = True
for d2c in PREDEFINED_DIR_NA... | def function[verify_dir_structure, parameter[full_path]]:
constant[Check if given directory to see if it is usable by s2.
Checks that all required directories exist under the given
directory, and also checks that they are writable.
]
if compare[name[full_path] equal[==] constant[None]] be... | keyword[def] identifier[verify_dir_structure] ( identifier[full_path] ):
literal[string]
keyword[if] identifier[full_path] == keyword[None] :
keyword[return] keyword[False]
identifier[r] = keyword[True]
keyword[for] identifier[d2c] keyword[in] identifier[PREDEFINED_DIR_NAMES] :
... | def verify_dir_structure(full_path):
"""Check if given directory to see if it is usable by s2.
Checks that all required directories exist under the given
directory, and also checks that they are writable.
"""
if full_path == None:
return False # depends on [control=['if'], data=[]]
r... |
def iter_item_handles(self):
"""Return iterator over item handles."""
for abspath in self._ls_abspaths_with_cache(self._data_abspath):
try:
relpath = self._get_metadata_with_cache(abspath, "handle")
yield relpath
except IrodsNoMetaDataSetError:
... | def function[iter_item_handles, parameter[self]]:
constant[Return iterator over item handles.]
for taget[name[abspath]] in starred[call[name[self]._ls_abspaths_with_cache, parameter[name[self]._data_abspath]]] begin[:]
<ast.Try object at 0x7da18dc99bd0> | keyword[def] identifier[iter_item_handles] ( identifier[self] ):
literal[string]
keyword[for] identifier[abspath] keyword[in] identifier[self] . identifier[_ls_abspaths_with_cache] ( identifier[self] . identifier[_data_abspath] ):
keyword[try] :
identifier[relpath] ... | def iter_item_handles(self):
"""Return iterator over item handles."""
for abspath in self._ls_abspaths_with_cache(self._data_abspath):
try:
relpath = self._get_metadata_with_cache(abspath, 'handle')
yield relpath # depends on [control=['try'], data=[]]
except IrodsNoMeta... |
def from_string(values, separator, remove_duplicates = False):
"""
Splits specified string into elements using a separator and assigns
the elements to a newly created AnyValueArray.
:param values: a string value to be split and assigned to AnyValueArray
:param separator: a sepa... | def function[from_string, parameter[values, separator, remove_duplicates]]:
constant[
Splits specified string into elements using a separator and assigns
the elements to a newly created AnyValueArray.
:param values: a string value to be split and assigned to AnyValueArray
:para... | keyword[def] identifier[from_string] ( identifier[values] , identifier[separator] , identifier[remove_duplicates] = keyword[False] ):
literal[string]
identifier[result] = identifier[AnyValueArray] ()
keyword[if] identifier[values] == keyword[None] keyword[or] identifier[len] ( identifi... | def from_string(values, separator, remove_duplicates=False):
"""
Splits specified string into elements using a separator and assigns
the elements to a newly created AnyValueArray.
:param values: a string value to be split and assigned to AnyValueArray
:param separator: a separator ... |
def CutAtClosestPoint(self, p):
"""
Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first point
returned in the secon... | def function[CutAtClosestPoint, parameter[self, p]]:
constant[
Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first ... | keyword[def] identifier[CutAtClosestPoint] ( identifier[self] , identifier[p] ):
literal[string]
( identifier[closest] , identifier[i] )= identifier[self] . identifier[GetClosestPoint] ( identifier[p] )
identifier[tmp] =[ identifier[closest] ]
identifier[tmp] . identifier[extend] ( identifier[sel... | def CutAtClosestPoint(self, p):
"""
Let x be the point on the polyline closest to p. Then
CutAtClosestPoint returns two new polylines, one representing
the polyline from the beginning up to x, and one representing
x onwards to the end of the polyline. x is the first point
returned in the secon... |
def decode_setid(encoded):
"""Decode setid as uint128"""
try:
lo, hi = struct.unpack('<QQ', b32decode(encoded.upper() + '======'))
except struct.error:
raise ValueError('Cannot decode {!r}'.format(encoded))
return (hi << 64) + lo | def function[decode_setid, parameter[encoded]]:
constant[Decode setid as uint128]
<ast.Try object at 0x7da1b26b44f0>
return[binary_operation[binary_operation[name[hi] <ast.LShift object at 0x7da2590d69e0> constant[64]] + name[lo]]] | keyword[def] identifier[decode_setid] ( identifier[encoded] ):
literal[string]
keyword[try] :
identifier[lo] , identifier[hi] = identifier[struct] . identifier[unpack] ( literal[string] , identifier[b32decode] ( identifier[encoded] . identifier[upper] ()+ literal[string] ))
keyword[except] i... | def decode_setid(encoded):
"""Decode setid as uint128"""
try:
(lo, hi) = struct.unpack('<QQ', b32decode(encoded.upper() + '======')) # depends on [control=['try'], data=[]]
except struct.error:
raise ValueError('Cannot decode {!r}'.format(encoded)) # depends on [control=['except'], data=[]... |
def parse_reports(self):
""" Find Picard InsertSizeMetrics reports and parse their data """
# Set up vars
self.picard_GCbias_data = dict()
self.picard_GCbiasSummary_data = dict()
# Go through logs and find Metrics
for f in self.find_log_files('picard/gcbias', filehandles=True):
s_name ... | def function[parse_reports, parameter[self]]:
constant[ Find Picard InsertSizeMetrics reports and parse their data ]
name[self].picard_GCbias_data assign[=] call[name[dict], parameter[]]
name[self].picard_GCbiasSummary_data assign[=] call[name[dict], parameter[]]
for taget[name[f]] in st... | keyword[def] identifier[parse_reports] ( identifier[self] ):
literal[string]
identifier[self] . identifier[picard_GCbias_data] = identifier[dict] ()
identifier[self] . identifier[picard_GCbiasSummary_data] = identifier[dict] ()
keyword[for] identifier[f] keyword[in] identifier[self... | def parse_reports(self):
""" Find Picard InsertSizeMetrics reports and parse their data """
# Set up vars
self.picard_GCbias_data = dict()
self.picard_GCbiasSummary_data = dict()
# Go through logs and find Metrics
for f in self.find_log_files('picard/gcbias', filehandles=True):
s_name = ... |
def protorpc_to_endpoints_error(self, status, body):
"""Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from ... | def function[protorpc_to_endpoints_error, parameter[self, status, body]]:
constant[Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HT... | keyword[def] identifier[protorpc_to_endpoints_error] ( identifier[self] , identifier[status] , identifier[body] ):
literal[string]
keyword[try] :
identifier[rpc_error] = identifier[self] . identifier[__PROTOJSON] . identifier[decode_message] ( identifier[remote] . identifier[RpcStatus] , identifier[... | def protorpc_to_endpoints_error(self, status, body):
"""Convert a ProtoRPC error to the format expected by Google Endpoints.
If the body does not contain an ProtoRPC message in state APPLICATION_ERROR
the status and body will be returned unchanged.
Args:
status: HTTP status of the response from ... |
def max_width(*args, **kwargs):
"""Returns formatted text or context manager for textui:puts.
>>> from clint.textui import puts, max_width
>>> max_width('123 5678', 8)
'123 5678'
>>> max_width('123 5678', 7)
'123 \n5678'
>>> with max_width(7):
... puts('1... | def function[max_width, parameter[]]:
constant[Returns formatted text or context manager for textui:puts.
>>> from clint.textui import puts, max_width
>>> max_width('123 5678', 8)
'123 5678'
>>> max_width('123 5678', 7)
'123
5678'
>>> with max_width(7):
... | keyword[def] identifier[max_width] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[args] = identifier[list] ( identifier[args] )
keyword[if] keyword[not] identifier[args] :
identifier[args] . identifier[append] ( identifier[kwargs] . identifier[get] ( literal[strin... | def max_width(*args, **kwargs):
"""Returns formatted text or context manager for textui:puts.
>>> from clint.textui import puts, max_width
>>> max_width('123 5678', 8)
'123 5678'
>>> max_width('123 5678', 7)
'123
5678'
>>> with max_width(7):
... puts('12... |
def mark(self):
"""
Mark the unit of work as failed in the database and update the listener
so as to skip it next time.
"""
self.reliableListener.lastRun = extime.Time()
BatchProcessingError(
store=self.reliableListener.store,
processor=self.reliab... | def function[mark, parameter[self]]:
constant[
Mark the unit of work as failed in the database and update the listener
so as to skip it next time.
]
name[self].reliableListener.lastRun assign[=] call[name[extime].Time, parameter[]]
call[name[BatchProcessingError], paramet... | keyword[def] identifier[mark] ( identifier[self] ):
literal[string]
identifier[self] . identifier[reliableListener] . identifier[lastRun] = identifier[extime] . identifier[Time] ()
identifier[BatchProcessingError] (
identifier[store] = identifier[self] . identifier[reliableListene... | def mark(self):
"""
Mark the unit of work as failed in the database and update the listener
so as to skip it next time.
"""
self.reliableListener.lastRun = extime.Time()
BatchProcessingError(store=self.reliableListener.store, processor=self.reliableListener.processor, listener=self.r... |
def mkCuttingStock(s):
"""mkCuttingStock: convert a bin packing instance into cutting stock format"""
w,q = [],[] # list of different widths (sizes) of items, their quantities
for item in sorted(s):
if w == [] or item != w[-1]:
w.append(item)
q.append(1)
else:
... | def function[mkCuttingStock, parameter[s]]:
constant[mkCuttingStock: convert a bin packing instance into cutting stock format]
<ast.Tuple object at 0x7da1b18e3df0> assign[=] tuple[[<ast.List object at 0x7da1b18e0820>, <ast.List object at 0x7da1b18e01f0>]]
for taget[name[item]] in starred[call[na... | keyword[def] identifier[mkCuttingStock] ( identifier[s] ):
literal[string]
identifier[w] , identifier[q] =[],[]
keyword[for] identifier[item] keyword[in] identifier[sorted] ( identifier[s] ):
keyword[if] identifier[w] ==[] keyword[or] identifier[item] != identifier[w] [- literal[int] ]:
... | def mkCuttingStock(s):
"""mkCuttingStock: convert a bin packing instance into cutting stock format"""
(w, q) = ([], []) # list of different widths (sizes) of items, their quantities
for item in sorted(s):
if w == [] or item != w[-1]:
w.append(item)
q.append(1) # depends on ... |
def extract(self, remotepath, subpath, saveaspath = None):
''' Usage: extract <remotepath> <subpath> [<saveaspath>]'''
rpath = get_pcs_path(remotepath)
topath = get_pcs_path(saveaspath)
if not saveaspath:
topath = os.path.dirname(rpath) + '/' + subpath
return self.__panapi_unzipcopy_file(rpath, subpath, to... | def function[extract, parameter[self, remotepath, subpath, saveaspath]]:
constant[ Usage: extract <remotepath> <subpath> [<saveaspath>]]
variable[rpath] assign[=] call[name[get_pcs_path], parameter[name[remotepath]]]
variable[topath] assign[=] call[name[get_pcs_path], parameter[name[saveaspath]]... | keyword[def] identifier[extract] ( identifier[self] , identifier[remotepath] , identifier[subpath] , identifier[saveaspath] = keyword[None] ):
literal[string]
identifier[rpath] = identifier[get_pcs_path] ( identifier[remotepath] )
identifier[topath] = identifier[get_pcs_path] ( identifier[saveaspath] )
k... | def extract(self, remotepath, subpath, saveaspath=None):
""" Usage: extract <remotepath> <subpath> [<saveaspath>]"""
rpath = get_pcs_path(remotepath)
topath = get_pcs_path(saveaspath)
if not saveaspath:
topath = os.path.dirname(rpath) + '/' + subpath # depends on [control=['if'], data=[]]
r... |
def command(state, args):
"""Add an anime from an AniDB search."""
args = parser.parse_args(args[1:])
if args.watching:
rows = query.select.select(state.db, 'regexp IS NOT NULL', [], ['aid'])
aids = [anime.aid for anime in rows]
elif args.incomplete:
rows = query.select.select(st... | def function[command, parameter[state, args]]:
constant[Add an anime from an AniDB search.]
variable[args] assign[=] call[name[parser].parse_args, parameter[call[name[args]][<ast.Slice object at 0x7da18ede63e0>]]]
if name[args].watching begin[:]
variable[rows] assign[=] call[name... | keyword[def] identifier[command] ( identifier[state] , identifier[args] ):
literal[string]
identifier[args] = identifier[parser] . identifier[parse_args] ( identifier[args] [ literal[int] :])
keyword[if] identifier[args] . identifier[watching] :
identifier[rows] = identifier[query] . identif... | def command(state, args):
"""Add an anime from an AniDB search."""
args = parser.parse_args(args[1:])
if args.watching:
rows = query.select.select(state.db, 'regexp IS NOT NULL', [], ['aid'])
aids = [anime.aid for anime in rows] # depends on [control=['if'], data=[]]
elif args.incomplet... |
def queries(self, last_updated_ms):
"""Get the updated queries."""
stats_logger.incr('queries')
if not g.user.get_id():
return json_error_response(
'Please login to access the queries.', status=403)
# Unix time, milliseconds.
last_updated_ms_int = int... | def function[queries, parameter[self, last_updated_ms]]:
constant[Get the updated queries.]
call[name[stats_logger].incr, parameter[constant[queries]]]
if <ast.UnaryOp object at 0x7da1b2061270> begin[:]
return[call[name[json_error_response], parameter[constant[Please login to access the ... | keyword[def] identifier[queries] ( identifier[self] , identifier[last_updated_ms] ):
literal[string]
identifier[stats_logger] . identifier[incr] ( literal[string] )
keyword[if] keyword[not] identifier[g] . identifier[user] . identifier[get_id] ():
keyword[return] identifier... | def queries(self, last_updated_ms):
"""Get the updated queries."""
stats_logger.incr('queries')
if not g.user.get_id():
return json_error_response('Please login to access the queries.', status=403) # depends on [control=['if'], data=[]]
# Unix time, milliseconds.
last_updated_ms_int = int(f... |
def is_locked(self, key):
"""
Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in k... | def function[is_locked, parameter[self, key]]:
constant[
Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __has... | keyword[def] identifier[is_locked] ( identifier[self] , identifier[key] ):
literal[string]
identifier[check_not_none] ( identifier[key] , literal[string] )
identifier[key_data] = identifier[self] . identifier[_to_data] ( identifier[key] )
keyword[return] identifier[self] . identi... | def is_locked(self, key):
"""
Checks the lock for the specified key. If the lock is acquired, returns ``true``. Otherwise, returns false.
**Warning: This method uses __hash__ and __eq__ methods of binary form of the key, not the actual implementations
of __hash__ and __eq__ defined in key's... |
def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0]
return None | def function[get_argument, parameter[self, name]]:
constant[Return single argument by name]
variable[val] assign[=] call[name[self].arguments.get, parameter[name[name]]]
if name[val] begin[:]
return[call[name[val]][constant[0]]]
return[constant[None]] | keyword[def] identifier[get_argument] ( identifier[self] , identifier[name] ):
literal[string]
identifier[val] = identifier[self] . identifier[arguments] . identifier[get] ( identifier[name] )
keyword[if] identifier[val] :
keyword[return] identifier[val] [ literal[int] ]
... | def get_argument(self, name):
"""Return single argument by name"""
val = self.arguments.get(name)
if val:
return val[0] # depends on [control=['if'], data=[]]
return None |
def clone(self, value=univ.noValue, **kwargs):
"""Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
... | def function[clone, parameter[self, value]]:
constant[Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
... | keyword[def] identifier[clone] ( identifier[self] , identifier[value] = identifier[univ] . identifier[noValue] ,** identifier[kwargs] ):
literal[string]
identifier[cloned] = identifier[univ] . identifier[Choice] . identifier[clone] ( identifier[self] ,** identifier[kwargs] )
keyword[if] ... | def clone(self, value=univ.noValue, **kwargs):
"""Clone this instance.
If *value* is specified, use its tag as the component type selector,
and itself as the component value.
:param value: (Optional) the component value.
:type value: :py:obj:`pyasn1.type.base.Asn1ItemBase`
... |
def get_firefox_binary():
"""Gets the firefox binary
@rtype: FirefoxBinary
"""
browser_config = BrowserConfig()
constants_config = ConstantsConfig()
log_dir = os.path.join(constants_config.get('logs_dir'), 'firefox')
create_directory(log_dir)
log_path = os.path.join(log_dir, '{}_{}.log... | def function[get_firefox_binary, parameter[]]:
constant[Gets the firefox binary
@rtype: FirefoxBinary
]
variable[browser_config] assign[=] call[name[BrowserConfig], parameter[]]
variable[constants_config] assign[=] call[name[ConstantsConfig], parameter[]]
variable[log_dir] assig... | keyword[def] identifier[get_firefox_binary] ():
literal[string]
identifier[browser_config] = identifier[BrowserConfig] ()
identifier[constants_config] = identifier[ConstantsConfig] ()
identifier[log_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[constants_config] . ident... | def get_firefox_binary():
"""Gets the firefox binary
@rtype: FirefoxBinary
"""
browser_config = BrowserConfig()
constants_config = ConstantsConfig()
log_dir = os.path.join(constants_config.get('logs_dir'), 'firefox')
create_directory(log_dir)
log_path = os.path.join(log_dir, '{}_{}.log'... |
def in_64(library, session, space, offset, extended=False):
"""Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... | def function[in_64, parameter[library, session, space, offset, extended]]:
constant[Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifie... | keyword[def] identifier[in_64] ( identifier[library] , identifier[session] , identifier[space] , identifier[offset] , identifier[extended] = keyword[False] ):
literal[string]
identifier[value_64] = identifier[ViUInt64] ()
keyword[if] identifier[extended] :
identifier[ret] = identifier[librar... | def in_64(library, session, space, offset, extended=False):
"""Reads in an 64-bit value from the specified memory space and offset.
Corresponds to viIn64* function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:para... |
def _construct_options(options_bootstrapper, build_configuration):
"""Parse and register options.
:returns: An Options object representing the full set of runtime options.
"""
# Now that plugins and backends are loaded, we can gather the known scopes.
# Gather the optionables that are not scoped t... | def function[_construct_options, parameter[options_bootstrapper, build_configuration]]:
constant[Parse and register options.
:returns: An Options object representing the full set of runtime options.
]
variable[top_level_optionables] assign[=] binary_operation[binary_operation[binary_operation[<... | keyword[def] identifier[_construct_options] ( identifier[options_bootstrapper] , identifier[build_configuration] ):
literal[string]
identifier[top_level_optionables] =(
{ identifier[GlobalOptionsRegistrar] }|
identifier[GlobalSubsystems] . identifier[get] ()|
identifier[build_... | def _construct_options(options_bootstrapper, build_configuration):
"""Parse and register options.
:returns: An Options object representing the full set of runtime options.
"""
# Now that plugins and backends are loaded, we can gather the known scopes.
# Gather the optionables that are not scoped to... |
def parse_quantity(string):
"""
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:return: float
"""
... | def function[parse_quantity, parameter[string]]:
constant[
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:... | keyword[def] identifier[parse_quantity] ( identifier[string] ):
literal[string]
identifier[number] , identifier[unit] = literal[string] , literal[string]
keyword[for] identifier[char] keyword[in] identifier[string] :
keyword[if] identifier[char] . identifier[isdigit] () k... | def parse_quantity(string):
"""
Parse quantity allows to convert the value in the resources spec like:
resources:
requests:
cpu: "100m"
memory": "200Mi"
limits:
memory: "300Mi"
:param string: str
:return: float
"""
(... |
def runtime_import(object_path):
"""Import at runtime."""
obj_module, obj_element = object_path.rsplit(".", 1)
loader = __import__(obj_module, globals(), locals(), [str(obj_element)])
return getattr(loader, obj_element) | def function[runtime_import, parameter[object_path]]:
constant[Import at runtime.]
<ast.Tuple object at 0x7da1b1d6d900> assign[=] call[name[object_path].rsplit, parameter[constant[.], constant[1]]]
variable[loader] assign[=] call[name[__import__], parameter[name[obj_module], call[name[globals], ... | keyword[def] identifier[runtime_import] ( identifier[object_path] ):
literal[string]
identifier[obj_module] , identifier[obj_element] = identifier[object_path] . identifier[rsplit] ( literal[string] , literal[int] )
identifier[loader] = identifier[__import__] ( identifier[obj_module] , identifier[glob... | def runtime_import(object_path):
"""Import at runtime."""
(obj_module, obj_element) = object_path.rsplit('.', 1)
loader = __import__(obj_module, globals(), locals(), [str(obj_element)])
return getattr(loader, obj_element) |
def between(self, start, end):
"""Adds new `BETWEEN` condition
:param start: int or datetime compatible object (in SNOW user's timezone)
:param end: int or datetime compatible object (in SNOW user's timezone)
:raise:
- QueryTypeError: if start or end arguments is of an inva... | def function[between, parameter[self, start, end]]:
constant[Adds new `BETWEEN` condition
:param start: int or datetime compatible object (in SNOW user's timezone)
:param end: int or datetime compatible object (in SNOW user's timezone)
:raise:
- QueryTypeError: if start or ... | keyword[def] identifier[between] ( identifier[self] , identifier[start] , identifier[end] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[start] , literal[string] ) keyword[and] identifier[hasattr] ( identifier[end] , literal[string] ):
identifier[dt_between] =(
... | def between(self, start, end):
"""Adds new `BETWEEN` condition
:param start: int or datetime compatible object (in SNOW user's timezone)
:param end: int or datetime compatible object (in SNOW user's timezone)
:raise:
- QueryTypeError: if start or end arguments is of an invalid ... |
def prepare(self, params):
"""
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
"""
jsonparams = json... | def function[prepare, parameter[self, params]]:
constant[
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
]
... | keyword[def] identifier[prepare] ( identifier[self] , identifier[params] ):
literal[string]
identifier[jsonparams] = identifier[json] . identifier[dumps] ( identifier[params] )
identifier[payload] = identifier[base64] . identifier[b64encode] ( identifier[jsonparams] . identifier[encode] ()... | def prepare(self, params):
"""
Prepare, return the required HTTP headers.
Base 64 encode the parameters, sign it with the secret key,
create the HTTP headers, return the whole payload.
Arguments:
params -- a dictionary of parameters
"""
jsonparams = json.dumps(p... |
def string2latlon(lat_str, lon_str, format_str):
'''
Create a LatLon object from a pair of strings.
Inputs:
lat_str (str) - string representation of a latitude (e.g. '5 52 59.88 N')
lon_str (str) - string representation of a longitude (e.g. '162 4 59.88 W')
format_str (str) - format ... | def function[string2latlon, parameter[lat_str, lon_str, format_str]]:
constant[
Create a LatLon object from a pair of strings.
Inputs:
lat_str (str) - string representation of a latitude (e.g. '5 52 59.88 N')
lon_str (str) - string representation of a longitude (e.g. '162 4 59.88 W')
... | keyword[def] identifier[string2latlon] ( identifier[lat_str] , identifier[lon_str] , identifier[format_str] ):
literal[string]
identifier[lat] = identifier[string2geocoord] ( identifier[lat_str] , identifier[Latitude] , identifier[format_str] )
identifier[lon] = identifier[string2geocoord] ( identifie... | def string2latlon(lat_str, lon_str, format_str):
"""
Create a LatLon object from a pair of strings.
Inputs:
lat_str (str) - string representation of a latitude (e.g. '5 52 59.88 N')
lon_str (str) - string representation of a longitude (e.g. '162 4 59.88 W')
format_str (str) - format ... |
def load(cls,
config: Params,
serialization_dir: str,
weights_file: str = None,
cuda_device: int = -1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters... | def function[load, parameter[cls, config, serialization_dir, weights_file, cuda_device]]:
constant[
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters
----------
config: Params
The configuratio... | keyword[def] identifier[load] ( identifier[cls] ,
identifier[config] : identifier[Params] ,
identifier[serialization_dir] : identifier[str] ,
identifier[weights_file] : identifier[str] = keyword[None] ,
identifier[cuda_device] : identifier[int] =- literal[int] )-> literal[string] :
literal[string]
... | def load(cls, config: Params, serialization_dir: str, weights_file: str=None, cuda_device: int=-1) -> 'Model':
"""
Instantiates an already-trained model, based on the experiment
configuration and some optional overrides.
Parameters
----------
config: Params
The c... |
def tasks(self, task_cls=None):
""" :meth:`.WTaskRegistryBase.tasks` implementation
"""
result = []
for tasks in self.__registry.values():
result.extend(tasks)
if task_cls is not None:
result = filter(lambda x: issubclass(x, task_cls), result)
return tuple(result) | def function[tasks, parameter[self, task_cls]]:
constant[ :meth:`.WTaskRegistryBase.tasks` implementation
]
variable[result] assign[=] list[[]]
for taget[name[tasks]] in starred[call[name[self].__registry.values, parameter[]]] begin[:]
call[name[result].extend, parameter[name[t... | keyword[def] identifier[tasks] ( identifier[self] , identifier[task_cls] = keyword[None] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[tasks] keyword[in] identifier[self] . identifier[__registry] . identifier[values] ():
identifier[result] . identifier[extend] ( identifier[tasks] ... | def tasks(self, task_cls=None):
""" :meth:`.WTaskRegistryBase.tasks` implementation
"""
result = []
for tasks in self.__registry.values():
result.extend(tasks) # depends on [control=['for'], data=['tasks']]
if task_cls is not None:
result = filter(lambda x: issubclass(x, task_cls), re... |
def get_service_info(self):
"""
Get information about Workflow Execution Service. May
include information related (but not limited to) the
workflow descriptor formats, versions supported, the
WES API versions supported, and information about general
the service availabili... | def function[get_service_info, parameter[self]]:
constant[
Get information about Workflow Execution Service. May
include information related (but not limited to) the
workflow descriptor formats, versions supported, the
WES API versions supported, and information about general
... | keyword[def] identifier[get_service_info] ( identifier[self] ):
literal[string]
identifier[postresult] = identifier[requests] . identifier[get] ( literal[string] %( identifier[self] . identifier[proto] , identifier[self] . identifier[host] ),
identifier[headers] = identifier[self] . identi... | def get_service_info(self):
"""
Get information about Workflow Execution Service. May
include information related (but not limited to) the
workflow descriptor formats, versions supported, the
WES API versions supported, and information about general
the service availability.
... |
def as_xml(self,parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
if s... | def function[as_xml, parameter[self, parent]]:
constant[Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libx... | keyword[def] identifier[as_xml] ( identifier[self] , identifier[parent] ):
literal[string]
keyword[if] identifier[self] . identifier[value] keyword[in] ( literal[string] , literal[string] , literal[string] ):
identifier[n] = identifier[parent] . identifier[newChild] ( keyword[None] ,... | def as_xml(self, parent):
"""Create vcard-tmp XML representation of the field.
:Parameters:
- `parent`: parent node for the element
:Types:
- `parent`: `libxml2.xmlNode`
:return: xml node with the field data.
:returntype: `libxml2.xmlNode`"""
if self.val... |
def p_expr1(p):
"""expr1 : MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
| NEG expr
| HANDLE ident
| PLUSPLUS ident
| MINUSMINUS ident
"""
p[0] = node.expr(op=p[1], args=node.expr_list([p[2]])) | def function[p_expr1, parameter[p]]:
constant[expr1 : MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
| NEG expr
| HANDLE ident
| PLUSPLUS ident
| MINUSMINUS ident
]
call[name[p]][constant[0]] assign[=] call[name[node].expr, parameter... | keyword[def] identifier[p_expr1] ( identifier[p] ):
literal[string]
identifier[p] [ literal[int] ]= identifier[node] . identifier[expr] ( identifier[op] = identifier[p] [ literal[int] ], identifier[args] = identifier[node] . identifier[expr_list] ([ identifier[p] [ literal[int] ]])) | def p_expr1(p):
"""expr1 : MINUS expr %prec UMINUS
| PLUS expr %prec UMINUS
| NEG expr
| HANDLE ident
| PLUSPLUS ident
| MINUSMINUS ident
"""
p[0] = node.expr(op=p[1], args=node.expr_list([p[2]])) |
def default_asset_manager(self):
"""
Returns the default asset manager using the current config.
This is only used if asset_manager is set to None in the constructor.
"""
cache_path = None
cache_directory = self.config['CACHE_DIRECTORY']
if cache_directory:
... | def function[default_asset_manager, parameter[self]]:
constant[
Returns the default asset manager using the current config.
This is only used if asset_manager is set to None in the constructor.
]
variable[cache_path] assign[=] constant[None]
variable[cache_directory] ass... | keyword[def] identifier[default_asset_manager] ( identifier[self] ):
literal[string]
identifier[cache_path] = keyword[None]
identifier[cache_directory] = identifier[self] . identifier[config] [ literal[string] ]
keyword[if] identifier[cache_directory] :
identifier[c... | def default_asset_manager(self):
"""
Returns the default asset manager using the current config.
This is only used if asset_manager is set to None in the constructor.
"""
cache_path = None
cache_directory = self.config['CACHE_DIRECTORY']
if cache_directory:
cache_directo... |
def setup_graph(self):
"""
Creates our Graph and figures out, which shared/global model to hook up to.
If we are in a global-model's setup procedure, we do not create
a new graph (return None as the context). We will instead use the already existing local replica graph
of the mod... | def function[setup_graph, parameter[self]]:
constant[
Creates our Graph and figures out, which shared/global model to hook up to.
If we are in a global-model's setup procedure, we do not create
a new graph (return None as the context). We will instead use the already existing local repli... | keyword[def] identifier[setup_graph] ( identifier[self] ):
literal[string]
identifier[graph_default_context] = keyword[None]
keyword[if] identifier[self] . identifier[execution_type] == literal[string] :
identifier[self] . identifier[graph] = identifier[tf] . ident... | def setup_graph(self):
"""
Creates our Graph and figures out, which shared/global model to hook up to.
If we are in a global-model's setup procedure, we do not create
a new graph (return None as the context). We will instead use the already existing local replica graph
of the model.
... |
def refine (self, requirements):
""" Refines this set's properties using the requirements passed as an argument.
"""
assert isinstance(requirements, PropertySet)
if requirements not in self.refined_:
r = property.refine(self.all_, requirements.all_)
self.refined_... | def function[refine, parameter[self, requirements]]:
constant[ Refines this set's properties using the requirements passed as an argument.
]
assert[call[name[isinstance], parameter[name[requirements], name[PropertySet]]]]
if compare[name[requirements] <ast.NotIn object at 0x7da2590d7190> nam... | keyword[def] identifier[refine] ( identifier[self] , identifier[requirements] ):
literal[string]
keyword[assert] identifier[isinstance] ( identifier[requirements] , identifier[PropertySet] )
keyword[if] identifier[requirements] keyword[not] keyword[in] identifier[self] . identifier[re... | def refine(self, requirements):
""" Refines this set's properties using the requirements passed as an argument.
"""
assert isinstance(requirements, PropertySet)
if requirements not in self.refined_:
r = property.refine(self.all_, requirements.all_)
self.refined_[requirements] = creat... |
def clean_config(config):
"""Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All failed values will be replaced
b... | def function[clean_config, parameter[config]]:
constant[Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All faile... | keyword[def] identifier[clean_config] ( identifier[config] ):
literal[string]
keyword[if] identifier[config] . identifier[configspec] keyword[is] keyword[None] :
keyword[return]
identifier[vld] = identifier[Validator] ()
identifier[validation] = identifier[config] . identifier[valida... | def clean_config(config):
"""Check if all values have defaults and replace errors with their default value
:param config: the configobj to clean
:type config: ConfigObj
:returns: None
:raises: ConfigError
The object is validated, so we need a spec file. All failed values will be replaced
b... |
def read_dir(path, folder):
""" Returns a list of relative file paths to `path` for all files within `folder` """
full_path = os.path.join(path, folder)
fnames = glob(f"{full_path}/*.*")
directories = glob(f"{full_path}/*/")
if any(fnames):
return [os.path.relpath(f,path) for f in fnames]
... | def function[read_dir, parameter[path, folder]]:
constant[ Returns a list of relative file paths to `path` for all files within `folder` ]
variable[full_path] assign[=] call[name[os].path.join, parameter[name[path], name[folder]]]
variable[fnames] assign[=] call[name[glob], parameter[<ast.Joined... | keyword[def] identifier[read_dir] ( identifier[path] , identifier[folder] ):
literal[string]
identifier[full_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[path] , identifier[folder] )
identifier[fnames] = identifier[glob] ( literal[string] )
identifier[directories] = i... | def read_dir(path, folder):
""" Returns a list of relative file paths to `path` for all files within `folder` """
full_path = os.path.join(path, folder)
fnames = glob(f'{full_path}/*.*')
directories = glob(f'{full_path}/*/')
if any(fnames):
return [os.path.relpath(f, path) for f in fnames] ... |
def loads(cls, data, store_password, try_decrypt_keys=True):
"""
See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whether to automatically t... | def function[loads, parameter[cls, data, store_password, try_decrypt_keys]]:
constant[
See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whet... | keyword[def] identifier[loads] ( identifier[cls] , identifier[data] , identifier[store_password] , identifier[try_decrypt_keys] = keyword[True] ):
literal[string]
keyword[try] :
identifier[pos] = literal[int]
... | def loads(cls, data, store_password, try_decrypt_keys=True):
"""
See :meth:`jks.jks.KeyStore.loads`.
:param bytes data: Byte string representation of the keystore to be loaded.
:param str password: Keystore password string
:param bool try_decrypt_keys: Whether to automatically try t... |
def t_prepro_define_pragma_defargs_defargsopt_CONTINUE(self, t):
r'[_\\]\r?\n'
t.lexer.lineno += 1
t.value = t.value[1:]
t.type = 'NEWLINE'
return t | def function[t_prepro_define_pragma_defargs_defargsopt_CONTINUE, parameter[self, t]]:
constant[[_\\]\r?\n]
<ast.AugAssign object at 0x7da1b0652890>
name[t].value assign[=] call[name[t].value][<ast.Slice object at 0x7da1b06535e0>]
name[t].type assign[=] constant[NEWLINE]
return[name[t]] | keyword[def] identifier[t_prepro_define_pragma_defargs_defargsopt_CONTINUE] ( identifier[self] , identifier[t] ):
literal[string]
identifier[t] . identifier[lexer] . identifier[lineno] += literal[int]
identifier[t] . identifier[value] = identifier[t] . identifier[value] [ literal[int] :]
... | def t_prepro_define_pragma_defargs_defargsopt_CONTINUE(self, t):
"""[_\\\\]\\r?\\n"""
t.lexer.lineno += 1
t.value = t.value[1:]
t.type = 'NEWLINE'
return t |
def _dasd_reverse_conversion(cls, val, **kwargs):
'''
converts DASD String values to the reg_sz value
'''
if val is not None:
if val.upper() == 'ADMINISTRATORS':
# "" also shows 'administrators' in the GUI
return '0'
elif val.upper(... | def function[_dasd_reverse_conversion, parameter[cls, val]]:
constant[
converts DASD String values to the reg_sz value
]
if compare[name[val] is_not constant[None]] begin[:]
if compare[call[name[val].upper, parameter[]] equal[==] constant[ADMINISTRATORS]] begin[:]
... | keyword[def] identifier[_dasd_reverse_conversion] ( identifier[cls] , identifier[val] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[val] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[val] . identifier[upper] ()== literal[string] :
... | def _dasd_reverse_conversion(cls, val, **kwargs):
"""
converts DASD String values to the reg_sz value
"""
if val is not None:
if val.upper() == 'ADMINISTRATORS':
# "" also shows 'administrators' in the GUI
return '0' # depends on [control=['if'], data=[]]
... |
def translate(self, vector):
"""Translates `Atom`.
Parameters
----------
vector : 3D Vector (tuple, list, numpy.array)
Vector used for translation.
inc_alt_states : bool, optional
If true, will rotate atoms in all states i.e. includes
alternat... | def function[translate, parameter[self, vector]]:
constant[Translates `Atom`.
Parameters
----------
vector : 3D Vector (tuple, list, numpy.array)
Vector used for translation.
inc_alt_states : bool, optional
If true, will rotate atoms in all states i.e. in... | keyword[def] identifier[translate] ( identifier[self] , identifier[vector] ):
literal[string]
identifier[vector] = identifier[numpy] . identifier[array] ( identifier[vector] )
identifier[self] . identifier[_vector] += identifier[numpy] . identifier[array] ( identifier[vector] )
ke... | def translate(self, vector):
"""Translates `Atom`.
Parameters
----------
vector : 3D Vector (tuple, list, numpy.array)
Vector used for translation.
inc_alt_states : bool, optional
If true, will rotate atoms in all states i.e. includes
alternate co... |
def read(*args):
"""Reads complete file contents."""
return io.open(os.path.join(HERE, *args), encoding="utf-8").read() | def function[read, parameter[]]:
constant[Reads complete file contents.]
return[call[call[name[io].open, parameter[call[name[os].path.join, parameter[name[HERE], <ast.Starred object at 0x7da1b26ad8a0>]]]].read, parameter[]]] | keyword[def] identifier[read] (* identifier[args] ):
literal[string]
keyword[return] identifier[io] . identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[HERE] ,* identifier[args] ), identifier[encoding] = literal[string] ). identifier[read] () | def read(*args):
"""Reads complete file contents."""
return io.open(os.path.join(HERE, *args), encoding='utf-8').read() |
def to_swc(self):
"""
Prototype SWC file generator.
c.f. http://research.mssm.edu/cnic/swc.html
"""
from . import __version__
swc = """# ORIGINAL_SOURCE CloudVolume {}
# CREATURE
# REGION
# FIELD/LAYER
# TYPE
# CONTRIBUTOR {}
# REFERENCE
# RAW
# EXTRAS
# SOMA_AREA
# SHINKAGE_CORRECTION
# V... | def function[to_swc, parameter[self]]:
constant[
Prototype SWC file generator.
c.f. http://research.mssm.edu/cnic/swc.html
]
from relative_module[None] import module[__version__]
variable[swc] assign[=] call[constant[# ORIGINAL_SOURCE CloudVolume {}
# CREATURE
# REGION
# FIELD/LAYER
#... | keyword[def] identifier[to_swc] ( identifier[self] ):
literal[string]
keyword[from] . keyword[import] identifier[__version__]
identifier[swc] = literal[string] . identifier[format] (
identifier[__version__] ,
literal[string] . identifier[join] ([ identifier[str] ( identifier[_] ) keyword[f... | def to_swc(self):
"""
Prototype SWC file generator.
c.f. http://research.mssm.edu/cnic/swc.html
"""
from . import __version__
swc = '# ORIGINAL_SOURCE CloudVolume {}\n# CREATURE \n# REGION\n# FIELD/LAYER\n# TYPE\n# CONTRIBUTOR {}\n# REFERENCE\n# RAW \n# EXTRAS \n# SOMA_AREA\n# SHINKAGE_CORRECT... |
def is_same_file (filename1, filename2):
"""Check if filename1 and filename2 point to the same file object.
There can be false negatives, ie. the result is False, but it is
the same file anyway. Reason is that network filesystems can create
different paths to the same physical file.
"""
if filen... | def function[is_same_file, parameter[filename1, filename2]]:
constant[Check if filename1 and filename2 point to the same file object.
There can be false negatives, ie. the result is False, but it is
the same file anyway. Reason is that network filesystems can create
different paths to the same physi... | keyword[def] identifier[is_same_file] ( identifier[filename1] , identifier[filename2] ):
literal[string]
keyword[if] identifier[filename1] == identifier[filename2] :
keyword[return] keyword[True]
keyword[if] identifier[os] . identifier[name] == literal[string] :
keyword[return] ... | def is_same_file(filename1, filename2):
"""Check if filename1 and filename2 point to the same file object.
There can be false negatives, ie. the result is False, but it is
the same file anyway. Reason is that network filesystems can create
different paths to the same physical file.
"""
if filena... |
def prop2b(gm, pvinit, dt):
"""
Given a central mass and the state of massless body at time t_0,
this routine determines the state as predicted by a two-body
force model at time t_0 + dt.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prop2b_c.html
:param gm: Gravity of the central ma... | def function[prop2b, parameter[gm, pvinit, dt]]:
constant[
Given a central mass and the state of massless body at time t_0,
this routine determines the state as predicted by a two-body
force model at time t_0 + dt.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prop2b_c.html
:para... | keyword[def] identifier[prop2b] ( identifier[gm] , identifier[pvinit] , identifier[dt] ):
literal[string]
identifier[gm] = identifier[ctypes] . identifier[c_double] ( identifier[gm] )
identifier[pvinit] = identifier[stypes] . identifier[toDoubleVector] ( identifier[pvinit] )
identifier[dt] = iden... | def prop2b(gm, pvinit, dt):
"""
Given a central mass and the state of massless body at time t_0,
this routine determines the state as predicted by a two-body
force model at time t_0 + dt.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/prop2b_c.html
:param gm: Gravity of the central ma... |
def itemByPath( self, path, includeRoot = False ):
"""
Loads the items for the given path.
:param path | <str>
includeRoot | <bool>
"""
sep = self.separator()
path = nativestring(path).strip(sep)
if ( not path ):
... | def function[itemByPath, parameter[self, path, includeRoot]]:
constant[
Loads the items for the given path.
:param path | <str>
includeRoot | <bool>
]
variable[sep] assign[=] call[name[self].separator, parameter[]]
variable[path] a... | keyword[def] identifier[itemByPath] ( identifier[self] , identifier[path] , identifier[includeRoot] = keyword[False] ):
literal[string]
identifier[sep] = identifier[self] . identifier[separator] ()
identifier[path] = identifier[nativestring] ( identifier[path] ). identifier[strip] ( identi... | def itemByPath(self, path, includeRoot=False):
"""
Loads the items for the given path.
:param path | <str>
includeRoot | <bool>
"""
sep = self.separator()
path = nativestring(path).strip(sep)
if not path:
if includeRoot:
... |
def gridlines(ax, scale, multiple=None, horizontal_kwargs=None,
left_kwargs=None, right_kwargs=None, **kwargs):
"""
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
... | def function[gridlines, parameter[ax, scale, multiple, horizontal_kwargs, left_kwargs, right_kwargs]]:
constant[
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
multiple:... | keyword[def] identifier[gridlines] ( identifier[ax] , identifier[scale] , identifier[multiple] = keyword[None] , identifier[horizontal_kwargs] = keyword[None] ,
identifier[left_kwargs] = keyword[None] , identifier[right_kwargs] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] litera... | def gridlines(ax, scale, multiple=None, horizontal_kwargs=None, left_kwargs=None, right_kwargs=None, **kwargs):
"""
Plots grid lines excluding boundary.
Parameters
----------
ax: Matplotlib AxesSubplot, None
The subplot to draw on.
scale: float
Simplex scale size.
multiple: ... |
def putcellslice(self, rownr, value, blc, trc, inc=[]):
"""Put into a slice of a table cell holding an array.
(see :func:`table.putcellslice`)"""
return self._table.putcellslice(self._column, rownr, value, blc, trc, inc) | def function[putcellslice, parameter[self, rownr, value, blc, trc, inc]]:
constant[Put into a slice of a table cell holding an array.
(see :func:`table.putcellslice`)]
return[call[name[self]._table.putcellslice, parameter[name[self]._column, name[rownr], name[value], name[blc], name[trc], name[inc]]... | keyword[def] identifier[putcellslice] ( identifier[self] , identifier[rownr] , identifier[value] , identifier[blc] , identifier[trc] , identifier[inc] =[]):
literal[string]
keyword[return] identifier[self] . identifier[_table] . identifier[putcellslice] ( identifier[self] . identifier[_column] , i... | def putcellslice(self, rownr, value, blc, trc, inc=[]):
"""Put into a slice of a table cell holding an array.
(see :func:`table.putcellslice`)"""
return self._table.putcellslice(self._column, rownr, value, blc, trc, inc) |
def dasopr(fname):
"""
Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int
"""
fname = stypes.stringToCharP(fn... | def function[dasopr, parameter[fname]]:
constant[
Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int
]
... | keyword[def] identifier[dasopr] ( identifier[fname] ):
literal[string]
identifier[fname] = identifier[stypes] . identifier[stringToCharP] ( identifier[fname] )
identifier[handle] = identifier[ctypes] . identifier[c_int] ()
identifier[libspice] . identifier[dasopr_c] ( identifier[fname] , identifi... | def dasopr(fname):
"""
Open a DAS file for reading.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopr_c.html
:param fname: Name of a DAS file to be opened.
:type fname: str
:return: Handle assigned to the opened DAS file.
:rtype: int
"""
fname = stypes.stringToCharP(fn... |
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST:
"""Return a Python AST Node for a `let*` expression."""
assert node.op == NodeOp.LET
with ctx.new_symbol_table("let"):
let_body_ast: List[ast.AST] = []
for binding in node.bindings:
init_node = binding.init
... | def function[_let_to_py_ast, parameter[ctx, node]]:
constant[Return a Python AST Node for a `let*` expression.]
assert[compare[name[node].op equal[==] name[NodeOp].LET]]
with call[name[ctx].new_symbol_table, parameter[constant[let]]] begin[:]
<ast.AnnAssign object at 0x7da1b0285300>
... | keyword[def] identifier[_let_to_py_ast] ( identifier[ctx] : identifier[GeneratorContext] , identifier[node] : identifier[Let] )-> identifier[GeneratedPyAST] :
literal[string]
keyword[assert] identifier[node] . identifier[op] == identifier[NodeOp] . identifier[LET]
keyword[with] identifier[ctx] . i... | def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST:
"""Return a Python AST Node for a `let*` expression."""
assert node.op == NodeOp.LET
with ctx.new_symbol_table('let'):
let_body_ast: List[ast.AST] = []
for binding in node.bindings:
init_node = binding.init
... |
def set_servo_position(self, goalposition, goaltime, led):
""" Set the position of Herkulex
Enable torque using torque_on function before calling this
Args:
goalposition (int): The desired position, min-0 & max-1023
goaltime (int): the time taken to move from present
... | def function[set_servo_position, parameter[self, goalposition, goaltime, led]]:
constant[ Set the position of Herkulex
Enable torque using torque_on function before calling this
Args:
goalposition (int): The desired position, min-0 & max-1023
goaltime (int): the time t... | keyword[def] identifier[set_servo_position] ( identifier[self] , identifier[goalposition] , identifier[goaltime] , identifier[led] ):
literal[string]
identifier[goalposition_msb] = identifier[int] ( identifier[goalposition] )>> literal[int]
identifier[goalposition_lsb] = identifier[int] (... | def set_servo_position(self, goalposition, goaltime, led):
""" Set the position of Herkulex
Enable torque using torque_on function before calling this
Args:
goalposition (int): The desired position, min-0 & max-1023
goaltime (int): the time taken to move from present
... |
def earth_gyro(RAW_IMU,ATTITUDE):
'''return earth frame gyro vector'''
r = rotation(ATTITUDE)
accel = Vector3(degrees(RAW_IMU.xgyro), degrees(RAW_IMU.ygyro), degrees(RAW_IMU.zgyro)) * 0.001
return r * accel | def function[earth_gyro, parameter[RAW_IMU, ATTITUDE]]:
constant[return earth frame gyro vector]
variable[r] assign[=] call[name[rotation], parameter[name[ATTITUDE]]]
variable[accel] assign[=] binary_operation[call[name[Vector3], parameter[call[name[degrees], parameter[name[RAW_IMU].xgyro]], cal... | keyword[def] identifier[earth_gyro] ( identifier[RAW_IMU] , identifier[ATTITUDE] ):
literal[string]
identifier[r] = identifier[rotation] ( identifier[ATTITUDE] )
identifier[accel] = identifier[Vector3] ( identifier[degrees] ( identifier[RAW_IMU] . identifier[xgyro] ), identifier[degrees] ( identifier[... | def earth_gyro(RAW_IMU, ATTITUDE):
"""return earth frame gyro vector"""
r = rotation(ATTITUDE)
accel = Vector3(degrees(RAW_IMU.xgyro), degrees(RAW_IMU.ygyro), degrees(RAW_IMU.zgyro)) * 0.001
return r * accel |
def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs):
"""Overridden to only call `notify` if model matches.
"""
notified = False
instance = kwargs.get("instance")
if instance._meta.label_lower == self.model:
notified = super().notify(
... | def function[notify, parameter[self, force_notify, use_email, use_sms]]:
constant[Overridden to only call `notify` if model matches.
]
variable[notified] assign[=] constant[False]
variable[instance] assign[=] call[name[kwargs].get, parameter[constant[instance]]]
if compare[name[i... | keyword[def] identifier[notify] ( identifier[self] , identifier[force_notify] = keyword[None] , identifier[use_email] = keyword[None] , identifier[use_sms] = keyword[None] ,** identifier[kwargs] ):
literal[string]
identifier[notified] = keyword[False]
identifier[instance] = identifier[kwa... | def notify(self, force_notify=None, use_email=None, use_sms=None, **kwargs):
"""Overridden to only call `notify` if model matches.
"""
notified = False
instance = kwargs.get('instance')
if instance._meta.label_lower == self.model:
notified = super().notify(force_notify=force_notify, use_... |
def create_datacenter(service_instance, datacenter_name):
'''
Creates a datacenter.
.. versionadded:: 2017.7.0
service_instance
The Service Instance Object
datacenter_name
The datacenter name
'''
root_folder = get_root_folder(service_instance)
log.trace('Creating datac... | def function[create_datacenter, parameter[service_instance, datacenter_name]]:
constant[
Creates a datacenter.
.. versionadded:: 2017.7.0
service_instance
The Service Instance Object
datacenter_name
The datacenter name
]
variable[root_folder] assign[=] call[name[ge... | keyword[def] identifier[create_datacenter] ( identifier[service_instance] , identifier[datacenter_name] ):
literal[string]
identifier[root_folder] = identifier[get_root_folder] ( identifier[service_instance] )
identifier[log] . identifier[trace] ( literal[string] , identifier[datacenter_name] )
k... | def create_datacenter(service_instance, datacenter_name):
"""
Creates a datacenter.
.. versionadded:: 2017.7.0
service_instance
The Service Instance Object
datacenter_name
The datacenter name
"""
root_folder = get_root_folder(service_instance)
log.trace("Creating datac... |
def _check_json_data(self, json_data):
"""
Ensure that the request body is both a hash and has a data key.
:param json_data: The json data provided with the request
"""
if not isinstance(json_data, dict):
raise BadRequestError('Request body should be a JSON hash')
... | def function[_check_json_data, parameter[self, json_data]]:
constant[
Ensure that the request body is both a hash and has a data key.
:param json_data: The json data provided with the request
]
if <ast.UnaryOp object at 0x7da1b0ed18d0> begin[:]
<ast.Raise object at 0x7da... | keyword[def] identifier[_check_json_data] ( identifier[self] , identifier[json_data] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[json_data] , identifier[dict] ):
keyword[raise] identifier[BadRequestError] ( literal[string] )
keyword[if] ... | def _check_json_data(self, json_data):
"""
Ensure that the request body is both a hash and has a data key.
:param json_data: The json data provided with the request
"""
if not isinstance(json_data, dict):
raise BadRequestError('Request body should be a JSON hash') # depends on ... |
def translate_to_dbus_type(typeof, value):
"""
Helper function to map values from their native Python types
to Dbus types.
:param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
:param value: Value to assign using type 'typeof'
:return: 'value' converted to type 'typeof'
:rt... | def function[translate_to_dbus_type, parameter[typeof, value]]:
constant[
Helper function to map values from their native Python types
to Dbus types.
:param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
:param value: Value to assign using type 'typeof'
:return: 'value' con... | keyword[def] identifier[translate_to_dbus_type] ( identifier[typeof] , identifier[value] ):
literal[string]
keyword[if] (( identifier[isinstance] ( identifier[value] , identifier[types] . identifier[UnicodeType] ) keyword[or]
identifier[isinstance] ( identifier[value] , identifier[str] )) keyword[and... | def translate_to_dbus_type(typeof, value):
"""
Helper function to map values from their native Python types
to Dbus types.
:param type typeof: Target for type conversion e.g., 'dbus.Dictionary'
:param value: Value to assign using type 'typeof'
:return: 'value' converted to type 'typeof'
:rt... |
def selected_subcategory(self):
"""Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None
"""
item = self.lstSubcategories.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole))
except ... | def function[selected_subcategory, parameter[self]]:
constant[Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None
]
variable[item] assign[=] call[name[self].lstSubcategories.currentItem, parameter[]]
<ast.Try object at ... | keyword[def] identifier[selected_subcategory] ( identifier[self] ):
literal[string]
identifier[item] = identifier[self] . identifier[lstSubcategories] . identifier[currentItem] ()
keyword[try] :
keyword[return] identifier[definition] ( identifier[item] . identifier[data] ( id... | def selected_subcategory(self):
"""Obtain the subcategory selected by user.
:returns: Metadata of the selected subcategory.
:rtype: dict, None
"""
item = self.lstSubcategories.currentItem()
try:
return definition(item.data(QtCore.Qt.UserRole)) # depends on [control=['try'],... |
def alert_policy_condition_path(cls, project, alert_policy, condition):
"""Return a fully-qualified alert_policy_condition string."""
return google.api_core.path_template.expand(
"projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}",
project=project,
... | def function[alert_policy_condition_path, parameter[cls, project, alert_policy, condition]]:
constant[Return a fully-qualified alert_policy_condition string.]
return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}]]]] | keyword[def] identifier[alert_policy_condition_path] ( identifier[cls] , identifier[project] , identifier[alert_policy] , identifier[condition] ):
literal[string]
keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] (
literal[string] ,... | def alert_policy_condition_path(cls, project, alert_policy, condition):
"""Return a fully-qualified alert_policy_condition string."""
return google.api_core.path_template.expand('projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}', project=project, alert_policy=alert_policy, condition=condit... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.