content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def adjust_lag2_corrcoef1(gamma_1, gamma_2):
"""A simple adjustment of lag-2 temporal autocorrelation coefficient to
ensure that the resulting AR(2) process is stationary when the parameters
are estimated from the Yule-Walker equations.
Parameters
----------
gamma_1 : float
Lag-1 tempor... | 54665f6c1d3dbda4c33ec01cdf24539e21a53bed | 3,601,300 |
def zooms_string(z1, z2):
"""Prints 'zoom N' or 'zooms N-M'."""
if z2 != z1:
return "zooms {}-{}".format(min(z1, z2), max(z1, z2))
else:
return "zoom {}".format(z1) | 2e433472d721767cfc152b75a74f9976ba340f7a | 3,601,301 |
from PIL import ImageEnhance
def enhance_brightness(image: napari.types.ImageData, enhancement_factor: float = 1, viewer: napari.Viewer = None) -> napari.types.ImageData:
"""
This function can be used to control the brightness of an image.
An enhancement factor of 0.0 gives a black image. A factor of 1.0 ... | 68004710ca752a05467fc4e91d14f2442ed31006 | 3,601,302 |
def collect(group, p, barrier_token):
""" Collect partitions from partd, yield dataframes """
return p.get(group) | d3824864defbdec8b1712483b7b1e41ef7941268 | 3,601,303 |
def d_relu(X):
""" Derivative of the ReLU activation function """
return np.where(X > 0, 1, 0) | ca01e2895a6bc2fcd9e3e44082df98afddfdac67 | 3,601,304 |
async def collect_messages(channel, *, mode, before=None):
"""Collects messages from a channel for Shirt Bot"""
lst = []
async for x in channel.history(limit=50, before=before):
context = await bot.get_context(x)
if context.valid and context.command.name == "reset":
break
... | 2580d9143bc83843dd2f02d2d3abc1264d318d24 | 3,601,305 |
def ret_schema():
"""Defines dictionary of schema."""
schema = {
('path to directory', str, 'path'): ('path', str, '/apps/homefs1/.*'),
('dict of stocks', str, 'stocks'): {
('ticker', str, '[A-Z]*', '+'): {
('stock price', str, 'price'): ('price', float),
... | 83c66bc000a471ff0787eb98a1a8b4146b628911 | 3,601,306 |
import os
import sys
def wrap_open(method, exceptions = (OSError, IOError)):
"""Wrap Open method in order to create containing directories if they does not exist"""
def fn(*args, **kwargs):
try:
mkdir_p(os.path.dirname(args[0]))
return method(*args, **kwargs)
except exc... | aeea3000f570292d3ea0af20d43b75d2b94e7452 | 3,601,307 |
def schemaToAvroType(schema):
"""Convert an Avro schema into a titus.datatype.AvroType.
:type schema: avro.schema.Schema
:param schema: schema object from the Avro library
:rtype: titus.datatype.AvroType
:return: AvroType object
"""
if schema.type == "null":
return AvroNull()
e... | 3c275e2b44d42c9947afaa3c86f2e2c16b592b55 | 3,601,308 |
def augment_and_average_prediction(n, inp):
"""Augment input by rotating and flipping, and
average network output to improve results.
:param n: MS-D network :class:`.network.Network`.
:param inp: input array (size: :math:`N_{c} \\times N_{x} \\times N_{y}`).
:return: averaged output array.
... | 9afc74a9110749c5082c72d2f84ce1e5cdf91f10 | 3,601,309 |
def _simulate_and_fit(exp_dep: np.ndarray, simulation_method: str='multinominal', lambda_:str='log-likelihood') -> float:
"""split off simulate function to allow for parallellization"""
simdata = sim_data(exp_dep, method=simulation_method)
simchi2 = get_chi2_using_dependent_frequency_estimates(simdata, lamb... | e832c05143f076cbb08254ef79c1b979f85ca1e1 | 3,601,310 |
import os
def files_and_folders(dir_path="."):
"""Return a dict containing a sorted tuple of files and a sorted
tuple of folders"""
f_and_f = os.listdir(dir_path)
folders = [f for f in f_and_f if os.path.isdir(os.path.abspath(f))]
files = set(f_and_f) - set(folders)
return {
"files": t... | 3858d603acd208de0e81667fcd8ad79a9ea590e7 | 3,601,311 |
def resample_to_freq_medians(ds, freq='YS', inplace=True):
"""
Takes a xarray dataset/array and a frequency value in which to
resample to. Based on pandas resample frequencies. This function
is basically just an xarray resample wrapped up with some error
handling.
Parameters
----------
... | 676d672181792fd715bf23a11c547f5c78757223 | 3,601,312 |
def parent(par, hierarchy, shorten=False):
"""Look up the parent of an object in the hierarchy dict
We *could* shorten the path in the hierarchy afterwards
(with a recursive algorithm this could be on the way out)
"""
# seen = []
init = par
try:
while par is not None:
l... | 3b8f49e7a0e35c7740cfd1d53d2593a02978b232 | 3,601,313 |
def _imag_2d_func(x, y, func):
"""Return imag part of a 2d function."""
return func(x, y).imag | b95f64fb2bca54db89c85349ed3ca961d2b47b4c | 3,601,314 |
from typing import List
def get_interaction_matrix(
cell_data,
neighbourhood_bcs,
neighbourhood_indices,
all_set,
sig_bool,
L_bool,
R_bool,
cell_prop_cutoff,
):
"""Gets the interaction count matrix."""
# Now counting the interactions under 3 situations:
# 1) sig spot with l... | 6e057b67e7671904bb9915fc558b623e2b805b0c | 3,601,315 |
def generate_dunder_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:
"""Generates a wrapper for native __dunder__ methods to be able to fit into the mapping
protocol slot. This specifically means that the arguments are taken as *PyObjects and returned
as *PyObjects.
"""
gen = WrapperGenera... | b2788528f6c411a8209344cf769afe00a50a9289 | 3,601,316 |
def remove_monitor(nodenet_uid, monitor_uid):
""" Delete the given monitor"""
try:
runtime.remove_monitor(nodenet_uid, monitor_uid)
return dict(status='success')
except KeyError:
return dict(status='error', msg='unknown agent or monitor') | 4a31a1726f081649f114f6eff4fb0519e4d5a5b4 | 3,601,317 |
def save_config( bkp_config, config_file, for_restart = False ):
""" save the configuration to the file object passed as a parameter """
print("bucket =", bkp_config["bucket"], file=config_file)
print("dirs = ", ";".join(bkp_config["dirs"]), file=config_file)
print("exclude_files = ", bkp_config["exclud... | a4894cf29a44200442c6fb32b59eab9aefb5352c | 3,601,318 |
def download_channel_csv(request):
""" Writes list of channels to csv, which is then returned """
if not request.user.is_admin:
raise SuspiciousOperation("You are not authorized to access this endpoint")
response = StreamingHttpResponse(stream_csv_response_generator(request), content_type="text/csv... | 892ae0fbd40510bd0ab7a0fc78973beb1e62c7df | 3,601,319 |
def add_atom_map(molecule, in_place=True):
"""
Add canonical ordered atom maps to existing molecule
Parameters
----------
molecule : oechem.OEMol
in_place : bool, optional, default True
Returns
-------
mapped OEMol if in_place is False
"""
# First canonical order atoms
... | d1d9157ea0f6c51954480ec6e7b14d8b3b140423 | 3,601,320 |
def handle_single_copy_subtree(
all_tips: list,
terms: list,
newtree,
subgroup_counter: int,
fasta: str,
support: float,
fasta_dict: dict,
assigned_tips: list,
):
"""
handling case where subtree contains all single copy genes
"""
# prune subtree to get subtree of interest... | c991d4dfb470a53ada516057ab607c78f9c61204 | 3,601,321 |
def index(l, val, default=-1):
"""
find the index the val in list
:param l: index list
:param val: value to find index
:param default: default value to return that value not in list
:return: value index in list
"""
try:
getattr(l, 'index')
except:
raise TypeError('ipn... | 6c953b278cb65451879bbde19dfd4392a034b36f | 3,601,322 |
def bandpass(
nsamp: int,
dt: float,
f1: float,
f2: float,
f3: float,
f4: float,
norm: bool = True,
precision: float = 0.1,
) -> WaveletDtype:
"""Create a bandpass wavelet
Args:
nsamp: Number of samples in wavelet
dt: Sample rate in seconds
f1: Lower freq... | 02a711c75178ca89bd9b7377f86d8b7988b73f04 | 3,601,323 |
def get_pairs(word):
"""
Return set of symbol pairs in a word.
word is represented as tuple of symbols (symbols being variable-length strings)
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs | 28a14f9b7502540c6645345c07e9be4bf1437960 | 3,601,324 |
import logging
def node_weight_by_type(results, node_type):
"""
Extracts node weights (if exist) of all components of the specified
`node_type`.
Node weight are endogenous optimzation variables associated with the node
and not the edge between two node, foxample the variable representing the
... | c7fd77deca090a2326bd24904cc026bffe4430a9 | 3,601,325 |
def new_file_archive(*args):
"""
Instantiates a new FileArchive, passing the given arguments to the constructor.
"""
return _file_archive_resource_type(*args) | c9f125b27409aa31d3754d7ece2b463da6e06f4c | 3,601,326 |
def save_to_store(content, name, mime_type, location):
"""
Save named content to store by location.
Returns location of saved content.
"""
content_location = Transcript.asset_location(location, name)
content = StaticContent(content_location, name, mime_type, content)
contentstore().save(con... | 7d60ddc5b645348f2a5e4d9e151bd57a1111faf5 | 3,601,327 |
from typing import OrderedDict
def dict_order(_dict):
"""Controls the print order of the dictionary
"""
new_dict = OrderedDict()
new_dict['name'] = _dict.get('name')
new_dict['type'] = _dict.get('type')
new_dict['conditions'] = _dict.get('conditions')
new_dict['scopes'] = _dict.get('scopes... | a4ed107403289093065ce169d549dda88b5dee5c | 3,601,328 |
def batch_directions(z, y, Q, path_sizes, step_vals, subtract_projection=True):
"""
This function takes an input batch of z vectors (and corresponding class label vectors y)
and applies the directions in Q to the batch of z vectors.
:param z: (N, nz) tensor of base random noise to manipulate with direc... | 4adeab5b8a9ded7b4a10affbb5427435dbd5a599 | 3,601,329 |
def build_reduced_city_lookup():
"""
Convert city_lookup types and assert data is valid
"""
city_lookup = build_city_lookup()
# First 12 rows are information about the cities
city_lookup = build_city_lookup()
city_lookup = city_lookup[["city", "country", "lat", "lng", "population"]]
cit... | 3aeb13655aefbbf4c03c100e9e7a1b14e670ebb7 | 3,601,330 |
from typing import Optional
import requests
def get_access_token(
username=f"test_user{info.major}{info.minor}@example.com",
password="testPass1-",
scope: Optional[str] = None,
):
"""
NOTE: the followings setting in Auth0 dashboard is required
- sidebar > Applications > settings > Advanced set... | 9aa64bb3b474804ce3080ad4387e12e9184e18d4 | 3,601,331 |
import os
import logging
import bz2
def download(url, destination, uncompress=True):
"""
Download a file from the web
Parameters
----------
url : string
the web address
destination : string
path to store the file. The file will only be downloaded once.
uncompress... | 6d4bdf5b91d3259584dc86c31c66378808c2e58b | 3,601,332 |
import asyncio
from typing import Optional
async def run_tui(
loop: asyncio.AbstractEventLoop,
consoles_filepath: str,
auth_mgr: Optional[AuthenticationManager] = None
) -> int:
"""
Main entrypoint for TUI
Args:
loop: Eventloop
consoles_filepath: Console json filepath
... | b2ba9cee4d74bd706d42ac35d2cc3bcb322625eb | 3,601,333 |
def rescale_logvalues(lst):
"""Rescales a list of log values by setting max value to 0.0
This function is necessary when working with list of log values. Without
it, we could have overflows. This is a lot faster than using arbitrary
precision math libraries.
"""
if not isinstance(lst, N.n... | bb97db53e89e6ebe6dec9c0ffed4c798af91f0d3 | 3,601,334 |
def check_rsync_stderr(err):
"""
Checks to see if the errors in the stderr of rsync are actual errors or can be ignored.
:param err: stderr from an execution of rsync
:return: True if errors can be ignored
"""
res = True
for l in err.split('\n'):
if not len(l):
continue
... | 5ae536d636010ec7cb23a8401c2c6f088182ba85 | 3,601,335 |
from typing import List
from typing import Dict
def current_passengers(
driving: List[str],
open_requests: List[Request],
vehicle_positions: Dict[str, Vehicle],
) -> List[str]:
"""
store all personIDs that are in any vehicles
- if person occurs for the first time: call req.enter
- if perso... | a2c87c1afef29038c443b8dcafd6711af769ab6a | 3,601,336 |
def update_tax_nodes(nodes, tax):
"""
nodes can be a list of strings: taxids or names or a list of tuples with (rank, taxid/name)
Return a dictionary mapping nodes and updated nodes (or None)
First look for id, if nothing found, lookup by unique name
"""
updated_nodes = {}
for node in nodes... | 7d292ddf43e39280e699f76765079799f61dc0dc | 3,601,337 |
def collection_resolve_package_path(path):
"""Configure the Python package path so that pytest can find our collections."""
for parent in path.parents:
if str(parent) == ANSIBLE_COLLECTIONS_PATH:
return parent
raise Exception('File "%s" not found in collection path "%s".' % (path, ANSIB... | 8ef1fdabc36d66cda36978a2b74abf2f82843a1c | 3,601,338 |
import autopep8
import os
def remove_extra_spaces_and_pep8(filename, apply_pep8=True, aggressive=False, is_string=None):
"""
Removes extra spaces in a filename, replaces the file in place.
@param filename file name or string (but it assumes it is python).
@param apply_pep8 if Tr... | f543b2e58f04df233fe19bc37726765448f5ff38 | 3,601,339 |
def vgg16(**kwargs):
"""
Constructs a VGG16 model.
"""
return VGG16(**kwargs) | 85edc5232e51d7c8ebae4e9159d03260afe032c8 | 3,601,340 |
import os
import math
def global_index_map(npz_directory, overlapping, clip_length, keep=0.8):
"""
args:
- `npz_directory`: Directory containing `.npz` files
- `overlapping`: Whether clips can overlap
- `clip_length`:
returns:
- map from global index to corresponding file a... | 2b11815f3db5eaad71c85293b4a83300d3456709 | 3,601,341 |
def calculate_background_cost(u, v, w, weights, u_back, v_back, Cb=0.01):
"""
Calculates the background cost function. The background cost function is
simply the sum of the squared differences between the wind field and the
background wind field multiplied by the weighting coefficient.
Parameters
... | 95c2cf0c3062f1d95061e78a53dc8c6309ac6e6a | 3,601,342 |
def protocol_store(decoy: Decoy) -> ProtocolStore:
"""Get a mock ProtocolStore interface."""
return decoy.mock(cls=ProtocolStore) | 3c2e8ec207d482ac46a85811298cf37266491e58 | 3,601,343 |
def _sparseconv(data, kernel, mode):
"""Returns the discrete, linear convolution of two 1D sequences
This function returns the discrete, linear convolution of two
one-dimensional sequences, where the length of the output is determined
by ``mode``.
Can run faster than ``np.convolve`` if:
(1) ``d... | c4d239fa11ce52708b7fbe205fc01fc9cd7ad4a5 | 3,601,344 |
from typing import Union
def parse_domain(domain: Union[Text, "Domain"]) -> "Domain":
"""
Transforms a domain as a text string into a Domain instance. Calling with
a domain will return a copy of the said domain
"""
if isinstance(domain, Domain):
return replace(domain)
else:
pa... | 8f1f735813e1e5d730543935a00357c8afe5cff1 | 3,601,345 |
def value_formating():
"""Format a value with the underlying format function."""
happy_value = type('HappyFormater', (object,), {
'__format__': lambda _, template: template.replace('lol', '(^_^)')})()
return "{:lol}".format(happy_value) | a637bace1337d73658eb667bc3eafc866e5cd9ba | 3,601,346 |
import torch
def keypoints_to_heatmap_gaussian(keypoints, rois, heatmap_size):
"""
input:
keypoint的维度为[person_num, 17, 3], "3"代表(x, y, visibility)
rois的维度为[person_num, 4], "4"代表(x1, y1, x2, y2)
heatmap_size的大小等于cfg.MODEL.ROI_KEYPOINT_HEAD.RESOLUTION, 配置文件中为56
output:
heatma... | ab4b571ae4ae1e3a8da8fa71a76db300d508e77c | 3,601,347 |
def solve_equations_system(variables, equations, replace_values=None):
"""Solve linear and non linear equations system using Sympy library.
Parameters
----------
variables : list of str
Name of independent variable to solve for.
equations : list of sympy equations objects
Conform th... | cfc51a741f7ba080cf6f428e227e1dd41ed2040b | 3,601,348 |
import json
def _CanParseJSON(my_json):
"""Returns True if the input can be parsed as JSON, False otherwise."""
try:
json.loads(my_json)
except ValueError:
return False
return True | c8602b9e9544a70102135bd875d19c66664bdefc | 3,601,349 |
def is_user_lockable(request):
"""Check if the user has a profile with nolockout
If so, then return the value to see if this user is special
and doesn't get their account locked out
"""
if hasattr(request.user, 'nolockout'):
return not request.user.nolockout
if request.method != 'POST':... | a505bcee65f758071ef97cdf378124a434c25df4 | 3,601,350 |
import csv
def write_csv(f, items):
"""
:type items: list[OrderedDict]
"""
if len(items) == 0:
# nothing to write
return f
fieldnames = items[0].keys() # this works as expected because we use OrderedDicts
writer = csv.DictWriter(f, fieldnames)
writer.writeheader()
f... | 1cabe109bb42e892cc85b40bc6c6930987c042ee | 3,601,351 |
def get_list(sorted_by='name'):
"""Returns the pages list
"""
page_list = model.pages.find(sorted_by='name')
if page_list:
return dict(success=True, page_list=page_list)
else:
errors = [{ "message": "Error" }]
return dict(success=False, errors=errors) | 3b4270d9205e6a4e8c088652154a87be84b8805b | 3,601,352 |
import json
def get_brawl_cookie(request):
"""
Get brawl cookie
"""
return json.loads(request.cookies.get('brawl') or '[]') | e9264476a44bebfa9a43106678d1653ba86e555d | 3,601,353 |
from mglutil.math.rotax import mat_to_quat
def _interpolateMat(mat, percent):
"""called only by interpolate3DTransform()"""
if mat.shape != (16,) and mat.shape != (4, 4):
raise ValueError("matrix should be of shape (4,4) or (16,)")
return None
if mat.shape == (16,):
mat = N.reshap... | ae2560328b97f32e684eb88288587f6932f45ba5 | 3,601,354 |
def str_istitle__Rope(space, w_self):
"""Return True if S is a titlecased string and there is at least one
character in S, i.e. uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return False
otherwise."""
cased = False
previous_is_cased = False
iter = rop... | d5deba5615d85d245ac7743f42efdcff79841ee5 | 3,601,355 |
import copy
def jordan_blocks_by_scale_and_unimodular(self, p, safe_flag=True):
"""
Returns a list of pairs `(s_i, L_i)` where `L_i` is a maximal
`p^{s_i}`-unimodular Jordan component which is further decomposed into
block diagonals of block size `\le 2`. For each `L_i` the 2x2 blocks are
listed a... | 4300e88c2a0711b4044054e762fa2e22efeb0da6 | 3,601,356 |
import copy
def pp_init(local_X, k):
"""Do a version of KM++ initialization"""
ind = np.random.choice(len(local_X), 1)[0]
m, n = get_data_dims(local_X)
X_flat = [np.matrix(x.reshape(1, m*n)) for x in local_X]
first = X_flat[ind]
xcopy = copy.deepcopy(local_X)
del X_flat[ind]
del xcopy[... | 7f3c3d591dc51de391e21cfce8ead1c5b7fa88f1 | 3,601,357 |
def _AddTopicToResource(topic_name, new_config, resource, resource_name):
"""Add the PubsubConfig message to Repo/ProjectConfig message."""
if resource.pubsubConfigs is None:
config_additional_properties = []
else:
config_additional_properties = resource.pubsubConfigs.additionalProperties
resource_msg_... | 066b3b9ebda7b5921fbe4f2cbc577d6e86ac38e1 | 3,601,358 |
def addition_inputs(
vocab_size=gin.REQUIRED, batch_size=gin.REQUIRED, train_length=gin.REQUIRED,
eval_min_length=gin.REQUIRED, eval_max_length=gin.REQUIRED,
pad_to_multiple=32, encdec=False):
"""Inputs for the add problem: <S>x+y<S>(x+y).
Args:
vocab_size: how many symbols to use.
batch_size: ... | e6defb14f3fc6bfaf3197edd4001dca4d57469f0 | 3,601,359 |
import os
def load(fileOrStream, env_prefix='') -> dict:
"""Load environment file as dictionary.
File is just lines of key value pairs separated by an equal sign.
Blank lines and lines starting with # are ignored.
Values that are numbers or decimal numbers are automatically converted.
To defin... | bf06470ce04c6430a58774350466a51eab8eb4c4 | 3,601,360 |
import torch
def label_smoothed_nll_loss(
lprobs: torch.Tensor, target: torch.Tensor, epsilon: float, ignore_index=None, reduction="mean", dim=-1
) -> torch.Tensor:
"""
Source: https://github.com/pytorch/fairseq/blob/master/fairseq/criterions/label_smoothed_cross_entropy.py
:param lprobs: Log-probab... | 5c85297cda97746413c747fe10fae1ecaa16dea9 | 3,601,361 |
async def update_guild(guild_id: int, request: UpdateGuildRequest) -> GuildResponse:
"""
Update a guild in the API.
This operation will always succeed. If the guild does not exist it will be created.
"""
guild = await get_db_guild(guild_id, strict=False)
guild = await guild.update(**request.di... | 191ce7bad7cddff2ef3dc24156b73f67b572db67 | 3,601,362 |
import numpy
def expm(Ci):
"""Return the matrix exponential of a covariance matrix defined by :
.. math::
\mathbf{C} = \mathbf{V} \exp{(\mathbf{\Lambda})} \mathbf{V}^T
where :math:`\mathbf{\Lambda}` is the diagonal matrix of eigenvalues
and :math:`\mathbf{V}` the eigenvectors of :math:`\... | 38b15e41c3b95ec8ed673dd8469d27f5f183cf05 | 3,601,363 |
def expand_list_element_locations(ctx, args, data):
"""Performs location-macro expansion on a list of string values.
$(execroot ...) and $(location ...) are prefixed with ${pwd},
which process_wrapper and build_script_runner will expand at run time
to the absolute path.
See [`expand_location`](htt... | d14182843e96770ea694ef42753f6e5a63fd3d13 | 3,601,364 |
def select_latest(engine, ticker, time_x):
"""
获取离time_x最近的一个
:param engine:
:param ticker:
:param time_x:
:return:
"""
sql = 'select price,adj_factor from security_lookup_cn_wave_10 where ticker="{}" and time_x<="{}" ORDER BY time_x desc limit 1'.format(
ticker, time_x)
rs_s... | d33d817afdf58407c9e4ecb66ed9f43e9de6128a | 3,601,365 |
from typing import Union
import json
def prettify(data: Union[list, dict]) -> str:
"""
Return input data structure (list or dict) as a prettified JSON-formatted string.
Default is set here to stringify values like datetime values.
"""
return json.dumps(data, indent=4, sort_keys=True, default=str) | 800ef5d3f7a5765bca6fe42fc32e40da5a1cc398 | 3,601,366 |
import time
def search(vector, k=10):
"""
vector: numpy array vector
Return: predicted name of the face and search time
"""
db = DBObject(db=DB_NAME, user=USER, password=PASSWORD)
q = 'SELECT name from images order by vector <-> %s asc limit %s'
_vector = AsIs('cube(ARRAY[' + ','.... | 9c647fe8831f63a2397b83ac411c48abe55f3c5e | 3,601,367 |
import sys
import logging
def make_async(thread_name_prefix=''):
"""Returns a decorator that runs any function it wraps in a background thread.
When called, the decorated function will immediately return a future
representing its result.
The function being decorated can be an instance method or normal fun... | 3036a7db4dcc2f92cfb7544207beb71736b88916 | 3,601,368 |
def filter_semesters(c, semesters):
"""Filters the collection by matching its date-time index with the specified semesters."""
indices = find_all_in(get_semesters(c), get_semesters(semesters))
return take_at(c, indices) | 54bc88b30d856594d779b465a292c29fd850fa82 | 3,601,369 |
def download_pos_file():
"""
Devuelve el fichero de posiciones. En caso de error, muestra un mensaje flash por pantalla.
"""
# Si el servidor está activo, mostramos la página correspondiente
if active:
# Se intenta enviar el fichero de posiciones
try:
return send_from... | e0cc2b28869794957257c3f0ce6aabbf8c1224a7 | 3,601,370 |
def repnet_deep(pretrained=False, **kwargs):
"""Constructs a ResNet-Mini-Imagenet model"""
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
'resnet50': 'https://download.pytorc... | 8f3bbd56832444234f8266f41cba02a0b2ebc734 | 3,601,371 |
import unittest
def getTestSuite():
"""
set up composite test suite
"""
test_suite = unittest.TestSuite([])
test_suite.addTests(unittest.TestLoader().loadTestsFromTestCase(TestPairs))
return test_suite | ac8b40220da1cbce87ab256f249ac0aceed59cf7 | 3,601,372 |
def fetch_inactive_objects(connection):
"""Returns list of inactive objects"""
resp = connection.execute('GET', 'activation/inactiveobjects')
return Marshal.deserialize(resp.text, IOCList()) | ec09bf30d9b8f75c5028f76e1f81195d4d4a86c1 | 3,601,373 |
def find_outlier(x):
"""
return a bool array indicating outliers or not in *x*
"""
l, m, h = np.percentile(x, [16.0, 50.0, 84.0])
d = (h-l) * 0.5
return (x > (m + d*3)) | (x < (m - d*3)) | a3d981769f847ec114b546de2fb2b48e80594c3c | 3,601,374 |
def create_placeholders(n_H0, n_W0, n_C0, n_y):
"""
Creates the placeholders for the tensorflow session.
Arguments:
n_H0 -- scalar, height of an input image
n_W0 -- scalar, width of an input image
n_C0 -- scalar, number of channels of the input
n_y -- scalar, number of classes
Returns:... | 2619b84901f1f27a433655d5d1fbdc54e2ce0035 | 3,601,375 |
import profile
import torch
import time
def profile_inference(
model,
dataloader,
device,
metric_fn,
profiler,
flow_scale=1.0,
count_params=False,
pad_divisor=1,
):
"""
Uses a model to perform inference on a dataloader and profiles model characteristics such as memory usage, in... | 6759e86841cce8d0e272ebc0b110c138f8e2404b | 3,601,376 |
def _image_pos(name):
"""
查找指定图片在背景图中的位置
"""
pull_screenshot()
imsrc = ac.imread('bg.png')
imobj = ac.imread('images/0{}.PNG'.format(name))
# find the match position
pos = ac.find_template(imsrc, imobj, 0.8)
circle_center_pos = None
if pos != None:
circle_center_pos = pos... | 2eac5ff9aba651e51eaf492adcaffb2a42c8dfe7 | 3,601,377 |
import os
import tarfile
import shutil
import subprocess
def fetch(data_dir, dest="conll03"):
"""
Fetches and extracts the CoNLL03 dataset. If the Reuters dataset is
not available, it prints instructions on how to get it.
Creates the `dest` if it doesn't exist.
Args:
data_dir (str): abso... | f570fc61354343697fb785f09df89bfb830a93ab | 3,601,378 |
import json
def face_register(input_dict):
"""
Registers only one picture.
:param input_dict:
e.x. {"user_id": "10098440", "group_id": "staff", "gender": "女", "user_info": "康佳慧", "user_image": base64_image}
:return: None, results will be written into database.
"""
try:
# _json ... | 61975dbd2a930ff76443b64879263ec7dcb87b77 | 3,601,379 |
def power_series(z, cs):
"""
returns cs[0] + cs[1] * z + cs[2] * z ** 2 + ... + cs[-1] * z ** (len(cs) - 1)
"""
s = cs[-1]
for c in reversed(cs[:-1]):
s *= z
s += c
return s | a9fe54d8a4bc15385f5c1da61eb1696b43a470d4 | 3,601,380 |
def database_creation(func):
"""
Creates the database and tables if it dose not exist
Tables:
username (text):
password (text):
salt (text):
"""
@wraps(func)
def wrapper(*args, **kwargs)->None:
database_cursor.execute("""
CREATE TABLE IF NOT EXIS... | bc45a8f4763a748d47c38152f76f6d84872c3b0e | 3,601,381 |
import os
import logging
def run_unit(dsid, ncfiles, qc, checker):
"""
Runs the specific qc method for the NetCDF files given.
Records the log files in a given directory.
Only records the ".log" if the QC check was successfully executed.
:param stat: (string) Statistic to calculate as specified a... | 00302efdcf0939408ebd0b7176d9a327dba594ab | 3,601,382 |
def array(
item_processor, # type: Processor
alias=None, # type: Optional[Text]
nested=None, # type: Optional[Text]
omit_empty=False, # type: bool
hooks=None # type: Optional[Hooks]
):
# type: (...) -> RootProcessor
"""
Create an array processor that can be used ... | 268e0046a9fe4e96d2bb6224227b9c7689d81ac5 | 3,601,383 |
def normalize(signal):
"""Restrict the range of a signal to the closed interval [-1.0, 1.0]. """
normalized_signal = signal / max(signal.max(), signal.min(), key=abs)
return normalized_signal | d86fe058302ee133e6318f5c0a3fa24430e7e24c | 3,601,384 |
from pathlib import Path
import os
import hashlib
def pseudo_hash(path: Path, string: str = "") -> str:
"""Compute a pseudo hash based on :
- The file size
- The file last modification date
- A given string
(Real hash is too long to compute for big file.)
"""
string = "-".join([str(os.pat... | 10bdf79dfcb78bead4ec8f9b165496b977ce2e81 | 3,601,385 |
from corpkit.constants import transobjs, transshow
def to_cql(dquery, exclude=False, **kwargs):
"""
Turn dictionary query into cql format
"""
qlist = []
if exclude:
operator = '!='
else:
operator = '='
for k, v in dquery.items():
obj, show = transobjs.get(k[0]), tra... | e1b73abd8c2fbaaa697ff9899613c774938dbe6f | 3,601,386 |
def build_table_schema(data, index=True, primary_key=None, version=True):
"""
Create a Table schema from ``data``.
Parameters
----------
data : Series, DataFrame
index : bool, default True
Whether to include ``data.index`` in the schema.
primary_key : bool or None, default True
... | bb84be571d2e151285099a9a1f2c44b93427cced | 3,601,387 |
def get(request,hash,db_name):
"""
Get features of a sequence, using the sequence's sha-1 hash as the
identifier.
If the 'sc' key appears in GET dictionary, then return single
cutters and non-cutter features. Otherwise, return all cutters and
non-cutter features.
"""
db = models.Feature... | 80b49e637b377e8c0ca90a6653f7971e2e868a81 | 3,601,388 |
def remove_non_ascii(s):
"""
Remove non-ascii characters in a file. Needed when support for non-ASCII
is not available.
Args:
s (str): Input string
Returns:
String with all non-ascii characters removed.
"""
return "".join(i for i in s if ord(i) < 128) | 0a215ffa1841667d7dd7d9c1d9a12bbe84e2cbcd | 3,601,389 |
def gaussian_z(covar):
"""Single-dimensional Gaussian PDF normalizing coefficient.
Args:
covar (scalar): Covariance of the Gaussian PDF
Returns:
float: Normalizing coefficient Z
"""
return np.sqrt(2.0 * np.pi * covar) | 3691a37f5925cf2c12c54e8a31649ad09ece0297 | 3,601,390 |
def _hoeffding_interval(sample: np.ndarray, ref_size, c, delta, mode) -> float:
"""
A helper function calculates the concentration interval using Hoeffding inequality.
No assumptions over the sampled distribution.
Parameters
----------
sample : np.ndarray
Sample data
ref_size : (int... | a51e72a3ac6fd14ce6469a670e5982727add3d3e | 3,601,391 |
def animation_make(year_range, save_name = None, approx=10):
"""
Makes an animation for the given diagram. Optionally, it saves
Parameters
----------
year_range : TYPE
DESCRIPTION.
save_name : TYPE, optional
DESCRIPTION. The default is None.
approx : TYPE, optional
S... | 67076212eed0c989b0f2b8bd824f2548dbadbbc7 | 3,601,392 |
def get_acis_fp_limits(states, acis_s=-111.0, acis_i=-112.0):
""" Get ACIS Focal Plane limits based on SIM position.
This function uses SIM position to assign temperature limits.
Args:
states (ndarray): States array, in the form returned by the cmd_states.get_cmd_states.fetch_states function
... | ae7aca016d8af77dae3c8c079c12ca3577cc81e9 | 3,601,393 |
from functools import reduce
def compose(fns, x=nil):
"""Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (left-to-right) to the result, etc. If no value is supplied, returns a
s... | 56952b8e7d653355e138844ce91ea8db9d9c3b30 | 3,601,394 |
def fuzzy_match(s, choices, score_cutoff=80):
"""Fuzzy match string to list of possible values.
Based on http://pbpython.com/excel-pandas-comp.html
"""
m = process.extractOne(s, choices=choices, score_cutoff=score_cutoff)
if m:
return m[0]
else:
return nan | 2165bdce5cba5612d4aebcc47444cd68043149d9 | 3,601,395 |
def handle_formula_data(Y, X, formula, depth=0):
"""
Returns endog, exog, and the model specification from arrays and formula
Parameters
----------
Y : array-like
Either endog (the LHS) of a model specification or all of the data.
Y must define __getitem__ for now.
X : array-lik... | 38081650b99d1b917c6d986e6fc3ab2b9a8cd0b7 | 3,601,396 |
def draw_animation_layers(app, current_frame, img):
"""
Draw animation layers
:param app: generator app context
:param current_frame: array with number of current frames
:param img: target image
:return: new image and states array
"""
config = app.config
state = [False, False, False,... | f6bc4f8a59f3c108ab1182f76b959a05a7dbcef9 | 3,601,397 |
def generate_streak_matrix(weeks_data):
"""
Create the streak matrix
1 if the user committed
0 if the user hasn't committed
-1 to store null values
:param weeks_data: week-wise contribution data of the user
:return: matrix containing the values of the contribution streak
"""... | e6cc9e3c96aebb20ca8af11ae19e7f86aab96d62 | 3,601,398 |
def any_in_seq(search_vals, seq):
"""Check if any value in search_vals in the sequence seq"""
for v in search_vals:
if v in seq:
return True
return False | d314355aef2cba89833394ff6aeacf675daec7e6 | 3,601,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.