content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def ntu_tranform_skeleton(test):
"""
:param test: frames of skeleton within a video sample
"""
remove_frame = False
test = np.asarray(test)
transform_test = []
d = test[0, 0:3]
v1 = test[0, 1 * 3:1 * 3 + 3] - test[0, 0 * 3:0 * 3 + 3]
v1 = v1 / np.linalg.norm(v1)
v2_ = test[0, ... | 6f8e9e3ff0b6fa95b5f3b8c22aef2de05730a78c | 17,438 |
import random
import time
import requests
def request_to_dataframe(UF):
"""Recebe string do estado, retona DataFrame com faixa de CEP do estado"""
#Try to load the proxy list. If after several attempts it still doesn't work, raise an exception and quit.
proxy_pool = proxy_list_to_cycle()
#Set i... | f71de0ec169f375fff1fba87d55aa8021b851990 | 17,439 |
import csv
def read_sto_mot_file(filename):
"""
Read sto or mot file from Opensim
----------
filename: path
Path of the file witch have to be read
Returns
-------
Data Dictionary with file informations
"""
data = {}
data_row = []
first_li... | 584cff26cb217d5fadfcea025ad58e431f46676a | 17,440 |
def verify_cef_labels(device, route, expected_first_label, expected_last_label=None, max_time=90,
check_interval=10):
""" Verify first and last label on route
Args:
device ('obj'): Device object
route ('str'): Route address
expected_first_label ('str'): Expected fir... | c082920d0c93ec0c2897dc5a06c9d9d9452151af | 17,441 |
def fcat(*fs):
"""Concatenate a sequence of farrays.
The variadic *fs* input is a homogeneous sequence of functions or arrays.
"""
items = list()
for f in fs:
if isinstance(f, boolfunc.Function):
items.append(f)
elif isinstance(f, farray):
items.extend(f.flat... | 440a850ed17b8fc844cafaa765b24620a29fa0fd | 17,442 |
def get_path_to_spix(
name: str,
data_directory: str,
thermal: bool,
error: bool = False,
file_ending: str = "_6as.fits",
) -> str:
"""Get the path to the spectral index
Args:
name (str): Name of the galaxy
data_directory (str): dr2 data directory
thermal (bool): non... | bf8fdff001049ed0738ed856e8234c43ce4511b7 | 17,443 |
def hexpos (nfibres,diam) :
"""
Returns a list of [x,y] positions for a classic packed hex IFU configuration.
"""
positions = [[np.nan,np.nan] for i in range(nfibres)]
# FIND HEX SIDE LENGTH
nhex = 1
lhex = 1
while nhex < nfibres :
lhex += 1
nhex = 3*lhex**2-3*lhex+1
if nhex != nfibres:
lhex -= 1
nhex ... | 4dbf1209d7021c6a4defd1c58e420b362bdbf84c | 17,444 |
from bs4 import BeautifulSoup
def parse_object_properties(html):
"""
Extract key-value pairs from the HTML markup.
"""
if isinstance(html, bytes):
html = html.decode('utf-8')
page = BeautifulSoup(html, "html5lib")
propery_ps = page.find_all('p', {'class': "list-group-item-text"})
o... | 8eb2d15cb5f46075ec44ff61265a8f70123a8646 | 17,445 |
def rgb2hex(r, g, b, normalised=False):
"""Convert RGB to hexadecimal color
:param: can be a tuple/list/set of 3 values (R,G,B)
:return: a hex vesion ofthe RGB 3-tuple
.. doctest::
>>> from colormap.colors import rgb2hex
>>> rgb2hex(0,0,255, normalised=False)
'#0000FF'
... | 03afd09cc280d7731ca6b28098cf3f5605fddda7 | 17,446 |
def test_hookrelay_registry(pm):
"""Verify hook caller instances are registered by name onto the relay
and can be likewise unregistered."""
class Api:
@hookspec
def hello(self, arg):
"api hook 1"
pm.add_hookspecs(Api)
hook = pm.hook
assert hasattr(hook, "hello")
... | 5f7733efbdbaf193b483c108838d2571ff686e52 | 17,447 |
def model_choices_from_protobuf_enum(protobuf_enum):
"""Protobufs Enum "items" is the opposite order djagno requires"""
return [(x[1], x[0]) for x in protobuf_enum.items()] | d3f5431293a9ab3fdf9a92794b1225a0beec40cc | 17,448 |
def kmeans(boxes, k):
"""
Group into k clusters the BB in boxes.
http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html#sklearn.cluster.KMeans
:param boxes: The BB in format Nx4 where (x1,y1,x2,y2)
:param k: the number of clusters.
:return: k clusters with the element in... | 0d2bcfb2fb7d5639f95db92ac5aa5e73b1b27498 | 17,450 |
def observation_min_max_in_hex_grid_json(request: HttpRequest):
"""Return the min, max observations count per hexagon, according to the zoom level. JSON format.
This can be useful to dynamically color the grid according to the count
"""
zoom = extract_int_request(request, "zoom")
species_ids, datas... | 24a3f4846aceea2df0b724d6bada88315b815ee2 | 17,451 |
from bs4 import BeautifulSoup
def parseHtml(html):
"""
BeautifulSoup でパースする
Parameters
----------
html : str
HTML ソース文字列
Returns
-------
soup : BeautifulSoup
BeautifulSoup オブジェクト
"""
soup = BeautifulSoup(html, 'html.parser')
return soup | e8d7a39a9881606d1dfee810ab1c2cecd11eaba2 | 17,454 |
def am_score(probs_data, probs_gen):
"""
Calculate AM Score
"""
mean_data = np.mean(probs_data, axis=0)
mean_gen = np.mean(probs_gen, axis=0)
entropy_gen = np.mean(entropy(probs_gen, axis=1))
am_score = entropy(mean_data, mean_gen) + entropy_gen
return am_score | 5e3c3f42ed2402dd2e48ab1ff4f9ff13754d5c31 | 17,455 |
import torch
def load_image(path_image, size=None, bgr_mean=[103.939, 116.779, 123.68]):
"""
Loads and pre-process the image for SalGAN model.
args:
path_image: abs path to image
size: size to input to the network (it not specified, uses SalGAN predifined)
bgr_mean: mean values (B... | 3a9ca220bb48f26d76ae35fd58897c8e59cdae0c | 17,456 |
def GetWsdlNamespace(version):
""" Get wsdl namespace from version """
return "urn:" + serviceNsMap[version] | bc75fa0e45c4ce4750898db75571de84aa302fc2 | 17,457 |
def is_PC(parcels):
"""
Dummy for Pinal County.
"""
return (parcels.county == 'PC').astype(int) | 60aa7dcc7adaefee177406c7e6bb963a5a4567d9 | 17,458 |
import hashlib
import requests
def check_password(password: str) -> int:
"""Use Have I Been Pwned to determine whether a password is bad.
If the request fails, this function will assume the password is fine, but
log an error so that administrators can diagnose it later.
:param password: The password... | 609dd29ee2b252452e31d64b18e835a39e1cbf22 | 17,459 |
def rqpos(A):
"""
RQ decomp. of A, with phase convention such that R has only positive
elements on the main diagonal.
If A is an MPS tensor (d, chiL, chiR), it is reshaped and
transposed appropriately
before the throughput begins. In that case, Q will be a tensor
of the same size, while R ... | 026629b6638265daee83e8d8b5ab5b47b61e64d8 | 17,460 |
import torch
from typing import OrderedDict
def load_checkpoint(model,
filename,
map_location=None,
strict=False,
logger=None,
show_model_arch=True,
print_keys=True):
""" Note that official pre-... | 1d948f45f81c93af73394c891dc7e692c24378b3 | 17,461 |
def basic_image_2():
"""
A 10x10 array with a square (3x3) feature
Equivalent to results of rasterizing basic_geometry with all_touched=True.
Borrowed from rasterio/tests/conftest.py
Returns
-------
numpy ndarray
"""
image = np.zeros((20, 20), dtype=np.uint8)
image[2:5, 2:5] = 1... | 8e83070721b38f2a886c7affb4aadc9a053f1748 | 17,462 |
def download(url, verbose, user_agent='wswp', num_retries=2, decoding_format='utf-8', timeout=5):
"""
Function to download contents from a given url
Input:
url: str
string with the url to download from
user_agent: str
Default 'wswp'
num_retries:... | 31592018b6f6f62154444dfc44b723efc1bd7f47 | 17,463 |
from typing import Union
from typing import List
def _write_deform(model: Union[BDF, OP2Geom], name: str,
loads: List[AEROS], ncards: int,
op2_file, op2_ascii, endian: bytes, nastran_format: str='nx') -> int:
"""
(104, 1, 81)
NX 2019.2
Word Name Type Description
... | 55f2cb18336a940c550ee68bd5148c8d74f5bb93 | 17,464 |
def polygonize(geometries, **kwargs):
"""Creates polygons formed from the linework of a set of Geometries.
Polygonizes an array of Geometries that contain linework which
represents the edges of a planar graph. Any type of Geometry may be
provided as input; only the constituent lines and rings will be u... | 20b883734a1acedb1df3241e1815687640cac8cd | 17,465 |
def slerp(input_latent1, input_latent2, interpolation_frames=100):
"""Spherical linear interpolation ("slerp", amazingly enough).
Parameters
----------
input_latent1, input_latent2 : NumPy arrays
Two arrays which will be interpolated between.
interpolation_frames : int, optional
... | 392b2e61f3369cf1e4038fac4240dca36f848dce | 17,466 |
from datetime import datetime
def parent_version_config():
"""Return a configuration for an experiment."""
config = dict(
_id="parent_config",
name="old_experiment",
version=1,
algorithms="random",
metadata={
"user": "corneauf",
"datetime": datet... | ff1f123ce06d687eb3b0031d6bc82c808918c46e | 17,467 |
import re
def sanitize_k8s_name(name):
"""From _make_kubernetes_name
sanitize_k8s_name cleans and converts the names in the workflow.
"""
return re.sub('-+', '-', re.sub('[^-0-9a-z]+', '-', name.lower())).lstrip('-').rstrip('-') | edaf6dc3083f0b57aeb1d95a66b5a7f8c1347b55 | 17,468 |
def main():
""" Process command line arguments and run x86 """
run = X86Run()
result = run.Run()
return result | 7de61875207aa17bcf2ef87ff138540626fc7d2b | 17,469 |
def gen_key(uid, section='s'):
"""
Generate store key for own user
"""
return f'cs:{section}:{uid}'.encode() | 5e6386650f6bbaef681636424fd813f2df93fe58 | 17,470 |
def convert_atom_to_voxel(coordinates: np.ndarray, atom_index: int,
box_width: float, voxel_width: float) -> np.ndarray:
"""Converts atom coordinates to an i,j,k grid index.
This function offsets molecular atom coordinates by
(box_width/2, box_width/2, box_width/2) and then divides by
... | 6f08b594f2012aa0ba4a7985d5f4e2049c4629d3 | 17,471 |
def plot_det_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None,
log_wandb=False):
"""Function for plotting DET curve
Args:
y_true_arr (list/np.array): list of all GT arrays
y_pred_proba_arr (list/np.array): list of all predicted probabili... | 0437d700a9555b48b84cbb6e225bc88f1a57e34d | 17,473 |
def harmonic_separation(audio, margin=3.0):
"""
Wraps librosa's `harmonic` function, and returns a new Audio object.
Note that this folds to mono.
Parameters
---------
audio : Audio
The Audio object to act on.
margin : float
The larger the margin, the larger the separation.... | 3ac3e0d87f719814ca021f594a21dde08e9fd02f | 17,474 |
def merge(
left,
right,
how: str = "inner",
on=None,
left_on=None,
right_on=None,
left_index: bool = False,
right_index: bool = False,
sort: bool = False,
suffixes=("_x", "_y"),
copy: bool = True,
indicator: bool = False,
validate=None,
): # noqa: PR01, RT01, D200
... | da07b44fb80ee28cc8320c071876ef6ad573d974 | 17,475 |
def generate_modal(title, callback_id, blocks):
"""
Generate a modal view object using Slack's BlockKit
:param title: Title to display at the top of the modal view
:param callback_id: Identifier used to help determine the type of modal view in future responses
:param blocks: Blocks to add to the mo... | e0caeec1ab1cf82ed6f02ec77a984dcb25e329f5 | 17,476 |
def dir_thresh(img, sobel_kernel=3, thresh=(0.7, 1.3)):
"""
#---------------------
# This function applies Sobel x and y,
# then computes the direction of the gradient,
# and then applies a threshold.
#
"""
# Take the gradient in x and y separately
sobelx = cv2.Sobel(img, cv2.CV_64F... | 0f5aefdbc9ffbe8e3678145e2926a4fbd7e01629 | 17,477 |
from datetime import datetime, timedelta
def seconds_to_time( time ):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
"""
if not time:
return "0s"
if isinstance( time, timedelta ) or is... | 407fa93f782c8cff142be1ab721969d3e4c2b42f | 17,478 |
def load_txt_into_set(path, skip_first_line=True):
"""Load a txt file (one value per line) into a set."""
result = set()
file = open_file_dir_safe(path)
with file:
if skip_first_line:
file.readline()
for line in file:
line = line.strip()
result.add(li... | 17ad3c15820595b72254dbe4c9097a8857511599 | 17,480 |
def failed(obj):
"""Returns True if ``obj`` is an instance of ``Fail``."""
return isinstance(obj, Fail) | 715fe3ae1154e3e5712b6f4535021b44e8020146 | 17,481 |
def linkCount(tupleOfLists, listNumber, lowerBound, upperBound):
"""Counts the number of links in one of the lists passed.
This function is a speciality function to aid in calculating
statistics involving the number of links that lie in a given
range. It is primarily intended as a private helper functi... | 239fd8d3c01fe6c88444cfa7369459e3c76005dc | 17,482 |
def encode_md5(plain_text):
"""
Encode the plain text by md5
:param plain_text:
:return: cipher text
"""
plain_text = plain_text + EXT_STRING
encoder = md5()
encoder.update(plain_text.encode('utf-8'))
return encoder.hexdigest() | ad88ebc12334c9438c38719cd7c836edb9736d3c | 17,483 |
import warnings
def delta(x, y, assume_normal=True, percentiles=[2.5, 97.5],
min_observations=20, nruns=10000, relative=False, x_weights=1, y_weights=1):
"""
Calculates the difference of means between the samples (x-y) in a
statistical sense, i.e. with confidence intervals.
NaNs are ignored... | 37b742775777b5a0bd26f7e8fdf7a189a69b199f | 17,484 |
def CircleCircumference(curve_id, segment_index=-1):
"""Returns the circumference of a circle curve object
Parameters:
curve_id = identifier of a curve object
segment_index [opt] = identifies the curve segment if
curve_id identifies a polycurve
Returns:
The circumference of the circl... | 7a9200b089cebab93cbea387a4dd92590157dc45 | 17,485 |
def generate_handshake(info_hash, peer_id):
"""
The handshake is a required message and must be the first message
transmitted by the client. It is (49+len(pstr)) bytes long in the form:
<pstrlen><pstr><reserved><info_hash><peer_id>
Where:
pstrlen: string length of <pstr>, as a single raw byte
... | ae13462608f3e2ec47abdb12e87a3bc08faa1cba | 17,486 |
def tokenizer_decorator(func, **kwargs):
"""
This decorator wraps around a tokenizer function.
It adds the token to the info dict and removes the found token from the given name.
"""
if not callable(func):
raise TypeError(f"func {func} not callable")
@wraps(func)
def wrapper(name, i... | d1827ab75a12f923c6da69927323d9c5013124c0 | 17,487 |
def reverse_complement( seq ):
"""
Biological reverse complementation. Case in sequences are retained, and
IUPAC codes are supported. Code modified from:
http://shootout.alioth.debian.org/u32/program.php?test=revcomp&lang=python3&id=4
"""
return seq.translate(_nt_comp_table)[::-1] | 86229dfeceecb7e0d2e1215b25074c35fbd38792 | 17,488 |
def computeLPS(s, n):
"""
Sol with better comle
"""
prev = 0 # length of the previous longest prefix suffix
lps = [0]*(n)
i = 1
# the loop calculates lps[i] for i = 1 to n-1
while i < n:
if s[i] == s[prev]:
prev += 1
lps[i] = prev
i += 1
... | 8b4374c9ac29f59cf1f4b0e6e07628776828c11a | 17,489 |
def roundedCorner(pc, p1, p2, r):
"""
Based on Stackoverflow C# rounded corner post
https://stackoverflow.com/questions/24771828/algorithm-for-creating-rounded-corners-in-a-polygon
"""
def GetProportionPoint(pt, segment, L, dx, dy):
factor = float(segment) / L if L != 0 else segment
... | e77497918025deba211469616d210c23483e2152 | 17,490 |
def synthetic_data(n_points=1000, noise=0.05,
random_state=None, kind="unit_cube",
n_classes=None, n_occur=1, legacy_labels=False, **kwargs):
"""Make a synthetic dataset
A sample dataset generators in the style of sklearn's
`sample_generators`. This adds other function... | 740b5d2f708e177ce703f2124806ab7bd0079a09 | 17,491 |
def _load_default_profiles():
# type: () -> Dict[str, Any]
"""Load all the profiles installed on the system."""
profiles = {}
for path in _iter_default_profile_file_paths():
name = _get_profile_name(path)
if _is_abstract_profile(name):
continue
definition = _read_p... | b53411dce6bdf3baba876a626b023a2b93e48c99 | 17,493 |
import torch
def train_model(model, train_loader, valid_loader, learning_rate, device,
epochs):
"""Trains a model with train_loader and validates it with valid_loader
Arguments:
model -- Model to train
train_loader -- Data to train
valid_loader -- Data to validate the ... | 3addd258adddcbb43d846dae09d943d9a7016b69 | 17,494 |
def get_weapon_techs(fighter=None):
"""If fighter is None, return list of all weapon techs.
If fighter is given, return list of weapon techs fighter has."""
if fighter is None:
return weapon_tech_names
else:
return [t for t in fighter.techs if get_tech_obj(t).is_weapon_tech] | bbda76e55fdbe80e9883ff05746256fb56767136 | 17,495 |
def xml_to_values(l):
"""
Return a list of values from a list of XML data potentially including null values.
"""
new = []
for element in l:
if isinstance(element, dict):
new.append(None)
else:
new.append(to_float(element))
return new | 30b6af4101f45697e0f074ddedcd051aba37cb99 | 17,496 |
def _get_options(raw_options, apply_config):
"""Return parsed options."""
if not raw_options:
return parse_args([''], apply_config=apply_config)
if isinstance(raw_options, dict):
options = parse_args([''], apply_config=apply_config)
for name, value in raw_options.items():
... | e88014f0f5497e72973afbdf669cf14bf4537051 | 17,497 |
def csvdir_equities(tframes=None, csvdir=None):
"""
Generate an ingest function for custom data bundle
This function can be used in ~/.zipline/extension.py
to register bundle with custom parameters, e.g. with
a custom trading calendar.
Parameters
----------
tframes: tuple, optional
... | 6dc4b76e52f7512074eb044d5505c904a323eb69 | 17,498 |
def normalize_skeleton(joints):
"""Normalizes joint positions (NxMx2 or NxMx3, where M is 14 or 16) from parent to child order. Each vector from parent to child is normalized with respect to it's length.
:param joints: Position of joints (NxMx2) or (NxMx3)
:type joints: numpy.ndarray
:retur... | 579862d05814eaa9b04f3e1a4812e727b02175aa | 17,499 |
def is_valid_instruction(instr: int, cpu: Cpu = Cpu.M68000) -> bool:
"""Check if an instruction is valid for the specified CPU type"""
return bool(lib.m68k_is_valid_instruction(instr, cpu.value)) | ae528e503e24698507971334d33dc6abf0f4c39c | 17,501 |
def docker_available():
"""Check if Docker can be run."""
returncode = run.run(["docker", "images"], return_code=True)
return returncode == 0 | 43ce2c7f5cb16657b4607faa5eac61b20e539e53 | 17,503 |
from datetime import datetime
def is_bc(symbol):
"""
判断是否背驰
:param symbol:
:return:
"""
bars = get_kline(symbol, freq="30min", end_date=datetime.now(), count=1000)
c = CZSC(bars, get_signals=get_selector_signals)
factor_ = Factor(
name="背驰选股",
signals_any=[
... | 07dc2f01374f95544898375b8bc02b6128d70090 | 17,504 |
import time
import calendar
def IEEE2030_5Time(dt_obj, local=False):
""" Return a proper IEEE2030_5 TimeType object for the dt_obj passed in.
From IEEE 2030.5 spec:
TimeType Object (Int64)
Time is a signed 64 bit value representing the number of seconds
since 0... | fbb9466e927f1162226760efbe609bf3e779e163 | 17,505 |
def learning_rate_schedule(params, global_step):
"""Handles learning rate scaling, linear warmup, and learning rate decay.
Args:
params: A dictionary that defines hyperparameters of model.
global_step: A tensor representing current global step.
Returns:
A tensor representing current learning rate.
... | b88d67dd0d241d26bf183e90e3d3c215e0abd957 | 17,506 |
def profile(step):
"""
Profiles a Pipeline step and save the results as HTML file in the project output
directory.
Usage:
@profile
def step(self):
pass
"""
@wraps(step)
def wrapper(*arg, **kwargs):
pipeline_instance = arg[0]
project = pipeline_in... | f300000a0471a2439ae951a2d33b8a03aa61b333 | 17,508 |
from modin.pandas.series import Series
def make_dataframe_wrapper(DataFrame):
"""
Prepares a "delivering wrapper" proxy class for DataFrame.
It makes DF.loc, DF.groupby() and other methods listed below deliver their
arguments to remote end by value.
"""
conn = get_connection()
class Obt... | a2d523f6e9cb9d23ae722195a091d8e2b68139cc | 17,509 |
def download_cmems_ts(lats, lons, t0, tf, variables, fn=None):
"""Subset CMEMS output using OpenDAP
:params:
lats = [south, north] limits of bbox
lons = [west, east] limits of bbox
t0 = datetime for start of time series
tf = datetime for end of time series
variables = li... | b97de3a7428d6e2b50ab36b28e47afe479c24042 | 17,510 |
def construct_gpu_info(statuses):
""" util for unit test case """
m = {}
for status in statuses:
m[status.minor] = status
m[status.uuid] = status
return m | b8b2f41799b863d2e22066005b901f17a610d858 | 17,511 |
def load_data_time_machine(batch_size, num_steps, use_random_iter=False,
max_tokens=10000):
"""Return the iterator and the vocabulary of the time machine dataset."""
data_iter = SeqDataLoader(batch_size, num_steps, use_random_iter,
max_tokens)
return ... | ed9d6b63c34cf9d1a750daabbdb81e03e467e939 | 17,512 |
def scan_paths(paths, only_detect, recursive, module_filter):
"""
Scans paths for known bots and dumps information from them
@rtype : dict
@param paths: list of paths to check for files
@param only_detect: only detect known bots, don't process configuration information
@param recursive: recursi... | f58216f1ed5955828738689fa67522a8cc0e497a | 17,513 |
def generate_masks(input_size, output_size=1, observed=None):
"""
Generates some basic input and output masks.
If C{input_size} is an integer, the number of columns of the mask will be
that integer. If C{input_size} is a list or tuple, a mask with multiple channels
is created, which can be used with RGB images, f... | dee12176f72a158e9f39036981fa1dbd6be81817 | 17,514 |
def average(time_array,height_array,data_array,height_bin_size=100,time_bin_size=3600):
"""
average: function that averages the radar signal by height and time
Args:
time_array: numpy 1d array with timestamps
height_array: numpy 1d array with height range
data_array: numpy 2d arra... | 710f4c8821cffe110511bda0dd3d4fd3052f33a9 | 17,516 |
def new_pitch():
"""
route to new pitch form
:return:
"""
form = PitchForm()
if form.validate_on_submit():
title = form.title.data
pitch = form.pitch.data
category = form.category.data
fresh_pitch = Pitch(title=title, pitch_actual=pitch, category=category, user_... | a7724149a7e6b9d545559fef643dcc8fd2f5c731 | 17,518 |
def get_entity_bios(seq,id2label):
"""Gets entities from sequence.
note: BIOS
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
# >>> seq = ['B-PER', 'I-PER', 'O', 'S-LOC']
# >>> get_entity_bios(seq)
[[... | 25219d29ba8ecb2d44ca5a8245059432f3220d8d | 17,519 |
import torch
import copy
def early_stopping_train(model, X, Y_, x_test, y_test, param_niter=20001, param_delta=0.1):
"""Arguments:
- X: model inputs [NxD], type: torch.Tensor
- Y_: ground truth [Nx1], type: torch.Tensor
- param_niter: number of training iterations
- param_delta: learning rate
... | 83a8acdd24a4fde3db77184c3b4a99a1c1783349 | 17,520 |
def my_vtk_grid_props(vtk_reader):
"""
Get grid properties from vtk_reader instance.
Parameters
----------
vtk_reader: vtk Reader instance
vtk Reader containing information about a vtk-file.
Returns
----------
step_x : float
For regular grid, stepsize in x-direction.
... | 26ef8a51648ea487372ae06b54c8ccf953aeb414 | 17,521 |
def make_env(stack=True, scale_rew=True):
"""
Create an environment with some standard wrappers.
"""
env = grc.RemoteEnv('tmp/sock')
env = SonicDiscretizer(env)
if scale_rew:
env = RewardScaler(env)
env = WarpFrame(env)
if stack:
env = FrameStack(env, 4)
return env | 347376103fa00d4d43714f30097b0d129ef45f43 | 17,522 |
def plot_distr_cumsum(result, measure="degree", scale=['log', 'log'], figures=[], prefix="", show_std=True, show_figs=True, mode="safe", colors=('r', 'b')):
""" plots the cummulative distribution functions
special care has to be taken because averaging these is not trivial in comparison to e.g. degree
"""
... | 6b0a526cf8f09dd66ac7b0988c9445d57416be21 | 17,523 |
def state_space_model(A, z_t_minus_1, B, u_t_minus_1):
"""
Calculates the state at time t given the state at time t-1 and
the control inputs applied at time t-1
"""
state_estimate_t = (A @ z_t_minus_1) + (B @ u_t_minus_1)
return state_estimate_t | 0e04207028df8d4162c88aad6606e792ef618f5a | 17,526 |
def get_post(id , check_author=True):
"""Get a post and its author by id.
Checks that the id exists and optionally that the current user is
the author.
:param id: id of post to get
:param check_author: require the current user to be the author
:return: the post with author information
:rai... | a15ac3816d134f1dd89bf690c2f800e412d7219b | 17,527 |
def get_pixel(x, y):
"""Get the RGB value of a single pixel.
:param x: Horizontal position from 0 to 7
:param y: Veritcal position from 0 to 7
"""
global _pixel_map
return _pixel_map[y][x] | 47a77090683a5b8e7178b3c7d83ae5b1a090342f | 17,528 |
from typing import Callable
import re
def check_for_NAs(func: Callable) -> Callable:
"""
This decorator function checks whether the input string qualifies as an
NA. If it does it will return True immediately. Otherwise it will run
the function it decorates.
"""
def inner(string: str, *args, *... | e9336cca2e6cd69f81f6aef1d11dc259492774f8 | 17,529 |
from typing import Union
from typing import Callable
def integrateEP_w0_ode( w_init: np.ndarray, w0: Union[ Callable, np.ndarray ], w0prime: Union[ Callable, np.ndarray ],
B: np.ndarray, s: np.ndarray, s0: float = 0, ds: float = None,
R_init: np.ndarray = np.eye( 3 ), B... | 75a042b94ac46b7ecbb86e23abacde0d4034b9fe | 17,530 |
def change_coordinate_frame(keypoints, window, scope=None):
"""Changes coordinate frame of the keypoints to be relative to window's frame.
Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint
coordinates from keypoints of shape [num_instances, num_keypoints, 2]
to be relative to this windo... | 2aa69a55d7f8177784afb41f50cd7ccfbffdbde3 | 17,531 |
import random
def _get_name(filename: str) -> str:
"""
Function returns a random name (first or last)
from the filename given as the argument.
Internal function. Not to be imported.
"""
LINE_WIDTH: int = 20 + 1 # 1 for \n
with open(filename) as names:
try:
total_n... | 1b4cd75488c6bd1814340aee5669d1631318e77f | 17,533 |
def map_to_udm_section_associations(enrollments_df: DataFrame) -> DataFrame:
"""
Maps a DataFrame containing Canvas enrollments into the Ed-Fi LMS Unified Data
Model (UDM) format.
Parameters
----------
enrollments_df: DataFrame
Pandas DataFrame containing all Canvas enrollments
Ret... | 303223302e326854f7a19b2f3c9d0b626a2807bc | 17,534 |
def plot_electrodes(mris, grid, values=None, ref_label=None, functional=None):
"""
"""
surf = mris.get('pial', None)
if surf is None:
surf = mris.get('dura', None)
pos = grid['pos'].reshape(-1, 3)
norm = grid['norm'].reshape(-1, 3)
labels = grid['label'].reshape(-1)
right_or_le... | 0bcc5545c625675be080e6b70bf7a74d247ba1c9 | 17,535 |
from typing import Tuple
def _get_laplace_matrix(bcs: Boundaries) -> Tuple[np.ndarray, np.ndarray]:
"""get sparse matrix for laplace operator on a 1d Cartesian grid
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
{ARG_BOUNDARIES_INSTANCE}
Returns:
tuple: A sparse ... | 80880c7fb1d54a7d4502e1096c2f2ade4d30ce21 | 17,536 |
import warnings
def column_or_1d(y, warn=False):
""" Ravel column or 1d numpy array, else raises an error
Parameters
----------
y : array-like
warn : boolean, default False
To control display of warnings.
Returns
-------
y : array
"""
shape = np.shape(y)
if len(s... | ef3a5bfe7a1ae07b925c1d9b897bce0eff29b275 | 17,537 |
def conv_tower(
inputs,
filters_init,
filters_end=None,
filters_mult=None,
divisible_by=1,
repeat=1,
**kwargs
):
"""Construct a reducing convolution block.
Args:
inputs: [batch_size, seq_length, features] input sequence
filters_init: Initial Conv1D filters
... | 82ff878423309e2963090a9569f14090a85d30e5 | 17,538 |
def edit_coach(request, coach_id):
""" Edit a coach's information """
if not request.user.is_superuser:
messages.error(request, 'Sorry, only the owners can do that.')
return redirect(reverse('home'))
coach = get_object_or_404(Coach, pk=coach_id)
if request.method == 'POST':
for... | ecaf07df3249d3349928b4e9da9c0524b27e603e | 17,539 |
import torch
def estimate_translation(S,
joints_2d,
focal_length=5000.,
img_size=224.,
use_all_joints=False,
rotation=None):
"""Find camera translation that brings 3D joints S closest to 2D... | 70b5cc75dc28919b6bb6cea70b49eae8ca593452 | 17,540 |
import random
def create_midterm_data(all_students):
"""
Create the midterm data set
Ten questions, two from each topic, a percentage of students did not
show up, use it as an example of merge
Rules:
- International students have a 10% drop out rate
- Performance changes by PROGRAM!
... | b1f946ebab616362113ada54a17cc3e857b33f98 | 17,541 |
def identify_outliers(x_vals, y_vals, obj_func, outlier_fraction=0.1):
"""Finds the indices of outliers in the provided data to prune for subsequent curve fitting
Args:
x_vals (np.array): the x values of the data being analyzed
y_vals (np.array): the y values of the data being analyzed
... | e1742747ac63b34c39d1e57cbc896b9df5af85e0 | 17,542 |
def GetTypeMapperFlag(messages):
"""Helper to get a choice flag from the commitment type enum."""
return arg_utils.ChoiceEnumMapper(
'--type',
messages.Commitment.TypeValueValuesEnum,
help_str=(
'Type of commitment. `memory-optimized` indicates that the '
'commitment is for mem... | f00e645a2dbfcae94a33fc5b016809f72e87c0a9 | 17,543 |
def prepare_concepts_index(create=False):
"""
Creates the settings and mappings in Elasticsearch to support term search
"""
index_settings = {
"settings": {"analysis": {"analyzer": {"folding": {"tokenizer": "standard", "filter": ["lowercase", "asciifolding"]}}}},
"mappings": {
... | a33e7e6172c7a7c8577abab77cb467125e629e39 | 17,545 |
def pack_wrapper(module, att_feats, att_masks):
"""
for batch computation, pack sequences with different lenghth with explicit setting the batch size at each time step
"""
if att_masks is not None:
packed, inv_ix = sort_pack_padded_sequence(att_feats, att_masks.data.long().sum(1))
return... | ff5e02ac5977cf525a0e2f2a96714ff8a6cf1fe3 | 17,546 |
def recommendation_inspiredby(film: str, limit: int=20) -> list:
"""Movie recommandations from the same inspiration with selected movie
Args:
film (str): URI of the selected movie
limit (int, optional): Maximum number of results to return. Defaults to 20.
Returns:
list: matching mo... | d70d6a30eabc5d1a5b5a7c3b0cebc28a9dcb0fa9 | 17,548 |
import string
def str2twixt(move):
""" Converts one move string to a twixt backend class move.
Handles both T1-style coordinates (e.g.: 'd5', 'f18'') as well as tsgf-
style coordinates (e.g.: 'fg', 'bi') as well as special strings
('swap' and 'resign'). It can handle letter in upper as well as lowerc... | fe1e644519f7d6fe7df2be8a38754ba230981a91 | 17,549 |
from datetime import datetime
import re
def celery_health_view(request):
"""Admin view that displays the celery configuration and health."""
if request.method == 'POST':
celery_health_task.delay(datetime.now())
messages.success(request, 'Health task created.')
return HttpResponseRedire... | 52f7fb76af5dc5557e22976b1930c19e6249f1cc | 17,550 |
def get_n_runs(slurm_array_file):
"""Reads the run.sh file to figure out how many conformers or rotors were meant to run
"""
with open(slurm_array_file, 'r') as f:
for line in f:
if 'SBATCH --array=' in line:
token = line.split('-')[-1]
n_runs = 1 + int(to... | 5574ef40ef87c9ec5d9bbf2abd7d80b62cead2ab | 17,551 |
def get_field_attribute(field):
"""
Format and return a whole attribute string
consists of attribute name in snake case and field type
"""
field_name = get_field_name(field.name.value)
field_type = get_field_type(field)
strawberry_type = get_strawberry_type(
field_name, field.descrip... | fbbe2dbdf6c5f0427365fbbb0d5f43df8bb74678 | 17,553 |
def shuffle_data(data):
"""
Shuffle the data
"""
rng_state = np.random.get_state()
for c, d in data.items():
np.random.set_state(rng_state)
np.random.shuffle(d)
data[c] = d
return data | 5a1fa1f81fbec54092c8d7b50ebf75f8edb526c7 | 17,554 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.