code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_info(self, symbol, as_of=None):
"""
Reads and returns information about the data stored for symbol
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of th... | Reads and returns information about the data stored for symbol
Parameters
----------
symbol : `str`
symbol name for the item
as_of : `str` or int or `datetime.datetime`
Return the data as it was as_of the point in time.
`int` : specific version number... |
def set_installed_packages():
"""Idempotently caches the list of packages installed in the virtualenv.
Can be run safely before the virtualenv is created, and will be rerun
afterwards.
"""
global INSTALLED_PACKAGES, REQUIRED_VERSION
if INSTALLED_PACKAGES:
return
if os.path.exi... | Idempotently caches the list of packages installed in the virtualenv.
Can be run safely before the virtualenv is created, and will be rerun
afterwards. |
def _writeStructureLink(self, link, fileObject, replaceParamFile):
"""
Write Structure Link to File Method
"""
fileObject.write('%s\n' % link.type)
fileObject.write('NUMSTRUCTS %s\n' % link.numElements)
# Retrieve lists of structures
weirs = link.weirs
... | Write Structure Link to File Method |
def _get_top_states(saltenv='base'):
'''
Equivalent to a salt cli: salt web state.show_top
'''
alt_states = []
try:
returned = __salt__['state.show_top']()
for i in returned[saltenv]:
alt_states.append(i)
except Exception:
raise
# log.info("top states: %s"... | Equivalent to a salt cli: salt web state.show_top |
def _select_word_cursor(self):
""" Selects the word under the mouse cursor. """
cursor = TextHelper(self.editor).word_under_mouse_cursor()
if (self._previous_cursor_start != cursor.selectionStart() and
self._previous_cursor_end != cursor.selectionEnd()):
self._remove_... | Selects the word under the mouse cursor. |
def _part_cls_for(cls, content_type):
"""
Return the custom part class registered for *content_type*, or the
default part class if no custom class is registered for
*content_type*.
"""
if content_type in cls.part_type_for:
return cls.part_type_for[content_type... | Return the custom part class registered for *content_type*, or the
default part class if no custom class is registered for
*content_type*. |
def adult(display=False):
""" Return the Adult census data in a nice package. """
dtypes = [
("Age", "float32"), ("Workclass", "category"), ("fnlwgt", "float32"),
("Education", "category"), ("Education-Num", "float32"), ("Marital Status", "category"),
("Occupation", "category"), ("Relati... | Return the Adult census data in a nice package. |
def setup(self):
"""Method runs the plugin"""
if self.dry_run is not True:
self.client = self._get_client()
self._disable_access_key() | Method runs the plugin |
def do_AUTOCOMPLETE(cmd, s):
"""Shows autocomplete results for a given token."""
s = list(preprocess_query(s))[0]
keys = [k.decode() for k in DB.smembers(edge_ngram_key(s))]
print(white(keys))
print(magenta('({} elements)'.format(len(keys)))) | Shows autocomplete results for a given token. |
def needs_renewal(name, window=None):
'''
Check if a certificate needs renewal
:param name: CommonName of cert
:param window: Window in days to renew earlier or True/force to just return True
Code example:
.. code-block:: python
if __salt__['acme.needs_renewal']('dev.example.com'):
... | Check if a certificate needs renewal
:param name: CommonName of cert
:param window: Window in days to renew earlier or True/force to just return True
Code example:
.. code-block:: python
if __salt__['acme.needs_renewal']('dev.example.com'):
__salt__['acme.cert']('dev.example.com'... |
def replace_namespace_finalize(self, name, body, **kwargs): # noqa: E501
"""replace_namespace_finalize # noqa: E501
replace finalize of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asyn... | replace_namespace_finalize # noqa: E501
replace finalize of the specified Namespace # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespace_finalize(name, body, async_req=... |
def cross_fade(self):
"""bool: The speaker's cross fade state.
True if enabled, False otherwise
"""
response = self.avTransport.GetCrossfadeMode([
('InstanceID', 0),
])
cross_fade_state = response['CrossfadeMode']
return bool(int(cross_fade_state)) | bool: The speaker's cross fade state.
True if enabled, False otherwise |
def find_version(project, source, force_init): # type: (str, str, bool) ->None
"""
Entry point to just find a version and print next
:return:
"""
# quiet! no noise
file_opener = FileOpener()
finder = FindVersion(project, source, file_opener, force_init=force_init)
if finder.PROJECT is N... | Entry point to just find a version and print next
:return: |
def _analyze_indexed_fields(indexed_fields):
"""Internal helper to check a list of indexed fields.
Args:
indexed_fields: A list of names, possibly dotted names.
(A dotted name is a string containing names separated by dots,
e.g. 'foo.bar.baz'. An undotted name is a string containing no
dots, e.g. 'foo'... | Internal helper to check a list of indexed fields.
Args:
indexed_fields: A list of names, possibly dotted names.
(A dotted name is a string containing names separated by dots,
e.g. 'foo.bar.baz'. An undotted name is a string containing no
dots, e.g. 'foo'.)
Returns:
A dict whose keys are undotted ... |
def assert_allclose(actual, desired, rtol=1.e-5, atol=1.e-8,
err_msg='', verbose=True):
r"""wrapper for numpy.testing.allclose with default tolerances of
numpy.allclose. Needed since testing method has different values."""
return assert_allclose_np(actual, desired, rtol=rtol, atol=atol,
... | r"""wrapper for numpy.testing.allclose with default tolerances of
numpy.allclose. Needed since testing method has different values. |
def update_user(self, user_id, **kwargs):
"""Update user properties of specified user.
:param str user_id: The ID of the user to update (Required)
:param str username: The unique username of the user
:param str email: The unique email of the user
:param str full_name: The full n... | Update user properties of specified user.
:param str user_id: The ID of the user to update (Required)
:param str username: The unique username of the user
:param str email: The unique email of the user
:param str full_name: The full name of the user
:param str password: The pass... |
def initialize_registry(args: argparse.Namespace, backend: StorageBackend, log: logging.Logger):
"""
Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files... | Initialize the registry and the index.
:param args: :class:`argparse.Namespace` with "backend", "args", "force" and "log_level".
:param backend: Backend which is responsible for working with model files.
:param log: Logger supplied by supply_backend
:return: None |
def needs_to_run(G, target, in_mem_shas, from_store, settings):
"""
Determines if a target needs to run. This can happen in two ways:
(a) If a dependency of the target has changed
(b) If an output of the target is missing
Args:
The graph we are going to build
The name of the target
... | Determines if a target needs to run. This can happen in two ways:
(a) If a dependency of the target has changed
(b) If an output of the target is missing
Args:
The graph we are going to build
The name of the target
The dictionary of the current shas held in memory
The dictio... |
def filter_by_transcript_expression(
self,
transcript_expression_dict,
min_expression_value=0.0):
"""
Filters effects to those which have an associated transcript whose
expression value in the transcript_expression_dict argument is greater
than min_exp... | Filters effects to those which have an associated transcript whose
expression value in the transcript_expression_dict argument is greater
than min_expression_value.
Parameters
----------
transcript_expression_dict : dict
Dictionary mapping Ensembl transcript IDs to e... |
def _color(str_, fore_color=None, back_color=None, styles=None):
""" Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (s... | Return the string wrapped with the appropriate styling escape sequences.
Args:
str_ (str): The string to be wrapped.
fore_color (str, optional): Any foreground color supported by the
`Colorama`_ module.
back_color (str, optional): Any background color supported by the
`Colorama`_ ... |
async def get_counts(self):
"""
see :class:`datasketch.MinHashLSH`.
"""
fs = (hashtable.itemcounts() for hashtable in self.hashtables)
return await asyncio.gather(*fs) | see :class:`datasketch.MinHashLSH`. |
def replay_scope(self, sess):
"""Enters a replay scope that unsets it at the end."""
current_replay = self.replay(sess)
try:
self.set_replay(sess, True)
yield
finally:
self.set_replay(sess, current_replay) | Enters a replay scope that unsets it at the end. |
def build_param_doc(arg_names, arg_types, arg_descs, remove_dup=True):
"""Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup :... | Build argument docs in python style.
arg_names : list of str
Argument names.
arg_types : list of str
Argument type information.
arg_descs : list of str
Argument description information.
remove_dup : boolean, optional
Whether remove duplication or not.
Returns
... |
def invoke(invocation):
"""
Find a Planner subclass corresnding to `invocation` and use it to invoke
the module.
:param Invocation invocation:
:returns:
Module return dict.
:raises ansible.errors.AnsibleError:
Unrecognized/unsupported module type.
"""
(invocation.module_... | Find a Planner subclass corresnding to `invocation` and use it to invoke
the module.
:param Invocation invocation:
:returns:
Module return dict.
:raises ansible.errors.AnsibleError:
Unrecognized/unsupported module type. |
def _MakeExecutable(self, metadata_script):
"""Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file.
"""
mode = os.stat(metadata_script).st_mode
os.chmod(metadata_script, mode | stat.S_IEXEC) | Add executable permissions to a file.
Args:
metadata_script: string, the path to the executable file. |
def infer(self, sensationList, reset=True, objectName=None):
"""
Infer on a given set of sensations for a single object.
The provided sensationList is a list of sensations, and each sensation is a
mapping from cortical column to a tuple of three SDR's respectively
corresponding to the locationInput... | Infer on a given set of sensations for a single object.
The provided sensationList is a list of sensations, and each sensation is a
mapping from cortical column to a tuple of three SDR's respectively
corresponding to the locationInput, the coarseSensorInput, and the
sensorInput.
For example, the i... |
def add_item(self, api_token, content, **kwargs):
"""Add a task to a project.
:param token: The user's login token.
:type token: str
:param content: The task description.
:type content: str
:param project_id: The project to add the task to. Default is ``Inbox``
:... | Add a task to a project.
:param token: The user's login token.
:type token: str
:param content: The task description.
:type content: str
:param project_id: The project to add the task to. Default is ``Inbox``
:type project_id: str
:param date_string: The deadline... |
def write_question(self, question):
"""Writes a question to the packet"""
self.write_name(question.name)
self.write_short(question.type)
self.write_short(question.clazz) | Writes a question to the packet |
def get_singlesig_privkey(privkey_info, blockchain='bitcoin', **blockchain_opts):
"""
Given a private key bundle, get the (single) private key
"""
if blockchain == 'bitcoin':
return btc_get_singlesig_privkey(privkey_info, **blockchain_opts)
else:
raise ValueError('Unknown blockchain ... | Given a private key bundle, get the (single) private key |
def insert(self, rectangle):
"""
Insert a rectangle into the bin.
Parameters
-------------
rectangle: (2,) float, size of rectangle to insert
"""
rectangle = np.asanyarray(rectangle, dtype=np.float64)
for child in self.child:
if child is not ... | Insert a rectangle into the bin.
Parameters
-------------
rectangle: (2,) float, size of rectangle to insert |
def insert_base_bank_options(parser):
"""
Adds essential common options for template bank generation to an
ArgumentParser instance.
"""
def match_type(s):
err_msg = "must be a number between 0 and 1 excluded, not %r" % s
try:
value = float(s)
except ValueError:
... | Adds essential common options for template bank generation to an
ArgumentParser instance. |
def _fix_dot_imports(not_consumed):
""" Try to fix imports with multiple dots, by returning a dictionary
with the import names expanded. The function unflattens root imports,
like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
and 'xml.sax' respectively.
"""
# TODO: this sho... | Try to fix imports with multiple dots, by returning a dictionary
with the import names expanded. The function unflattens root imports,
like 'xml' (when we have both 'xml.etree' and 'xml.sax'), to 'xml.etree'
and 'xml.sax' respectively. |
def wait_for_net(self, timeout=None, wait_polling_interval=None):
"""Wait for the device to be assigned an IP address.
:param timeout: Maximum time to wait for an IP address to be defined
:param wait_polling_interval: Interval at which to poll for ip address.
"""
if timeout is N... | Wait for the device to be assigned an IP address.
:param timeout: Maximum time to wait for an IP address to be defined
:param wait_polling_interval: Interval at which to poll for ip address. |
def _send_request(self, request, **kwargs):
"""Send GET request."""
log.debug(LOG_CHECK, "Send request %s with %s", request, kwargs)
log.debug(LOG_CHECK, "Request headers %s", request.headers)
self.url_connection = self.session.send(request, **kwargs)
self.headers = self.url_conn... | Send GET request. |
def setup_argument_parser():
"""Setup command line parser"""
# Fix help formatter width
if 'COLUMNS' not in os.environ:
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
parser = argparse.ArgumentParser(
prog='soapy_power',
formatter_class=argparse.RawDescriptionHe... | Setup command line parser |
def transform_file(ELEMS, ofname, EPO, TREE, opt):
"transform/map the elements of this file and dump the output on 'ofname'"
BED4_FRM = "%s\t%d\t%d\t%s\n"
log.info("%s (%d) elements ..." % (opt.screen and "screening" or "transforming", ELEMS.shape[0]))
with open(ofname, 'w') as out_fd:
if opt.s... | transform/map the elements of this file and dump the output on 'ofname |
def _sorted_resource_labels(labels):
"""Sort label names, putting well-known resource labels first."""
head = [label for label in TOP_RESOURCE_LABELS if label in labels]
tail = sorted(label for label in labels if label not in TOP_RESOURCE_LABELS)
return head + tail | Sort label names, putting well-known resource labels first. |
def db_file(self, value):
""" Setter for _db_file attribute """
assert not os.path.isfile(value), "%s already exists" % value
self._db_file = value | Setter for _db_file attribute |
def get_or_create(
cls, name: sym.Symbol, module: types.ModuleType = None
) -> "Namespace":
"""Get the namespace bound to the symbol `name` in the global namespace
cache, creating it if it does not exist.
Return the namespace."""
return cls._NAMESPACES.swap(Namespace.__get_or... | Get the namespace bound to the symbol `name` in the global namespace
cache, creating it if it does not exist.
Return the namespace. |
def emit_db_sequence_updates(engine):
"""Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection.
Needed to avoid subsequent unique key violations after DB build."""
if engine and engine.name == 'postgresql':
# not implemented for othe... | Set database sequence objects to match the source db
Relevant only when generated from SQLAlchemy connection.
Needed to avoid subsequent unique key violations after DB build. |
def find_by_b64ids(self, _ids, **kwargs):
"""
Pass me a list of base64-encoded ObjectId
"""
return self.find_by_ids([ObjectId(base64.b64decode(_id)) for _id in _ids], **kwargs) | Pass me a list of base64-encoded ObjectId |
def get_or_create_edge(self,
source: Node,
target: Node,
relation: str,
bel: str,
sha512: str,
data: EdgeData,
evidence: Optional[E... | Create an edge if it does not exist, or return it if it does.
:param source: Source node of the relation
:param target: Target node of the relation
:param relation: Type of the relation between source and target node
:param bel: BEL statement that describes the relation
:param s... |
def execute(self, proxy, method, args):
"""Execute given XMLRPC call."""
try:
result = getattr(proxy, method)(raw_xml=self.options.xml, *tuple(args))
except xmlrpc.ERRORS as exc:
self.LOG.error("While calling %s(%s): %s" % (method, ", ".join(repr(i) for i in args), exc))
... | Execute given XMLRPC call. |
def reload(self):
"""Reload the metadata for this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_instance]
:end-before: [END bigtable_reload_instance]
"""
instance_pb = self._client.instance_admin_client.get_i... | Reload the metadata for this instance.
For example:
.. literalinclude:: snippets.py
:start-after: [START bigtable_reload_instance]
:end-before: [END bigtable_reload_instance] |
def _attempt_command_recovery(command, ack, serial_conn):
'''Recovery after following a failed write_and_return() atempt'''
with serial_with_temp_timeout(serial_conn, RECOVERY_TIMEOUT) as device:
response = _write_to_device_and_return(command, ack, device)
if response is None:
log.debug("No ... | Recovery after following a failed write_and_return() atempt |
def save_report_to_html(self):
"""Save report in the dock to html."""
html = self.page().mainFrame().toHtml()
if self.report_path is not None:
html_to_file(html, self.report_path)
else:
msg = self.tr('report_path is not set')
raise InvalidParameterErro... | Save report in the dock to html. |
def create_queue(self, queue_name, metadata=None, fail_on_exist=False, timeout=None):
'''
Creates a queue under the given account.
:param str queue_name:
The name of the queue to create. A queue name must be from 3 through
63 characters long and may only contain lowerca... | Creates a queue under the given account.
:param str queue_name:
The name of the queue to create. A queue name must be from 3 through
63 characters long and may only contain lowercase letters, numbers,
and the dash (-) character. The first and last letters in the queue
... |
def merging_cli(debug=False):
"""
simple commandline interface of the merging module.
This function is called when you use the ``discoursegraphs`` application
directly on the command line.
"""
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--tiger-file',
... | simple commandline interface of the merging module.
This function is called when you use the ``discoursegraphs`` application
directly on the command line. |
def gradient(self):
"""
Sum of covariance function derivatives.
Returns
-------
dict
∂K₀ + ∂K₁ + ⋯
"""
grad = {}
for i, f in enumerate(self._covariances):
for varname, g in f.gradient().items():
grad[f"{self._name}[... | Sum of covariance function derivatives.
Returns
-------
dict
∂K₀ + ∂K₁ + ⋯ |
def make_pdb(self, ligands=True, alt_states=False, pseudo_group=False, header=True, footer=True):
"""Generates a PDB string for the Assembly.
Parameters
----------
ligands : bool, optional
If `True`, will include ligands in the output.
alt_states : bool, optional
... | Generates a PDB string for the Assembly.
Parameters
----------
ligands : bool, optional
If `True`, will include ligands in the output.
alt_states : bool, optional
If `True`, will include alternate conformations in the output.
pseudo_group : bool, optional... |
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
... | Get the first instance of a `self.pod_types` |
def strip_prefix(string, prefix, regex=False):
"""Strip the prefix from the string
If 'regex' is specified, prefix is understood as a regular expression."""
if not isinstance(string, six.string_types) or not isinstance(prefix, six.string_types):
msg = 'Arguments to strip_prefix must be string types... | Strip the prefix from the string
If 'regex' is specified, prefix is understood as a regular expression. |
def posterior_marginals(self, x, mask=None):
"""Run a Kalman smoother to return posterior mean and cov.
Note that the returned values `smoothed_means` depend on the observed
time series `x`, while the `smoothed_covs` are independent
of the observed series; i.e., they depend only on the model itself.
... | Run a Kalman smoother to return posterior mean and cov.
Note that the returned values `smoothed_means` depend on the observed
time series `x`, while the `smoothed_covs` are independent
of the observed series; i.e., they depend only on the model itself.
This means that the mean values have shape `concat... |
def user_in_group(user, group):
"""Returns True if the given user is in given group"""
if isinstance(group, Group):
return user_is_superuser(user) or group in user.groups.all()
elif isinstance(group, six.string_types):
return user_is_superuser(user) or user.groups.filter(name=group).exists()... | Returns True if the given user is in given group |
def from_devanagari(self, data):
"""A convenience method"""
from indic_transliteration import sanscript
return sanscript.transliterate(data=data, _from=sanscript.DEVANAGARI, _to=self.name) | A convenience method |
def version(self, value):
"""
Setter for **self.__version** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"versi... | Setter for **self.__version** attribute.
:param value: Attribute value.
:type value: unicode |
def getImports(pth):
"""Forwards to the correct getImports implementation for the platform.
"""
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if is_win or is_cygwin:
if pth.lower().endswith(".manifest"):
return []
try:
return _getImpo... | Forwards to the correct getImports implementation for the platform. |
def get(cont=None, path=None, local_file=None, return_bin=False, profile=None):
'''
List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list con... | List the contents of a container, or return an object from a container. Set
return_bin to True in order to retrieve an object wholesale. Otherwise,
Salt will attempt to parse an XML response.
CLI Example to list containers:
.. code-block:: bash
salt myminion swift.get
CLI Example to list... |
def someoneKnownSeen(self, home=None, camera=None):
"""
Return True if someone known has been seen
"""
try:
cam_id = self.cameraByName(camera=camera, home=home)['id']
except TypeError:
logger.warning("personSeenByCamera: Camera name or home is unknown")
... | Return True if someone known has been seen |
def numToDigits(num, places):
"""
Helper, for converting numbers to textual digits.
"""
s = str(num)
if len(s) < places:
return ("0" * (places - len(s))) + s
elif len(s) > places:
return s[len(s)-places: ]
else:
return s | Helper, for converting numbers to textual digits. |
def comb_jit(N, k):
"""
Numba jitted function that computes N choose k. Return `0` if the
outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0,
or k > N.
Parameters
----------
N : scalar(int)
k : scalar(int)
Returns
-------
val : scalar(int)
"""
# Fro... | Numba jitted function that computes N choose k. Return `0` if the
outcome exceeds the maximum value of `np.intp` or if N < 0, k < 0,
or k > N.
Parameters
----------
N : scalar(int)
k : scalar(int)
Returns
-------
val : scalar(int) |
def _score_macro_average(self, n_classes):
"""
Compute the macro average scores for the ROCAUC curves.
"""
# Gather all FPRs
all_fpr = np.unique(np.concatenate([self.fpr[i] for i in range(n_classes)]))
avg_tpr = np.zeros_like(all_fpr)
# Compute the averages per c... | Compute the macro average scores for the ROCAUC curves. |
def node_rank(self):
"""
Returns the maximum rank for each **topological node** in the
``DictGraph``. The rank of a node is defined as the number of edges
between the node and a node which has rank 0. A **topological node**
has rank 0 if it has no incoming edges.
... | Returns the maximum rank for each **topological node** in the
``DictGraph``. The rank of a node is defined as the number of edges
between the node and a node which has rank 0. A **topological node**
has rank 0 if it has no incoming edges. |
def fit_transform(self, X, **kwargs):
"""Computes the diffusion operator and the position of the cells in the
embedding space
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions.... | Computes the diffusion operator and the position of the cells in the
embedding space
Parameters
----------
X : array, shape=[n_samples, n_features]
input data with `n_samples` samples and `n_dimensions`
dimensions. Accepted data types: `numpy.ndarray`,
... |
def move_pos(self, line=1, column=1):
""" Move the cursor to a new position.
Default: line 1, column 1
"""
return self.chained(move.pos(line=line, column=column)) | Move the cursor to a new position.
Default: line 1, column 1 |
def fhi_header(filename, ppdesc):
"""
Parse the FHI abinit header. Example:
Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994
21.00000 3.00000 940714 zatom, zion, pspdat
1 1 2 0 2001 .00000 pspcod,pspxc,lmax,l... | Parse the FHI abinit header. Example:
Troullier-Martins psp for element Sc Thu Oct 27 17:33:22 EDT 1994
21.00000 3.00000 940714 zatom, zion, pspdat
1 1 2 0 2001 .00000 pspcod,pspxc,lmax,lloc,mmax,r2well
1.80626423934776 .22824404... |
def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False
if arg.startswith('--'):
arg_without_dash = arg[2:]
else:
arg_without_dash = arg[1:]
if '=' in arg_without_dash:
name, _ = arg_without_das... | Returns whether we can ignore arg based on a set of undefok flag names. |
def _create_extended_jinja_tags(self, nodes):
"""Loops through the nodes and looks for special jinja tags that
contains more than one tag but only one ending tag."""
jinja_a = None
jinja_b = None
ext_node = None
ext_nodes = []
for node in nodes:
if ... | Loops through the nodes and looks for special jinja tags that
contains more than one tag but only one ending tag. |
def action_set(self, hostname=None, action=None, subdoms=None, *args):
"Adds a hostname to the LB, or alters an existing one"
usage = "set <hostname> <action> <subdoms> [option=value, ...]"
if hostname is None:
sys.stderr.write("You must supply a hostname.\n")
sys.stderr.... | Adds a hostname to the LB, or alters an existing one |
def load_model_by_id(self, model_id):
"""Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation
"""
with open(os.path.join(self... | Get the model by model_id
Parameters
----------
model_id : int
model index
Returns
-------
load_model : Graph
the model graph representation |
def endpoint_get(service, region=None, profile=None, interface=None, **connection_args):
'''
Return a specific endpoint (keystone endpoint-get)
CLI Example:
.. code-block:: bash
salt 'v2' keystone.endpoint_get nova [region=RegionOne]
salt 'v3' keystone.endpoint_get nova interface=adm... | Return a specific endpoint (keystone endpoint-get)
CLI Example:
.. code-block:: bash
salt 'v2' keystone.endpoint_get nova [region=RegionOne]
salt 'v3' keystone.endpoint_get nova interface=admin [region=RegionOne] |
def append_instances(cls, inst1, inst2):
"""
Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible.
:param inst1: the first dataset
:type inst1: Instances
:param inst2: the first dataset
:type inst2: Instances
:retur... | Merges the two datasets (one-after-the-other). Throws an exception if the datasets aren't compatible.
:param inst1: the first dataset
:type inst1: Instances
:param inst2: the first dataset
:type inst2: Instances
:return: the combined dataset
:rtype: Instances |
def generate_filterbank_header(self, nchans=1, ):
""" Generate a blimpy header dictionary """
gp_head = self.read_first_header()
fb_head = {}
telescope_str = gp_head.get("TELESCOP", "unknown")
if telescope_str in ('GBT', 'GREENBANK'):
fb_head["telescope_id"] = 6
... | Generate a blimpy header dictionary |
def _ActionDatabase(self, cmd, args = None, commit = True, error = True):
"""
Do action on database.
Parameters
----------
cmd : string
SQL command.
args : tuple [optional : default = None]
Arguments to be passed along with the SQL command.
e.g. cmd="SELECT Value FR... | Do action on database.
Parameters
----------
cmd : string
SQL command.
args : tuple [optional : default = None]
Arguments to be passed along with the SQL command.
e.g. cmd="SELECT Value FROM Config WHERE Name=?" args=(fieldName, )
commit : boolean [optional : default... |
def set_servers(self, servers):
"""
Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:po... | Set the pool of servers used by this client.
@param servers: an array of servers.
Servers can be passed in two forms:
1. Strings of the form C{"host:port"}, which implies a default weight of 1.
2. Tuples of the form C{("host:port", weight)}, where C{weight} is
an int... |
def main(argv):
"""This function sets up a command-line option parser and then calls fetch_and_write_mrca
to do all of the real work.
"""
import argparse
description = 'Uses Open Tree of Life web services to the MRCA for a set of OTT IDs.'
parser = argparse.ArgumentParser(prog='ot-tree-of-life-m... | This function sets up a command-line option parser and then calls fetch_and_write_mrca
to do all of the real work. |
def forceupdate(self, *args, **kw):
"""Like a bulk :meth:`forceput`."""
self._update(False, self._ON_DUP_OVERWRITE, *args, **kw) | Like a bulk :meth:`forceput`. |
def post_process_images(self, doctree):
"""Pick the best candidate for all image URIs."""
super(AbstractSlideBuilder, self).post_process_images(doctree)
# figure out where this doctree is in relation to the srcdir
relative_base = (
['..'] *
doctree.attributes.ge... | Pick the best candidate for all image URIs. |
def call_actions_parallel_future(self, service_name, actions, **kwargs):
"""
This method is identical in signature and behavior to `call_actions_parallel`, except that it sends the requests
and then immediately returns a `FutureResponse` instead of blocking waiting on responses and returning a
... | This method is identical in signature and behavior to `call_actions_parallel`, except that it sends the requests
and then immediately returns a `FutureResponse` instead of blocking waiting on responses and returning a
generator. Just call `result(timeout=None)` on the future response to block for an ava... |
def name2idfobject(idf, groupnamess=None, objkeys=None, **kwargs):
"""return the object, if the Name or some other field is known.
send filed in **kwargs as Name='a name', Roughness='smooth'
Returns the first find (field search is unordered)
objkeys -> if objkeys=['ZONE', 'Material'], search only those
... | return the object, if the Name or some other field is known.
send filed in **kwargs as Name='a name', Roughness='smooth'
Returns the first find (field search is unordered)
objkeys -> if objkeys=['ZONE', 'Material'], search only those
groupnames -> not yet coded |
def _set_sfm_walk(self, v, load=False):
"""
Setter method for sfm_walk, mapped from YANG variable /sysmon/sfm_walk (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sfm_walk is considered as a private
method. Backends looking to populate this variable shoul... | Setter method for sfm_walk, mapped from YANG variable /sysmon/sfm_walk (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_sfm_walk is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sfm_walk() dire... |
def _compute_vs30_star_factor(self, imt, vs30):
"""
Compute and return vs30 star factor, equation 5, page 77.
"""
v1 = self._compute_v1_factor(imt)
vs30_star = vs30.copy()
vs30_star[vs30_star >= v1] = v1
return vs30_star, v1 | Compute and return vs30 star factor, equation 5, page 77. |
def _obtain_api_token(self, username, password):
"""Use username and password to obtain and return an API token."""
data = self._request("POST", "auth/apitoken",
{"username": username, "password": password},
reestablish_session=False)
ret... | Use username and password to obtain and return an API token. |
def query_value(stmt, args=(), default=None):
"""
Execute a query, returning the first value in the first row of the
result set. If the query returns no result set, a default value is
returned, which is `None` by default.
"""
for row in query(stmt, args, TupleFactory):
return row[0]
... | Execute a query, returning the first value in the first row of the
result set. If the query returns no result set, a default value is
returned, which is `None` by default. |
def rnd_date_array(size, start=date(1970, 1, 1), end=None, **kwargs):
"""
Array or Matrix of random date generator.
:returns: 1d or 2d array of datetime.date
"""
if end is None:
end = date.today()
start = parser.parse_date(start)
end = parser.parse_date(end)
_assert_correct_star... | Array or Matrix of random date generator.
:returns: 1d or 2d array of datetime.date |
def get_default_configfile_path():
"""Return the default configuration-file path.
Typically returns a user-local configuration file; e.g:
``~/.config/dwave/dwave.conf``.
Returns:
str:
Configuration file path.
Examples:
This example displays the default configuration fi... | Return the default configuration-file path.
Typically returns a user-local configuration file; e.g:
``~/.config/dwave/dwave.conf``.
Returns:
str:
Configuration file path.
Examples:
This example displays the default configuration file on an Ubuntu Unix system
runnin... |
def run(self, writer, reader):
"""
Pager entry point.
In interactive mode (terminal is a tty), run until
``process_keystroke()`` detects quit keystroke ('q'). In
non-interactive mode, exit after displaying all unicode points.
:param writer: callable writes to output st... | Pager entry point.
In interactive mode (terminal is a tty), run until
``process_keystroke()`` detects quit keystroke ('q'). In
non-interactive mode, exit after displaying all unicode points.
:param writer: callable writes to output stream, receiving unicode.
:type writer: call... |
def search(self, query, fetch_messages=False, thread_limit=5, message_limit=5):
"""
Searches for messages in all threads
:param query: Text to search for
:param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only
:param thread_limit: Max. number of threa... | Searches for messages in all threads
:param query: Text to search for
:param fetch_messages: Whether to fetch :class:`models.Message` objects or IDs only
:param thread_limit: Max. number of threads to retrieve
:param message_limit: Max. number of messages to retrieve
:type threa... |
def create(self, alpha_sender):
"""
Create a new AlphaSenderInstance
:param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters.
:returns: Newly created AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance
... | Create a new AlphaSenderInstance
:param unicode alpha_sender: An Alphanumeric Sender ID string, up to 11 characters.
:returns: Newly created AlphaSenderInstance
:rtype: twilio.rest.messaging.v1.service.alpha_sender.AlphaSenderInstance |
def setup_legacy_graph(native, options_bootstrapper, build_configuration):
"""Construct and return the components necessary for LegacyBuildGraph construction."""
bootstrap_options = options_bootstrapper.bootstrap_options.for_global_scope()
return EngineInitializer.setup_legacy_graph_extended(
bootstra... | Construct and return the components necessary for LegacyBuildGraph construction. |
def _escaped(self):
""" Escape character is at end of accumulated token
character list.
"""
chars = self._token_info['chars']
count = len(chars)
# prev char is escape, keep going
if count and chars[count - 1] == self.ESCAPE:
chars.pop() # sw... | Escape character is at end of accumulated token
character list. |
def raw(self):
"""Try to transform str to raw str"
... this will not work every time
"""
escape_dict = {'\a': r'\a',
'\b': r'\b',
'\c': r'\c',
'\f': r'\f',
'\n': r'\n',
'\r'... | Try to transform str to raw str"
... this will not work every time |
def get_search_for_slugs(self, slug):
""" Search for a particular slug
"""
return _get_request(_SLUG_SEARCH.format(c_api=_C_API_BEGINNING,
api=_API_VERSION,
slug=_format_query(slug),
... | Search for a particular slug |
def cd(path):
"""
Change working directory.
Returns absolute path to new working directory.
"""
_cdhist.append(pwd()) # Push to history.
path = abspath(path)
os.chdir(path)
return path | Change working directory.
Returns absolute path to new working directory. |
def remove(self, item):
"""Remove an item from the list.
"""
self.items.pop(item)
self._remove_dep(item)
self.order = None
self.changed(code_changed=True) | Remove an item from the list. |
def update_or_create(cls, name, external_endpoint=None, vpn_site=None,
trust_all_cas=True, with_status=False):
"""
Update or create an ExternalGateway. The ``external_endpoint`` and
``vpn_site`` parameters are expected to be a list of dicts with key/value
pairs to satisfy the res... | Update or create an ExternalGateway. The ``external_endpoint`` and
``vpn_site`` parameters are expected to be a list of dicts with key/value
pairs to satisfy the respective elements create constructor. VPN Sites will
represent the final state of the VPN site list. ExternalEndpoint that are
... |
def prefetch(self, bucket, key):
"""镜像回源预取文件:
从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考
http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
Args:
bucket: 待获取资源所在的空间
key: 代获取资源文件名
Returns:
一个dict变量,成功返回NULL,失败返回{"error": "<errMsg... | 镜像回源预取文件:
从镜像源站抓取资源到空间中,如果空间中已经存在,则覆盖该资源,具体规格参考
http://developer.qiniu.com/docs/v6/api/reference/rs/prefetch.html
Args:
bucket: 待获取资源所在的空间
key: 代获取资源文件名
Returns:
一个dict变量,成功返回NULL,失败返回{"error": "<errMsg string>"}
一个ResponseInfo对象 |
def get_object(cls, api_token):
"""
Class method that will return an Account object.
"""
acct = cls(token=api_token)
acct.load()
return acct | Class method that will return an Account object. |
def __objecthasfields(bunchdt, data, commdct, idfobject, places=7, **kwargs):
"""test if the idf object has the field values in kwargs"""
for key, value in list(kwargs.items()):
if not isfieldvalue(
bunchdt, data, commdct,
idfobject, key, value, places=places):
... | test if the idf object has the field values in kwargs |
def get_value(self, dictionary):
"""
Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value.
"""
if html.is_html_input(dictionary):
# HTML forms will represent empty fields as '', and cannot
... | Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.