content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import scipy
def discount_cumsum(x, discount):
"""
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]
"""
re... | 1d90659cbb0fa1e98f012e5a21cc8fd74db59be0 | 69,356 |
import ast
def unpool_theory_atom(x):
"""
Removes all pools from the conditions of theory atoms.
See note in unpool_term.
"""
x.elements = list(chain.from_iterable(
(ast.TheoryAtomElement(element.tuple, condition)
for condition in unpool_list_with(unpool_literal, element.conditio... | 390b482ef12f1c0679e0f351671197415020b957 | 69,357 |
def fixture_response_get_docs(
base_url: str, repo_owner: str, repo_name: str
) -> ResponseLabel:
"""Return a dict respresenting the GitHub API response body for the docs
label.
"""
return {
"id": 2222,
"node_id": "4444",
"url": f"{base_url}/repos/{repo_owner}/{repo_name}/lab... | 05bfcef0927f6202ff0ae3445dd2d128187de751 | 69,358 |
def box(parser, token):
"""
{% box label [args] [kwargs] %}
All args/kwargs are passed directly to callable defined in the setting
BOXES_CAN_EDIT_CALLABLE which returns True or False to determine if the
box can be edited.
"""
return BoxNode.handle(parser, token) | 77aafb61e49dec8b040046838d22060fbe79b2ee | 69,359 |
from typing import Optional
def _create_projector_config(
path_metadata: str, path_sprite: Optional[str]
) -> projector.ProjectorConfig:
"""Creates a projector-config as needed to show the embedding in Tensorboard."""
config = projector.ProjectorConfig()
embedding = config.embeddings.add()
embeddi... | 4742c89c47630be9a8f7527fa3b1480df9cadb88 | 69,360 |
import select
from datetime import datetime
def edit_project(project_id):
"""
Takes "name" and/or "published" as JSON data
Returns "msg" and "project_id" on success, otherwise 40x
"""
request_data = request.get_json()
if not request_data:
return jsonify({"msg": "No data provided."}), 4... | e4cdee50b4d7e40b950b62f8d0f388588075895e | 69,361 |
import http
import socket
import ssl
import errno
def _is_conn_error(exception):
"""
Checks if the given exception resembles an error in the network connection, e.g. a timeout or connection
abort.
"""
conn_exceptions = (
BrokenPipeError, # Raised on SIGPIPE
ConnectionAbortedErr... | 3c5b23060e60a4a763ada5812ec008ea6dcf87a9 | 69,362 |
def log_posterior_helper(ip: np.ndarray, dof: float, n: int) -> float:
"""Computes the log-density of the Student-t distribution given the inner
product, the degrees of freedom, and the dimensionality of the space.
Args:
ip: The Mahalanobis inner product regularized by the degrees of freedom.
... | aedee887eaacd65786a4dbdea321aeb2857604bd | 69,363 |
import base64
def arr_to_b64(numpy_arr, ensure_RGB=True):
"""Convert a numpy array into a b64 string"""
# Generate image in bytes format; will convert using `tobytes` if not contiguous
image_pil = PIL_Image.fromarray(numpy_arr)
if ensure_RGB:
image_pil = image_pil.convert('RGB')
byte_io ... | 87ab965ecb8f11bc59209ff6de85b14ae123b43a | 69,365 |
def testdat(testdir):
"""Path to the testdat directory"""
return testdir / "testdat" | d7c278fba718164d50863e3fb353155a1ff00eee | 69,367 |
def quartznet15x5(**kwargs):
"""
QuartzNet 15x5 model from 'QuartzNet: Deep Automatic Speech Recognition with 1D Time-Channel Separable
Convolutions,' https://arxiv.org/abs/1910.10261.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for mod... | 2140ea59b65368ef9357733c7c942d1671911bcd | 69,369 |
def hub_modules():
"""Return list of hub modules"""
global modules
modules = import_modules()
context = {
"modules": modules,
}
result = render_template(
"powershell/modules.ps1",
**context,
).encode()
result = b64encode(encrypt_aes((result... | 72bfec7c5d6a2b44314c64bcb2f3d973972a7773 | 69,371 |
from typing import Tuple
def gcb_build_base_images() -> Tuple[int, str]:
"""Build base images on GCB."""
return gcb_build(get_build_config_file('base-images.yaml'), 'base-images') | 2534ee05655567f2fe7f6e51ba1a50d75e1b2547 | 69,373 |
def load_data(source=None):
"""Load original data, and key lists"""
if 'parquet' in source:
df = pd.read_parquet(source)
else:
df = pd.read_csv(source)
df['TotalCharges'] = df['TotalCharges'].str.replace(r' ','0').astype(float)
df['Churn'] = df['Churn'].apply(lambda x: 0 if x... | 62ae7305d32affabeebc5cb7bd781bda919b73f5 | 69,375 |
def sigmoid(x):
"""
Simple sigmoid function. Warning: when overflow problems are encountered use sigmoid2 instead.
:param x: numerical value or numpy.ndarray
:return: sigmoid(x)
"""
return 1 / (1 + np.exp(-x)) | 09f8809a3bdc494f744aa12e5e9e6dff782fe28b | 69,377 |
def send_receipt(payload: receipt_schemas.atrributes, background_tasks: BackgroundTasks, db: orm.Session = Depends(get_db)):
"""
An endpoint to send receipts.
Note: The message field in the payload should be HTML formatted.
"""
pdf_name = (payload.subject)+str(uuid4().hex)+".pdf"
... | 34124b1168f17edd41e26d4af01e2158b07fa32a | 69,378 |
def _sample_haar_mtx(size):
"""Samples Haar-distributed matrices.
Samples Haar-distributed matrices that are useful to generate
random matrices for COE, CUE and CSE ensembles.
Args:
n (int): matrix size.
Returns:
numpy array containing Haar-distributed random matrix.
"""
#... | 3adfb047fb87deb1612ed059380d4b907743deba | 69,379 |
import math
def crop_helper(image_stack, crop_size):
""""Helper function to take an image, and return crops of size crop_size
Inputs:
image_stack (np.array): A 4D numpy array of shape(points, rows, columns, channels)
crop_size (int): Size of the crop to take from the image. Assumes square cro... | b99c257dd268ec48624161e1ad18b7d2537f88f5 | 69,380 |
import tqdm
def set_progeny_size(G, root):
"""
Store as a node attribute the number of leaves below a given node. Traverses from the root provided.
:param G:
input tree
:param root:
Root of tree
:return:
Graph with progeny size stored as a node attribute (for some nod... | 98de04cd2e7221f464ac52136e050968828e0491 | 69,381 |
def bbox_info_from_point_list(point_list):
""" Generate bounding box info from a point list. """
if len(point_list) == 0:
return BoundaryInfo()
x = [c[0] for c in point_list]
y = [c[1] for c in point_list]
return BoundaryInfo(min(x), max(x), max(y), min(y)) | a1b44edf26c1e187057d9756c21a83ddce8fb6ad | 69,382 |
def upgrade_available():
"""Check for upgrade for ceph
:returns: whether an upgrade is available
:rtype: boolean
"""
c = config()
old_version = ceph_utils.resolve_ceph_version(c.previous('source') or
'distro')
new_version = ceph_utils.resolv... | 33d501182176e76e911272b3d83a425044b88ca6 | 69,383 |
import pytz
from datetime import datetime
def get_current_timezone(location="Europe/Bucharest"):
""" @location: Continent/City"""
if location not in pytz.all_timezones:
raise TimezoneNotFoundError
current_datetime = datetime.now(pytz.timezone(location)).strftime("%d.%m.%Y-%H:%M:%S")
_location... | ea0e59160c188d2ba985c806a2fa8ad6a59f2a34 | 69,384 |
def CARAutility(c, alpha):
"""
Evaluates constant absolute risk aversion (CARA) utility of consumption c
given risk aversion parameter alpha.
Parameters
----------
c: float
Consumption value
alpha: float
Risk aversion
Returns
-------
(unnamed): float
Uti... | 51cff418899872c201a5cf3a4989320e3381b2f4 | 69,385 |
def solve_part1(data: list[str]) -> int:
"""
Finds the solution to part 1 (the power consumption of the submarine)
"""
gamma = ""
epsilon = ""
for bits in zip(*data):
gamma += more_common_bit(bits)
epsilon += less_common_bit(bits)
return multiply_binary(gamma, epsilon) | 46a7af1329d335271d2278de4a87e0a6c3df7983 | 69,386 |
def allowed_anions():
"""
Args:
Returns:
list of elements (str) that tau should be able to classify
NOTE: only trained on ['O', 'F', 'Cl', 'Br', 'I']
"""
return ['O', 'S', 'Se', 'Te', 'F', 'Cl', 'Br', 'I', 'N', 'P', 'As', 'Sb'] | 337c25b4d2097e920885630fe52c322ac23480b0 | 69,387 |
def sigmoid_prime(z):
"""Derivative of the sigmoid function.
sigmoid函数的导数"""
return sigmoid(z) * (1 - sigmoid(z)) | 15b3512d81ae0562e527bddefb20c25aee9e7ea1 | 69,388 |
def _RequireOpenQueue(fn):
"""Decorator for "public" functions.
This function should be used for all 'public' functions. That is,
functions usually called from other classes. Note that this should
be applied only to methods (not plain functions), since it expects
that the decorated function is called with a ... | fe1b79b33e092bc5f1e5a4afe78f3ec23b2f7102 | 69,389 |
def get_human_annotation(config: Config) -> str:
"""Get the best human genome annotation available in config."""
if config.use_hg38:
return "hg38"
elif config.use_hg19:
return "hg19"
else:
raise AnnotationError("no available human annotation in config") | 5e52b9f668a17894767b85ce566b211d79c64652 | 69,390 |
def query_yes_no(question,default="yes"):
"""
Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is... | f6c767d14b425716ee72ab6b8fbc5e596cb52474 | 69,391 |
def get_mse_sorted(series1, series2):
"""
sorted but not normalized values
the series will be sorted
"""
assert len(series1) == len(series2)
mse = 0.0
series2_s = sorted(series2)
for index, data1 in enumerate(sorted(series1)):
diff = (data1 - series2_s[index])
mse += dif... | 9debccd97dd146468e28c01f9db5e8a80f55e4db | 69,392 |
def AutoGooey(fn): # pragma: no cover
"""Automatically show a Gooey GUI if --gui is passed as the first argument, else it will just run the function as normal"""
if check_gui_arg():
return gooey.Gooey(fn)
else:
return fn | 96abab8921fd9db18ce8b401cc66cd210f96f82c | 69,393 |
def parity(self, allow_rescaling_flag=True):
"""
Returns the parity ("even" or "odd") of an integer-valued quadratic
form over `ZZ`, defined up to similitude/rescaling of the form so that
its Jordan component of smallest scale is unimodular. After this
rescaling, we say a form is even if it only re... | 12c68f6dfb447cd88d59367ad1fed9c2ba9aedde | 69,394 |
def add_cc_month(path):
"""
Adds complete common crawl month
"""
programms = []
for file in path.iterdir():
print(file.suffix)
if file.suffix == '.gz' and 'head' in file.name:
print(f'Adding lines from {file}')
p = Process(target=add2mongo, args=(file,))
... | be39951a1478204b3ded474d875314a75d45842a | 69,395 |
def pitches_leveinsthein_diff(original, compare_to, noteNode1, noteNode2, ids):
"""Compute the leveinsthein distance between two sequences of pitches
Arguments:
original {list} -- list of pitches
compare_to {list} -- list of pitches
noteNode1 {annotatedNote} --for referencing
not... | 74cb07c5b4a3c6d8d5ec1135371f30a1011a805f | 69,396 |
def edit_extensions(request):
"""
Edit known file extensions
:param request:
:return:
"""
form_set = modelformset_factory(FileExtension, form=FileExtensionForm, can_delete=True, extra=3)
qu = FileExtension.objects.all()
formset = form_set(queryset=qu)
if request.method == 'POST':
... | 8fede9fa4a7734bb2bc4806eba674b66bf473515 | 69,397 |
def get_sentiment(news: NewsObject) -> float:
"""
Given a news object, return the probability that its underlying sentiment is liberal
"""
return sentiment_model(news.title + news.content) | e2fe4cf89f7bd6377e7ccc333e70c31ef992123e | 69,398 |
from pathlib import Path
import tempfile
import shutil
import yaml
def fork():
"""Generate a local fork of the current state of naucse for testing.
1) Copies the entire local state of naucse
2) Adds one working course and one working run
3) Commits everything on branch ``test_branch``
4) Adds one... | 605f98d2b77d7133aeb5da4b03816eac0814f083 | 69,399 |
import PyOpenColorIO as ocio
import logging
def create_builtin_transform(style):
"""
Creates an *OpenColorIO* builtin transform for given style.
If the style does not exist, a placeholder transform is used in place
of the builtin transform.
Parameters
----------
style : unicode
*... | c56031d9f737ebbd7ead7c438b942845cab3a229 | 69,401 |
def generate_rcmap_table(kmerlen, kmers):
"""make a lookup table for reverse complement k-mer ids for speed
Arguments:
kmerlen -- integer, length of k-mer
kmers -- list, a full set of k-mers generated by generate_kmers
Return:
a dictionary containing the mapping table
"""
revcomp_func = revcomp
kmer_id_dic... | acaf4e07e3c8b0847b4341708e0e5a48a756c1d0 | 69,402 |
import re
def _get_pcode_ids(pcode):
"""
Pull out the function and variable names from the given p-code
disassembly.
pcode - (str) The p-code disassembly.
return - (set) The set of function and variable names.
"""
# Look at each line of the disassembly.
ids = set()
in_id_section... | 84223a944a1f20b4e324748349fdf1d83d1ebc77 | 69,403 |
def add_motif_consensus_sequence(metadata_file, pwm_dict, out_file, model_col=2):
"""Add consensus motif
"""
with open(out_file, 'w') as out:
with open(metadata_file, 'r') as fp:
for line in fp:
if "ensembl" in line:
# write out header
... | 1ebedb16f717084d8a0199d63aea67ed5d7b48bd | 69,404 |
from typing import Sequence
from typing import Iterable
def _remove_decorators(
decorators: Sequence, module_aliases: Iterable[str], method_aliases: Iterable[str]
) -> Sequence:
"""Removes decorators specified as a `blqs.DecoratorSpec` from the decorator node list.
This performs a best effort to remove t... | 2d57a093b9371b02699436915f876cc69dd03033 | 69,405 |
from pathlib import Path
def strings_to_paths(strings: list[str]) -> list[Path]:
"""Converts a list of filenames in string form into a list of paths"""
return [Path(string) for string in strings] | 660e5f0fe72f32a4c4f2b218386e4c640c038846 | 69,406 |
def hybrid_encrypt(lang: str, pub_keyset: bytes) -> _primitives.HybridEncrypt:
"""Returns a HybridEncrypt primitive, implemented in lang."""
global _ts
return _primitives.HybridEncrypt(lang, _ts.hybrid_stub(lang), pub_keyset) | 4d728185729e2be4a8a132fde4ef06f3971fdee1 | 69,408 |
from colorama import Cursor
def async_alert_str(*, terminal_columns: int, prompt: str, line: str, cursor_offset: int, alert_msg: str) -> str:
"""Calculate the desired string, including ANSI escape codes, for displaying an asynchronous alert message.
:param terminal_columns: terminal width (number of columns)... | 9db90846a75378f13a38a97a215e2965785c01b8 | 69,410 |
def text2tfidf(dataset:Dataset, min_df=3, sublinear_tf=True, inplace=False, **kwargs):
"""
Transforms a Dataset of textual instances into a Dataset of tfidf weighted sparse vectors
:param dataset: a Dataset where the instances are lists of str
:param min_df: minimum number of occurrences for a word to b... | 8e3a2f8c1eab792268fca7dddaeb7f6289b27231 | 69,411 |
def three_sum_closest(nums, target):
"""
Return total closest to target
Worst case: O(n^2)
"""
nums.sort() # sort nums to perform two pointers
result = sum(nums[:3]) # initial sum
for i, _ in enumerate(nums):
left = i + 1
right = len(nums) - 1
while left < right:
... | 8114a5b1ccd8fec0782f1757c69c183411ba1966 | 69,412 |
def min_required_char(text: str) -> int:
"""
NAIVE VERSION!
Find minimum number of characters required to make a String Palindromic
NOTE:The only operation allowed is to insert characters in the beginning
of the string. Return the number of characters that are needed to be
inserted to make the s... | 7c2b90c9f0bfebb0de96737eac1c84729172123e | 69,413 |
def process_station_list(stationlist,id_col="id",agency_id_col="agency_id",
param_col=None,param=None,
subloc_col=None,subloc_lookup=None,subloc="default",
station_lookup=None,param_lookup=None,source = 'cdec'):
"""Process a csv list of stat... | c15b8a30ea673c7381a6ddb71abc99c1edd6921e | 69,414 |
def build_argparser():
"""
Parse command line arguments.
:return: command line arguments
"""
parser = ArgumentParser()
parser.add_argument("-m", "--model", required=True, type=str,
help="Model path")
parser.add_argument("-l", "--label", required=True, type=str,
... | 582bf197b72bf5c7dd52a63122cadbf61fe6a77a | 69,416 |
def contains_invalid_mxid_characters(localpart: str) -> bool:
"""Check for characters not allowed in an mxid or groupid localpart
Args:
localpart: the localpart to be checked
Returns:
True if there are any naughty characters
"""
return any(c not in mxid_localpart_allowed_characters... | f5be39becb8c39f87462b32e51acc9ad084b124a | 69,417 |
def images_crop(arFrames, nHeightTarget, nWidthTarget):
"""
Crop array of frames to specified size, choose centered image
Keyword arguments:
arFrames -- np.array representing list of images, shape : (nSamples, nHeight, nWidth, nDepth)
nHeightTarget -- height of target image
nWidthTarget -- widt... | 29be05ce06a29d2a69c1b850dd2949252d64bd63 | 69,418 |
def track_to_mask(track: Track, idx: np.ndarray = None) -> Mask:
"""
Gives Track with parent values filled in by closest neighbor
Args:
- track
- idx: locations of parent values to fill in
"""
if idx is None: idx = track < 0
ind = ndi.distance_transform_edt(idx,
... | 4bf71e22e77971da5e8119b1a4663748e8ee80b3 | 69,419 |
def Rotation_fromRotX(*args):
"""Rotation_fromRotX(float const pRotX) -> Rotation"""
return _almathswig.Rotation_fromRotX(*args) | 22ed7a23b4207f463077751c00975cd2dd6626dc | 69,420 |
def get_reddit_stream(reddit):
"""Returns the comment and submission stream.
Streams need to be restarted/re-obtained when they throw exception.
:param reddit: The reddit account instance
:return: The comment and subreddit stream
"""
comment_stream = reddit.subreddit(config.SUBREDDIT).stream.co... | 7e1f62b9f68796c08fc3af7bd1f874f991d46c55 | 69,421 |
import re
def find_between(a, b, string):
"""Returns a list of substrings between a and b in the given string."""
p = "%s(.*?)%s" % (a, b)
p = re.compile(p, re.DOTALL | re.I)
return [m for m in p.findall(string)] | b522cfd698d8a304e7964d9a1ff25556963ce36b | 69,422 |
def predict(params, inputs):
"""A functional interface to the trained Module."""
return QuickDrawModule().apply({'params': params}, inputs) | d20aca173b4b08c81735a890e1fba3bdfb5d1587 | 69,423 |
def meta(str1, str2, ratios, weights):
"""A meta ratio function. Returns a weighted meta ratio.
The Wiesendahl ratio is a meta ratio which combines a weighted
ratio of given ratio functions.
Args:
str1 (str): first string
str2 (str): second string
ratios (list(function(str... | b694216cce7b78e15065788497985416537ea95c | 69,424 |
def make_channel_layer(
name, layer_size, channel_width, color_RGB, z_position=0.0, parent=None
):
"""Create a 3D print channel layer.
Args:
name (str): Name to give the object.
layer_size (3-element tuple or list of floats or ints): x,y,z size
channel_width (float or int): Width of... | 719b074fd336f1604d92d489a77f860ffe424af1 | 69,425 |
import requests
def cbsodatav3_to_gbq(id, third_party=False, schema="cbs", credentials=None, GCP=None):
"""Load CBS odata v3 into Google BigQuery.
For given dataset id, following tables are uploaded into schema (taking `cbs` as default and `83583NED` as example):
- cbs.83583NED_DataProperties: descripti... | 68f316fa60fe588fdced23842482e5744189cb94 | 69,426 |
from typing import Dict
def infer_data(data: Dict[str, np.ndarray], infer_request: InferRequest, cw_l: int = 0, cw_r: int = 0) -> np.ndarray:
"""Do a synchronous matrix inference"""
frames_to_infer = {}
result = {}
batch_size = infer_request.get_input_tensor(0).shape[0]
num_of_frames = next(iter(... | 6dae3b3cb240dc6ee2f118742b9fa3576d035eb4 | 69,427 |
def infer_metadata(
featureset: FeatureSet,
source,
entity_columns=None,
timestamp_key=None,
namespace=None,
options: InferOptions = None,
) -> pd.DataFrame:
"""Infer features schema and stats from a local DataFrame
example::
quotes_set = FeatureSet("stock-quotes", entities=[En... | 6f183bc097b5f91e9a94c8b5bffb8c0eb974f13c | 69,428 |
def tjoin(leftkey, leftseq, rightkey, rightseq, left_default=no_default, right_default=no_default):
"""
>>> tjoin(identity, [1, 2, 3], identity, [2, 3, 4],
... left_default=None, right_default=None)
((2, 2), (3, 3), (None, 4), (1, None))
"""
return tuple(join(leftkey, leftseq, rightkey, ri... | c3e00ea628abe6f5fb2b04c0d20c5b6d81861c9b | 69,429 |
import warnings
def get_unique_schema_name(components, name, counter=0):
"""Function to generate a unique name based on the provided name and names
already in the spec. Will append a number to the name to make it unique if
the name is already in the spec.
:param Components components: instance of th... | 68086fc7a8e523322f5a1745996b6dc8056833a1 | 69,430 |
def snakeuppercase(var): # SOME_VARIABLE
"""
Snake uppercase convention. Include '_' between each element and transform in uppercase.
:param var: Variable to transform
:type var: :py:class:`list`
:returns: **transformed**: (:py:class:`str`) - Transformed input in ``SNAKE_UPPERCASE`` conve... | 60f93e7b3c3c3e2a4e6667c4786cad1c1dbe4acc | 69,431 |
import io
import select
from operator import and_
def read_task_timing(proc_url, task_name, tag):
""" Reads timing info for a given timing tag """
if io.is_db_url(proc_url):
metadata = io.open_db_metadata(proc_url)
timing_log = metadata.tables["timing_log"]
columns = list(timing_log.c... | 0025d50eb7a860b3d35453e77145d2c64f05a917 | 69,432 |
def df_aidxf_macro_cbb():
"""Example df_aidxf of a macrocycle with a fragment combination of type cbb. This tests that redundant intermediary rings are filtered out."""
mol = Chem.MolFromSmiles('C1CC2CC(CCC3CC(CCO3)CCCCC3CCC(CC3)CCCCCC2)N1')
return pd.DataFrame([
['macro_cbb', 'XXX'... | 7f7d92956d55bbc5ee6da2b55aa52258ad53efc4 | 69,433 |
def map(function, *collections):
"""does 3 separate things, hence this enormous docstring.
1. if function is None, return a list of tuples, each with one
item from each collection. If the collections have different
lengths, shorter ones are padded with None.
2. if function i... | 8b5eb71ec70ce18b7030e3c01dabc84f8f293e48 | 69,434 |
import six
import re
import keyword
def is_valid_varname(varname):
""" Checks syntax and validity of a variable name """
if not isinstance(varname, six.string_types):
return False
match_obj = re.match(varname_regex, varname)
valid_syntax = match_obj is not None
valid_name = not keyword.isk... | 4746ccb19d43dbe10ff2579184c5b925a030c6fc | 69,435 |
def split_train_variableInput(sequence, minSamplesTrain, numOutputs, numJumps):
""" Returns sets to train a model with variable input length
i.e. X[0] = sequence[0], ..., sequence[minSamplesTrain]
y[0] = sequence[0], ..., sequence[minSamplesTrain+numOutputs]
...
X[k] =... | 7f8a03da19d21b4c29145cfeab7c2b20eb25ef25 | 69,437 |
import torch
def Ncontrast(x_dis, adj_label, tau=1):
"""
compute the Ncontrast loss
"""
x_dis = torch.exp(tau * x_dis)
x_dis_sum = torch.sum(x_dis, 1)
x_dis_sum_pos = torch.sum(x_dis * adj_label, 1)
loss = -torch.log(x_dis_sum_pos * (x_dis_sum**(-1))).mean()
return loss | dbec91553c38249f0aca5c7e11d6272f8f147879 | 69,438 |
def read_str_num(string, sep=None):
"""Returns a list of floats pulled from a string.
Delimiter is optional; if not specified, uses whitespace.
Parameters
----------
string : str
String to be parsed.
sep : str, optional
Delimiter (default is None, which means consecutive whites... | 87851e73fc8e81559d890abafc91cef8fc5f8a0a | 69,439 |
def _numeric_summary(arg, exact_nunique=False, prefix=None):
"""
Compute a set of summary metrics from the input numeric value expression
Parameters
----------
arg : numeric value expression
exact_nunique : boolean, default False
prefix : string, default None
String prefix for metric ... | cd2b14acaaa907aa5345e689125f45e8ad31aea1 | 69,440 |
def get(isamAppliance, name, check_mode=False, force=False):
"""
Retrieve a specific mapping rule
"""
ret_obj = search(isamAppliance, name=name)
id = ret_obj['data']
if id == {}:
return isamAppliance.create_return_object()
else:
return _get(isamAppliance, id) | 8d05f1aca64e86400a8ddb57de8b76dd4b2ecfff | 69,441 |
def assert_http_server(test, host, port,
path=b"", expected_response=b"hi"):
"""
Assert that a HTTP serving a response with body ``b"hi"`` is running
at given host and port.
This can be coupled with code that only conditionally starts up
the HTTP server via Flocker in order t... | 2c2eec1317ca584d5f1dc21c534101b39cc68eca | 69,442 |
import re
def to_bare_command_name(seq):
"""
Strips register and count data from @seq.
"""
# Special case.
if seq == '0':
return seq
new_seq = re.sub(r'^(?:".)?(?:[1-9]+)?', '', seq)
# Account for d2d and similar sequences.
new_seq = list(KeySequenceTokenizer(new_seq).iter_tok... | 70879c5f60fba5709f3c00c12d805e5de3309f1b | 69,443 |
def model_from_config(config: ml_collections.ConfigDict):
"""Builds a text classification model from a config."""
model = models.TextClassifier(
embedding_size=config.embedding_size,
hidden_size=config.hidden_size,
vocab_size=config.vocab_size,
output_size=config.output_size,
dropout_r... | 77a188b0b4c584f53a4fc001b193334da1def8a4 | 69,444 |
def _nobarrier(ts_dct):
""" Determine if reaction is barrierless
"""
print('cla', ts_dct['class'])
rad_rad = bool('radical radical' in ts_dct['class'])
low_spin = bool('low' in ts_dct['class'])
return rad_rad and low_spin | 393831d8b0af5085f8ff0f42d54bf8d14faca680 | 69,448 |
def resid_vs_pred_plot(y_true, y_pred, target):
"""Return plot containing residuals versus predictions."""
# -------------------------------------------------------------------------
# Setup
# -------------------------------------------------------------------------
# Define constants
MARKER = '... | 88933ce01fd4a43b4b8693d7d7964bedf03b8b4f | 69,449 |
def load_tfcsv_dataset(config, batch_size, augmentation=False, exclude=[], ann_dir=None, ann_file=None, img_dir=None):
""" Load the hardhat dataset
"""
ann_dir = config.data.ann_dir if ann_dir is None else ann_dir
ann_file = config.data.ann_file if ann_file is None else ann_file
img_dir = config.dat... | 1be2d697a6d123d64a0350aef7b500c8c33adf18 | 69,450 |
def identity_block(input_tensor,
kernel_size,
filters,
stage,
block,
weight_decay=1e-4,
batch_norm_decay=0.9,
batch_norm_epsilon=1e-5):
"""The identity block is the block that has no co... | 10c3dc77ed051ec93ea5af31dc3837c87ed7aadc | 69,451 |
def make_empty_df():
""" Make an empty dataframe as a placeholder. """
df = pd.DataFrame(data=None, dtype=int, columns=SEG_INFO_COLUMNS)
return df.set_index(cn.seg_id) | 7a6226fad2636cd5e21b6ef56fed0842716e6468 | 69,452 |
def create_args_string(num):
"""
生成占位符
返回 '?,?,?,?'
"""
L = []
for n in range(num):
L.append("?")
return ", ".join(L) | f9d52affe17c9dfb138338a3258d2d21dbd12c6e | 69,453 |
def escape_html(text):
"""
escape text for html file e.g. comment file
"""
text = multiple_str_sub(ESCAPE_HTML_CHAR_MAP_REGEX, ESCAPE_HTML_CHAR_MAP, text)
return text | ace05f9824a827ffd74af61c6e906d3f8690ad69 | 69,454 |
import slicer, fnmatch
def getNodes(pattern = "", scene=None):
"""Return a dictionary of nodes where the name or id matches the 'pattern'.
Providing an empty 'pattern' string will return all nodes.
"""
nodes = {}
if scene is None:
scene = slicer.mrmlScene
count = scene.GetNumberOfNodes()... | f1a3d15a9a416c2312e82c43f03443e6ff6f9f21 | 69,455 |
def get_preferred_sparse_format():
"""Get the preferred sparse matrix format supported by the backend.
Different backends have their preferred backend. This info is useful when
constructing a sparse matrix.
"""
return "csr" | 266a0af45f274a28597a89bcaac38d9713addd11 | 69,457 |
def roll2(arr, xy):
"""Translates an array by the shift xy, wrapping at the edges."""
if (xy == 0).all():
return arr
return np.roll(np.roll(arr, xy[0], -1), xy[1], -2) | e1030e54a4b8f9ef5469ff8bbc4e9273a059f9bb | 69,458 |
import torch
def pad_collate_func(batch):
"""
This should be used as the collate_fn=pad_collate_func for a pytorch DataLoader object in order to pad out files in a batch to the length of the longest item in the batch.
"""
vecs = [x[0] for x in batch]
labels = [x[1] for x in batch]
x = torch.n... | 89d4f2c2adb7295457afe7f6a3235bbc4d9c8155 | 69,460 |
def get_regex(resolver_or_pattern):
# type: (Union[URLPattern, URLResolver]) -> Pattern[str]
"""Utility method for django's deprecated resolver.regex"""
try:
regex = resolver_or_pattern.regex
except AttributeError:
regex = resolver_or_pattern.pattern.regex
return regex | 1ade237453800f9995e31f43a61e6507010b388b | 69,461 |
def get_type_from_default(default_var, vm):
"""Get the type of an attribute from its default value."""
if default_var.data == [vm.convert.none]:
# A default of None doesn't give us any information about the actual type.
return vm.convert.unsolvable
typ = vm.convert.merge_classes(default_var.data)
if typ... | 244720a5d0956a2ea300357e4134f04a491f810e | 69,463 |
def create_model_table(Enrollments_dict,segments):
"""
Generate the models recarray and the phone number hashtable
Parameters
----------
Enrollments_dict : dict
Dictionnary created by create_enrollments_dict()
segments : recarray
array containing informations all the segments
... | cd378d26fe510b31c4a54ddfdc787c9b965a268a | 69,464 |
def get_results(df, model, label_translation):
"""
get prediction results from a model 'model'
and a dataframe 'df'
:param df: data to predict
:type df: pd.DataFrame
:param model: classification model
:type model: any model from the module 'models'
:return: results
:rtype: pd.DataFr... | c550000b8586136af6b25d1e30cfa637e285fa35 | 69,465 |
def _FilterForUnsignedImageArchives(artifacts):
"""Return only instances of UnsignedImageArchive from a list of artifacts."""
return [x for x in artifacts if gspaths.IsUnsignedImageArchive(x)] | 17c2194fd9da459f0248265902f99c992cdcf72b | 69,466 |
def random_saturation(img, annotation, saturation=0.5):
""" Change the saturation randomly. """
coef = np.array([[[0.299, 0.587, 0.114]]])
alpha = np.random.uniform(-saturation, saturation)
gray = img * coef
gray = np.sum(gray, axis=2, keepdims=True)
img = alpha * img + (1.0 - alpha) * gray
... | 7405315987cb35e2db7c0beff5a1eca2cf48db89 | 69,468 |
def naively_call_mutation_directly(
alt_pos, cov_pos, p, min_alt_pos=2, only_call_if_rare=False
):
"""The guts of naively_call_mutation().
Abstracted to a separate function so that I can call this from other
contexts besides ordinary pileup -- e.g. for calling codons as p-mutated.
"""
if p > 50... | ec5b06fee1707ebd50bde8fbb880dfee005076b1 | 69,469 |
def cdlunique3river(opn, high, low, close):
"""Unique 3 River:
The unique three river is a candlestick chart pattern that predicts a bullish reversal,
although there is some evidence that it could act as a bearish continuation pattern. The
unique three river pattern is composed of three price candles. ... | b5f118066d1f4b0ccdc29f0f108863b1ed40e54e | 69,470 |
def PGaus(inImage, Beam):
"""
Create an ObitFArray containing a unit area Gaussian in the center
returns Python FArray object with normalized Gaussian
* inImage = Obit Image with geometry
* Beam = [maj, min, PA] defining eliptical Gaussian
size in image cell units or pixels if none... | 526aa7db3a238328d3e9c271ae91a82ab036a407 | 69,471 |
import re
def splitMySQLcode(string):
"""
MySQL code can only be executed one command at a time, and fails if it has any empty slots
So as a convenience wrapper, I'm just splitting it and returning an array.
"""
try:
output = ['%s;\n' % query for query in string.split(';') if re.search(r"\... | 43bf3f9209ced9c3c19c0ad4476b06a4d68f6e0c | 69,472 |
from typing import Optional
def get_article_by_id(article_id: int, annotate: bool = False) -> Optional[Article]:
"""Return article by the article's id"""
try:
article = get_all_articles(annotate).get(id=article_id)
except ObjectDoesNotExist:
raise Http404()
return article | 905e55538824cd378bc3e73c3ec919c200c7fd34 | 69,474 |
from typing import Callable
def three_body_mc_force_en(env1: AtomicEnvironment, env2: AtomicEnvironment,
d1: int, hyps: 'ndarray', cutoffs: 'ndarray',
cutoff_func: Callable = cf.quadratic_cutoff) \
-> float:
"""3-body multi-element k... | 306b690f0a4e769a0a70e44af5e221c656c126a6 | 69,475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.