text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def category_label(arg, labels, nulls=None):
"""
Format a known number of categories as strings
Parameters
----------
labels : list of string
nulls : string, optional
How to label any null values among the categories
Returns
-------
string_categories : string value expression... | 0.002532 |
def math_dataset_init(alphabet_size=26, digits=None, functions=None):
"""Initializes required objects to generate symbolic math datasets.
Produces token set, ExprOp instances, solve_op dictionary, encoders, and
decoders needed to generate the algebra inverse dataset.
Args:
alphabet_size: How many possible... | 0.007368 |
def unlock(name,
zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example)
identifier=None,
max_concurrency=1,
ephemeral_lease=False,
profile=None,
scheme=None,
username=None,
password=None,... | 0.003526 |
def _handle_start_relation(self, attrs):
"""
Handle opening relation element
:param attrs: Attributes of the element
:type attrs: Dict
"""
self._curr = {
'attributes': dict(attrs),
'members': [],
'rel_id': None,
'tags': {}
... | 0.004219 |
def train_on_audio(self, fn: str):
"""Run through a single audio file"""
save_test = random() > 0.8
audio = load_audio(fn)
num_chunks = len(audio) // self.args.chunk_size
self.listener.clear()
for i, chunk in enumerate(chunk_audio(audio, self.args.chunk_size)):
... | 0.004337 |
def total_surface_energy(self):
"""
Total surface energy of the Wulff shape.
Returns:
(float) sum(surface_energy_hkl * area_hkl)
"""
tot_surface_energy = 0
for hkl in self.miller_energy_dict.keys():
tot_surface_energy += self.miller_energy_dict[hk... | 0.004751 |
def get_logfile_path(working_dir):
"""
Get the logfile path for our service endpoint.
"""
logfile_filename = virtualchain_hooks.get_virtual_chain_name() + ".log"
return os.path.join( working_dir, logfile_filename ) | 0.026201 |
def add_event(self, key, event):
"""Add an event and its corresponding key to the store."""
assert isinstance(key, str)
assert isinstance(event, bytes)
if all([char.isalnum() or char == '-' for char in key]):
safe_key = key
else:
raise ValueError("Key must... | 0.003082 |
def token_generator(self, texts, **kwargs):
"""Yields tokens from texts as `(text_idx, character)`
"""
for text_idx, text in enumerate(texts):
if self.lower:
text = text.lower()
for char in text:
yield text_idx, char | 0.006757 |
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False,
rofi_args=None, **kwargs):
"""Prompt the user to enter a date and time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
... | 0.003717 |
def logfile_generator(self):
"""Yield each line of the file, or the next line if several files."""
if not self.args['exclude']:
# ask all filters for a start_limit and fast-forward to the maximum
start_limits = [f.start_limit for f in self.filters
if h... | 0.001905 |
def profil_hebdo(df, func='mean'):
"""
Calcul du profil journalier
Paramètres:
df: DataFrame de données dont l'index est une série temporelle
(cf module xair par exemple)
func: function permettant le calcul. Soit un nom de fonction numpy ('mean', 'max', ...)
soit la fonction elle-mê... | 0.004651 |
def tsp(points, start=0):
"""
Find an ordering of points where each is visited and
the next point is the closest in euclidean distance,
and if there are multiple points with equal distance
go to an arbitrary one.
Assumes every point is visitable from every other point,
i.e. the travelling s... | 0.000381 |
def _parse_networks(networks):
'''
Common logic for parsing the networks
'''
networks = salt.utils.args.split_input(networks or [])
if not networks:
networks = {}
else:
# We don't want to recurse the repack, as the values of the kwargs
# being passed when connecting to th... | 0.000369 |
def name(self):
"""The identifier of the machine."""
name = self.__class__.__name__
for i, character in enumerate(name):
if character.isdigit():
return name[:i] + "-" + name[i:]
return name | 0.008032 |
def get_params(self, params, name_request):
'''
Prepare and add for further render parameters.
:param params: --dictionary with parameters
:type params: dict
:param name_request: --type of the parameters
:type name_request: str, unicode
:return:
'''
... | 0.001901 |
def read_legacy_cfg_files(self, cfg_files, alignak_env_files=None):
# pylint: disable=too-many-nested-blocks,too-many-statements
# pylint: disable=too-many-branches, too-many-locals
"""Read and parse the Nagios legacy configuration files
and store their content into a StringIO object whi... | 0.00286 |
def make_archive(name, repo, ref, destdir):
"""Makes an archive of a repository in the given destdir.
:param text name: Name to give the archive. For instance foo. The file
that is created will be called foo.tar.gz.
:param text repo: Repository to clone.
:param text ref: Tag/SHA/branch to check o... | 0.00107 |
def signal_to_exception(signum, frame):
"""
Called by the timeout alarm during the collector run time
"""
if signum == signal.SIGALRM:
raise SIGALRMException()
if signum == signal.SIGHUP:
raise SIGHUPException()
if signum == signal.SIGUSR1:
raise SIGUSR1Exception()
if... | 0.002421 |
def to_task(self):
"""Return a task object representing this MessageProcessor job."""
task_args = self.get_task_args()
# check for name in task args
name = task_args.get('name', MESSAGE_PROCESSOR_NAME)
# if the countdown isn't in the task_args set it to the frequency
if... | 0.004815 |
def get_tiles_list(element):
"""
Returns the list of all tile names from Product_Organisation element
in metadata.xml
"""
tiles = {}
for el in element:
g = (el.findall('.//Granules') or el.findall('.//Granule'))[0]
name = g.attrib['granuleIdentifier']
name_parts = name... | 0.002475 |
def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web... | 0.008357 |
def transform_record(self, pid, record, links_factory=None, **kwargs):
"""Transform record into an intermediate representation."""
context = kwargs.get('marshmallow_context', {})
context.setdefault('pid', pid)
return self.dump(self.preprocess_record(pid, record,
... | 0.005435 |
def cmd_gimbal_roi(self, args):
'''control roi position'''
latlon = None
try:
latlon = self.module('map').click_position
except Exception:
print("No map available")
return
if latlon is None:
print("No map click position available")
... | 0.004292 |
def persist(self):
'''
Persist the modified schedule into <<configdir>>/<<default_include>>/_schedule.conf
'''
config_dir = self.opts.get('conf_dir', None)
if config_dir is None and 'conf_file' in self.opts:
config_dir = os.path.dirname(self.opts['conf_file'])
... | 0.002803 |
def key_present(name, save_private=None, upload_public=None, region=None,
key=None, keyid=None, profile=None):
'''
Ensure key pair is present.
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}
}
exists = __salt__['boto_e... | 0.000437 |
async def patch_register(self, register: Dict, request: 'Request'):
"""
Store all options in the "choices" sub-register. We store both the
text and the potential intent, in order to match both regular
quick reply clicks but also the user typing stuff on his keyboard that
matches ... | 0.002963 |
def get(self, thing_id='0'):
"""
Handle a GET request, including websocket requests.
thing_id -- ID of the thing this request is for
"""
self.thing = self.get_thing(thing_id)
if self.thing is None:
self.set_status(404)
self.finish()
re... | 0.002051 |
def legend(self, txt=None):
"""Set/get ``Actor`` legend text.
:param str txt: legend text.
Size and positions can be modified by setting attributes
``Plotter.legendSize``, ``Plotter.legendBC`` and ``Plotter.legendPos``.
.. hint:: |fillholes.py|_
"""
if txt:
... | 0.004843 |
def set_sampling_strategies(self, filter, strategy_and_parms):
"""Set a strategy for all sensors matching the filter, including unseen sensors
The strategy should persist across sensor disconnect/reconnect.
filter : str
Filter for sensor names
strategy_and_params : seq of st... | 0.00545 |
def well_images(self, well_row, well_column):
"""Get list of paths to images in specified well.
Parameters
----------
well_row : int
Starts at 0. Same as --V in files.
well_column : int
Starts at 0. Save as --U in files.
Returns
-------
... | 0.00519 |
def sam2fastq(line):
"""
print fastq from sam
"""
fastq = []
fastq.append('@%s' % line[0])
fastq.append(line[9])
fastq.append('+%s' % line[0])
fastq.append(line[10])
return fastq | 0.004673 |
def downgrade():
"""alexm: i believe this method is never called"""
with op.batch_alter_table(t2_name) as batch_op:
batch_op.drop_column('do_not_use')
with op.batch_alter_table(t1_name) as batch_op:
batch_op.drop_column('enabled') | 0.003861 |
def _normalize(self, string):
''' Returns a sanitized string. '''
string = super(VerbixDe, self)._normalize(string)
string = string.replace('sie; Sie', 'sie')
string = string.strip()
return string | 0.033816 |
def get(cls, tag_id_or_URI, label=None):
'''Return the tag with the given id or URI, or None.
:param tag_id_or_name: the id or name of the tag to return
:type tag_id_or_name: string
:returns: the tag object with the given id or name, or None if there is
no tag with that id or name
:rtype: ckan.model.tag.... | 0.029795 |
def Network_setCookie(self, name, value, **kwargs):
"""
Function path: Network.setCookie
Domain: Network
Method name: setCookie
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'name' (type: string) -> Cookie name.
'value' (type: string) -> Cookie valu... | 0.037173 |
def getaddrlist(self, name):
"""Get a list of addresses from a header.
Retrieves a list of addresses from a header, where each address is a
tuple as returned by getaddr(). Scans all named headers, so it works
properly with multiple To: or Cc: headers for example.
"""
ra... | 0.002714 |
def set_system_conf(self, key=None, value=None, d=None):
""" Sets a java system property as a ('key', 'value') pair of using a dictionary
{'key': 'value', ...}
:param key: string
:param value: string
:param d: dictionary
:return: None
"""
if isinstance(d,... | 0.005618 |
def getElementsByAttr(self, attrName, attrValue, root='root'):
'''
getElementsByAttr - Searches the full tree for elements with a given attribute name and value combination. This is always a full scan.
@param attrName <lowercase str> - A lowercase attribute name
... | 0.004803 |
def perform_experiment(self, engine_list):
"""
Performs nearest neighbour experiments with custom vector data
for all engines in the specified list.
Returns self.result contains list of (distance_ratio, search_time)
tuple. All are the averaged values over all request vectors.
... | 0.001593 |
def percentile(values, percent):
"""
PERCENTILE WITH INTERPOLATION
RETURN VALUE AT, OR ABOVE, percentile OF THE VALUES
snagged from http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/
"""
N = sorted(values)
if not N:
return None
k = (len(N) - 1) * pe... | 0.004124 |
def find_argument_target(xmrs, nodeid, rargname):
"""
Return the target of an argument (rather than just the variable).
Note:
If the argument value is an intrinsic variable whose target is
an EP that has a quantifier, the non-quantifier EP's nodeid
will be returned. With this nodeid... | 0.000578 |
def pinyin_to_zhuyin(s):
"""Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin,
remove_apostrophes=True, separate_syl... | 0.003012 |
def normalize_list_of_dicts(value, default_key, default_value=UNDEFINED):
"""
Converts given value to a list of dictionaries as follows:
* ``[{...}]`` → ``[{...}]``
* ``{...}`` → ``[{...}]``
* ``'xyz'`` → ``[{default_key: 'xyz'}]``
* ``None`` → ``[{default_key: default_value}]`` (if spe... | 0.002066 |
def get_by_addr(self, address):
"""
Lookup a set of notifications by address
Args:
address (UInt160 or str): hash of address for notifications
Returns:
list: a list of notifications
"""
addr = address
if isinstance(address, str) and len(ad... | 0.004049 |
def resume_writing(self, exc=None):
'''Resume writing.
Successive calls to this method will fails unless
:meth:`pause_writing` is called first.
'''
assert self._paused
self._paused = False
waiter = self._waiter
if waiter is not None:
self._wai... | 0.003413 |
def list_user(context, id, sort, limit, where, verbose):
"""list_user(context, id, sort, limit, where, verbose)
List users attached to a remoteci.
>>> dcictl remoteci-list-user [OPTIONS]
:param string id: ID of the remoteci to list the user from
[required]
:param string sort... | 0.001445 |
def dataRestoreRecords(mimeData):
"""
Extracts the records from the inputed drag & drop mime data information.
This will lookup the models based on their primary key information and
generate the element class.
:param mimeData | <QMimeData>
:... | 0.014451 |
def _loadData(self, data):
""" Load attribute values from Plex XML response. """
self._data = data
self.codec = data.attrib.get('codec')
self.codecID = data.attrib.get('codecID')
self.id = cast(int, data.attrib.get('id'))
self.index = cast(int, data.attrib.get('index', '-... | 0.00316 |
def list2html(lst):
"""
convert a list to html using table formatting
"""
txt = '<TABLE width=100% border=0>'
for l in lst:
txt += '<TR>\n'
if type(l) is str:
txt+= '<TD>' + l + '</TD>\n'
elif type(l) is list:
txt+= '<TD>'
for i in l:
... | 0.015936 |
def asjsonld(self):
"""Create JSON-LD with the original source data."""
source = {}
if self.__source__:
source.update(self.__source__)
source.update(asjsonld(self))
return source | 0.008696 |
def set_const(const, val):
'''Convenience wrapper to reliably set the value of a constant from
outside of package scope'''
try:
cur = getattr(_c, const)
except AttributeError:
raise FSQEnvError(errno.ENOENT, u'no such constant:'\
u' {0}'.format(const))
ex... | 0.004669 |
def smart_content_encoding(self):
"""Smart content encoding."""
encoding = self.content_encoding
if not encoding:
base_list = self.basename.split('.')
while (not encoding) and len(base_list) > 1:
_, encoding = mimetypes.guess_type('.'.join(base_list))
... | 0.005376 |
def get_items(self, query_params=None):
'''
Get all the items for this label. Returns a list of dictionaries.
Each dictionary has the values for an item.
'''
return self.fetch_json(
uri_path=self.base_uri + '/checkItems',
query_params=query_params or {}
... | 0.006116 |
def _pop_params(cls, kwargs):
"""
Pop entries from the `kwargs` passed to cls.__new__ based on the values
in `cls.params`.
Parameters
----------
kwargs : dict
The kwargs passed to cls.__new__.
Returns
-------
params : list[(str, objec... | 0.001097 |
async def resolve(
self, host, port=80, family=None, qtype='A', logging=True
):
"""Return resolving IP address(es) from host name."""
if self.host_is_ip(host):
return host
_host = self._cached_hosts.get(host)
if _host:
return _host
resp = awa... | 0.002586 |
def pluralize(count, item_type):
"""Pluralizes the item_type if the count does not equal one.
For example `pluralize(1, 'apple')` returns '1 apple',
while `pluralize(0, 'apple') returns '0 apples'.
:return The count and inflected item_type together as a string
:rtype string
"""
def pluralize_string(x):
... | 0.016 |
def _get_limits_spot(self):
"""
Return a dict of limits for spot requests only.
This method should only be used internally by
:py:meth:~.get_limits`.
:rtype: dict
"""
limits = {}
limits['Max spot instance requests per region'] = AwsLimit(
'Max... | 0.001317 |
def info(self, text):
"""
Posts an info message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their ti... | 0.009709 |
def get_all_knoreq_user_objects(self, include_machine = False):
"""
Fetches all user objects with useraccountcontrol DONT_REQ_PREAUTH flag set from the AD, and returns MSADUser object.
"""
logger.debug('Polling AD for all user objects, machine accounts included: %s'% include_machine)
if include_machine == ... | 0.032967 |
def Weibull(lamda, k, tag=None):
"""
A Weibull random variate
Parameters
----------
lamda : scalar
The scale parameter
k : scalar
The shape parameter
"""
assert (
lamda > 0 and k > 0
), 'Weibull "lamda" and "k" parameters must be greater than zero'
re... | 0.005556 |
def branchScale(self):
"""See docs for `Model` abstract base class."""
bs = -(self.Phi_x * scipy.diagonal(self.Pxy[0])).sum() * self.mu
assert bs > 0
return bs | 0.010471 |
def human_readable_number(number, suffix=""):
"""
Format the given number into a human-readable string.
Code adapted from http://stackoverflow.com/a/1094933
:param variant number: the number (int or float)
:param string suffix: the unit of the number
:rtype: string
"""
for unit in ["",... | 0.001938 |
def load_url(self, url, force=False, reload_seconds=0,
callback_function=None):
"""
Starts loading a URL with an optional reload time
in seconds.
Setting force to True may load pages which block
iframe embedding, but will prevent reload from
working and ... | 0.002887 |
def contains_extractor(document):
"""A basic document feature extractor that returns a dict of words that the
document contains."""
tokens = _get_document_tokens(document)
features = dict((u'contains({0})'.format(w), True) for w in tokens)
return features | 0.003636 |
def sync_user(self, url, token, encoding_aes_key, media_id, to_invite=True):
"""
增量更新成员
https://work.weixin.qq.com/api/doc#90000/90135/90980
:param url: 企业应用接收企业微信推送请求的访问协议和地址,支持http或https协议
:param token: 用于生成签名
:param encoding_aes_key: 用于消息体的加密,是AES密钥的Base64编码
... | 0.003584 |
def get_diff_idxs(array, rtol, atol):
"""
Given an array with (C, N, L) values, being the first the reference value,
compute the relative differences and discard the one below the tolerance.
:returns: indices where there are sensible differences.
"""
C, N, L = array.shape
diff_idxs = set() ... | 0.001786 |
def create(self, store_id, data):
"""
Add a new customer to a store.
:param store_id: The store id.
:type store_id: :py:class:`str`
:param data: The request body parameters
:type data: :py:class:`dict`
data = {
"id": string*,
"email_addres... | 0.002564 |
def pipe_to_process(self, payload):
"""Send something to stdin of a specific process."""
message = payload['input']
key = payload['key']
if not self.process_handler.is_running(key):
return {'message': 'No running process for this key',
'status': 'error'}
... | 0.004376 |
def StartRun(self, wait_for_start_event, signal_event, wait_for_write_event):
"""Starts a new run for the given cron job."""
# Signal that the cron thread has started. This way the cron scheduler
# will know that the task is not sitting in a threadpool queue, but is
# actually executing.
wait_for_st... | 0.008778 |
def get_hostfirmware(self,callb=None):
"""Convenience method to request the device firmware info from the device
This method will check whether the value has already been retrieved from the device,
if so, it will simply return it. If no, it will request the information from the device
a... | 0.020928 |
def _recursive_dict_update(dict_, other, **kwargs):
"""Deep/recursive version of ``dict.update``.
If a key is present in both dictionaries, and points to
"child" dictionaries, those will be appropriately merged.
:param overwrite: Whether to overwrite exisiting dictionary values
"""
overwrite =... | 0.00137 |
def exists(self):
"""
Determine if any rows exist for the current query.
:return: Whether the rows exist or not
:rtype: bool
"""
limit = self.limit_
result = self.limit(1).count() > 0
self.limit(limit)
return result | 0.006873 |
def format_norm(kwargs, current=None):
"""Format a `~matplotlib.colors.Normalize` from a set of kwargs
Returns
-------
norm, kwargs
the formatted `Normalize` instance, and the remaining keywords
"""
norm = kwargs.pop('norm', current) or 'linear'
vmin = kwargs.pop('vmin', None)
v... | 0.001164 |
def run_cutadapt(job, fastqs, univ_options, cutadapt_options):
"""
This module runs cutadapt on the input RNA fastq files and then calls the RNA aligners.
ARGUMENTS
1. fastqs: Dict of list of input RNA-Seq fastqs
fastqs
+- 'tumor_rna': [<JSid for 1.fastq> , <JSid for 2.fastq>]
... | 0.002821 |
def connect(self, inputs):
'''Create Theano variables representing the outputs of this layer.
Parameters
----------
inputs : dict of Theano expressions
Symbolic inputs to this layer, given as a dictionary mapping string
names to Theano expressions. Each string ke... | 0.001616 |
def load_lime(self, remote_path, listen_port, dump_format='lime'):
"""
Load LiME kernel module from remote filesystem
:type remote_path: str
:param remote_path: path to LiME kernel module on remote host
:type listen_port: int
:param listen_port: port LiME uses to listen ... | 0.002829 |
def get_help(self, prefix='', include_special_flags=True):
"""Returns a help string for all known flags.
Args:
prefix: str, per-line output prefix.
include_special_flags: bool, whether to include description of
SPECIAL_FLAGS, i.e. --flagfile and --undefok.
Returns:
str, formatted... | 0.011494 |
def _read_output(path):
"""Read CmdStan output.csv.
Parameters
----------
path : str
Returns
-------
List[DataFrame, DataFrame, List[str], List[str], List[str]]
pandas.DataFrame
Sample data
pandas.DataFrame
Sample stats
List[str]
... | 0.001432 |
def pointsToVoronoiGridShapefile(lat, lon, vor_shp_path, extent=None):
"""
Converts points to shapefile grid via voronoi
"""
voronoi_centroids = _get_voronoi_centroid_array(lat, lon, extent)
# set-up output polygon shp
log("Creating output polygon shp {0}"
.format(os.path.basename(vor_s... | 0.000451 |
def reportMemory(k, options, field=None, isBytes=False):
""" Given k kilobytes, report back the correct format as string.
"""
if options.pretty:
return prettyMemory(int(k), field=field, isBytes=isBytes)
else:
if isBytes:
k /= 1024.
if field is not None:
re... | 0.002415 |
def build_catalog_info(self, catalog_info):
""" Build a CatalogInfo object """
cat = SourceFactory.build_catalog(**catalog_info)
catalog_info['catalog'] = cat
# catalog_info['catalog_table'] =
# Table.read(catalog_info['catalog_file'])
catalog_info['catalog_table'] = c... | 0.005008 |
def request(
self,
method,
url,
data=None,
headers=None,
withhold_token=False,
client_id=None,
client_secret=None,
**kwargs
):
"""Intercept all requests and add the OAuth 2 token if present."""
if not is_secure_transport(url):
... | 0.002154 |
def dependency_lines(self):
"""The formatted dependencies=[...] lines for this target.
If there are no dependencies, this returns an empty list.
"""
deps = sorted(self._dependencies_by_address.values(), key=lambda d: d.spec)
def dep_lines():
yield ' dependencies = ['
for dep in deps:
... | 0.013761 |
def from_string(cls, epstr, name, distro=None):
"""Parse an entry point from the syntax in entry_points.txt
:param str epstr: The entry point string (not including 'name =')
:param str name: The name of this entry point
:param Distribution distro: The distribution in which the entry poi... | 0.003856 |
def computeMultipleExpectations(self, A_in, u_n, compute_uncertainty=True, compute_covariance=False,
uncertainty_method=None, warning_cutoff=1.0e-10, return_theta=False):
"""Compute the expectations of multiple observables of phase space functions.
Compute the expect... | 0.0084 |
def yiq_to_rgb(y, i=None, q=None):
"""Convert the color from YIQ coordinates to RGB.
Parameters:
:y:
Tte Y component value [0...1]
:i:
The I component value [0...1]
:q:
The Q component value [0...1]
Returns:
The color as an (r, g, b) tuple in the range:
r[0...1],
g[0...... | 0.014041 |
def _self_pipe(self):
"""
This sets up a self-pipe so we can hand back an fd to the caller
allowing the object to manage event triggers. The ends of the pipe are
set non-blocking so it doesn't really matter if a bunch of events fill
the pipe buffer.
"""
import fcntl
... | 0.003745 |
def mk_token(opts, tdata):
'''
Mint a new token using the config option hash_type and store tdata with 'token' attribute set
to the token.
This module uses the hash of random 512 bytes as a token.
:param opts: Salt master config options
:param tdata: Token data to be stored with 'token' attirbu... | 0.002392 |
def good_sequences_to_track(flow, motion_threshold=1.0):
"""Get list of good frames to do tracking in.
Looking at the optical flow, this function chooses a span of frames
that fulfill certain criteria.
These include
* not being too short or too long
* not too low or too high mean flow m... | 0.006743 |
def iso_to_datetime(date):
""" Convert ISO 8601 time format to datetime format
This function converts a date in ISO format, e.g. ``2017-09-14`` to a `datetime` instance, e.g.
``datetime.datetime(2017,9,14,0,0)``
:param date: date in ISO 8601 format
:type date: str
:return: datetime instance
... | 0.004283 |
def flatten_phases_and_groups(phases_or_groups):
"""Recursively flatten nested lists for the list of phases or groups."""
if isinstance(phases_or_groups, PhaseGroup):
phases_or_groups = [phases_or_groups]
ret = []
for phase in phases_or_groups:
if isinstance(phase, PhaseGroup):
ret.append(phase.fl... | 0.017208 |
def _patch_stats_request(request):
'''If the request has no filter config, add one that should do what is
expected (include all items)
see: PE-11813
'''
filt = request.get('filter', {})
if not filt.get('config', None):
request['filter'] = filters.date_range('acquired',
... | 0.002538 |
def fire(self, name, operation, args=None, **kwargs):
"""Send a message without waiting for a reply
@param name: name of destination service queue
@param operation: name of service operation to invoke
@param args: dictionary of keyword args to pass to operation.
Use... | 0.004174 |
def _bind(self):
"""Bind events to handlers"""
main_window = self.main_window
handlers = self.handlers
c_handlers = self.cell_handlers
# Non wx.Grid events
self.Bind(wx.EVT_MOUSEWHEEL, handlers.OnMouseWheel)
self.Bind(wx.EVT_KEY_DOWN, handlers.OnKey)
... | 0.000328 |
def _inning_actions(self, soup, inning_number, inning_id):
"""
Inning Actions.
:param soup: Beautifulsoup object
:param inning_number: Inning Number
:param inning_id: Inning Id(0:home, 1:away)
"""
# at bat(batter box data) & pitching data
for act in soup.f... | 0.006593 |
def zpopmin(self, name, count=None):
"""
Remove and return up to ``count`` members with the lowest scores
from the sorted set ``name``.
"""
args = (count is not None) and [count] or []
options = {
'withscores': True
}
return self.execute_comman... | 0.005618 |
def get_ar(self):
"""Create a temporary AR to fetch the fields from
"""
if not self.tmp_ar:
logger.info("*** CREATING TEMPORARY AR ***")
self.tmp_ar = self.context.restrictedTraverse(
"portal_factory/AnalysisRequest/Request new analyses")
return se... | 0.006079 |
def manage_submissions(self):
"""
If there are no or only one submissions left, get new submissions.
This function manages URL creation and the specifics for front page
or subreddit mode.
"""
if not hasattr(self, 'submissions') or len(self.submissions) == 1:
s... | 0.00273 |
def get_node_type(type_str):
"""Returns the NodeType given a name of a JSON function object."""
if type_str == "container":
return NodeType.CONTAINER
elif type_str == "loop_plate":
return NodeType.LOOP
elif type_str == "assign":
return NodeType.ASSIGN
elif type_str == "condit... | 0.002 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.