content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import argparse
def parse_path():
"""Parses path from command line argument"""
parser = argparse.ArgumentParser(description="Benchmark Functions")
parser.add_argument(
"--path",
"-p",
type=str,
required=False,
default=None,
help="path to save function benchm... | 2c8a648a487922aebae0be82a3bda1908b7b5cb8 | 71,400 |
import httpx
def call_app(app, event):
"""
call wsgi app
see https://cloud.yandex.ru/docs/functions/concepts/function-invoke
#response
"""
host_url = event["headers"].get("Host", "https://raw-function.net")
if not host_url.startswith("http"):
host_url = f"https://{host_url}"
bo... | 94087d442360de95dbd3251b4fbc675a7a7e79ea | 71,401 |
def split_region(region):
"""
Splits a EE FeatureCollection/Feature into four equal parts
:param region: EE FeatureCollection/Feature to split
:return: dictionary containing the four parts of FeatureCollection
"""
bounding_box = region.geometry().bounds() # gets the bounding box of the region
... | e470fb4200c440e6185263771cc98844e74d08ca | 71,402 |
def general_parser(parser):
"""
This is the parser which collects all the parameters passed through the command to launch the script
- experiment_name
- run_description
- val_freq
- acc_log_freq
- loss_log_freq
- images_log_freq
- SN_log_freq
- save_model_freq
- restore_train... | 12cb2beeb5eb7c821b5ff1380a568c6dd5d1e904 | 71,403 |
def fit_function_general(varying_parameters_values_array,
varying_parameters_keys,
Miller_indices,
allparameters,
absolutespotsindices,
Xexp,
... | 9bd8ea9b0b9febd4844b3de2da68a915c75632e9 | 71,404 |
from typing import Union
def divergence(
adata: AnnData,
basis: str = "pca",
color: Union[str, list, None] = None,
cmap: str = "bwr",
frontier: bool = True,
sym_c: bool = True,
*args,
**kwargs,
):
"""\
Scatter plot with cells colored by the estimated divergence (and other infor... | acc03948606dc26a0b7146f5d095744d872a08cf | 71,405 |
def load_vertex_label(dataset_name):
"""Returns vertex label for each dataset."""
if dataset_name == 'BH':
vertex_label = [
'Y_MEDV', 'CRIM', 'ZN', 'INDUS', 'CHAS', 'NOX', 'RM', 'AGE', 'DIS',
'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT'
]
elif dataset_name == 'Insurance':
vertex_label = [
... | 087f2e51451eb8f95d3908a2af5e1095dda32684 | 71,406 |
def pad(array, n):
"""
ISO/IEC 9797-1 pad array to blocks of size n
"""
pads = len(array) % n
return array + [0]*(n - (len(array)%n)) | cc128428a8c446c1437b5b87d563d67bb2d11f48 | 71,407 |
def unidecode_country(country):
"""Replaces diacritics with corresponding english characters.
Parameters
----------
country : Country
the Country object to have fields sanitized.
Returns
-------
Country
the Country object after fields were sanitized.
"""
country.nam... | 84f64c7d524a79c5bff6771923d1c8293be6fd3f | 71,408 |
def multiclass_log_loss(y_true, y_pred, eps=1e-15):
"""Multi class version of Logarithmic Loss metric.
https://www.kaggle.com/wiki/MultiClassLogLoss
Parameters
----------
y_true : array, shape = [n_samples]
true class, intergers in [0, n_classes - 1)
y_pred : array, shape = [n_sampl... | 981a877ad369cee8821948c9ef464126eedd09ac | 71,409 |
import tqdm
def convert_dictionary_to_name2cui(dictionary, text_preprocessor=None):
"""
convert dictionary to name2cui to get unique names and the corresponding cuis
Note! For names which are duplicate, concat the cui with '|' delimiter.
Parameters
----------
dictionary : list
... | 3e0726fd12208487801e76ee83bcba7565d02a00 | 71,410 |
def show_year_1():
"""
Render page for year1 selection page
:return: rendered page with selection list
"""
group_list = Y1Group.query.all()
return render_template('year-1.html', group_list=group_list) | 1d354828115693279c837282598e5804f1e40990 | 71,411 |
def train_cascade(train_dataset, eval_dataset, stats, action_eval_list, opt):
"""
Train a cascade of deep neural networks that lift 2D key-points to 3D pose.
"""
# initialize an empty cascade
cascade = model.get_cascade()
stage_record = []
input_size = len(stats['dim_use_2d'])
output_siz... | 7cc3c24f7ae2a4391d656a9a5cb17d042c6ae17a | 71,412 |
def from_binho_error(error_number):
"""
Returns the error class appropriate for the given Binho host adapter error.
"""
error_class = BINHO_ERRORS.get(error_number, binhoError)
message = "Error {}".format(error_number)
return error_class(message) | f60c1208c9a22e3be62a38d4df326d68a7eda956 | 71,413 |
def get_auc(test_values, predicted):
"""
Get area under the curve value
:param test_values: values to test with
:param predicted: predicted values
:return: auc value
"""
auc = metrics.roc_auc_score(test_values, predicted,
multi_class="ovr")
return round(au... | 37330adc88fd206a8e6f30f680f4e950c08fe185 | 71,414 |
import numpy
def MLOG(img):
"""Implements the MLOG focus measure algorithm.
:param img: the image the measure is applied to
:type img: numpy.ndarray
:returns: numpy.float32 -- the degree of focus
"""
return numpy.max(cv2.convertScaleAbs(cv2.Laplacian(img, 3))) | 95b4b1aa6ed090e1d814cc0ca0b5ca09c6b642f2 | 71,415 |
from typing import Tuple
from typing import List
def EPS_get_spectrum(EPS: SLEPc.EPS,
mpc: MultiPointConstraint) -> Tuple[List[complex], List[PETSc.Vec], List[PETSc.Vec]]:
""" Retrieve eigenvalues and eigenfunctions from SLEPc EPS object.
Parameters
----------
EPS
... | 240a1b9547417138bc3bc80cab14ef1ef996b5bb | 71,416 |
from typing import Any
from datetime import datetime
from dateutil import tz
def convert_created_at_to_local_time(row: Any) -> datetime:
"""
Convert the 'createdAt' field from UTC time to the application's local time.
Args:
row: The pandas row to be analysed.
Raises:
N/A
Returns:
... | 1da20cd06ac25be8dd8cba65e3653d33bc6a08a5 | 71,417 |
def obtener_descuento_list():
"""
retorna lista de descuentos de base
:return:
"""
return Disccount.objects.all() | 48977fad25e75514b81436d31a2f37cc24676d2e | 71,418 |
import hashlib
def hash_file(pathname):
"""Returns a byte string that is the SHA-256 hash of the file at the given pathname."""
h = hashlib.sha256()
with open(pathname, 'rb') as ifile:
h.update(ifile.read())
return h.digest() | bdd82aa57abacee91a4631d401af35f0274eb804 | 71,419 |
def ResNetRS350(
include_top=True,
weights="imagenet",
classes=1000,
input_shape=(None, None, 3),
input_tensor=None,
pooling=None,
classifier_activation="softmax",
):
"""Build ResNet-RS350 model."""
allow_bigger_recursion(1500)
return ResNetRS(
depth=350,
include_... | 7fbcaa8c01c893541b6312e515b61587fee48d2b | 71,420 |
def title_value(req):
"""
查询副标题参数
:param req: request
:return:
"""
ret = ResModel()
ret.msg = req_invalid_check(req)
if ret.msg:
# 请求合法性校验不通过
ret.code = ret.ResCode.fail
ret.data = {}
return JsonResponse(ret.to_dic())
ret.code = ret.ResCode.succ
w... | 4aaede177f6a62d906a01496dd55501ec328a426 | 71,421 |
import torch
def test_unbalanced_logging_with_multiple_optimizers(tmpdir):
"""
This tests ensures reduction works in un-balanced logging settings
"""
class TestModel(BoringModel):
loss_1 = []
loss_2 = []
def training_step(self, batch, batch_idx, optimizer_idx):
ou... | 1ba95e55c2d8215977424f920733220b8ac95f39 | 71,422 |
import importlib
def convert(string, convert_type):
"""Execute convert.
This module call convert module selected from choices.
"""
module = importlib.import_module("converter." + convert_type)
return module.convert(string) | b0d89172b813df3f009b904339fe6af672917419 | 71,423 |
def iob_iobes(tags):
"""
IOB -> IOBES
"""
new_tags = []
for i, tag in enumerate(tags):
if tag == 'O':
new_tags.append(tag)
elif tag.split('-')[0] == 'B':
if i + 1 != len(tags) and \
tags[i + 1].split('-')[0] == 'I':
new_tags.appe... | b0ba7d6efc16218a5686ab60a7dedb59aed3ab7d | 71,424 |
from datetime import datetime
def get_local_time():
"""
获取时间
Return:
datetime: 时间
"""
cur = datetime.datetime.now()
cur = cur.strftime('%b-%d-%Y_%H-%M-%S')
return cur | f06e9b8da578bc4fef1fc736323aa0f6642cd02d | 71,425 |
def mask_complex_polygon(image, vertices, triangles, bbox_only=False):
"""
Crops out a complex polygon from an image. The returned image is cropped
to the bounding box of the vertices.
:param image: path or :class:`PIL.Image`
:param vertices: List ``[[x1, y1], [x2, y2]]`` or string
``"x1,... | 93a2d693f6caf784107b523a699c4041c3692064 | 71,426 |
def training(loss, learning_rate):
"""Sets up the training Ops.
Creates a summarizer to track the loss over time in TensorBoard.
Creates an optimizer and applies the gradients to all trainable variables.
The Op returned by this function is what must be passed to the
`sess.run()` call to cause the model to ... | fd7ee15e68c6e6a4726de8ffc1becd670fba0844 | 71,427 |
def set_op_type(*args):
"""set_op_type(ea_t ea, flags_t type, int n) -> bool"""
return _idaapi.set_op_type(*args) | e4ca744e936755d3066dd4b9e6472f4bf6ed91dc | 71,428 |
from pathlib import Path
import fnmatch
def _get_package_name(file: PackagePath):
"""Determine the package name of a Python file in :data:`sys.path`.
Arguments:
file:
A Python filename relative to Conda root (sys.prefix).
Returns:
Package name or None.
This function only ... | 77571db89cce4411443573a3e9810e08639e94af | 71,429 |
import copy
import warnings
from typing import Iterable
def jnum2str(jnum, x_orientation=None):
"""
Convert jones polarization number to str according to calfits memo.
Parameters
----------
num : int
antenna (jones) polarization number
x_orientation : str, optional
Orientation... | a8776819aa60eb46a92a7e7ac3a242361da6845a | 71,430 |
def note():
"""Serves a *notes set* **record** page.
Usually from an overview page or a shared link.
The page consists of a sidebar with the details of the notes set,
and the main area displays the notes between the verses.
"""
session.forget(response)
request.vars["mr"] = "r"
request.... | 356c0a047b2ceaf7381143f3c57943a7450cc007 | 71,431 |
import os
import pickle
def gen_sample(folder, ftype='jpg', savepath=None,
crop_box=(200, 200), res_box=(50, 50), clipflag=False, clipparam=None):
"""
Read the sample images and reshape to required structure
input
=====
folder: str
Name of the folder, i.e., the path
ft... | a8f46b80fca43f14541230d935a0e86f16559424 | 71,432 |
def __report_detail(health, items):
"""Report the details of health check item
:type health: dict
:param health: the overall health status
:type items: dict
:param items: a dict that contains all detail items to check
:rtype dict
:return health status including overall status and details ... | eea2cad2c52d62cd40cea757d0a128b9c283f618 | 71,433 |
import os
def load_case_data(flag='TEST_CASE'):
"""
:Desc:
load DDT data form YAML.
:param flag:
The starting node of the interface case in YAML.
default:
TEST_CASE
:import
from httptesting.library.scripts import load_case_data
or
form httpte... | da6b2d0d863ee60f181b62f9f4a837a274df48a1 | 71,434 |
def clean_field(field):
"""Return a cleaned version of field.
Parameters
==========
field : numeric or string
DataFrame cell to clean
Returns
=======
field : numeric
Cleaned DataFrame cell
Notes
=====
In most cases, pandas will correctly read the contents of a... | 6a19d3b75e5009d3d1f4e34cfa0f9b2f51b4f301 | 71,435 |
def read_iaga(fname, return_xyzf=True):
"""Reads an IAGA-2002 data file and returns data in XYZF format."""
# Get the header information
header_records = read_iaga_header(fname)
# This contains 4 letters stating the reported values
# - XYZF, HDZF, etc...
if len(header_records['reported']) % 4 ... | 9bfaa14544e923a5d41749cf7fc7715f4cf32fce | 71,436 |
def Qpar(sortedEigVec,d=1):
"""concatenation of first d eig vectors . (parallel decompositon of hessian)"""
return np.concatenate(sortedEigVec[0:d]).T | c28123b4f067ef4c8b876aeb6a20ba3e00dd21cd | 71,437 |
def reduce_columns(dataset: Dataset, min_df=5, inplace=False):
"""
Reduces the dimensionality of the instances, represented as a `csr_matrix` (or any subtype of
`scipy.sparse.spmatrix`), of training and test documents by removing the columns of words which are not present
in at least `min_df` instances ... | 6caee331b3ce0cec4186a3ca72bdef4c1748e3b1 | 71,438 |
def tcn(
inputs,
filters,
kernel_size,
strides=1,
padding='valid',
data_format='channels_last',
dilation_rate=1,
activation=None,
use_bias=True,
kernel_initializer=None,
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=None,
bias_regularizer=None,
activ... | 1a2118c67c5d597e9b3f5268570c484493ff49fe | 71,439 |
def integrate(times):
"""
Returns the seconds of staked times for an array of alternating deposit
and withdrawal times for a token.
"""
if len(times) == 1:
return CURRENT_TIME - times[0]
elif len(times) % 2 == 0:
s = 0
for i in range(0, len(times), 2):
s += ti... | 93385d77595014a8fc7540048af74bac3afb3cea | 71,440 |
import os
def get_default_log_path():
"""
Returns the absolute path to the log folder
:return:
"""
return f'{os.path.dirname(os.path.realpath(__file__))}/../logs' | c83133221a89c8d0a7afe5b7fcfae11edc422d7b | 71,441 |
def fastdtw(XL, YL, radius, L = 0, do_plot=False):
"""
An implementation of [1]
[1] FastDTW: Toward Accurate Dynamic Time Warping in Linear Time and Space. Stan Salvador and Philip Chan
Parameters
----------
XL: ndarray(floor(M/2^L), d)
An array of coordinates for the first path
... | 588527b0168e6d251220b630c67c5bb8503d15a7 | 71,442 |
def get_PLUMBER_metrics(name, site='all', variables=['Qle', 'Qh', 'NEE']):
"""get metrics dataframe from a site, with benchmarks for comparison
:returns: dataframe with metrics for model at site
"""
csv_file = './source/models/{n}/metrics/{n}_{s}_metrics.csv'
# benchmark_names = ['1lin', '2lin', '... | 807a6c3e2fff6b087f6fdcfb9d99f22c417f7209 | 71,443 |
from time_series import Time_series
def _serie_get(project, row, cur, id1, ifecha, ivalue, situaciones, isitu):
"""
hace select a una BDD e instancia un objeto Temporal_series
input
project: tag del proyecto seleccionado
row: fila de select_master correspondiente al punto cuyos umbrales
q... | afc12c3199c66f3471399b4dc1c621ef0ef5bf89 | 71,444 |
import xarray as xr
from scipy.signal import welch
def fft_average( da,
nperseg=None,
noverlap=None,
plot=False,
verbose=True,
trimNegFreqs=False,
normalizeAmplitude=False,
sortFreqIndex=False,
returnAbs=False,
zeroTheZeroFrequency=False,
realAmplitudeUnits=False,
... | c515a67b4a2157131ec241b2b751ca3068880a44 | 71,445 |
def get_resized_size(org_h, org_w, long_size=513):
"""get_resized_size"""
if org_h > org_w:
new_h = long_size
new_w = int(1.0 * long_size * org_w / org_h)
else:
new_w = long_size
new_h = int(1.0 * long_size * org_h / org_w)
return new_h, new_w | 699b91a1fbdb1e5228872d3ea5812dcc29cfbaa5 | 71,446 |
def parse(url, defaultPort=True):
"""
Split the given URL into the scheme, host, port, and path.
@type url: C{str}
@param url: An URL to parse.
@type defaultPort: C{bool}
@param defaultPort: Whether to return the default port associated with the
scheme in the given url, when the url do... | 6bd14455a8e0f72a413c4f1055e372f48708c49f | 71,447 |
def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None):
"""Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.
This builds a PairPos subtable from a dictionary of glyph pairs and
their positioning adjustments. See also :func:`buildPairPosGlyphs`.
Note ... | 68db50654c517cf7cb10e6c87bba05021087e4e7 | 71,448 |
import random
def is_prime(number, test_count):
"""
Uses the Miller-Rabin test for primality to determine, through TEST_COUNT
tests, whether or not NUMBER is prime.
"""
if number == 2 or number == 3:
return True
if number <= 1 or number % 2 == 0:
return False
d = 0
r = ... | 49b0149dad5f053bbf813845a10267766784c775 | 71,449 |
import os
def getclass(storefile, ignore=None, classes=classes, hiddenclasses=hiddenclasses):
"""Factory that returns the applicable class for the type of file presented.
Specify ignore to ignore some part at the back of the name (like .gz). """
storefilename = _getname(storefile)
if ignore and storef... | 416c00333a6a7bc47ec1db6dec5d5c6a379b361a | 71,450 |
def MergeSequences(seqs):
"""Merge a sequence of sequences into a single sequence.
This code is copied from https://www.python.org/download/releases/2.3/mro/
with print statements removed and modified to take a sequence of sequences.
We use it to merge both MROs and class templates.
Args:
seqs: A sequen... | 24ab5d84dc4c9416810b6e99cf3b18b996b570ad | 71,451 |
def PvtuToVtu(pvtu, model = None, oldNodeIdToNew = [], oldCellIdToNew = [],
fieldlist = []):
"""
Convert a parallel vtu to a serial vtu. Does nothing (except generate a copy)
if the supplied vtu is already a serial vtu.
"""
# Steps 1-5 are now handled by ModelPvtuToVtu (or aren't necess... | 5f8dd3d8e607891c2bfc4e873eda1955788afe1a | 71,452 |
def monitor_code(hook, task_name=None):
"""
Provide a context manager to monitor code blocks.
Parameters
----------
hook : callable (:class:`Task`, [exception])
A hook on which to register progress. It must have
- one mandatory argument which is a :class:`Task`instance
- one... | 4f05691ce82a9425c8045c1ba7a336fdb2b28307 | 71,453 |
def setFramerate(absValue=20):
""" This function sets the framrate and returns the value from the camera as it will not be exact """
cam.setProperty(type = PyCapture2.PROPERTY_TYPE.FRAME_RATE, autoManualMode = False, absValue = absValue)
return getFramerate(cam) | aa577419a5a73436ad593745e695a2dd130ca8d8 | 71,454 |
def create_segment(**kwargs):
"""
Takes the same arguments as gparray.Segment's constructor, but with friendly
defaults to minimize typing.
"""
content = kwargs.get('content', 0)
role = kwargs.get('role', gparray.ROLE_PRIMARY)
preferred_role = kwargs.get('preferred_role', ro... | c56dad2692a8d212643d6729192c71c68ebf13f2 | 71,455 |
def compute_f1(actual, predicted):
"""
Computes the F1 score of your predictions. Note that we use 0.5 as the cutoff here.
"""
num = len(actual)
true_positives = 0
false_positives = 0
false_negatives = 0
true_negatives = 0
precision = 0
recall = 0
for i in range(num):
... | 2af79c51056114ac35b6b03fe21f49978f7499e6 | 71,456 |
def learn_d_z_weighted(
X, n_atoms, n_times_atom, func_d=update_d_block, reg=0.1, alpha=1.9,
lmbd_max='fixed', n_iter_global=10, init_tau=False, n_iter_optim=10,
n_iter_mcmc=10, n_burnin_mcmc=0, random_state=None, n_jobs=1,
solver_z='l-bfgs', solver_d_kwargs=dict(), solver_z_kwargs=dict(... | cd1fc156e6d8f94d7539562ed570b2a0ef6bd8d2 | 71,457 |
async def _setup(hass, filter_config):
"""Shared set up for filtering tests."""
config = {
google_pubsub.DOMAIN: {
"project_id": "proj",
"topic_name": "topic",
"credentials_json": "creds",
"filter": filter_config,
}
}
assert await async_set... | 83e63a25d22bbefb578cb0f2d797ae59511b1f52 | 71,458 |
def select_metadata(metadata, **attributes):
"""Select specific metadata describing preprocessed data.
Parameters
----------
metadata : :obj:`list` of :obj:`dict`
A list of metadata describing preprocessed data.
**attributes :
Keyword arguments specifying the required variable attri... | 5ba8c990f77d635c3dcdd21512adf61fd6d18812 | 71,459 |
import cPickle
def search_vars_represent(search_vars):
"""
Unpickle and convert saved search form variables into
a human-readable HTML.
@param search_vars: the (c)pickled search form variables
@returns: HTML as string
"""
s = ""
search_vars = search_vars.replace("&a... | 5f08eb4c0c18929816eab43ea5f489a60ff162b0 | 71,460 |
def main():
"""
main function
"""
print("---- Tengine YOLOv3 Optimize Tool ----\n")
args = parse_args()
if args == None or args.input == None:
usage_info()
return None
print("Input model : %s" % (args.input))
print("Output model : %s" % (args.output))
print... | ee95997338ac666da9f5bfce3a5d3e95306cbb50 | 71,461 |
def weave_fast_clauses(clauses,
embed,
apply_,
not_,
or_,
and_=None,
shuffle=True,
seed=None):
"""Weave serialized FastClauses using TensorLoom.
Computes ... | be39858947805fc656575224c6e75529fe10a602 | 71,462 |
from typing import Iterable
from typing import AnyStr
from typing import Optional
from typing import Iterator
from typing import cast
from typing import List
def iterhtmldecode(
iterable: Iterable[AnyStr],
http_charset: Optional[str] = None,
default_encoding: str = "cp1252",
errors: str = "replace",
... | a5011e7baf889a3702e9afcf9150ab64187c1865 | 71,463 |
import os
def as_path(path, label, is_dir=False, preexists=True, null_is_valid=True):
"""
Processes the path and returns the absolute path.
If the path does not exist and ``preexists`` is true
an ``OasisException`` is raised.
:param path: The path to process
:type path: str
:param label... | bbfd73318b882127ea0b3c7e12a9e654ccb96d60 | 71,464 |
def _get_flight_level(aircraft_id):
"""
Get a dataframe with the aircraft's current, requested and cleared flight levels.
Parameters
----------
aircraft_id : str
A string aircraft identifier. For the BlueSky simulator, this has to be
at least three characters.
Returns
-----... | b93caa2866ccb43ab5b9d5fa024b4de800e0445f | 71,465 |
def compute_centroid(coords):
"""Compute the centroid of coordinates.
.. math::
\\mathbf{C} =
\\frac{\\sum_{i=1}^{N}m_i\\mathbf{r}_i}{\\sum_{i=1}^{N}m_i}
Returns
-------
C : `~sknano.core.math.Vector`
The position vector of the centroid coordinates.
"""
C = Vector(np.... | 0b307af3110d3deadc3ce1b19bb8c177849533a1 | 71,466 |
def query_yes_no(question, default="yes"):
"""
Ask a yes/no question using input() and return the answer.
:param question: a string that is presented to the user
:param default: the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an an... | 117e0d05811fc7eb80e9e94e08942744c256cef8 | 71,467 |
from .sampler import Sampler
from typing import Tuple
import numpy
def image_compose(
imlist:list,
outsize:Tuple,
bgcolor:list = [255,255,255],
) -> numpy.ndarray:
"""
Compose image from parts
Parameters
----------
imlist : list
List of image parts, each element a 3-elemen... | 71bfc52aca23e52f99bb709ece0465d815a618b7 | 71,468 |
def ff_bin( smiles = 'c1ccccc1O'):
"""
It generates binary string fingerprint value
Output -> '0b0010101...'
"""
mol = Chem.MolFromSmiles( smiles)
fp = AllChem.GetMorganFingerprint(mol,2)
fp_hex = fp.ToBinary().encode("hex")
fp_bin = bin( int( fp_hex, 16))
# print fp_bin
return fp_bin | c94cfa1a24fe6830b07edaa741326fee9707daa1 | 71,469 |
def handle_django_file_upload(f, group):
"""
Handles the uploading of a file from a django form fileField
"""
f_obj = open(get_inbox_file_path(f.name, group), "wb")
for chunk in f.chunks():
f_obj.write(chunk)
f_obj.close()
return f.name | abc9936a78014fd2a8cc1be22177acaf4528cbd1 | 71,470 |
def test_rejects_funcs():
"""#SPC-asts.tst-rejects_funcs"""
def dummy_func(x):
return x
with raises(MacroError):
inrange(dummy_func) | cfae551daef77ee682372313ae76d30c6608102f | 71,471 |
def filter_entry(line, min_obs, min_indiv):
"""
Check the samples and filter
returns a bit flag with
0 - pass
1 - too-few observations
2 - too-few individuals
"""
data = line.strip().split('\t')
fmt = data[8].split(':')
dp_idx = fmt.index("PAD")
obs = 0
n_indivs = 0
f... | 5e8e98b256c8f07aa106dbf7a33df21a797d4bab | 71,472 |
import logging
def get_tile(year, z, x, y, map_object=None):
"""Get tile Endpoint"""
logging.info(f"[ROUTER]: Getting url for tiles for year {year}")
return analyze(year, z, x, y, map_object) | b2da36f4fa3e8b52196e4b4890a86b448bb7d17e | 71,473 |
import os
def barbara():
"""Return the "barbara" test image."""
return np.load(os.path.join(os.path.dirname(__file__), 'barbara.npz'))['barbara'] | 68dfcdc7548379b913a807c6d57ab308576c2c39 | 71,474 |
import tempfile
from masci_tools.util.xml.common_functions import reverse_xinclude
import os
def modify_fleurinpdata(original, modifications, **kwargs):
"""
A CalcFunction that performs the modification of the given FleurinpData and stores
the result in a database.
:param original: a FleurinpData to ... | a54e7307336356e8a10919972e17840ffb4b6289 | 71,475 |
def decode_object(value):
"""
Given a Grist-encoded value, returns an object represented by it.
If typename is unknown, or construction fails for any reason, returns (not raises!)
RaisedException with the original exception in its .error property.
"""
try:
if not isinstance(value, (list, tuple)):
... | ef024005724a64d6975894a5eedc4f0e4fd9a5cf | 71,476 |
def imread(f, flatten=False, dtype='float32'):
"""
Read image from file, backend=scipy
f : str or file object -> The file name or file object to be read.
flatten : bool, optional -> If True, flattens the color channels into a single gray-scale channel.
Returns ndarray
"""
# return sp.... | b2c828d3d982492383ef7a726455e40a74e64141 | 71,477 |
def relative_speeds(group_speeds):
"""
Calculates the ratio of a each track's speed to the mean of all other
tracks using leave-one-out loop.
Parameters
----------
group_speeds: iterable
A list of track speeds from all tracks in an experiment
Returns
-------
features: list ... | a82713a601e330c166d8583d1bb96e3f8e81d108 | 71,478 |
def create_orthogonal_projection(
left,
right,
bottom,
top,
near,
far,
dtype=None
):
"""Creates an orthogonal projection matrix.
:param float left: The left of the near plane relative to the plane's centre.
:param float right: The right of the near pla... | c9a213f528dac55781539d1dfd6f5fa3e56fe0f7 | 71,479 |
import numpy
def plot_image_and_mask(img, mask, alpha=0.6, deprocess_func=None,
reference_mask=None,
show_original_image=True,
small=False):
"""Plot an image and overlays a transparent segmentation mask.
Args:
img (arr): the imag... | 516c357ccd1af41c3770edb13b3a26a3d0d8776d | 71,480 |
import math
def sample_size(population_size, confidence_level, confidence_interval):
"""
Get a sample number of the whole population
:param population_size:
:param confidence_level:
:param confidence_interval:
:return:
"""
z = 0.0
p = 0.5
e = confidence_interval / 100.0
n =... | ad3c412b8adc91147a76f192347e4488bd41c8a1 | 71,481 |
def strip_inputs(c):
"""
Converts inputs to buffers for easy
instantiation.
Parameters
----------
c : Circuit
Input circuit.
Returns
-------
Circuit
Circuit with removed io
"""
g = c.graph.copy()
for i in c.inputs():
g.nodes[i]["type"] = ... | bed0032478094f0784116eeb13052d96f4f53540 | 71,482 |
import platform
import subprocess
def find_children_pids(pid_in, ps_out=None):
"""
Tries to locate the PIDs of all children recursively) of pid_in.
ps_out is used when called recursively to avoid extra system calls.
"""
if ps_out is None:
if 'CYGWIN' in platform.system():
ps_ou... | 83d22c6ef7e1bc06f1f872b3d0f16190e2ff4ced | 71,483 |
def st_webscrap_tool(html, key=None):
"""Create a new instance of "streamlit_webscrap_tool".
Parameters
----------
html: list
List of html strings.
key: str or None
An optional key that uniquely identifies this component. If this is
None, and the component's arguments are ch... | a7479b5ae7f425af0ed13191f9d1b531288ce56f | 71,484 |
def get_uv_index(zipcode='', city_name='', state_code=''):
"""Returns ultra violet index for a given city, state, or zipcode."""
if not zipcode and not (city_name and state_code):
raise TypeError('Pass a zipcode or a city and state')
url = 'http://oaspub.epa.gov/enviro/uv_search?'+ urlencode(
... | 1809759b572dabdba4c71e5f89e3157fef237835 | 71,485 |
import subprocess
def run_async(
stream_spec,
cmd,
pipe_stdin=False,
pipe_stdout=False,
pipe_stderr=False,
quiet=False,
overwrite_output=False,
cwd=None
):
"""Asynchronously invoke ffmpeg for the supplied node graph.
Args:
pipe_stdin: if True, connect pipe to subproces... | 75073646cc0cd8ed51d00ac303877bf26fc9d2c1 | 71,486 |
import sys
import os
def file_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath("")
# return o... | 0c0a064fc8341f1063035a96f03c1acf0421cfdc | 71,487 |
def log_level(level=None):
"""``log_level(level=None)`` return current log level and
set new log level if ``level is not None and level``.
:param level: must be 'error' or 'warning' or 'info' or 'debug', listed
with increasing verbosity, or '' which doesn't change anything.
"""
return _int... | 889d747014186f35c6d597586b36aca20c3cf757 | 71,488 |
def _render_pattern(pattern, nested=False):
"""Renders the given pattern as a string."""
# TODO(axch) Think through breaking lines in patterns; currently just splats
# the whole thing out on one line.
if isinstance(pattern, (list, tuple)):
subs = [_render_pattern(sub, nested=True) for sub in pattern]
su... | 8228ba88c234d34a8a08f822bcc9983c3e3a9c75 | 71,489 |
import math
def data_to_sorted_xy(data, logx):
"""
Return a list of (x, y) pairs with distinct x values and sorted by x value.
Enter: data: a list of (x, y) or [x, y] values.
logx: True to return (log10(x), y) for each entry.
Exit: data: the sorted list with unique x values.
"""
i... | 7e84a3f684dc9a82bf5fd48256e5f5c18a5eedb6 | 71,490 |
def is_catalog_record_owner(catalog_record, user_id):
"""
Does user_id own catalog_record.
:param catalog_record:
:param user_id:
:return:
"""
if user_id and catalog_record.get('metadata_provider_user') == user_id:
return True
return False | bb5e649b4cfd38ee17f3ab83199b4736b374d312 | 71,491 |
import requests
def get_transmem_from_uniprot(uniprot_id):
"""
Retains transmembrane regions from Uniprot (first and last residue each).
This function requires internet access.
Parameters
----------
uniprot_id : str
The UNIPROT ID of the protein.
Returns
-... | 3fb8b5061d3ce051d108784a0b9e8d83c875feb3 | 71,492 |
import glob
def load_onezone_data(data_path = './'):
"""
Grab and load all of the summary outputs that exist
"""
dfiles = glob.glob(data_path + 'run????_summary_output.txt')
dfiles = np.sort(dfiles)
all_data = [None]*len(dfiles)
for i in np.arange(len(dfiles)):
all_data[i] = np.... | a7ef49658b9d3322a2131702febe391b63fd6170 | 71,493 |
def odoo_maybe(value, *functions):
"""Like maybe, but treats False as a null value too, so suitable
for dealing with values from Odoo models.
Bear in mind that False can also be a valid value for a boolean
field, so use with care.
>>> from .mappings import lookup
>>> from operator import metho... | 711fa143d3fe408b3403482226f22945a7c3df6a | 71,494 |
def find_latest_tag_version(tag):
""" Find the latest version for the given tag. Returns an integer. """
r = Repo()
version = 1
while make_versioned_tag(tag, version+1) in r.tags:
version += 1
status_update(
'Latest version for tag %s is %d: %s' % \
(tag, version, make... | d39b110483d88c253d913a36dcbc21ea02578c56 | 71,495 |
import os
def detection_files():
"""Fixture for reading detection file and ground truth."""
result_folder = os.path.join(
os.path.dirname(__file__), "mock_results", "transcripts"
)
gt_file = os.path.join(result_folder, "OND.0.90001.8714062_single_df.csv")
gt = pd.read_csv(gt_file, sep=",",... | 5f1630251deed052325a3eb856e436aee4668d7d | 71,496 |
import joblib
def load_model(filename):
"""
Loads a Scikit-learn model saved with joblib.dump.
This is just an example, you can write your own function to load the model.
Some examples can be found in src/utils.py.
:param filename: string, path to the file storing the model.
:return: the mode... | ad7d165c4ba48fd803e13cc872840e968aa651f5 | 71,497 |
def groupfinder(userid, request):
"""
find the user attached to the current user
"""
# result = None
# user = request.user
# if user is not None :
# result = GROUPS.get(user.email,['group:editors'])
# whatever every body is an editor
return ['group:editors'] | f23bab45b4170a2897bbd34a1068564b53e10a67 | 71,498 |
from ethereum.frontier.vm.interpreter import (
STACK_DEPTH_LIMIT,
process_message,
)
def call(evm: Evm) -> None:
"""
Message-call into an account.
Parameters
----------
evm :
The current EVM frame.
"""
gas = pop(evm.stack)
to = to_address(pop(evm.stack))
v... | 677515debe68863fc9aed896ffcd66de2f51f9d4 | 71,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.