content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pkg_resources
def pool_drivers():
""" Return a list of EntryPoints names """
return [ep.name
for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)] | 1818d645ef7ddd67641ed88929ec67a444d3b601 | 3,620,200 |
from typing import Union
import torch
def to_bagua_process_group(
process_group: Union[TorchProcessGroup, BaguaProcessGroup, None] = None
):
"""Convert a PyTorch process group to a Bagua process group.
Args:
process_group (Union[TorchProcessGroup, BaguaProcessGroup, None], optional): PyTorch
... | 7e97a8eb1cab8192076cb084e68eb6609c38d0d0 | 3,620,201 |
def operate_favorite(bvid: str = None, aid: int = None, add_media_ids: list = None,
del_media_ids: list = None, verify: utils.Verify = None):
"""
操作音频收藏夹
:param aid:
:param bvid:
:param add_media_ids:
:param del_media_ids:
:param verify:
:return:
"""
if not (... | 7232b490d206fbda8abd79f008eaaa58c49d5693 | 3,620,202 |
def client_code(abstraction: OperationSystem) -> str:
"""
За исключением этапа инициализации, когда объект Абстракции связывается с
определённым объектом Реализации, клиентский код должен зависеть только от
класса Абстракции. Таким образом, клиентский код может поддерживать любую
комбинацию абстракц... | ce34f6256ea9282af24edcebd5ea3487d90eb5f0 | 3,620,203 |
def consistent_langevin_dynamics(rng,
model,
sigmas,
init,
epsilon,
T,
denoise=True,
infi... | 95cdb247f6ba68cd053819946df34a3b22e3c644 | 3,620,204 |
def _random_colour_masks(image):
"""
Generates a random color mask.
:param image: Image to generate the mask.
:return: Coloured mask.
"""
r = np.zeros_like(image).astype(np.uint8)
g = np.zeros_like(image).astype(np.uint8)
b = np.zeros_like(image).astype(np.uint8)
r[image == 0], g[ima... | f294dd1337ee6bfeac28681b3d42a738c7b745df | 3,620,205 |
def get_cell_numbers(contained):
"""Retrieve non-overlapping cell numbers from the output of `get_overlapping`.
None may appear at the ends of the output, indicating that the corresponding
target cells are not overlapping with any source cells. These should be ignored
when regridding.
Cell numbers... | b0bf32676ec7bfa73e04d3afd7053675f95d4abd | 3,620,206 |
def get_mos(da, da_peak_times):
"""
Takes an xarray DataArray containing veg_index values and calculates the vegetation
values (time not available) at middle of season (mos) for each timeseries per-pixel.
The middle of season is the mean vege value and time (day of year) in the timeseries
at 80% t... | 510452f4e89e2e26107f4c8bc9cc7617f7b56b61 | 3,620,207 |
def alternate_remove_duplicates(qdb: dt.QueriesTextParser):
"""Different commands, same result"""
_dup_list = []
for topic, q_vars in qdb.query_vars.items():
_dup_list.extend(qdb.queries_df.loc[qdb.queries_df['qid'].isin(q_vars)].duplicated('text'))
return qdb.queries_df[~qdb.queries_df['qid'].i... | 66904ba17296ac2db4a13220c77e0415488297de | 3,620,208 |
def to_hash_bucket_deterministic(batch, num_buckets, seed=None):
"""Buckets input examples, roughly uniformly and deterministically.
Args:
batch: a tensor of rank >= 1, containing the input examples
(batch axis = 0).
num_buckets: an integer, number of buckets.
seed: (optional) this seed will be u... | 349e0ef889aaa01e328789717077a57bd0c6def0 | 3,620,209 |
import torch
def random_training_set(chunks, revmap, volatile=False, start=0, batch_size=util.BATCH_SIZE):
"""Generate a training set from the randomized set of chunks (sequences),
returning them in descending order by size (per Torch's variable length
sequence RNN support).
If `volatile` is True, th... | 9dbacfadd6e323bb9cc7e4e20827762563bd0100 | 3,620,210 |
def verify_password(username, password):
"""Verify that user exists and that password is correct."""
user = models.User.query.get(username)
if user and verify_password_argon2id(user.password, password):
return user
return None | 4be318a31589bc1cc91f7695b3c017c17597a5d2 | 3,620,211 |
def check_half_links(ln):
""" Scan line for SE half-links where '[https://...]' appears.
SE half-links support specifying only the URL and SE goes
out to get the current name for the URL. This only works in
SE though, not in G-H Pages.
From: https://meta.stackexchange.com/help/forma... | 19fc1bbb5c0de4cd877cc54e2916bd4270c5f2ed | 3,620,212 |
def RandomUniform(inp, low=-1.0, high=1.0):
"""
Random uniformly distributed initialization.
"""
return np.random.uniform(size=inp, low=low, high=high) | d9a9ebf9417ab2af8a4e724c25699992f7814040 | 3,620,213 |
def twdb_texuni(dataframe, drop_dcp_metadata=True, dual_well=False):
"""Parser for twdb texuni dataloggers.
Data is transmitted every 12 hours and each message contains 12 water level
measurements on the hour for the previous 12 hours
format examples:
'"\r\n+0.000,-245.3,\r\n+0.000,-245.3,\r\n+0.00... | 19d1404cae00d0596c42a7d33eaa83b798702260 | 3,620,214 |
from typing import Optional
def FromMol(
mol: Chem.Mol, useGroups: Optional[bool] = True, useFilters: Optional[bool] = True
) -> str:
"""Convert RDKit Mol to AMSR
:param mol: RDKit Mol
:param useGroups: use group symbols/abbreviations
:param useFilters: apply filters to exclude unstable or synthe... | 0c748e5d118481cea41f838c8dd9f9d57de8e391 | 3,620,215 |
import heapq
import operator
def _similar_names(owner, attrname, distance_threshold, max_choices):
"""Given an owner and a name, try to find similar names.
The similar names are searched given a distance metric and only
a given number of choices will be returned.
"""
possible_names = []
names... | 6dd891666f6e5323a0a99529f5a3c3968bde4126 | 3,620,216 |
from typing import List
import requests
def list_remote_pipelines() -> List[str]:
"""List all the repositories in the pangeo-forge organization."""
r = requests.get(f"{BASE}/orgs/pangeo-forge/repos", headers=HEADERS)
r.raise_for_status()
repos = r.json()
repos = [repo["name"] for repo in repos if ... | 7ee508ae23cebc640da070e98c0faf0c7b8c204b | 3,620,217 |
def get_amended_desc(drev, ctx, folded):
"""similar to ``getdescfromdrev``, but supports a folded series of commits
This is used when determining if an individual commit needs to have its
message amended after posting it for review. The determination is made for
each individual commit, even when they ... | 4c35145a0c46b1da49a9caae7ff6c58100756f3f | 3,620,218 |
from datetime import datetime
def todays_artist_spotlight():
"""
If there is an artist spotlight for today, return that artist object
"""
today = datetime.date.today()
# get today's artist spotlight, if there is one
try:
spotlight = ArtistSpotlight.objects.get(date=today)
except A... | cfbe4c05273ce597f3254a634d2d6b50f066cbb6 | 3,620,219 |
def _get_angle(a, b, c):
"""
Get angle between vector ba and bc
"""
ba = a - b
bc = c - b
cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)
return np.degrees(angle) | b31dc0afab798f4ad31120f5cc52e9bfb7e5996b | 3,620,220 |
def _wx(item: str) -> dict:
"""
Parses remaining weather elements
"""
ret = {'wx': []}
items = item.split()
for item in items:
if len(item) < 3:
ret['wx'].append(item)
elif item.startswith('FV'):
_, ret['flight_visibility'] = core.get_visibility([item[2:]]... | f59c3ed994f9bb3e7c918828fcd59fa5de55bbde | 3,620,221 |
from datetime import datetime
import sys
def zeroSR1(fcnGrad, h, prox, options):
"""
ZEROSR1 Solves smooth + nonsmooth/constrained optimization problems
xk,nit, stepSizes = zeroSR1(fcnGrad, h, prox_h, opts)
This uses the zero-memory SR1 method (quasi-Newton) to solve:
min_x f(x) + h(x)
where
'fcnGrad' calc... | d8587cc6184dd60724394fef4bad58411e8840d2 | 3,620,222 |
import re
def tag_validate(tags, case_ids, plan_id):
"""Tests tag checking func"""
error_msg = None
tag_id = re.findall('ID_\d+|id_\d+', str(tags))
if not tag_id:
error_msg = "Wrong Tag Format:\
\nPls add tag 'ID_case_id' to this case."
elif int(tag_id[0][3:]) not in case_i... | 3428426b480f2515ca08663f94dd0f8073ed8d18 | 3,620,223 |
def generate_tree_html(tree):
"""
Given a tree representing HTML file paths, return an HTML table plotting
those paths.
"""
items = []
for node, subtree in sorted(compat_items(tree)):
if 'entry' in subtree:
html = u'<li><a href="{}">{}</a></li>'.format(subtree['entry']['relpa... | a3aad84d08484958138126a78eb19def4587ed37 | 3,620,224 |
from typing import Tuple
def return_valid_table_names() -> Tuple[str, ...]:
"""Get a tuple of valid table names."""
return tuple(_TABLE_COLUMN_PATTERNS.keys()) | e03c84096c9ad3bf574d1ae473f5d58de757dec8 | 3,620,225 |
def _text_match(vobject_item, filter_, child_name, ns, attrib_name=None):
"""Check whether the ``item`` matches the text-match ``filter_``.
See rfc4791-9.7.5.
"""
# TODO: collations are not supported, but the default ones needed
# for DAV servers are actually pretty useless. Texts are lowered to
... | f219dffbb405996d91da7b05a119fb042983df8b | 3,620,226 |
def cached_dataset(f, url=None, version=None, paths=None):
"""Test decorator providing a clone of `url` from cache
If config datalad.tests.cache is not set, delivers a clone in a temporary
location of the original `url`. Otherwise that clone is in fact a clone of a
cached dataset (origin being the cach... | df1bedc6c3a506e67f488f0af5b95a69e04b7d1d | 3,620,227 |
def _concat_nested_arrays(arrs, cells_as_numpy=False):
"""
Helper function to nest tabular arrays from nested list of arrays.
Parameters
----------
arrs : list of numpy arrays
Arrays must have the same number of rows, but can have varying
number of columns.
cells_as_numpy : boo... | f03762832198d7932eb87ea166711e50fff74bcb | 3,620,228 |
def submit_to_remote(name, value, **options):
"""
A submit button that submits via an XMLHttpRequest call
Returns a button input tag that will submit form using XMLHttpRequest
in the background instead of regular reloading POST arrangement.
Keyword args are the same as in ``form_remote_tag``.... | a9f993df00cfa934c3fa5f2dab6a5d08efce96d8 | 3,620,229 |
def commutative_similarity(node, target, tolerance=0, *args, **kwargs):
"""Apply :func:`monosaccharide_similarity` to ``node`` and ``target`` for both
``node --> target`` and ``target --> node``, returning whether either comparison
passes the tolerance threshold.
Parameters
----------
node: :cl... | e326ec075effbe0fc7ac8af5f64fed5564d9e1f1 | 3,620,230 |
import torch
def dataloader_subset(dl, batches=1):
"""Like torch's dataset Subset but for dataloaders. This lets us easily
do things like fit on a single batch (or small number of batches) by
essentially copying an existing dataloader's options but using a smaller
dataset. A few limitations: custom sa... | 47313fdcbfb150446af46213288077dfdcc4f608 | 3,620,231 |
def RunOsUpgradeBuild(args, output_filter, instance_uri, release_track):
"""Run a OS Upgrade on Google Cloud Builder.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
output_filter: A list of strings indicating what lines from the log should
be... | 46190462625997be2979d302b0c6e89cd603ca03 | 3,620,232 |
import functools
def FormatFieldType(type_context, field):
"""Format a FieldDescriptorProto type description.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Returns:
Formatted proto field type as string.
"""
label = 'repeated ' if field.label =... | c2fdc78ccf443a9914e3ee8e443d39e6360e21fd | 3,620,233 |
import urllib
def get_ip():
"""
获取本地ip
"""
my_ip = ""
try:
my_ip = urllib.request.urlopen('http://api.ipify.org').read()
except Exception:
my_ip = urllib.request.urlopen('http://icanhazip.com').read()
return bytes.decode(my_ip).strip() | 429eeb4e013874d6d4e23b43f1df52e450768ea1 | 3,620,234 |
from typing import get_args
def get_ict_dataset(use_titles=True, query_in_block_prob=1):
"""Get a dataset which uses block samples mappings to get ICT/block indexing data (via get_block())
rather than for training, since it is only built with a single epoch sample mapping.
"""
args = get_args()
bl... | f9fc744d0081e76e51789daf6f860feec18a8286 | 3,620,235 |
import pickle
def test_parallel_pickling():
""" Check that pmap captures the errors when it is passed an object
that cannot be pickled.
"""
def g(x):
return x ** 2
try:
# pickling a local function always fail but the exception
# raised is a PickleError for python <= 3.... | a18182ddbe7e9e4733ff34465c1fc7c8c7b62681 | 3,620,236 |
from cytoolz import get # not curried version
from toolz import get
def pair_assemble(t, on_left=None, on_right=None):
""" Combine a pair of records into a single record
This is mindful to shared columns as well as missing records
Parameters
----------
t : Join
The join to combine.
... | 7ee4b0a8de9ae9925702dba987f5a6b115f4373c | 3,620,237 |
def create_OrdinalEncoderTransformer_test_df():
"""Create DataFrame to use OrdinalEncoderTransformer tests that correct values are
DataFrame column a is the response, the other columns are categorical columns
of types; object, category, int, float, bool.
"""
df = pd.DataFrame(
{
... | bee0524b10321779dbb8a5f0c4847e833786834d | 3,620,238 |
from .._tier1 import set_column
from .._tier2 import maximum_of_touching_neighbors
def local_maximum_touching_neighbor_count_map(input : Image, destination : Image = None) -> Image:
"""Takes a label map, determines which labels touch and replaces every
label with the number of touching neighboring labels.
... | 81168267fffc7261b444bcd833618ca4c3fb36c2 | 3,620,239 |
def split_to_discretized_mix_logistic_params(inputs):
"""Splits input tensor into parameters of discretized mixture logistic.
Args:
inputs: A [batch, height, width, num_mixtures*10] tensor of floats
comprising one unconstrained mixture probability, three means
(one per channel), three standard devi... | f2bfa39d1913b9145a2268508e4041ae978ffe8b | 3,620,240 |
def get_clean_urls(raw_urls):
"""
Known problems so far:
https vs http
https://www.test.de vs https://test.de
https://www.test.de/something vs https://www.test.de/something#something
https://www.test.de/something.html vs https://www.test.de/something.html?something
"""
cleaned_urls = []
... | 19e238ff382c7c3dc83b779d7d82c59ff82820e9 | 3,620,241 |
from importlib.util import find_spec
def _pytest_has_xdist() -> bool:
"""
Check if the pytest-xdist plugin is installed, providing parallel tests
"""
# Check xdist exists without importing, otherwise pytests emits warnings
return find_spec("xdist") is not None | 77cc6d04d21f76b35b183fc4e9ebc2bf6824b744 | 3,620,242 |
def collaborative_baseline(data_train, testData, corrMatrix, K):
"""
Baseline method is used to compute the reconstructed matrix
Parameters
----------
data_train :
data present in train.csv file
testData :
data in test.csv file
corrMatrix :
correla... | 86e4ce780403b0969b337a464dc66c93d16b2ff0 | 3,620,243 |
def unpack_contours(df_filename: str, threshold: float = 0.6) -> gpd.GeoDataFrame:
""" Convert multipolygon contour row above given threshold into multiple Polygon rows. """
df = gpd.read_file(df_filename)
if len(df) <= 2:
if len(df[df.amax > threshold]):
return gpd.GeoDataFrame(geometry... | 0d5643ccb9ee91185229393c92cf69bf40ab0046 | 3,620,244 |
def makedist(dist_type, *pars, **kwards):
"""
Creates a distribution class from scipy continuous distributions
See https://docs.scipy.org/doc/scipy/reference/stats.html.
Parameters
----------
dist_type: String -> Type of the distribution (see the scipy documentation)
*pars and **kwards... | b9fb48e80d51cbeac5977d3e469ea14854f94def | 3,620,245 |
def is_list_of_matching_dicts(list_of_dicts, expected_keys=None):
"""Comprueba que una lista esté compuesta únicamente por diccionarios,
que comparten exactamente las mismas claves.
Args:
list_of_dicts (list): Lista de diccionarios a comparar.
expected_keys (set): Conjunto de las claves que... | c9bbb5a1c4e375909496d6ab448702543ab3adf5 | 3,620,246 |
def sort(left_lane_sa,right_lane_sa):
""" Sorts lane values for left and right lanes
@left_lane_sa: Left Lane values after split and Append method
@right_lane_sa: Right Lane values after split and Append method
"""
#print(len(right_lane_sa));
if (len(left_lane_sa) != 0):
left_lane_sa =... | c9cc1e6e53c6d63754eb67c685d0282ec980e174 | 3,620,247 |
def normalize_km(KM, method='cosine'):
"""
Normalize a kernel matrix to have unit diagonal.
Cosine normalization normalizes the kernel matrix to have unit diagonal.
Implements definition according to Section 5.1 in book (Page 113)
Shawe-Taylor and Cristianini, "Kernels Methods for Pattern Analysis"... | f6964b59ad44a1ed1ab39e30bf7ca7d40511723c | 3,620,248 |
import sys
def colored(s, c):
""" Takes in string s and outputs it with color """
if sys.stdout.isatty():
return '{}{}{}'.format(c, s, color.reset)
return s | 4387c77fdc2a1dd46b05dd6f804d1617115bbbcb | 3,620,249 |
def init_tags(meta_tables, diffs):
"""
Initialize executable tags.
:param list[MetaTable] meta_tables: All related meta-tables.
:param list[bool] diffs: Whether to generate diff tags.
:rtype: list, dict
"""
tags = list()
meta_info = {
'cont': list(),
'disc': list(),
... | 092d905da84b7d9c2a23ad1e0838781e18b5dffb | 3,620,250 |
def get_bprop_concat(self):
"""Generate bprop for Concat"""
axis = self.axis
def bprop(x, out, dout):
dx = ()
out_offset = G.ConcatOffset(F.tuple_len(x), axis)(x)
for i in range(F.tuple_len(x)):
slice_out = P.Slice()(dout, out_offset[i], shape_op(x[i]))
dx = ... | d55ba8a71bbb786865f46fea793016d586adc1ed | 3,620,251 |
def network_allocation_update(context, id, values):
"""Update a network allocation DB record."""
return IMPL.network_allocation_update(context, id, values) | c06873b8f624b6b0bcdf4c3fdc5e7bab6a6a7736 | 3,620,252 |
import importlib
def build_model(model_name, weights_file=None, **kwargs):
"""Build the desired model."""
mod = importlib.import_module("."+model_name, __name__)
model = mod.build_model(**kwargs)
if weights_file:
try:
model.load_weights(weights_file, by_name=True)
print("Loaded existing model:... | 23cb3d093b435dc32ecefa8b1415d2c5d4cbc4dd | 3,620,253 |
def getExistingLineStringInBounds(*args, **kwargs):
"""Return the geom of the first Path whose geom is in bounds"""
bbox = kwargs.pop('bbox', settings.SPATIAL_EXTENT)
p = Polygon.from_bbox(bbox)
return models.Path.objects.filter(geom__contained=p)[0].geom | fecc1e7ab3803aade4eed6cfcd91c77211f65acc | 3,620,254 |
def solve(_n, tree):
"""
Given a list of list of tokens:
. (empty), or # (tree), compute the
number of trees one would encounter
if one traverses the 2D grid along
a slope of (3, 1).
:param _n: The number of rows in the
2D grid.
:param tree: The 2D grid as a list of list.
... | b4dbbc5c62d5b680242997e22c7a84d4ad583848 | 3,620,255 |
import os
import logging
def reencode_video(dict_, path_folder_encoded):
"""reencode videos
Args:
dict_ (dataframe): columns: [video_resolution_to_change,
file_path_folder_origin,
file_name_origin]
path_folder_encoded (... | 980d9fdc8fdf064985d0f2d85944ae5eade15f06 | 3,620,256 |
import argparse
def create_argument_parser() -> argparse.ArgumentParser:
"""
Create argument parser with subparsers for commands.
:return: argument parser.
"""
# Create main parser
parser = MyArgumentParser(
prog='contradictory-my-dear-watson',
description='Program to solve th... | e265b4f07c4ffe6ca4b65b1aeb59bba29ddb796b | 3,620,257 |
def _getNodeType(node): # {{{
""" return NodeType as String """
if node.nodeType == node.ELEMENT_NODE : return "ELEMENT_NODE"
elif node.nodeType == node.ATTRIBUTE_NODE : return "ATTRIBUTE_NODE"
elif node.nodeType == node.TEXT_NODE : return... | 70bda4da9f991f17602ba2992cb6c11f19141eac | 3,620,258 |
def rotate_map(hmap, rot_theta, rot_phi):
"""
Take hmap (a healpix map array) and return another healpix map array
which is ordered such that it has been rotated in (theta, phi) by the
amounts given.
"""
nside = hp.npix2nside(len(hmap))
# Get theta, phi for non-rotated map
t,p = hp.pi... | 82acb8c2fe91537a50d8ff2535e3d057f77f7960 | 3,620,259 |
import requests
def get_request(profile, resource):
"""Do a GET request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connec... | fceb53c4e1f840efcd0af069b44109085145130b | 3,620,260 |
def author_case_query(qn, author):
"""
Given a query number and an author, return a query for finding author
in VIVO
"""
if qn == 1:
query = """
SELECT ?uri
WHERE {
?uri foaf:lastName "{{ln}}" .
?uri a ufVivo:UFCurrentEntity .
?uri foaf:fir... | 08770e6d1768115c62dba522b4d67e7763d6a186 | 3,620,261 |
def snake() -> dict:
""" 4x2 Sanake """
temp = {
0 : {
0 : Conway(Position(0,0),True),
1 : Conway(Position(0,1),True),
2 : Conway(Position(0,2),False),
3 : Conway(Position(0,3),True)
},
1 : {
0 : Con... | b75483cd77c9dfaf515eedba54c4601f48c43d0f | 3,620,262 |
def parse_from_any(*classes):
"""Decorator for parsing a variably-typed class instance.
Attempt to parse the input as each of the provided classes, passing
the first successfully parsed class instance to the constructor of
this class. This operation is short-circuiting. Raise ParseError if
none of ... | 3c778cdaa1db7c4e39047de26fced0a0aac198c4 | 3,620,263 |
from typing import Dict
from typing import Any
import collections
def get_obs_dict(sys,
qp: brax.QP,
info: brax.Info,
observer: str = None,
component: Dict[str, Any] = None):
"""Observe."""
obs_dict = collections.OrderedDict()
if observer == 'q... | fb8437bb7cf179f2da16532e5e795578eb359a81 | 3,620,264 |
def part_two(data):
"""Part two"""
particles = []
i = 0
for line in data.splitlines():
split = line.split('>, ')
p, v, a = read(split[0]), read(split[1]), read(split[2])
particles.append([p, v, a, i])
i += 1
for _ in range(1000):
for particle in particles:
... | 5e4f9699452998a9e0b917e95444b1a9377d6437 | 3,620,265 |
def _raw_clean_data(survey):
"""Remaps values and cleans the data for saving"""
# Remap values for vote choice 2016 and 2020
remp_2020 = {
'I am not sure/don\'t know': 'No Vote',
'I will not vote, but am eligible': 'No Vote',
'I would not vote': 'No Vote',
'I am not eligible... | 58104c0d543c2a94e11f4b4aff9489b8725b3f45 | 3,620,266 |
def HT_TRENDMODE(data: xr.DataArray) -> xr.DataArray:
"""
Hilbert Transform - Trend vs Cycle Mode (Cycle Indicators)
Input:
data: time series
Output:
time series (values are 0 or 1)
"""
return single_series_call(talib.HT_TRENDMODE, data, ds.TIME) | 328459f579881ba5100749866bfa0316a64208fd | 3,620,267 |
from typing import OrderedDict
def get_with_text(key, path):
"""Get links for generated images."""
template = app.template_service.find(key)
if template.key != key:
return redirect(route('.get', key=template.key, path=path))
text = Text(path)
if text.path != path:
return redirect(... | ee17c572e9fa3806644b2f8f73a0cd15f896ce4c | 3,620,268 |
from xpedite.types import InvariantViloation
import time
def buildTimelineStats(category, route, probes, txnSubCollection): # pylint: disable=too-many-locals
"""
Builds timeline statistics from a subcollection of transactions
:param probes: List of probes enabled for a profiling session
:param txnSubCollecti... | 6f101006bb7cb96045ebeb45f1fc01377fa7d8b7 | 3,620,269 |
import math
def get_margin(home_team, away_team, home_team_score, away_team_score):
"""
Get the multiplier for the margin of victory
"""
goal_differential = home_team_score - away_team_score
return max(1, math.log(
abs(goal_differential - .85 * ((home_team.elo - away_team.elo)/100)) + math... | 0e54ff280e8a045230b221128539a9a6c054625f | 3,620,270 |
async def async_get_actions(
hass: HomeAssistant, device_id: str
) -> list[dict[str, str]]:
"""List device actions for Humidifier devices."""
registry = await entity_registry.async_get_registry(hass)
actions = await toggle_entity.async_get_actions(hass, device_id, DOMAIN)
# Get all the integrations... | d54b20296a3166540165875ed104de9592811f20 | 3,620,271 |
def map_all(process):
"""
"""
process_params1 = set_extra_values(process['arguments'])
process_params2 = get_process_params(process['arguments'], {'ignore_nodata': 'bool'})
return map_default(process, 'all_', 'reduce', {**process_params1, **process_params2}) | 87c5448d9f3bc208dba752f34eb343f1f3ac1a91 | 3,620,272 |
def create_scales(options):
"""
Creates the scales for imfil.m. Nothing much here right now, but
custom scales ... are in the near future.
dscal = create_scales(options)
C. T. Kelley, September 15, 2008
This code comes with no guarantee or warranty of any kind."""
custom_scales = options.custom_sca... | c0e42bec16761a83a532c7799622d9b35ee72367 | 3,620,273 |
import os
import logging
import pdb
import pickle
import time
import warnings
def make_schema_test_class(test_file, test_args, test_num, schema_class, check_with_lxml):
"""
Creates a schema test class.
:param test_file: the schema test file path.
:param test_args: line arguments for test case.
:p... | cb5d51ea8de452383847ba064a765d67b092f02d | 3,620,274 |
import time
from datetime import datetime
def translate_promela_to_slugsin(code):
"""Return SlugsIn code from Promela `code`."""
t0 = time.time()
spec = logic.compile_spec(code)
aut = slugs._symbolic._bitblast(spec)
s = slugs._to_slugs(aut)
t1 = time.time()
dt = datetime.timedelta(seconds=... | 6218d4425b3be50f410b0e427876b54f2ccef4da | 3,620,275 |
import math
import torch
import tqdm
def validate(val_dataloader, model, criterion, config, save_dir=None):
"""Run validation.
Args:
val_dataloader (batchgenerators.dataloading.MultiThreadedAugmenter): val data iterator.
model (torch.nn.Module): model to train.
criterion (torch.nn.Mod... | e3237f5bde593b3380f39168a9cc92f158e5f6ec | 3,620,276 |
def load_recommendations(recommendations_file):
"""
Load ratings from file.
Parameters
----------
scores_file : str
The file that contains the rating info
Returns
-------
recs : dict
A recommendations dictionary in which userID is the key.
"""
if not isfile(reco... | 6a780ec05dbdad654c31dee6150431fc049350b1 | 3,620,277 |
def cosponsored_from_offset(member_id, offset, *, verbose=False):
""" Fetches the list of bill_id cosponsored by member """
ans = _get(common.URL_COSPONS(member_id, offset), verbose=verbose)
if ans:
bills = ans["bills"]
return [bill["bill_id"] for bill in bills]
else:
return [] | 9bf659198225e4cf377b24ebb2446b86204aef3a | 3,620,278 |
async def get_all_units():
"""
Get a list of all known unit symbols.
"""
return sorted(getAllUnitSymbols()) | 0d51ea496ac098c6896040951646632d71527833 | 3,620,279 |
import subprocess
def get_out_off_date_packages() -> frozenset:
"""
Gets all the packages which connected to pip and out off date.
:side-effect: prints
:rtype: frozenset
"""
updater_logger.info("Getting packages")
pip_output_lines = subprocess.check_output(['pip', 'list', '-o']).decode()... | f6467716e383208c10cce9227ddf466a9c9bfa7c | 3,620,280 |
from exporter.storages import HMRCStorage
def hmrc_storage(s3):
"""Patch HMRCStorage with moto so that nothing is really uploaded to s3."""
return make_storage_mock(
s3,
HMRCStorage,
bucket_name=settings.HMRC_STORAGE_BUCKET_NAME,
) | 65d7fc24e1ee63eb8daa1442b8a72f9edd54bda3 | 3,620,281 |
from typing import List
from re import T
from typing import Generator
def _chunks(lst: List[T], chunk_size: int) -> Generator[List[T], None, None]:
"""return chunks of chunk_size for list lst
>>> list(chunks([0, 1, 2, 3, 4], 2))
[[0, 1], [2, 3], [4]]
"""
return (lst[i:i + chunk_size] for i in ran... | 24a301898df77f3f297cfd34d3830ee2b766ada1 | 3,620,282 |
def cooccurrence_distance(X, discount=False):
"""
Parameters
----------
X : np.ndarray of shape (n_sample, n_features)
discount : bool, default=False
If True, then increase the co-occurrence distance
between sample A and B proportional to the number
of samples both A and B i... | 6f81fbc90ac6b4b4d6de80ea757a6a3aa9b67e56 | 3,620,283 |
def load_data():
""" Load the csv data """
data = pd.read_csv(DATA_URL)
data['tweet_created'] = pd.to_datetime(data['tweet_created'])
return data | b41c3be9dea24a217a47a7e9456fcbd83a528e3d | 3,620,284 |
import subprocess
def run_command(cmd):
"""
Runs a command on the command line. Similar to
treadmill.easy.run_command,
but this method has not restrictions on what can be execute. Use
with caution!
:param cmd: command to run as an ordered list
:return: list of output lines
"""
l... | 91d6ad29c8022401c58c3f77dc62d5c204a6f999 | 3,620,285 |
def _sbtype_has_field(sbtype, field_name):
"""Recursive helper to have has_field search up the inheritance hierarchy."""
for f in sbtype.fields:
if f.name == field_name:
return True
for b in sbtype.bases:
if _sbtype_has_field(b.type, field_name):
return True
for b in sbtype.vbases:
if ... | 8f2ec709214c9080b96acf267c66f1671fa47da3 | 3,620,286 |
def t_s(n, costheta):
"""Fresneltransmittance for two interfaces.
**Arguments:**
- **n**: iterable with two entries for (n_0, n_1)
- **theta:** iterable with two entries for (theta_0, theta_1)
"""
i, j = 0, 1
a = 2 * n[i] * costheta[i]
b = n[i] * costheta[i] + n[j] * costheta[j]
... | ae74b459ce0bb9172ed5d66c657ddba3065f4dd7 | 3,620,287 |
def calc_linhas_largura(dict_circ_desc, ponto):
"""criar linhas de largura"""
if dict_circ_desc["tipo_circulo"] == "meio":
linha_nao_intersecta_ponto = None
point_circ = Point()
point_circ.X = dict_circ_desc["pt_medios_circ"]["x_ptm"]
point_circ.Y = dict_circ_desc["pt_medios_circ... | 90dd8ccd91b458b76021e0e36bdb0e35d4f7a275 | 3,620,288 |
import email
def rfc_1123_date() -> str:
"""
Return the date formatted as per RFC 2616, section 3.3.1, rfc1123-date, as
described in
https://library.vuforia.com/articles/Training/Using-the-VWS-API.
"""
return email.utils.formatdate(None, localtime=False, usegmt=True) | 60074971427aef77be3e6eceb5dcecb7623452ef | 3,620,289 |
async def secure_mont(a, b, r, n, n_prime):
"""Montgomery multiplication.
See mont() docstring for details.
"""
assert type(a).bit_length >= 3 * (r.bit_length()) # Ensure a*b*n_prime fits
t = a * b
t_np_mod_r = t*n_prime % r
u = (t + t_np_mod_r * n) / r
return mpc.if_else(u >= n, u - n... | 9b01bb52de4ae1b47c281ec94fb4a66c23aa3cd5 | 3,620,290 |
def slice_out_int_literals(tensor, args):
"""
Allow passing int literals to factors in place of marginal distributions.
For those args which are int, specialise the tensor to handle these integer
values & eliminate these args from the arg list.
"""
n_args = len(args)
tensor, output_size, er... | 135b15bbd823eeddbd3f0304c0c54cadd0934d99 | 3,620,291 |
def make_color_checker_image_with_system_gamma(
width=1920, height=1080, luminance=100, system_gamma=1.0):
"""
Make a ColorChecker image with system-gamma applied.
"""
color_checker_width = int(width * 0.4)
font_st_pos = np.uint16(np.array([width, width]) * 0.03)
font_size = int(width * ... | 0df13867c8f9d0ce0de326ac6182d023a26bccf9 | 3,620,292 |
import os
from datetime import datetime
import csv
def calculate_normalization_info(paths_to_data_information=None, plot_histograms=True, user_correction=True, path_to_norm_info=None):
"""
This function creates csv file with information about dataset statistics which may be used for normalization.
The sta... | ad4481978e24af357fff927ff95d9c06afc822df | 3,620,293 |
import json
import os
import collections
def get_tf_config():
"""Get configuration from TF_CONFIG environment variable.
"""
tf_config = json.loads(os.getenv('TF_CONFIG', '{}'))
if not tf_config:
return None
task = tf_config['task']
cluster = tf_config['cluster']
task_type = task['type']
task_id = ... | 376d034fe6790482c2a26e355348d932d0f33f43 | 3,620,294 |
def bin_bucket_sort(arr):
"""
Binary bucket sort / 2-Radix sort
Time: O(NLog2N)
Space: O(N)
input: 1D-list array
output: 1D-list sorted array
"""
bucket = [[], []]
aux = list(arr)
flgkey = 1
while True:
for ele in aux:
bucket[int(bool(ele & flgke... | 8945ef31d5705d1462ce71ed6447bcc8d76e4665 | 3,620,295 |
import os
def get_pythainlp_data_path():
"""
Return full path where PyThaiNLP keeps its (downloaded) data
"""
path = os.path.join(os.path.expanduser("~"), PYTHAINLP_DATA_DIR)
if not os.path.exists(path):
os.makedirs(path)
return path | 00babfad8321bcfa2afe000f7395dc77447d9b43 | 3,620,296 |
def _identity(store: KeyValueStore) -> KeyValueStore:
"""
Helper function for `lazy_store`.
"""
return store | f681549b88f899417371e316e654a7564baf5b56 | 3,620,297 |
import subprocess
def spawn(*popenargs, **kwargs):
"""Helper function around the Popen constructor
that puts the created process into a registry
"""
proc = subprocess.Popen(*popenargs, **kwargs)
CURRENT_SUBPROCS.append(proc)
return proc | 8c43af3258ec9cfb5ff7d8a06be479f930ecda5f | 3,620,298 |
def log2(x):
"""
Compute the logarithm base 2 of `x`.
Return the "principal value" (for a description of this, see
`numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is
a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns
``inf``). Otherwise, the complex principle val... | 3803b7d54758255692d7b2826512c39921195b40 | 3,620,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.