content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def guess_encoding(fname):
"""
Guesses the encoding of a file.
fname - the name of the file whose encoding to guess.
Returns the guessed encoding of the file (string).
"""
with open(fname, "rb") as file:
result = chardet.detect(file.read())
return result["encoding"] | 89fd77ab79d8bbf2c9879f836ef0a7373a8d2ea3 | 46,100 |
def buffer_filtering(buffer):
"""
Check whether "buffer" should be filtered.
"""
local = weechat.buffer_get_string(buffer, "localvar_%s" % SCRIPT_LOCALVAR)
return {"": None, "0": False, "1": True}[local] | a03fa0d5d2e75d9305ec9a9627e4ee68898df33a | 46,101 |
def parameter_count(funcsig):
"""Get the number of positional-or-keyword or position-only parameters in a
function signature.
Parameters
----------
funcsig : inspect.Signature
A UDF signature
Returns
-------
int
The number of parameters
"""
return sum(
p... | ff6e8ede23020d9d3c30333458e182f086e913c7 | 46,102 |
def sum_of_squares(v: Vector) -> float:
"""Uses dot_product function"""
return dot_product(v, v) | 44da95accc7444148b13a944f9a1fd85611238f1 | 46,103 |
def get_channel_index(image, label):
"""
Get the channel index of a specific channel
:param image: The image
:param label: The channel name
:return: The channel index (None if not found)
"""
labels = image.getChannelLabels()
if label in labels:
idx = labels.index(label)
... | 3980e83f61ac755f1fbcadef27964a405a0aaf31 | 46,104 |
def search_ignore_case(s, *keywords):
"""Convenience function to search a string for keywords. Case
insensitive version.
"""
acora = AcoraBuilder(keywords).build(ignore_case=True)
return acora.findall(s) | 5957e0c15a46743b43187203c5472442396d1bc1 | 46,105 |
def make_rgba(data_in: ArrayLike) -> ArrayLike:
"""Convert any array to an RGBA array.
RGBA arrays have 3 dimensions where the last represents the channels. If
an Alpha channel needs to be added it will be made completely opaque.
Returns
-------
3D RGBA unsigned 8-bit array
"""
max_va... | 52d57e95d1c7b7926ec8fa698d719da0c6b95aef | 46,106 |
import sys
def get_args():
"""Command line argument processing."""
usage="apply_ar_tweet_oov_rules.py [options] [infile [outfile]]"
help="""
Apply Arabic tweet preprocessing rules to Arabic OOVs in either the original
Arabic text or buckwalter transliterated text.
The script can also produce a ... | ddb21a27c0fbfa3000b1d646854963579db8296b | 46,107 |
def main(min_kmers, min_reads, slope, rank, longform_table, table_out):
"""Filter taxa according to the ratio of reads to kmers."""
long_taxa = pd.read_csv(longform_table)
long_taxa.columns = ['uuid', 'taxa', 'taxid', 'rank'] + long_taxa.columns.tolist()[4:]
long_taxa = long_taxa.query('rank == @rank')
... | 4a22e8fed4df65f16cd64a852750413269b4e6ff | 46,108 |
def error(v1, v2):
"""Returns the relative error with respect to the first value.
Positive error if program output is greater than AREMA table.
Negative error if program output is less than AREMA table.
"""
e = (v2 - v1)/v1
return e | c213751d1da06991f8cbef08c3c98b41f4fcc6af | 46,109 |
def read_meta(metafn=None):
"""
Read a [metadata] text file into a dictionary.
Function modified from https://github.com/JessicaS11/python_geotif_fns/blob/master/Landsat_TOARefl.py
"""
metadata = {}
# potential future improvement: strip quotation marks from strings, where applicable. Will then... | 834c2c8a0d1138b5c3ceb0ab6a7215a67c913acc | 46,110 |
def ODE_step_euler(x, y, h, derivs):
"""
Advances the solution y(x) from x to x+h using the Euler method.
derivs .... a python function f(x, (y1, y2, y3, ...)) returning
a tuple (y1', y2', y3', ...) where y1' is the derivative of y1 at x.
"""
X = derivs(y,x)
return vadd(y, smul(h, X)) | a696708e9aa854425c6af04395e401e48fb94490 | 46,111 |
def check_go(*args):
"""Check GO State. If all three panels are NOT a 'GO', ignitor state is set to 'Safe' mode.
Arguments
---------
args[0] : ucl --> UpperClass Instance
Nested Functions
----------------
getGOState() ... | 6c4a3c59991bcec5c6b25decc33ccca04b363e10 | 46,112 |
def max_abs_error_relative_to_mean_radius(standard_shape, test_shape):
"""
Compare test_shape to standard_shape, relative to mean radius of standard.
Returned value is a percentage.
standard_shape npy array
test_shape npy array
Must have the same shape. Either:
one-dimensional (s... | 5721eed0803cccec97370d54de544df7f7585497 | 46,113 |
def get_calendar(caldav_url):
"""
Get the calendar using credentials from `credentials.py`.
"""
url = caldav_url
client = caldav.DAVClient(url)
princ = caldav.Principal(client, url)
return princ.calendars()[0] | 19ea213c52a193034aed5be70b74bd4bd264d782 | 46,114 |
def batch_get_heuristic_mask_fetchpush_(s, a):
""" heuristic mask for disentangled fetch """
grip_poses = s[:, 0, :3]
obj_poses = s[:, 1, 10:13]
entangled = np.linalg.norm(grip_poses - obj_poses, axis=1, keepdims=True)[:, None] < 0.1
entangled_mask = np.ones((1, 3, 3))
disentangled_mask = np.array([[[1... | 1a511cb286f2054c2e8f12b80cbdbf0cbc31f902 | 46,115 |
from typing import Hashable
def is_hidden(tree: nx.DiGraph, node: Hashable, attr: str) -> bool:
"""Iterate on the node ancestors and determine if it is hidden along the chain"""
if tree is not None and node in tree:
if tree.nodes[node].get(attr, False):
return True
for ancestor in... | 703763188611f02fb1729e0d652f855a1207abc6 | 46,116 |
def parse_both_2(image_results):
""" parses the tags and repos from a image_results with the format:
{
'image': [{
'pluginImage': {
'ibmContainerRegistry': 'internalRepo/name'
'publicRegistry': 'repo/name'
},
'driverImage': {
'ibm... | 020cde41855d3bca26797cd9786e2733a50b6a00 | 46,117 |
from typing import Optional
from typing import cast
def decode_auth_token(token: str) -> Optional[LoginSessionDict]:
"""Decode an authorization token into a LoginSessionDict."""
decoded = None
try:
secret = get_secret_key()
decoded = jwt.decode(token, secret)
except InvalidSignatureE... | 153ae0f24470171ef75976d3f8a7ea8ef2729cc4 | 46,118 |
import os
def splitexts(path, exts=None):
"""
Split each extension of a given file (.tar.gz, .tar, .pp, etc).
"""
exts = []
ext = os.path.splitext(path)
while True:
if len(ext[1]) < 1:
break
else:
exts.append(ext[1])
ext = os.path.splitext(ex... | 67d9a29cabadaaa161eddddfc93dae6646258929 | 46,119 |
from numpy import NINF, PINF
from openravepy import AABB
import numpy
def ComputeEnabledAABB(kinbody):
"""
Returns the AABB of the enabled links of a KinBody.
@param kinbody: an OpenRAVE KinBody
@returns: AABB of the enabled links of the KinBody
"""
min_corner = numpy.array([PINF] * 3)
m... | 1390bb6b5199bbcd798848759724b0370d4356ce | 46,120 |
def find_last_version_pypi(package, delay):
"""Return the last version of a package
"""
url = 'https://pypi.org/project/{}/#history'.format(package)
page = requests_get_handler(url)
if page.status_code == 404:
print('{} not found'.format(package))
return ""
elements = pypi_parser... | 81ee46571ae555b0c445660079bb5d3da9c90476 | 46,121 |
def get_put_single_endpoint_schema(class_name, form_schema_model, response_schema):
"""
:param class_name:
:param form_schema_model:
:param response_schema:
"""
return {
"tags": [class_name],
"description": f"Create a {class_name}",
"requestBody": {
"descrip... | 1c073c02c025d563cba720e6e1334638c158e687 | 46,122 |
def get_bit(byte, bit_num):
""" Return bit number bit_num from right in byte.
@param int byte: a given byte
@param int bit_num: a specific bit number within the byte
@rtype: int
>>> get_bit(0b00000101, 2)
1
>>> get_bit(0b00000101, 1)
0
"""
return (byte & (1 << bit_num)) >> bit_... | 4f25c4ccdc4c3890fb4b80d42d90bfb94d6799c3 | 46,123 |
def dashboard(i):
"""
Input: {
(host) - Internal web server host
(port) - Internal web server port
(wfe_host) - External web server host
(wfe_port) - External web server port
(extra_url) - extra URL
}
... | e2a6990008c649cb3016845e5b60b41151327fc8 | 46,124 |
def create_translation_field(model, field_name, lang):
"""
Translation field factory. Returns a ``TranslationField`` based on a
fieldname and a language.
The list of supported fields can be extended by defining a tuple of field
names in the projects settings.py like this::
MODELTRANSLATION... | 9ba4783ab797634576abb52b5c4c3680f8f004f5 | 46,125 |
import logging
def ExtractPrompt(source, default):
"""Attempts to extract the prompt from the code cell.
Args:
source: The merged source string of the code cell.
default: The default prompt string.
Returns:
The source with prompt removed.
The first extracted prompt if pro... | 1142b7b546a174142d433a3123fba04d6c07b63e | 46,126 |
def find_dominant_axis(vertices):
"""
measures which axis has least variance and returns 0, 1, or 2 (x, y, z)
so the 3D coordinates can be reduced to 2D
"""
xArray = [x[0] for x in vertices]
yArray = [x[1] for x in vertices]
zArray = [x[2] for x in vertices]
xVariance = max(xArray) -... | f9a5adc52278a14e3a2a939bb0da57085a0bcb7a | 46,127 |
from datetime import datetime
def read_file(file_path):
"""
Read the given file path and its metadata. Returns a LoaderResult.
"""
with open(file_path, 'r') as f:
stats = fstat(f.fileno())
return LoaderResult(
buffer=f.read(),
successful=True,
metada... | c45e15653c451479e6c69d718b47072d766fef6d | 46,128 |
def generate_local_graph(N=N, n_divisions=4, mean_degree=MEAN_DEGREE):
"""Generates a graph with a much higher clustering coefficient.
Smaller n_divisions -> higher clustering.
"""
edges = genereate_local_edges(N, n_divisions, mean_degree)
H = edges2graph(edges, N)
# In Graph name, include the parameters.... | d119d70ad45a28b31fc58ad96beab958f7e9cec1 | 46,129 |
def GlyphCollection(mode="sdf", *args, **kwargs):
"""
mode: string
- "sdf" (speed: fast, size: small, output: decent)
- "agg" (speed: fasteest, size: big output: perfect)
"""
if mode == "agg":
return AggGlyphCollection(*args, **kwargs)
return SDFGlyphCollection(*arg... | faa401846c3fd9d94d81926efefb38e20ea79e31 | 46,130 |
def extract_dates_mp(raw_cert):
"""
Override SleekXMPP's TLS Certificte to handle all Valid TLS Date Formats
- Date prior to 1/1/2050:'%y%m%d%H%M%SZ'
- Date post after 1/1/2050: '%Y%m%d%H%M%SZ'
"""
slk_cert = sleekxmpp.xmlstream.cert
if not slk_cert.HAVE_PYASN1:
log.warning(... | c9dd000e88726745e1426d66f3876f4929800f0c | 46,131 |
def opt_pairwise(n_items, data, alpha=1e-6, method="Newton-CG",
initial_params=None, max_iter=None, tol=1e-5):
"""Compute the ML estimate of model parameters using ``scipy.optimize``.
This function computes the maximum-likelihood estimate of model parameters
given pairwise-comparison data (see :ref... | fb82e734aeedd9f4267698f873176f65251d463e | 46,132 |
def autocrop(img):
"""
Remove zero-valued rectangles at the border of the image.
Parameters
----------
img: ndarray
Image to be cropped
"""
slices = ndimage.find_objects(img > 0)[0]
return img[slices] | ebd6b90b0ee57ca779eb360d46f2b34cb3cef0e1 | 46,133 |
def authorize_payment(payment):
"""Activate client's payment authorization page from a PayPal Payment."""
for link in payment.links:
if link.rel == "approval_url":
# Convert to str to avoid Google App Engine Unicode issue
approval_url = str(link.href)
return approval_... | e489a1a2029535a8400f427a523665c49c872ef6 | 46,134 |
def import_sites_vcf(**kwargs) -> hl.Table:
"""Import site-level data from a VCF into a Hail Table."""
return hl.import_vcf(**kwargs).rows() | 82532ef35f882a8aa6794e3b5fca530c29892c50 | 46,135 |
def process_operator_filter(field, value):
""" Process a mongo operador attached to a field like name__in, pay__gte
Args:
field (str): The field name
value (str): The value
"""
params = field.split('__')
if len(params) is not 2:
return {}
field, operator = params
o... | 339fe67263edb318060abc5b122a6019148f031b | 46,136 |
def rref(mat, aug=0):
"""Performs Gauss-Jordan elimination to turn the matrix mat into RREF form in-place
and returns a string showing the working in LaTeX"""
row = 0
col = 0
n_rows = len(mat)
n_cols = len(mat[0])
ans = "\\begin{align*}\n"
while True:
if(row >= n_rows): # ran out of ... | bc2352ebda4a9e9834f7d17138aeed5d82663346 | 46,137 |
from typing import Pattern
import re
def _data_checks_pivot_longer(
df,
index,
column_names,
names_to,
values_to,
column_level,
names_sep,
names_pattern,
sort_by_appearance,
ignore_index,
):
"""
This function raises errors if the arguments have the wrong python type,
... | 0d1e6ed3d5a17d10edaf49b89e2a5bed922366ac | 46,138 |
def natsort_list(unsorted_list):
"""Basic function that organizes a list based on human (or natural) sorting
methodology.
Parameters
-----------
unsorted_list : list
List of strings.
Returns
-------
list
Sorted list of string.
"""
sorted_list = natsorted... | 4ee58867d2a2d3fa3e7a815826803facaf8e6d7a | 46,139 |
def getCatalogFiles(fname):
"""Return the files in an XML file catalog"""
print "Catalog content:"
print commands.getoutput("cat %s"%fname)
flist = []
xmldoc = minidom.parse(fname)
fileList = xmldoc.getElementsByTagName("File")
for thisfile in fileList:
fdict = {}
fdict['lfn'... | a5137b92ec07fed7580a6c0789acfbfb08294f37 | 46,140 |
def get_additional_features(eventlog_df):
"""
Transforms the initial eventlog dataset into a dataframe with trace vectors that describe
the Peformance Perspective of joruneys.
Input:
eventlog_df: [DataFrame] clean eventlog (one touchpoint per row)
Output:
A dataframe with t... | 1d77344d0067b3f8960788d726119d3938053e5d | 46,141 |
import os
import warnings
import string
def get_sequence(structure, label=None, return_type=None):
"""Get the sequence of amino acid residues from a PDB file
Determines the sequence from the order of amino acid residues in the
Protein Data Bank (PDB) file. The SEQRES records in the PDB file are
not u... | eeccac97bffa41e1b3d9ad1cd91a90e6cceac9c5 | 46,142 |
import hashlib
def CalcMD5(filepath):
"""generate a md5 code by a file path"""
with open(filepath,'rb') as f:
md5obj = hashlib.md5()
md5obj.update(f.read())
return md5obj.hexdigest() | fb339db0ec37dd46c9caeaf6ca74a114a9e85a87 | 46,143 |
def get_tf1(d):
"""
Returns the first order trend filtering matrix for d features.
Output
-------
D: array-like, shape (d -1, d)
The kth order difference matrix returned in a sparse matrix format.
"""
D = diags(diagonals=[-np.ones(d), np.ones(d - 1)], offsets=[0, 1])
D = D.tocsc... | 36cdfe6aec7f070df971542e3985b6e354b501ea | 46,144 |
def accepted_mimetypes(request, default='text/html'):
""" returns the accepted mimetypes of an HTTP/1.1 request
It returns a dictionary of the accepted mimetypes as
keys and their priorities as values.
"""
accepted_strings = request.requestHeaders.getRawHeaders(
'Accept', [default])
acc... | 785a53d43db807c903bff84e08e370ac26b71101 | 46,145 |
import os
def read_model(model_configuration, path, train_dataset):
"""
Creates ModelEntity based on model_configuration and data stored at path.
"""
if path.endswith(".bin") or path.endswith(".xml"):
model_adapters = {
"openvino.xml": ModelAdapter(read_binary(path[:-4] + ".xml"))... | 0a3b09180efaa8942e84711694e1c3de1bb0e6d7 | 46,146 |
def num2hex(num, width=1):
"""将数字转换为指定长度的十六进制字符串
Args:
num (int): 输入数字
width (int, optional): 指定字符串长度. Defaults to 1.
Returns:
str: 输入数字的十六进制字符串表示
"""
return '{:0>{width}}'.format(hex(num)[2:].replace('L', ''), width=width) | 3a328ece233f32402fd9ff7db14e948d8a63c35f | 46,147 |
def count_locked():
"""
Count number of distinct locked tiles that could still be runing
on aws lambda
"""
tiles = db.SQL("""SELECT tile, subx, suby, filter, count(filter)
FROM mosaic_tiles_exposures t, exposure_files e
WHERE t.expid = e.eid AND t... | befa4894bbff2c6d19be81fe822f4fe6ba1b5490 | 46,148 |
def Title():
"""
Return a :class:`zope.schema.interfaces.IField` representing
the standard title of some object. This should be stored in the `title`
field.
"""
return PlainTextLine(
max_length=140, # twitter
required=False,
title=u"The human-readable title of this objec... | 2767a7f7bd126eb173c49d943a3be1ab0bc95149 | 46,149 |
import torch
def test_max_pool2d_memory():
"""Test the memory usage"""
# arguments and test data
N, H, W, CI, kernel_size, stride, padding, dilation = 128, 28, 28, 8, 3, 2, 1, 1
ceil_mode, return_indices = False, False
print("========== MaxPool2d Memory Test ==========")
for dtype in ['float3... | 30b6f58558f469d16e4813446074b436de1bad0a | 46,150 |
import ipaddress
def is_ip_address(ipaddr):
""" Simple helper to determine if given string is an ip address or subnet """
try:
ipaddress.ip_interface(ipaddr)
return True
except ValueError:
return False | 56abc5a1a82f6a2e0c7532182867fdfae76a3b89 | 46,151 |
def clear_team_text(data):
"""
Function clears table if rows are not valid (doesn't hold jumper data), for team and mixed competition only.
:param data: data pulled from team-pdfs
:return: list of jumpers rows
"""
data_to_skip = ['Assistant', '"ruhrgas"', 'Ski-Jumping', 'Official', 'Finish', 'J... | 779cf9c2ae8198cf980dd60221b56db17c75414d | 46,152 |
def _merge_retry_options(retry_options, overrides):
"""Helper for ``construct_settings()``.
Takes two retry options, and merges them into a single RetryOption instance.
Args:
retry_options (RetryOptions): The base RetryOptions.
overrides (RetryOptions): The RetryOptions used for overriding ``r... | ff2e06bef23f4792422d25202490836ae5f1a836 | 46,153 |
def tg_healthcheck_port(x):
"""
Property: TargetGroup.HealthCheckPort
"""
if isinstance(x, str) and x == "traffic-port":
return x
return network_port(x) | 19896f9a2287e632591c5e6bad27a3dfaf955ac4 | 46,154 |
import json
def isjson(value):
"""
Return whether or not given value is valid JSON.
If the value is valid JSON, this function returns ``True``, otherwise ``False``.
Examples::
>>> isjson('{"Key": {"Key": {"Key": 123}}}')
True
>>> isjson('{ key: "value" }')
False
... | 0527a07500337c8ce8e39a428c71556d6e91c5dd | 46,155 |
def IDTtoxyz(Inc, Dec, Btot):
"""Convert from Inclination, Declination,
Total intensity of earth field to x, y, z
"""
Bx = Btot * np.cos(Inc / 180.0 * np.pi) * np.sin(Dec / 180.0 * np.pi)
By = Btot * np.cos(Inc / 180.0 * np.pi) * np.cos(Dec / 180.0 * np.pi)
Bz = Btot * np.sin(Inc / 180.0 * np.pi... | 414fa08a2d99b229423808cf68c4937cb5966146 | 46,156 |
def conv_2d(x, n_filters: int, kernel_size: int, stride: int, max_pool: bool = False):
"""
Conv2D layer
:param x: input to the layer
:param n_filters: Number of filters for the layer
:param kernel_size: Size of the kernel
:param stride: Stride to apply
:param max_pool: Add a max pooling laye... | ab91b47c1f9f8e3c860421dd094e654579115f54 | 46,157 |
import pykwiki.jinja_filters as jinja_filters
def set_jinja_filters(env):
""" Used to add custom Jinja2 filters to the env """
env.filters['idsafe'] = jinja_filters.idsafe
return env | 00ec354b2e92bfab12c32166574c54b7343874f6 | 46,158 |
import os
import logging
import subprocess
def check_version(repo, commit, commitkey_len=None):
"""
E.g. check_version('http://github.com/tskit-dev/tsinfer', 'efbafff')
Check that this module is installed, and return the installation dir and short commit hash.
If `commit`=='' then we download and... | 980b37ebb7f9cc2b46ae5083dec2762e5f5a2d79 | 46,159 |
def get_dicom_data(path):
"""
Given dicom data file path,
return the corresponding dicom data.
"""
return pydicom.read_file(path) | 4a0906a4c212221c56c7993409f4a3f7be3f5fc2 | 46,160 |
def get_stats(data):
"""
Given a data set from get_data, the function returns an array where each row
contains the mean and standard deviation for a fixed system size.
Parameters
----------
data : ndarray
A 2-dimentional numpy array containing resulting approximation ratios.
Ea... | 665aacf2aba5287000c990d8da4535fdee6f9274 | 46,161 |
def concatenate_segments(segments, max_break='30m', max_heading_rate=5):
"""
Concatenate consecutive segments if they meet the requirements defined by
the maximum ship break allowed and the maximum heading deviation allowed.
Parameters
---------
segments : list of Datasets
The list of segments to compare betwe... | 4414eaa9edfde9aa861af0459c9675f28920a1ca | 46,162 |
import scipy
def _discount_cumsum(x: np.array, discount: float):
"""
magic from rllab for computing discounted cumulative sums of vectors.
input:
vector x,
[x0,
x1,
x2]
output:
[x0 + discount * x1 + discount^2 * x2,
x1 + discount * x2,
x2]
""... | ffe5cefef3995926ae3b8ba9f760c20b4f8bce61 | 46,163 |
def is_pythagorean_triplet(a, b, c):
"""Determine whether the provided numbers are a Pythagorean triplet.
Arguments:
a, b, c (int): Three integers.
Returns:
Boolean: True is the provided numbers are a Pythagorean triplet, False otherwise.
"""
return (a < b < c) and (a**2 + b**2 == ... | c879eb0f441f1b0f79fcfed7361d584954dcff3f | 46,164 |
import os
def preprocess_image(img_path: str, output_file: str, **kwargs) -> str:
"""
Preprocess the images for SpineStraightening, put healthy mask, patient scan, patient mask in the same orientation "PIL"
:param img_path: str, path of image
:param output_file: str, output filename
:param kwargs:... | 64df8a91a887ebad9a292359e61b6677032b2980 | 46,165 |
def tune_search(train, test, fine_tune, project_name, verb, bayopt_trials):
"""Define the search space using keras-tuner and bayesian optimization"""
hypermodel = NASnet_transfer(input_shape=(331, 331, 3), fine_tune=fine_tune)
tuner = BayesianOptimization(
hypermodel,
max_trials=bayopt_tria... | a1634997b89ae3fff15f1ace02177dd1c2b4d9e4 | 46,166 |
def url_to_path(url: str):
"""Converts an incoming url into a path-slug."""
return slugify(url, max_length=199) | 8d48aaf6211c69b105f58a41129232f1f5e01230 | 46,167 |
import six
import time
def later_than(after, before):
""" True if then is later or equal to that """
if isinstance(after, six.string_types):
after = str_to_time(after)
elif isinstance(after, int):
after = time.gmtime(after)
if isinstance(before, six.string_types):
before = str... | e1ea29f35e315121f7b4e878fe86fa35a215c957 | 46,168 |
def make_adjacency_graph(frcs, bu_msg, max_dist=3):
"""Make a graph based on contour adjacency."""
preproc_pos = np.transpose(np.nonzero(bu_msg > 0))[:, 1:]
preproc_tree = cKDTree(preproc_pos)
# Assign each preproc to the closest F1
f1_bus_tree = cKDTree(frcs[:, 1:])
_, preproc_to_f1 = f1_bus_tr... | 6118c093d9c9342eaf6efa7157ccaab6b7906477 | 46,169 |
import torch
def drop_connect(inputs, p, training):
""" Drop connect. """
if not training: return inputs
batch_size = inputs.shape[0]
keep_prob = 1 - p
# random_tensor = keep_prob
random_tensor = torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device) + keep_prob
binary... | 10656b5050f1f2e90f3370d5392e7928f1c07ddc | 46,170 |
from datetime import datetime
def years_ago(years, from_date=None):
"""
Return datetime that was n years from some date (defaulting to right now)
:param years:
:param from_date: default `now`
:return:
"""
if from_date is None:
from_date = datetime.now()
return from_date - relat... | 8e503ddf3909b75566a6d7884a5583c2f03994fc | 46,171 |
def get_iters(mnist, batch_size):
"""Get MNIST iterators."""
train_iter = mx.io.NDArrayIter(mnist['train_data'],
mnist['train_label'],
batch_size,
shuffle=True)
val_iter = mx.io.NDArrayIter(mnist['test_d... | d63b99432f32b4735d84be6f9a8579e8e9e42b1b | 46,172 |
from typing import List
import logging
def _run_nary_op(op: str, kop: str,
stub: synthesis_service_pb2_grpc.SynthesisServiceStub,
num_inputs: int) -> List[delay_model_pb2.DataPoint]:
"""Characterizes an nary op."""
results = []
for bit_count in _bitwidth_sweep(0):
results.a... | 68e2b48a199ce9ae9018b2b9f4ba3173707df52c | 46,173 |
import os
def GhostNet(input_shape=None,
include_top=True,
weights='imagenet',
input_tensor=None,
cfgs=DEFAULT_CFGS,
width=1.0,
dropout_rate=0.2,
pooling=None,
classes=1000,
**kwargs):
"""Instantia... | 0af8b2dc13bd4490e21a28f56a115e63c990bbbc | 46,174 |
def list2words(l):
"""列表转换word对象列表"""
return [Word(i) for i in l] | 5bd4757004f114ac1db1e20bffd1a7cd91c99b0a | 46,175 |
def _passwd_tar_impl(ctx):
"""Core implementation of passwd_tar."""
f = "".join(["%s:x:%s:%s:%s:%s:%s\n" % (
entry[PasswdFileContentProviderInfo].username,
entry[PasswdFileContentProviderInfo].uid,
entry[PasswdFileContentProviderInfo].gid,
entry[PasswdFileContentProviderInfo].inf... | fb6adba6be2567a03f4f89ad98747c5d702349c1 | 46,176 |
import sys
def min_risk(mu, H, target_return=0.0, shortselling=True, verbose=False):
"""
Minimum Variance Portfolio
min w'Hw
s.t.
w'mu = target_return
sum(w) = 1
w >= 0 (if no shortselling)
In conic form
min s2
s.t.
... | e08cf5bc1fdc73aa2a3a7f872c282c1286b77ae2 | 46,177 |
def multi_replace(search, replace, path):
"""Replace search with replace in all filenames
and file contents in directory path.
@type search: string
@param search: The old string.
@type replace: string
@param replace: The new string.
@type path: string
@param path: The path in ... | 759591256bf233e58f823f5ccec574683adbadca | 46,178 |
def extract_JK(pos_seq):
"""The 'JK' method in Handler et al. 2016.
Returns token positions of valid ngrams."""
def find_ngrams(input_list, num_):
'''get ngrams of len n from input list'''
return zip(*[input_list[i:] for i in range(num_)])
# copied from M and S chp 5'''
patterns = set(['AN', 'NN', 'AAN', 'AN... | 0452e26abfbac94571fefcb5e455df5802617eff | 46,179 |
import logging
def get_child_logger(*names: str):
"""Returns a child logger of the project-level logger with the name toolshed.<name>."""
return logging.getLogger("toolshed." + '.'.join(names)) | a1760d34a620ffa3caf8abaca6cfb911209cf074 | 46,180 |
import types
def validate_pcrPlate_position_samplesetitems(
samplesetitems, pcrPlateRow, samplesetitem_id, sampleset=None
):
"""
1) validate pcrPlateRow position selected for sampleSetItem is unique
2) for Ampliseq on Chef pcrPlateRow value is required
If validating with a dict of sam... | fa8839ad8fb347d39b037845295ddcf328dd507c | 46,181 |
from rstoolbox.components import SequenceFrame
from rstoolbox.components import DesignFrame
import copy
import collections
def sequential_frequencies( df, seqID, query="sequence", seqType="protein",
cleanExtra=True, cleanUnused=-1 ):
"""Generates a :class:`.SequenceFrame` for the frequ... | 2969867ecedbf4e201da225cbd17f829b89d01b2 | 46,182 |
def get_csv_config(model):
"""Returns a configuration object based on the given model."""
if model == Accession:
return AccessionCSVConfig
elif model == Donor:
return DonorCSVConfig
elif model == Object:
return ObjectCSVConfig
else:
return GenericCSVConfig | d34579a94a0c661ee8c08dad97d13e7bfb033365 | 46,183 |
def import_vae(env: str, cams: list, mvae_mode: str, img_width: int, img_height: int) -> MultiCamVae:
"""
Loads an existing vae set with the specified properties, or returns an already cached goal set
:param env: the name of the environment, e.g. FetchReach-v1
:param cams: the list of camera names, e.g... | 16907adf63c9883e5b55239c1147b818a6522b04 | 46,184 |
def get_comment_tree(pid, sid, comments, root=None, only_after=None, uid=None, provide_context=True,
include_history=False, postmeta=None):
""" Returns a fully paginated and expanded comment tree.
TODO: Move to misc and implement globally
@param include_history:
@param pid: post fo... | d6e4c284ed3ba81cb93ba4a9027f1dde985f7e02 | 46,185 |
import fastapi
import profile
async def api_portal_restrictions(req: fastapi.Request):
"""
Returns all restrictions for the current user.
"""
keyword_restrictions, query_s = profile(restrictions, portal, req)
return {
'profile': {
'query': query_s,
},
'data': k... | 456ed71c0197b8dc7cbca6b36dacbecbabda0870 | 46,186 |
from pathlib import Path
import sys
def load_key(encryption_key_path):
"""
Read an encryption key
"""
if Path(encryption_key_path).is_file():
return open(encryption_key_path, "rb").read()
else:
console.print(f"[red] File does not exist[/red]: {encryption_key_path}")
sys.ex... | 140f0a1263f5ce50266ac49f3648fbf67ac6cfbf | 46,187 |
import cyvlfeat
def get_feature_extractor(name, *args, **kwargs):
"""Return appropriate feature extractor as a function
Args:
name (str):
*args :
*kwargs:
Returns:
extractor (function): feature extractor
"""
# TODO: select feature extractor by name
extractor = None
if name == 'sift':... | 6d30afd06b3f5e28f235c3d15ab53f62a0befb13 | 46,188 |
def cartesian_pose(args):
"""
Move the robot arm to the specified configuration.
Call using:
$ rosrun intera_examples go_to_cartesian_pose.py [arguments: see below]
-p 0.4 -0.3 0.18 -o 0.0 1.0 0.0 0.0 -t right_hand
--> Go to position: x=0.4, y=-0.3, z=0.18 meters
--> with quaternion orient... | 55d2ecf81c64f2f248da7bbdc3c7907d5838661d | 46,189 |
def test_basic_call_async():
""" The most basic Happy-Path test for Hug APIs using async """
@hug_core.local()
async def hello_world():
return "Hello World!"
assert hello_world() == "Hello World!" | ae96de3fe9ee440d55944434b862ef61b58b5a09 | 46,190 |
def Anomalies(Serie):
"""
Make anomalies compared with the annual cycle
INPUTS
Serie : Pandas DataFrame with data
"""
Ciclo = Cycles(Serie, type='annual')
Devtd = Cycles(Serie, type='annual',percentiles='std')
Anom = Serie.copy()
for i in range(len(Serie)):
med = Ciclo[Serie.... | e6d6a9ed11bd6a2d8985b99d3b8a065fab50c273 | 46,191 |
def close_con(session):
"""
Nothing to say
:param session: A section object
:return:
"""
session.close()
return 'Session closed' | 9e33de814328ac855d4c478de836dde543350a32 | 46,192 |
from typing import Tuple
from typing import Dict
def get_message_maps(
force_refresh: bool = False,
) -> Tuple[Dict[str, Node], Dict[str, Client]]:
"""Gets Node and Client protobufs, computes their internal statuses, and return their maps.
If the cache doesn't contain the message maps, this function read... | 082e1196f9c2117b350134bcab948cfece07c380 | 46,193 |
from .caller import caller
import logging
def getlogger(pkg='', handler=None):
"""
패키지 혹은 채널 로거
logging.getLogger(package_name) or logg.getLogger()
:param pkg: str
"""
if not pkg:
m = caller.modulename()
s = m.split('.', 1)
if len(s) > 1:
pkg = s[0]
if... | 2fdb9223846ad957929831cc8deb3dba21703b23 | 46,194 |
import os
def add_group(name, fname, fpath=os.path.join(config.get('path','db_dir'), 'Object'), proxy=True):
"""Add a Blender group to the current scene.
Add a group of Blender objects (all the parts of a single object, most likely) from another
file to the current scene. Optionally, add as a proxy obj... | 5f4129a91fcec0875295b091564c9bd54df73dd0 | 46,195 |
def safe_str_convert(s, strict=False):
"""Convert a string to ASCII without throwing a unicode decode error.
@param s (any) The thing to convert to a str.
@param strict (boolean) If True make sure that there are no
unprintable characters in the given string (if s is a str). If
False do no modifica... | 1937a9750a86c8fa2dadeb75595d2975c1c32b27 | 46,196 |
def _vectorize_voxels(voxels_linear, size_x, size_y):
"""
Convert linear array of voxel indices to 3D array of voxel indices.
Inputs:
voxels_linear (np vector of ints) - linear array of indicies
size_x (int) - size of voxel space in x direction (in voxels)
size_y (int) - size of voxel space in ... | 9d43d2d547e9bb59169bb118f4269bdde0f051ca | 46,197 |
import pkg_resources
def _get_user_dir():
"""Get the users data directory location."""
app_name = pkg_resources.require('zegami-cli')[0].project_name
return user_data_dir(app_name, 'zegami') | 7a7691be4cc91afcbec05aa14830df1af4369cde | 46,198 |
import inspect
def collect_derivatives(expressions):
"""
Exploit linearity of finite-differences to collect `Derivative`'s of
same type. This may help CIRE creating fewer temporaries while catching
larger redundant sub-expressions.
"""
processed = []
for e in expressions:
# Track t... | 097863fc0d71d1ec97be98ac46da5234b7331362 | 46,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.