text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def plot_compare(self, lD, key=None,
cmap=None, ms=4, vmin=None, vmax=None,
vmin_map=None, vmax_map=None, cmap_map=None, normt_map=False,
ntMax=None, nchMax=None, nlbdMax=3,
lls=None, lct=None, lcch=None, lclbd=None, cbck=None,
... | 0.010353 |
def genstis(outname):
""" Generate TestCases from cmdfile according to the pattern in patternfile"""
pattern="""class stisS%d(countrateCase):
def setUp(self):
self.obsmode="%s"
self.spectrum="%s"
self.setglobal(__file__)
self.runpy()\n"""
speclist=['/grp/hst/cdbs/calspec... | 0.022502 |
def find_config_files(
path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False
):
"""Return repos from a directory and match. Not recursive.
:param path: list of paths to search
:type path: list
:param match: list of globs to search against
:type match: list
:param f... | 0.001355 |
def root(self, parts):
"""
Find the path root.
@param parts: A list of path parts.
@type parts: [str,..]
@return: The root.
@rtype: L{xsd.sxbase.SchemaObject}
"""
result = None
name = parts[0]
log.debug('searching schema for (%s)', name)
... | 0.003165 |
def print_languages_and_exit(lst, status=1, header=True):
"""print a list of languages and exit"""
if header:
print("Available languages:")
for lg in lst:
print("- %s" % lg)
sys.exit(status) | 0.004505 |
def multiplicity(keys, axis=semantics.axis_default):
"""return the multiplicity of each key, or how often it occurs in the set
Parameters
----------
keys : indexable object
Returns
-------
ndarray, [keys.size], int
the number of times each input item occurs in the set
"""
i... | 0.002597 |
def get_specs(data):
"""
Takes a magic format file and returns a list of unique specimen names
"""
# sort the specimen names
speclist = []
for rec in data:
try:
spec = rec["er_specimen_name"]
except KeyError as e:
spec = rec["specimen"]
if spec not... | 0.002457 |
def to_struct(cls, name=None):
"""
Convert the TreeModel into a compiled C struct
"""
if name is None:
name = cls.__name__
basic_attrs = dict([(attr_name, value)
for attr_name, value in cls.get_attrs()
if isinsta... | 0.002911 |
def _split_along_width(x_left_right_blocks):
"""Helper function for local 2d attention.
Takes a tensor of [batch, heads, num_h_blocks, num_w_blocks,
height, width, depth] and returns two tensors which contain every alternate
position along the width
Args:
x_left_right_blocks: A [batch, num_h_blocks, nu... | 0.006981 |
def get_v_total_stress_at_depth(self, z):
"""
Determine the vertical total stress at depth z, where z can be a number or an array of numbers.
"""
if not hasattr(z, "__len__"):
return self.one_vertical_total_stress(z)
else:
sigma_v_effs = []
fo... | 0.006667 |
def on_action_run(self, task_vars, delegate_to_hostname, loader_basedir):
"""
Invoked by ActionModuleMixin to indicate a new task is about to start
executing. We use the opportunity to grab relevant bits from the
task-specific data.
:param dict task_vars:
Task variab... | 0.001994 |
async def send_rpc(self, client_id, conn_string, address, rpc_id, payload, timeout):
"""Send an RPC on behalf of a client.
See :meth:`AbstractDeviceAdapter.send_rpc`.
Args:
client_id (str): The client we are working for.
conn_string (str): A connection string that will ... | 0.003075 |
def del_location(self, location, sync=True):
"""
delete location from this routing area
:param location: the location to be deleted from this routing area
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the location object on list to be remov... | 0.004084 |
def call(self, name, request=None, **params):
""" Call resource by ``Api`` name.
:param name: The resource's name (short form)
:param request: django.http.Request instance
:param **params: Params for a resource's call
:return object: Result of resource's execution
"""
... | 0.003003 |
def set(self, point):
"""Set pixel at (x, y) point."""
if not isinstance(point, Point):
point = Point(point)
rx = self.round(point.x)
ry = self.round(point.y)
item = Point((rx >> 1, min(ry >> 2, self.size.y)))
self.screen[item] |= self.pixels[ry & 3][rx & 1] | 0.00625 |
def invoke_rest_method(**kwargs):
"""
Invokes a rest api test
:param kwargs:
REQUIRED:
method = 'GET', 'POST', 'PUT', 'DELETE'
url = "http://localhost/api/controller"
or
baseurl = "http://localhost/"
endpoint = "api/co... | 0.002651 |
def get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None,
projections=False):
"""
This method is used to get band structure info from a VASP directory. It
takes into account that the run can be divided in several branches named
"branch_x... | 0.000872 |
def set_prop(self, prop, value, ef=None):
"""
set attributes values
:param prop:
:param value:
:param ef:
:return:
"""
if ef:
# prop should be restricted to n_decoys, an int, the no. of decoys corresponding to a given FPF.
# value i... | 0.006935 |
def match_one(self, models, results, relation):
"""
Match the eargerly loaded resuls to their single parents.
:param models: The parents
:type models: list
:param results: The results collection
:type results: Collection
:param relation: The relation
:t... | 0.004505 |
def clip(obj, lower=0, upper=127):
"""
Return a copy of the object with piano-roll(s) clipped by a lower bound
and an upper bound specified by `lower` and `upper`, respectively.
Parameters
----------
lower : int or float
The lower bound to clip the piano-roll. Default to 0.
upper : ... | 0.001976 |
def build_pyfile_path_from_docname(self, docfile):
"""Build the expected Python file name based on the given documentation file name.
:param str docfile: The documentation file name from which to build the Python file name.
:rtype: str
"""
name, ext = os.path.splitext(docfile)
... | 0.009804 |
def convert_bool(key, val, attr_type, attr={}, cdata=False):
"""Converts a boolean into an XML element"""
LOG.info('Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if attr_... | 0.004175 |
def has_adjacent_fragments_only(self, min_index=None, max_index=None):
"""
Return ``True`` if the list contains only adjacent fragments,
that is, if it does not have gaps.
:param int min_index: examine fragments with index greater than or equal to this index (i.e., included)
:pa... | 0.004405 |
def __update_central_neurons(self, t, next_cn_membrane, next_cn_active_sodium, next_cn_inactive_sodium, next_cn_active_potassium):
"""!
@brief Update of central neurons in line with new values of current in channels.
@param[in] t (doubles): Current time of simulation.
@para... | 0.013809 |
def meta_enter_message(python_input):
"""
Create the `Layout` for the 'Meta+Enter` message.
"""
def get_text_fragments():
return [('class:accept-message', ' [Meta+Enter] Execute ')]
def extra_condition():
" Only show when... "
b = python_input.default_buffer
return ... | 0.001383 |
def _get_object(objname, objtype):
'''
Helper function to retrieve objtype from pillars if objname
is string_types, used for SupportedLoginProviders and
OpenIdConnectProviderARNs.
'''
ret = None
if objname is None:
return ret
if isinstance(objname, string_types):
if objn... | 0.001422 |
def normalize(value, unit):
"""Converts the value so that it belongs to some expected range.
Returns the new value and new unit.
E.g:
>>> normalize(1024, 'KB')
(1, 'MB')
>>> normalize(90, 'min')
(1.5, 'hr')
>>> normalize(1.0, 'object')
(1, 'object')
"""
if value < 0:
... | 0.001515 |
def delete(key,
host=DEFAULT_HOST,
port=DEFAULT_PORT,
time=DEFAULT_TIME):
'''
Delete a key from memcache server
CLI Example:
.. code-block:: bash
salt '*' memcached.delete <key>
'''
if not isinstance(time, six.integer_types):
raise SaltInvocati... | 0.002208 |
def rewrite_elife_datasets_json(json_content, doi):
""" this does the work of rewriting elife datasets json """
# Add dates in bulk
elife_dataset_dates = []
elife_dataset_dates.append(("10.7554/eLife.00348", "used", "dataro17", u"2010"))
elife_dataset_dates.append(("10.7554/eLife.01179", "used", "d... | 0.002816 |
def delete_alarms(deployment_id, alert_id=None, metric_name=None, api_key=None, profile='telemetry'):
'''delete an alert specified by alert_id or if not specified blows away all the alerts
in the current deployment.
Returns (bool success, str message) tuple.
CLI Example:
salt myminion te... | 0.004302 |
def drag(self, point):
"""Update the tracball during a drag.
Parameters
----------
point : (2,) int
The current x and y pixel coordinates of the mouse during a drag.
This will compute a movement for the trackball with the relative
motion between this ... | 0.000743 |
def handle_scroll(self, *args):
"""When my ``scroll`` changes, tell my deckbuilder how it's scrolled
now.
"""
if 'bar' not in self.ids:
Clock.schedule_once(self.handle_scroll, 0)
return
att = 'deck_{}_hint_offsets'.format(
'x' if self.orientat... | 0.003086 |
def _get_definitions(source):
# type: (str) -> Tuple[Dict[str, str], int]
"""Extract a dictionary of arguments and definitions.
Args:
source: The source for a section of a usage string that contains
definitions.
Returns:
A two-tuple containing a dictionary of all arguments ... | 0.001195 |
def expect_column_values_to_be_in_type_list(
self,
column,
type_list,
mostly=None,
result_format=None, include_config=False, catch_exceptions=None, meta=None
):
"""Expect each column entry to match a list of specified data types.
expect_column_values_to_be_in... | 0.006287 |
def __cloudflare_request(self, *, account, path, args=None):
"""Helper function to interact with the CloudFlare API.
Args:
account (:obj:`CloudFlareAccount`): CloudFlare Account object
path (`str`): URL endpoint to communicate with
args (:obj:`dict` of `str`: `str`):... | 0.003239 |
def AddFrequency(self, start_time, end_time, headway_secs, exact_times=0,
problem_reporter=problems_module.default_problem_reporter):
"""Adds a period to this trip during which the vehicle travels
at regular intervals (rather than specifying exact times for each stop).
Args:
start_time: The tim... | 0.009804 |
def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clone | 0.007092 |
def netgetdata(url, maxtry=3, timeout=10):
"""
Get content of a file via a URL.
Parameters
----------
url : string
URL of the file to be downloaded
maxtry : int, optional (default 3)
Maximum number of download retries
timeout : int, optional (default 10)
Timeout in seconds... | 0.001 |
def get_my_data(self, session=None):
"""
Returns a list of data descriptions for data which has been purchased by the signed in user.
:param requests.session session: Requests session object
:rtype: dict
"""
params = clean_locals(locals())
method = 'GetMyData'
... | 0.007229 |
def url_to_destination_params(url):
"""Convert a legacy runner URL to a job destination
>>> params_simple = url_to_destination_params("http://localhost:8913/")
>>> params_simple["url"]
'http://localhost:8913/'
>>> params_simple["private_token"] is None
True
>>> advanced_url = "https://1234x... | 0.000703 |
def extend_reservation(request, user_id, days=7):
''' Allows staff to extend the reservation on a given user's cart.
'''
user = User.objects.get(id=int(user_id))
cart = CartController.for_user(user)
cart.extend_reservation(datetime.timedelta(days=days))
return redirect(request.META["HTTP_REFER... | 0.003077 |
def plot_lnp(fignum, s, datablock, fpars, direction_type_key):
"""
plots lines and planes on a great circle with alpha 95 and mean
Parameters
_________
fignum : number of plt.figure() object
datablock : nested list of dictionaries with keys in 3.0 or 2.5 format
3.0 keys: dir_dec, dir_i... | 0.002533 |
def check_attr_dimension(attr_id, **kwargs):
"""
Check that the dimension of the resource attribute data is consistent
with the definition of the attribute.
If the attribute says 'volume', make sure every dataset connected
with this attribute via a resource attribute also has a dimen... | 0.008881 |
def stretch_linear(self, ch_nb, cutoffs=(0.005, 0.005)):
"""Stretch linearly the contrast of the current image on channel
*ch_nb*, using *cutoffs* for left and right trimming.
"""
logger.debug("Perform a linear contrast stretch.")
if((self.channels[ch_nb].size ==
np.... | 0.001616 |
def asset_url_for(self, asset):
"""
Lookup the hashed asset path of a file name unless it starts with
something that resembles a web address, then take it as is.
:param asset: A logical path to an asset
:type asset: str
:return: Asset path or None if not found
""... | 0.003976 |
def get(self, key, default=None, type=None):
"""Returns the first value for a key.
If `type` is not None, the value will be converted by calling
`type` with the value as argument. If type() raises `ValueError`, it
will be treated as if the value didn't exist, and `default` will be
... | 0.00361 |
def _should_retry(resp):
"""Given a urlfetch response, decide whether to retry that request."""
return (resp.status_code == httplib.REQUEST_TIMEOUT or
(resp.status_code >= 500 and
resp.status_code < 600)) | 0.0131 |
def set_env(envName, envValue):
"""
设置环境变量
:params envName: env名字
:params envValue: 值
"""
os.environ[envName] = os.environ[envName] + ':' + envValue | 0.005814 |
def plot_resp_diff(signal, rect_signal, sample_rate):
"""
Function design to generate a Bokeh figure containing the evolution of RIP signal, when
respiration was suspended for a long period, the rectangular signal that defines the
stages of inhalation and exhalation and the first derivative of the RIP s... | 0.00361 |
def get_properties(obj):
"""
Get values of all properties in specified object and its subobjects and returns them as a map.
The object can be a user defined object, map or array.
Returned properties correspondently are object properties, map key-pairs or array elements with their indexe... | 0.011611 |
def rotate_shift_mask_simplifier(a, b):
"""
Handles the following case:
((A << a) | (A >> (_N - a))) & mask, where
A being a BVS,
a being a integer that is less than _N,
_N is either 32 or 64, and
mask can be evaluated to 0xffff... | 0.003911 |
def _preprocess_scan_params(self, xml_params):
""" Processes the scan parameters. """
params = {}
for param in xml_params:
params[param.tag] = param.text or ''
# Set default values.
for key in self.scanner_params:
if key not in params:
para... | 0.001966 |
def wait(self, *args, **kwargs):
"""Wait for the completion event to be set."""
if _debug: IOCB._debug("wait(%d) %r %r", self.ioID, args, kwargs)
# waiting from a non-daemon thread could be trouble
return self.ioComplete.wait(*args, **kwargs) | 0.010909 |
def fw_update(self, data, fw_name=None):
"""Top level FW update function. """
LOG.debug("FW Update %s", data)
self._fw_update(fw_name, data) | 0.012195 |
def decr(self, key, value, default=0, time=100):
"""
Decrement a key, if it exists, returns its actual value, if it doesn't, return 0.
Minimum value of decrement return is 0.
:param key: Key's name
:type key: six.string_types
:param value: Number to be decremented
... | 0.004608 |
def get_all_units(self, params=None):
"""
Get all units
This will iterate over all pages until it gets all elements.
So if the rate limit exceeded it will throw an Exception and you will get nothing
:param params: search params
:return: list
"""
if not pa... | 0.008791 |
def set_l2cap_mtu (sock, mtu):
"""set_l2cap_mtu (sock, mtu)
Adjusts the MTU for the specified L2CAP socket. This method needs to be
invoked on both sides of the connection for it to work! The default mtu
that all L2CAP connections start with is 672 bytes.
mtu must be between 48 and 65535, inclus... | 0.009029 |
def get_document(
self,
collection_id, ref=None, mimetype="application/tei+xml, application/xml"):
""" Make a navigation request on the DTS API
:param collection_id: Id of the collection
:param ref: If ref is a tuple, it is treated as a range. String or int are treated a... | 0.005891 |
def rm(ctx, dataset, kwargs):
"removes the dataset's folder if it exists"
kwargs = parse_kwargs(kwargs)
data(dataset, **ctx.obj).rm(**kwargs) | 0.006494 |
def _create_deserializer(self) -> JsonObjectDeserializer:
"""
Creates a deserializer that is to be used by this decoder.
:return: the deserializer
"""
if self._deserializer_cache is None:
deserializer_cls = type(
"%sInternalDeserializer" % type(self),
... | 0.004399 |
def local_subset(self, *args, **kwargs):
'''
Run :ref:`execution modules <all-salt.modules>` against subsets of minions
.. versionadded:: 2016.3.0
Wraps :py:meth:`salt.client.LocalClient.cmd_subset`
'''
local = salt.client.get_local_client(mopts=self.opts)
retur... | 0.008451 |
def _model_unique(ins):
""" Get unique constraints info
:type ins: sqlalchemy.orm.mapper.Mapper
:rtype: list[tuple[str]]
"""
unique = []
for t in ins.tables:
for c in t.constraints:
if isinstance(c, UniqueConstraint):
unique.append(tuple(col.key for col in c.... | 0.002882 |
def get_json(self):
"""Create JSON data for iSCSI target.
:returns: JSON data for iSCSI target as follows:
{
"DHCPUsage":{
},
"Name":{
},
"IPv4Address":{
},
"PortNumber":{
... | 0.00165 |
def discrete_rainbow(N=7, cmap=cm.Set1, usepreset=True, shuffle=False, \
plot=False):
"""
Return a discrete colormap and the set of colors.
modified from
<http://www.scipy.org/Cookbook/Matplotlib/ColormapTransformations>
cmap: colormap instance, eg. cm.jet.
N: Number of co... | 0.017993 |
async def modify(self, **kwargs):
'''
Corresponds to PATCH request with a resource identifier, modifying a single document in the database
'''
try:
pk = self.pk_type(kwargs['pk'])
# modify is a class method on MongoCollectionMixin
result = await self._... | 0.007776 |
def stream_subsegments(self):
"""
Stream all closed subsegments to the daemon
and remove reference to the parent segment.
No-op for a not sampled segment.
"""
segment = self.current_segment()
if self.streaming.is_eligible(segment):
self.streaming.stre... | 0.005556 |
def read_mnist_labels(filename):
"""Read MNIST labels from the original ubyte file format.
Parameters
----------
filename : str
Filename/path from which to read labels.
Returns
-------
labels : :class:`~numpy.ndarray`, shape (nlabels, 1)
A one-dimensional unsigned byte arra... | 0.001437 |
def cli(ctx, packages, all, list, force, platform):
"""Install packages."""
if packages:
for package in packages:
Installer(package, platform, force).install()
elif all: # pragma: no cover
packages = Resources(platform).packages
for package in packages:
Inst... | 0.002004 |
def mainloop(self):
""" The main loop.
"""
# Print usage if not enough args or bad options
if len(self.args) < 2:
self.parser.error("No event type and info hash given!")
if sys.stdin.isatty():
self.options.no_fork = True | 0.007018 |
def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False):
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July ... | 0.001435 |
def has_all_nonzero_segment_lengths(neuron, threshold=0.0):
'''Check presence of neuron segments with length not above threshold
Arguments:
neuron(Neuron): The neuron object to test
threshold(float): value above which a segment length is considered to
be non-zero
Returns:
C... | 0.001427 |
def generate_items(self):
"""
Means array is valid only when all items are valid by this definition.
.. code-block:: python
{
'items': [
{'type': 'integer'},
{'type': 'string'},
],
}
Valid ... | 0.003901 |
def syzygyJD(jd):
""" Finds the latest new or full moon and
returns the julian date of that event.
"""
sun = swe.sweObjectLon(const.SUN, jd)
moon = swe.sweObjectLon(const.MOON, jd)
dist = angle.distance(sun, moon)
# Offset represents the Syzygy type.
# Zero is conjunction and... | 0.007849 |
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None):
"""Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None.
Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being... | 0.003911 |
def __get_percpu(self):
"""Update and/or return the per CPU list using the psutil library."""
# Never update more than 1 time per cached_time
if self.timer_percpu.finished():
self.percpu_percent = []
for cpu_number, cputimes in enumerate(psutil.cpu_times_percent(interval=... | 0.001846 |
def _fill(self, direction, limit=None):
"""
Shared function for `pad` and `backfill` to call Cython method.
Parameters
----------
direction : {'ffill', 'bfill'}
Direction passed to underlying Cython function. `bfill` will cause
values to be filled backwar... | 0.00172 |
def _recursively_replace_dict_for_pretty_dict(x):
"""Recursively replace `dict`s with `_PrettyDict`."""
# We use "PrettyDict" because collections.OrderedDict repr/str has the word
# "OrderedDict" in it. We only want to print "OrderedDict" if in fact the
# input really is an OrderedDict.
if isinstance(x, dict)... | 0.010352 |
def save_ids(f, self, *args, **kwargs):
"""Keep our history and outstanding attributes up to date after a method call."""
n_previous = len(self.client.history)
try:
ret = f(self, *args, **kwargs)
finally:
nmsgs = len(self.client.history) - n_previous
msg_ids = self.client.history... | 0.004717 |
def set_data_and_metadata(self, data_and_metadata, data_modified=None):
"""Sets the underlying data and data-metadata to the data_and_metadata.
Note: this does not make a copy of the data.
"""
self.increment_data_ref_count()
try:
if data_and_metadata:
... | 0.005006 |
def _create_serializer_of_type_with_cache(self, serializer_type: Type) -> "Serializer":
"""
Creates a deserializer of the given type, exploiting a cache.
:param serializer_type: the type of deserializer to create
:return: the created serializer
"""
if serializer_type not ... | 0.00789 |
def main(*args):
"""Launch the main routine."""
parser = argparse.ArgumentParser()
parser.add_argument("action",
help="create, check, run, make-nb, or run-nb")
parser.add_argument("--directory", "-dir", default=os.getcwd(),
help="path to directory with a .... | 0.000655 |
def parquet_to_df(filename, use_threads=1):
"""parquet_to_df: Reads a Parquet file into a Pandas DataFrame
Args:
filename (string): The full path to the filename for the Parquet file
ntreads (int): The number of threads to use (defaults to 1)
"""
try:
return pq.read_t... | 0.004082 |
def did_you_mean(message: str, user_input: str, choices: Sequence[str]) -> str:
""" Given a list of choices and an invalid user input, display the closest
items in the list that match the input.
"""
if not choices:
return message
else:
result = {
difflib.SequenceMatcher(... | 0.002045 |
def select_each(conn, query: str, parameter_groups, name=None):
"""Run select query for each parameter set in single transaction."""
with conn:
with conn.cursor(name=name) as cursor:
for parameters in parameter_groups:
cursor.execute(query, parameters)
yield ... | 0.002967 |
def branch_out(self, limb=None):
''' Set the individual section branches
This adds the various sections of the config file into the
tree environment for access later. Optically can specify a specific
branch. This does not yet load them into the os environment.
Parameters:
... | 0.001499 |
def inject():
"""Injects pout into the builtins module so it can be called from anywhere without
having to be explicitely imported, this is really just for convenience when
debugging
https://stackoverflow.com/questions/142545/python-how-to-make-a-cross-module-variable
"""
try:
from .com... | 0.00611 |
def snapshot_peek_sigb64( fd, off, bytelen ):
"""
Read the last :bytelen bytes of
fd and interpret it as a base64-encoded
string
"""
fd.seek( off - bytelen, os.SEEK_SET )
sigb64 = fd.read(bytelen)
if len(sigb64) != bytelen:
return None
try:
base64.b64decode(sigb64)
... | 0.01626 |
def get_key(raw=False):
""" Gets a single key from stdin
"""
while True:
try:
if kbhit():
char = getch()
ordinal = ord(char)
if ordinal in (0, 224):
extention = ord(getch())
scan_code = ordinal + exte... | 0.001592 |
def find_txt(xml_tree, path, default=''):
"""
Extracts the text value from an XML tree, using XPath.
In case of error, will return a default value.
:param xml_tree: the XML Tree object. Assumed is <type 'lxml.etree._Element'>.
:param path: XPath to be applied, in order to extract the desired da... | 0.003243 |
def update_pidfile(pidfile):
"""Update pidfile.
Notice:
We should call this function only after we have successfully acquired
a lock and never before. It exits main program if it fails to parse
and/or write pidfile.
Arguments:
pidfile (str): pidfile to update
"""
t... | 0.00062 |
def _log_error(self, request, error):
'''Log exceptions during a fetch.'''
_logger.error(
_('Fetching ‘{url}’ encountered an error: {error}'),
url=request.url, error=error
) | 0.00905 |
def size(self, units="MiB"):
"""
Returns the physical volume size in the given units. Default units are MiB.
*Args:*
* units (str): Unit label ('MiB', 'GiB', etc...). Default is MiB.
"""
self.open()
size = lvm_pv_get_size(self.handle)
self.clos... | 0.010989 |
def list_opts():
"""List all conf modules opts.
Goes through all conf modules and yields their opts.
"""
for mod in load_conf_modules():
mod_opts = mod.list_opts()
if type(mod_opts) is list:
for single_mod_opts in mod_opts:
yield single_mod_opts[0], single_m... | 0.002584 |
def get_psf_pix(self, ra, dec):
"""
Determine the local psf (a,b,pa) at a given sky location.
The psf is in pixel coordinates.
Parameters
----------
ra, dec : float
The sky position (degrees).
Returns
-------
a, b, pa : float
... | 0.006916 |
def load_permissions_on_identity_loaded(sender, identity):
"""Add system roles "Needs" to users' identities.
Every user gets the **any_user** Need.
Authenticated users get in addition the **authenticated_user** Need.
"""
identity.provides.add(
any_user
)
# if the user is not anonymo... | 0.002053 |
def batch_snapshot(self, read_timestamp=None, exact_staleness=None):
"""Return an object which wraps a batch read / query.
:type read_timestamp: :class:`datetime.datetime`
:param read_timestamp: Execute all reads at the given timestamp.
:type exact_staleness: :class:`datetime.timedelta... | 0.00436 |
def download_from_host(self, source, output_directory, filename):
"""Download a file from a given host.
This method renames the file to the given string.
:param source: Dictionary containing information about host.
:type source: dict
:param output_directory: Directory to place ... | 0.001781 |
def init_widget(self):
""" Initialize the underlying widget.
"""
# Create and init the client
c = self.client = BridgedWebViewClient()
c.setWebView(self.widget, c.getId())
c.onLoadResource.connect(self.on_load_resource)
c.onPageFinished.connect(self.on_page_finis... | 0.002999 |
def p_let_arr_substr_in_args(p):
""" statement : LET ARRAY_ID LP arguments TO RP EQ expr
| ARRAY_ID LP arguments TO RP EQ expr
"""
i = 2 if p[1].upper() == 'LET' else 1
id_ = p[i]
arg_list = p[i + 2]
substr = (arg_list.children.pop().value,
make_number(gl.MAX_STR... | 0.002198 |
def _safe_match_argument(expected_type, argument_value):
"""Return a MATCH (SQL) string representing the given argument value."""
if GraphQLString.is_same_type(expected_type):
return _safe_match_string(argument_value)
elif GraphQLID.is_same_type(expected_type):
# IDs can be strings or number... | 0.002733 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.