content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def freeze_loop(src, start, end, loopStart, loopEnd=None):
""" Freezes a range of frames form start to end using the frames
comprended between loopStart and loopEnd.
If no end frames are provided for the range or the loop,
start frames will be used instead.
"""
core = vs.get_core()
if loopE... | 67284a264ada601dbd01c30c1bf32f48ad9eb9d8 | 3,656,700 |
def timevalue(cflo, prate, base_date=0, utility=None):
"""
Computes the equivalent net value of a generic cashflow at time `base_date`
using the periodic interest rate `prate`. If `base_date` is 0, `timevalue`
computes the net present value of the
cashflow. If `base_date` is the index of the last e... | 704f6988d1995a8602314df08d1dcfbed549f1ed | 3,656,701 |
def munge(examples, multiplier, prob, loc_var, data_t, seed=0):
""" Generates a dataset from the original one
:param examples: Training examples
:type examples: 2d numpy array
:param multiplier: size multiplier
:type multiplier: int k
:param prob: probability of swapping values
:type prob: ... | 339d5cafedb8abd6094cde81004c5056a3830d26 | 3,656,702 |
def is_interested_source_code_file(afile):
"""
If a file is the source code file that we are interested.
"""
tokens = afile.split(".")
if len(tokens) > 1 and tokens[-1] in ("c", "cpp", "pl", "tmpl", "py", "s", "S"):
# we care about C/C++/perl/template/python/assembly source code files
... | 9bd77dc3b530262cc2bf8a32c0d050ea30077030 | 3,656,703 |
import json
import time
import logging
def handle_survey_answers():
"""
Receives form data adds submission to database.
Args:
data (str): From the POST request arguments. Should in JSON form and
have all the quiz response information.
Raises:
AssertionError: When the quiz... | 2abd696e009d95b58671369cdfb9f1449a991474 | 3,656,704 |
def recursively_extract(node, exfun, maxdepth=2):
"""
Transform a html ul/ol tree into a python list tree.
Converts a html node containing ordered and unordered lists and list items
into an object of lists with tree-like structure. Leaves are retrieved by
applying `exfun` function to the html nodes... | cc5732a786579172dda31958ad2bd468a4feef81 | 3,656,705 |
import math
def group_v2_deconv_decoder(latent_tensor,
output_shape,
hy_ncut=1,
group_feats_size=gin.REQUIRED,
lie_alg_init_scale=gin.REQUIRED,
lie_alg_init_type=gin.REQUIRED,
... | c098852a7d3e85be944494de74810e021d7fd106 | 3,656,706 |
import os
import colorsys
def cptfile2dict(filepath):
"""
Extracts a color dictionary and list for a colormap object from a .cpt file
Parameters
----------
filepath: str
filepath of a .cpt file including file extension
Returns
-------
colormap name, list containing all colors... | 8743c2a092b7749aaecbc3a5f6f815e74dd489df | 3,656,707 |
def UncertaintyLossNet():
"""Creates Uncertainty weighted loss model https://arxiv.org/abs/1705.07115
"""
l1 = layers.Input(shape=())
l2 = layers.Input(shape=())
loss = UncertaintyWeightedLoss()([l1, l2])
model = Model(inputs=[l1, l2], outputs=loss)
return model | 5a6553edc321a6e307848e261692541cedea4ebb | 3,656,708 |
from typing import Iterable
import logging
from pathlib import Path
def inject_signals(
frame_files: Iterable[str],
channels: [str],
ifos: [str],
prior_file: str,
n_samples: int,
outdir: str,
fmin: float = 20,
waveform_duration: float = 8,
snr_range: Iterable[float] = [25, 50],
):
... | 204aca5dee78e885191907890fc064503ff61f57 | 3,656,709 |
async def lyric(id: int, endpoint: NeteaseEndpoint = Depends(requestClient)):
"""
## Name: `lyric`
> 歌词
---
### Required:
- ***int*** **`id`**
- Description: 单曲ID
"""
return await endpoint.lyric(id=id) | 331c0bced7bbd2523426522286a85f3cc6a3a29f | 3,656,710 |
def get_body(m):
"""extract the plain text body. return the body"""
if m.is_multipart():
body = m.get_body(preferencelist=('plain',)).get_payload(decode=True)
else:
body = m.get_payload(decode=True)
if isinstance(body, bytes):
return body.decode()
else:
return body | 7980c1471a0a09c793cb8124066a97caac21ae0d | 3,656,711 |
import os
def get_image(img_path, ch=3, scale=None, tile_size=None, interpolate=cv2.INTER_AREA):
"""
Loads image data into standard Numpy array
Reads image and reverses channel order.
Loads image as 8 bit (regardless of original depth)
Parameters
------
img_path: str
Image file pa... | 2d34bb64762c2c478eed71caab02d4b39dfc28ce | 3,656,712 |
def density(mass, volume):
"""
Calculate density.
"""
return mass / volume * 1 | 53b1f76ba66695a9cd72be9186bcc374ee11f53b | 3,656,713 |
import sys
def _is_global(obj, name=None):
"""Determine if obj can be pickled as attribute of a file-backed module"""
if name is None:
name = getattr(obj, '__qualname__', None)
if name is None:
name = getattr(obj, '__name__', None)
module_name = _whichmodule(obj, name)
if module_... | b0846e156c1d9201e75d6e38d37bdb49b8ee9bfd | 3,656,714 |
from typing import Union
from typing import Callable
import torch
def get_augmenter(augmenter_type: str,
image_size: ImageSizeType,
dataset_mean: DatasetStatType,
dataset_std: DatasetStatType,
padding: PaddingInputType = 1. / 8.,
... | 7b065d9bd7c9bc2cf3c0aa2fdf105c714df24705 | 3,656,715 |
def query(limit=None, username=None, ids=None, user=None):
"""# Retrieve Workspaces
Receive a generator of Workspace objects previously created in the Stark Bank API.
If no filters are passed and the user is an Organization, all of the Organization Workspaces
will be retrieved.
## Parameters (option... | bc22336c7c76d549144e43b6d6c46793b1feedf9 | 3,656,716 |
def _add_output_tensor_nodes(net, preprocess_tensors, output_collection_name='inferece_op'):
"""
Adds output nodes for all preprocess_tensors.
:param preprocess_tensors: a dictionary containing the all predictions;
:param output_collection_name: Name of collection to add output tensors to.
:return: ... | cdbb2b69a795bcc74925cce138e9d73bc4737276 | 3,656,717 |
def f_prob(times, lats, lons, members):
"""Probabilistic forecast containing also a member dimension."""
data = np.random.rand(len(members), len(times), len(lats), len(lons))
return xr.DataArray(
data,
coords=[members, times, lats, lons],
dims=["member", "time", "lat", "lon"],
... | 43fe73abb5667b0d29f36a4ee73e8d8ec1943ad0 | 3,656,718 |
def dunning_total_by_corpus(m_corpus, f_corpus):
"""
Goes through two corpora, e.g. corpus of male authors and corpus of female authors
runs dunning_individual on all words that are in BOTH corpora
returns sorted dictionary of words and their dunning scores
shows top 10 and lowest 10 words
:par... | 324b0bb5e5f83451ca47cefed908cdd6dbc47c33 | 3,656,719 |
import os
import warnings
def get_apikey() -> str:
"""
Read and return the value of the environment variable ``LS_API_KEY``.
:return: The string value of the environment variable or an empty string
if no such variable could be found.
"""
api_key = os.environ.get("LS_API_KEY")
if api_k... | b88a6c0ac8e11add97abd1d7415126f75f50696d | 3,656,720 |
import uuid
import os
def test_pdf():
"""
测试pdf报表输出
:return:
"""
res = ResMsg()
report_path = current_app.config.get("REPORT_PATH", "./report")
file_name = "{}.pdf".format(uuid.uuid4().hex)
path = os.path.join(report_path, file_name)
path = pdf_write(path)
path = path.lstrip(".... | f5bba395c5899d34bbd422d403970f320d8e4843 | 3,656,721 |
import inspect
def vprint(*args, apply=print, **kwargs):
"""
Prints the variable name, its type and value.
::
vprint(5 + 5, sum([1,2]))
> 5 + 5 (<class 'int'>):
10
sum([1,2]) (<class 'int'>):
3
"""
def printarg(_name, _val) -> str:
_stri... | 759320b427ee26bded41a86e46ec6ce72cbfcf7a | 3,656,722 |
from typing import Optional
from typing import Callable
def get_int(prompt: Optional[str] = None,
min_value: Optional[int] = None,
max_value: Optional[int] = None,
condition: Optional[Callable[[int], bool]] = None,
default: Optional[int] = None) -> int:
"""Gets an i... | c6ea07b495330c74bd36523cf12dd3e208926ea5 | 3,656,723 |
def make_stream_callback(observer, raw, frame_size, start, stop):
"""
Builds a callback function for stream plying. The observer is an object
which implements methods 'observer.set_playing_region(b,e)' and
'observer.set_playing_end(e)'. raw is the wave data in a str object.
frame_size is the number of by... | c29f7998f848c51af57e42c92a62f80c7a0c2e70 | 3,656,724 |
import torch
def predictCNN(segments, artifacts, device:torch.device = torch.device("cpu")):
"""
Perform model predictions on unseen data
:param segments: list of segments (paragraphs)
:param artifacts: run artifacts to evaluate
:param device: torch device
:return category predictions
"""
... | 27ebdccaecd675104c670c1839daf634c142c640 | 3,656,725 |
import re
def transform_url(url):
"""Normalizes url to 'git@github.com:{username}/{repo}' and also
returns username and repository's name."""
username, repo = re.search(r'[/:](?P<username>[A-Za-z0-9-]+)/(?P<repo>[^/]*)', url).groups()
if url.startswith('git@'):
return url, username, repo
r... | 8d6e7d903d7c68d2f4fb3927bd7a02128cc09caf | 3,656,726 |
from typing import Optional
def prettyprint(data: dict, command: str, modifier: Optional[str] = '') -> str:
"""
Prettyprint the JSON data we get back from the API
"""
output = ''
# A few commands need a little special treatment
if command == 'job':
command = 'jobs'
if 'data' in ... | 727a59b22b2624fec56e685cc3b84f065bbfeffd | 3,656,727 |
def kmor(X: np.array, k: int, y: float = 3, nc0: float = 0.1, max_iteration: int = 100, gamma: float = 10 ** -6):
"""K-means clustering with outlier removal
Parameters
----------
X
Your data.
k
Number of clusters.
y
Parameter for outlier detection. Increase this to make ... | 5ffa55d45d615586971b1ec502981f1a7ab27cbe | 3,656,728 |
import tempfile
from shutil import copyfile
import importlib
import os
def compile_pipeline(pipeline_source: str, pipeline_name: str) -> str:
"""Read in the generated python script and compile it to a KFP package."""
# create a tmp folder
tmp_dir = tempfile.mkdtemp()
# copy generated script to temp di... | e17c7c8aea9ba8d1ec46c3ecde0a3d2cad92ff45 | 3,656,729 |
def turnout_div(turnout_main, servo, gpo_provider):
"""Create a turnout set to the diverging route"""
turnout_main.set_route(True)
# Check that the route was set to the diverging route
assert(servo.get_angle() == ANGLE_DIV)
assert(gpo_provider.is_enabled())
return turnout_main | 542a747cc7f4cdc78b7ad046b0c4ce4a0a3cd33d | 3,656,730 |
def num_jewels(J: str, S: str) -> int:
"""
Time complexity: O(n + m)
Space complexity: O(n)
"""
jewels = set(J)
return sum(stone in jewels for stone in S) | f1a9632a791e3ef94699b566da61e27d9dc46b07 | 3,656,731 |
import socket
def internet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
logger.info(... | 773f490baec40bf548ed2f13d1d1094c78b33366 | 3,656,732 |
import logging
def map_family_situation(code):
"""Maps French family situation"""
status = FamilySituation
mapping = {
"M": status.MARRIED.value,
"C": status.SINGLE.value,
"V": status.WIDOWED.value,
"D": status.DIVORCED.value,
"O": status.PACSED.value,
}
if ... | ae5ac0c9ffadb31d25825e65fcb81d6ea9b0115f | 3,656,733 |
def transform(x, channels, img_shape, kernel_size=7, threshold=1e-4):
"""
----------
X : WRITEME
data with axis [b, 0, 1, c]
"""
for i in channels:
assert isinstance(i, int)
assert i >= 0 and i <= x.shape[3]
x[:, :, :, i] = lecun_lcn(x[:, :, :, i],
... | c66725795585ea26dc9622ce42133a4a2f1445a8 | 3,656,734 |
import functools
def delete_files(files=[]):
"""This decorator deletes files before and after a function.
This is very useful for installation procedures.
"""
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(self, *args, **kwargs):
# Inside the de... | 09652e9dd527b6ae43cf47deb2eaf460de51552e | 3,656,735 |
import os
def get_town_table(screenshot_dir):
"""Generate python code for town table
Its format is
table[town_name] = (nearby town1, nearby town2...nearby town5)
The length of tuple may be different depends on town.
Arguments:
screenshot_dir (str): Directory which have town_name dir... | b6e1c9591cc0531fe9a28b7ce5fec5e5cc231849 | 3,656,736 |
def add_note(front, back, tag, model, deck, note_id=None):
"""
Add note with `front` and `back` to `deck` using `model`.
If `deck` doesn't exist, it is created.
If `model` doesn't exist, nothing is done.
If `note_id` is passed, it is used as the note_id
"""
model = mw.col.models.byName(model... | e45528705dbd658dcb708259043f4a4b590e884b | 3,656,737 |
def indices_to_one_hot(data, nb_classes): #separate: embedding
"""Convert an iterable of indices to one-hot encoded labels."""
targets = np.array(data).reshape(-1)
return np.eye(nb_classes)[targets] | 36fdf0dbad51ae6d64c1a6bf783f083013686e40 | 3,656,738 |
from rdkit.Chem import rdMolTransforms
def translateToceroZcoord(moleculeRDkit):
"""
Translate the molecule to put the first atom in the origin of the coordinates
Parameters
----------
moleculeRDkit : RDkit molecule
An RDkit molecule
Returns
-------
List
List with the... | cbe17cf023791517c01b0e52c11dde65532ab6d0 | 3,656,739 |
def standardize(mri):
"""
Standardize mean and standard deviation of each channel and z_dimension slice to mean 0 and standard
deviation 1.
Note: setting the type of the input mri to np.float16 beforehand causes issues, set it afterwards.
Args:
mri (np.array): input mri, shape (dim_x, dim... | 9c0847d1618023d83cdec48a1c43aae6efc1116f | 3,656,740 |
def current_floquet_kets(eigensystem, time):
"""
Get the Floquet basis kets at a given time. These are the
|psi_j(t)> = exp(-i energy[j] t) |phi_j(t)>,
using the notation in Marcel's thesis, equation (1.13).
"""
weights = np.exp(time * eigensystem.abstract_ket_coefficients)
weights = we... | 60fdb845fc026bf3a109f05945b251a224b12092 | 3,656,741 |
def summary():
""" DB summary stats """
cur = get_cur()
res = []
try:
cur.execute('select count(study_id) as num_studies from study')
res = cur.fetchone()
except:
dbh.rollback()
finally:
cur.close()
if res:
return Summary(num_studies=res['num_studies... | e0159452df1909626d523896f1c2735fb4fc3e75 | 3,656,742 |
import time
def get_clockwork_conformations(molobj, torsions, resolution,
atoms=None,
debug=False,
timings=False):
"""
Get all conformation for specific cost
cost defined from torsions and resolution
"""
n_torsions = len(torsions)
if atoms is None:
atoms, xyz = cheminfo... | 2d501adc974af4acf4dc5dd49879a9a8c72d2b22 | 3,656,743 |
def rotate_affine(img, rot=None):
"""Rewrite the affine of a spatial image."""
if rot is None:
return img
img = nb.as_closest_canonical(img)
affine = np.eye(4)
affine[:3] = rot @ img.affine[:3]
return img.__class__(img.dataobj, affine, img.header) | 4a06c286dcfc0832558c74f2cbce54d6e8d7a2d4 | 3,656,744 |
import math
def validate_ttl(options):
"""
Check with Vault if the ttl is valid.
:param options: Lemur option dictionary
:return: 1. Boolean if the ttl is valid or not.
2. the ttl in hours.
"""
if 'validity_end' in options and 'validity_start' in options:
ttl = math.floor(... | 83d7d323ae4b3db28f41879f630982d24515fcb1 | 3,656,745 |
from typing import Any
def vgg16(pretrained:bool=False,progress:bool=True,**kwargs:Any) ->VGG:
"""
Args:
pretrained(bool):是否加载预训练参数
progress(bool):是否显示下载数据的进度条
Return:
返回VGG模型
"""
return _vgg("vgg16","D",False,pretrained,progress,**kwargs) | 82d64394a705caa9e0a0c1e661078c9ea299fa05 | 3,656,746 |
def cy_gate(N=None, control=0, target=1):
"""Controlled Y gate.
Returns
-------
result : :class:`qutip.Qobj`
Quantum object for operator describing the rotation.
"""
if (control == 1 and target == 0) and N is None:
N = 2
if N is not None:
return gate_expand_2toN(cy... | 8927557d0afe096218acf1ac0283c5ec073e3f98 | 3,656,747 |
def sqf(f, *gens, **args):
"""
Compute square-free factorization of ``f``.
**Examples**
>>> from sympy import sqf
>>> from sympy.abc import x
>>> sqf(2*x**5 + 16*x**4 + 50*x**3 + 76*x**2 + 56*x + 16)
2*(1 + x)**2*(2 + x)**3
"""
return _generic_factor(f, gens, args, method='sqf') | 5f0267b7c314269e64c32951824346542e3e3452 | 3,656,748 |
def update_options_dpd2(dpd1_val):
"""
Updates the contents of the second dropdown menu based of the value of the first dropdown.
:param dpd1_val: str, first dropdown value
:return: list of dictionaries, labels and values
"""
all_options = [
strings.CITY_GDANSK,
strings.CITY_GDY... | 4a2d0494f04e3026b133f61a70757046f011b5f1 | 3,656,749 |
import csv
def compute_min_paths_from_monitors(csv_file_path, delimiter='\t', origin_as=PEERING_ORIGIN):
"""
Inputs: csv_file_path, delimiter : csv file containing entries with the following format:
|collector|monitor|as_path, and the delimiter used
origin_as: the ASN you want to u... | 6f0c1e26062213ea14af80a803c6e6ebd25c6543 | 3,656,750 |
def _blanking_rule_ftld_or3a(rule):
""" See _blanking_rule_ftld_or2a for rules """
if rule == 'Blank if Question 1 FTDIDIAG = 0 (No)':
return lambda packet: packet['FTDIDIAG'] == 0
elif rule == 'Blank if Question 3 FTDFDGPE = 0 (No)':
return lambda packet: packet['FTDFDGPE'] == 0
elif ru... | cc0a925c7ad6ad72c4041d369f9a820c0a6a6b96 | 3,656,751 |
def _fix_nested_array(func_ir):
"""Look for assignment like: a[..] = b, where both a and b are numpy arrays, and
try to eliminate array b by expanding a with an extra dimension.
"""
"""
cfg = compute_cfg_from_blocks(func_ir.blocks)
all_loops = list(cfg.loops().values())
def find_nest_level(l... | e60c1ad0259f26f2e50fb36c9d239a8bb900686f | 3,656,752 |
def compute_angular_differences(matrix, orientation1, orientation2, cutoff):
""" Compute angular difference between two orientation ndarrays
:param matrix: domain matrix
:type matrix: np.ndarray
:param orientation1: orientation as (x, y, z, 3)
:type orientation1: np.ndarray
... | 3ec860c484057de91eb306079328faff87a9b0e4 | 3,656,753 |
def await(*args):
"""Runs all the tasks specified in args,
and finally returns args unwrapped.
"""
return _await(args) | 1065986a6ac067222bf5c6ff47a395ab4d0c890e | 3,656,754 |
def convert_action_move_exists(action, board, player_turn):
"""
Converts action index to chess.Move object.
Assume the action key exists in map_action_uci
:param action:
:param board:
:param player_turn:
:return:
"""
move = chess.Move.from_uci(map_action_uci[action])
if player_t... | f4c508a99967d65b6f2f07159fe3003730b220a2 | 3,656,755 |
import os
import re
def find_phase_files(input_filePath, run_number=1):
"""
Returns a list of the phase space files, sorted by z position
(filemname , z_approx)
"""
path, infile = os.path.split(input_filePath)
prefix = infile.split('.')[0] # Astra uses inputfile to name output
phas... | 16f2ec29468e82f27f87de5a8323fc70effe3af7 | 3,656,756 |
import pwd
import win32api
def _get_system_username():
"""Return the current system user."""
if not win32:
return pwd.getpwuid(getuid())[0]
else:
return win32api.GetUserName() | 4dfdc93630d2c3940c7087fc2125f81f0e385d9f | 3,656,757 |
import glob
def _get_vmedia_device():
"""Finds the device filename of the virtual media device using sysfs.
:returns: a string containing the filename of the virtual media device
"""
sysfs_device_models = glob.glob("/sys/class/block/*/device/model")
vmedia_device_model = "virtual media"
for m... | e8f8e83b7bf0c73d10d8893a5b4b49670edba7ac | 3,656,758 |
def convert_to_posixpath(file_path):
"""Converts a Windows style filepath to posixpath format. If the operating
system is not Windows, this function does nothing.
Args:
file_path: str. The path to be converted.
Returns:
str. Returns a posixpath version of the file path.
"""
if ... | 9a8e6559b7916ba7547f87ce3bba6b50362c7ded | 3,656,759 |
def generateCards(numberOfSymb):
"""
Generates a list of cards which are themselves a list of symbols needed on each card to respect the rules of Dobble.
This algorithm was taken from the french Wikipedia page of "Dobble".
https://fr.wikipedia.org/wiki/Dobble
:param numberOfSymb: Number of symbols needed on each c... | 8f51c1f339d62b6fd88cb8d0fae692053bffc084 | 3,656,760 |
import os
def get_metadata(tmpdirname):
"""
Get metadata from kmp.json if it exists.
If it does not exist then will return get_and_convert_infdata
Args:
inputfile (str): path to kmp file
tmpdirname(str): temp directory to extract kmp
Returns:
list[5]: info, system, option... | 7096b2a67fddaa1774fe0e552af7d9d790c66d15 | 3,656,761 |
def match_facilities(facility_datasets,
authoritative_dataset,
manual_matches_df=None,
max_distance=150,
nearest_n=10,
meters_crs='epsg:5070',
reducer_fn=None):
"""Matches facilities. The da... | 97f169ccda8cf0b26bfa423936d8b663e6237d22 | 3,656,762 |
def has_field_warning(meta, field_id):
"""Warn if dataset has existing field with same id."""
if meta.has_field(field_id):
print(
"WARN: Field '%s' is already present in dataset, not overwriting."
% field_id
)
print("WARN: Use '--replace' flag to overwrite existin... | 1cc5016f8ffcce698bcb53dcf6f307b760d7df55 | 3,656,763 |
def volume(surface):
"""Compute volume of a closed triangulated surface mesh."""
properties = vtk.vtkMassProperties()
properties.SetInput(surface)
properties.Update()
return properties.GetVolume() | 1969e3c6245cd76c50cdea19be41165ff16f73fc | 3,656,764 |
def simulate():
"""
Simulate one thing
"""
doors = getRandomDoorArray()
pickedDoor = chooseDoor()
goatDoor, switchDoor = openGoatDoor(pickedDoor, doors)
return doors[pickedDoor], doors[switchDoor] | 607fc6d0bdb5d24dc68c371c81e9e7028a54631f | 3,656,765 |
def fc_layer(x):
"""Basic Fully Connected (FC) layer with an activation function."""
return x | f26865e13065187363746b8bfe7d95ac221bf236 | 3,656,766 |
from typing import Dict
import collections
def get_slot_counts(cls: type) -> Dict[str, int]:
"""
Collects all of the given class's ``__slots__``, returning a
dict of the form ``{slot_name: count}``.
:param cls: The class whose slots to collect
:return: A :class:`collections.Counter` counting the ... | 7cb7c41c1d4f40aab1acd473f5e1238e4aefad44 | 3,656,767 |
def rot6d_to_axisAngle(x):
""""Convert 6d rotation representation to axis angle
Input:
(B,6) Batch of 6-D rotation representations
Output:
(B,3) Batch of corresponding axis angle
"""
rotMat = rot6d_to_rotmat(x)
return rotationMatrix_to_axisAngle(rotMat) | 17b24e0bb7521baa56df034c4e59658d4320c4cf | 3,656,768 |
import six
def within_tolerance(x, y, tolerance):
"""
Check that |x-y| <= tolerance with appropriate norm.
Args:
x: number or array (np array_like)
y: number or array (np array_like)
tolerance: Number or PercentageString
NOTE: Calculates x - y; may raise an error for incompat... | 918b14e33aeca426e24151d7a1eda2d340423b4d | 3,656,769 |
def hermeint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Hermite_e series.
Returns the Hermite_e series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The sca... | af1f024f4b6d60793fb3aa6ca2bcbe517c4b178f | 3,656,770 |
def model_netradiation(minTair = 0.7,
maxTair = 7.2,
albedoCoefficient = 0.23,
stefanBoltzman = 4.903e-09,
elevation = 0.0,
solarRadiation = 3.0,
vaporPressure = 6.1,
extraSolarRadiation = 11.7):
"""
- Description:
* Title: NetRadi... | 369fffe5eef94148baa8526421adbbac7c3477fd | 3,656,771 |
def get_tagset(sentences, with_prefix):
""" Returns the set of entity types appearing in the list of sentences.
If with_prefix is True, it returns both the B- and I- versions for each
entity found. If False, it merges them (i.e., removes the prefix and only
returns the entity type).
"""
iobs =... | c0b00f7c5546bfc7fe10b2d4b35998b5dedeba21 | 3,656,772 |
def pdb_to_psi4(starting_geom, mol_name, method, basis_set, charge=0, multiplicity=1, symmetry='C1', geom_opt=True,
sp_energy=False, fixed_dih=None, mem=None, constrain='dihedral', dynamic_level=3,
consecutive_backsteps=None, geom_maxiter=250, xyz_traj=True):
"""
:param pdb: str... | ec9fffe05463f159cd47ce2c809f42d5b4289db4 | 3,656,773 |
def normpath(s: str) -> str:
"""Normalize path. Just for compatibility with normal python3."""
return s | 30c528b11f75f52275b753c789e2e3d5bf71641c | 3,656,774 |
def threshold_num_spikes(
sorting,
threshold,
threshold_sign,
sampling_frequency=None,
**kwargs
):
"""
Computes and thresholds the num spikes in the sorted dataset with the given sign and value.
Parameters
----------
sorting: SortingExtractor
The sort... | 37974060e23f8dbde2d3dd1246b0583ed16d4a87 | 3,656,775 |
def mad(stack, axis=0, scale=1.4826):
"""Median absolute deviation,
default is scaled such that +/-MAD covers 50% (between 1/4 and 3/4)
of the standard normal cumulative distribution
"""
stack_abs = np.abs(stack)
med = np.nanmedian(stack_abs, axis=axis)
return scale * np.nanmedian(np.abs(st... | c9425b8006476b11cc559a025597c5b620294b50 | 3,656,776 |
import logging
import time
from typing import Any
import sys
def set_up_logging(
*,
log_filename: str = "log",
verbosity: int = 0,
use_date_logging: bool = False,
) ->logging.Logger:
"""Set up proper logging."""
# log everything verbosely
LOG.setLevel(logging.DEBUG)
l... | 07c7b2623c02d52f8a6468654fa5e3519bf43be9 | 3,656,777 |
def _get_window(append, size=(1000, 600)):
"""
Return a handle to a plot window to use for this plot.
If append is False, create a new plot window, otherwise return
a handle to the given window, or the last created window.
Args:
append (Union[bool, PlotWindow]): If true, return the last
... | 45ff89055db2caa442f55c80042820194554bed8 | 3,656,778 |
def _proxies_dict(proxy):
"""Makes a proxy dict appropriate to pass to requests."""
if not proxy:
return None
return {'http': proxy, 'https': proxy} | ce51015dc652c494dc89bb11e21f18803ba34c85 | 3,656,779 |
def _get_schedule_times(name, date):
"""
Fetch all `from_time` from [Healthcare Schedule Time Slot]
:param name: [Practitioner Schedule]
:param date: [datetime.date]
:return:
"""
mapped_day = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
time_slots = frap... | 64de318f8bbe827e40566799172590f0e448a3d5 | 3,656,780 |
def delete(client, data, force=False):
"""
"""
param = {'logical-router-port-id': get_id(client, data)}
if force:
param['force'] = True
request = client.__getattr__(MODULE).DeleteLogicalRouterPort(**param)
response, _ = request.result()
return response | e573b962273f4ffc0ea4b0d5693329013fca4a6b | 3,656,781 |
import warnings
def z_standardization(
spark,
idf,
list_of_cols="all",
drop_cols=[],
pre_existing_model=False,
model_path="NA",
output_mode="replace",
print_impact=False,
):
"""
Standardization is commonly used in data pre-processing process. z_standardization standardizes the ... | 962a7aa5721cc7d672c858d573af3c1d021e74d7 | 3,656,782 |
def event_stats(wit_df, wit_im, wit_area, pkey='SYSID'):
"""
Compute inundation event stats with given wit wetness, events defined by (start_time, end_time)
and polygon areas
input:
wit_df: wetness computed from wit data
wit_im: inundation event
wit_area:... | f1bcef7604e15fc9b5a845ed45b976e22655d469 | 3,656,783 |
def upvote_book(book_id):
"""
Allows a user to upvote a book.
The upvotes field on the book document is updated,
as well as the booksUpvoted array on the user document
and the upvotedBy array on the book document.
"""
user_to_update = mongo.db.users.find_one({"username": session["user"]})
... | 6a27c46e9540b871f4123c166d9cecaebc016c6b | 3,656,784 |
import numpy
def bottlegrowth_split_mig(params, ns):
"""
params = (nuB, nuF, m, T, Ts)
ns = [n1, n2]
Instantanous size change followed by exponential growth then split with
migration.
nuB: Ratio of population size after instantanous change to ancient
population size
nuF: Ratio o... | dd191a7246d6575b784e61d8e1def17c0f143a7d | 3,656,785 |
def arch_to_macho(arch):
"""Converts an arch string into a macho arch tuple."""
try:
arch = rustcall(lib.symbolic_arch_to_macho, encode_str(arch))
return (arch.cputype, arch.cpusubtype)
except ignore_arch_exc:
pass | 2ffc1be349fc8438bc5b49bab1d9c79e8cbebdd3 | 3,656,786 |
def limit_ops_skeleton(**kwargs):
"""This function provides a skeleton for limit ops calculations"""
group_phase = kwargs['group_phase']
tail = kwargs['tail']
loading_phase = kwargs['loading_phase']
final_phase = kwargs['final_phase']
grouped_df = limit_ops_general_groups(
**group_phase... | fb2dd1da8f2229794705376e15076477160bce35 | 3,656,787 |
def xy2traceset(xpos, ypos, **kwargs):
"""Convert from x,y positions to a trace set.
Parameters
----------
xpos, ypos : array-like
X,Y positions corresponding as [nx,Ntrace] arrays.
invvar : array-like, optional
Inverse variances for fitting.
func : :class:`str`, optional
... | 7f4146600678cdb3699b239bf49a5d6062ef2a2e | 3,656,788 |
import inspect
def Fn(name, f, n_out=1): # pylint: disable=invalid-name
"""Returns a layer with no weights that applies the function `f`.
`f` can take and return any number of arguments, and takes only positional
arguments -- no default or keyword arguments. It often uses JAX-numpy (`jnp`).
The following, f... | 356753d0a10ee8294d4072f559657b8a032974eb | 3,656,789 |
import slate3k as slate
import logging
def leer_pdf_slate(ubicacion_archivo, password=None):
"""
Utiliza la librería slate3k para cargar un archivo PDF y extraer el texto de sus páginas.
:param ubicacion_archivo: (str). Ubicación del archivo PDF que se desea leer.
:param password: (str). Valor por d... | 3e52c463238f1ecec30d34661eb8f53a6cf031a7 | 3,656,790 |
def gen_run_entry_str(query_id, doc_id, rank, score, run_id):
"""A simple function to generate one run entry.
:param query_id: query id
:param doc_id: document id
:param rank: entry rank
:param score: entry score
:param run_id: run id
"""
return f'{query_id} Q0 {doc_id} {rank}... | 657c59fea34e4aed2159337360c973dc99b53082 | 3,656,791 |
from pathlib import Path
def remove_template(args, output_file_name):
"""
remove the arg to use template; called when you make the template
:param args:
:param output_file_name:
:return:
"""
template_name = ''
dir_name = ''
template_found = False
for i in args:
if i.st... | 652fa0112dd0b5287e1f98c5e70f84cacaa979c1 | 3,656,792 |
def replaceext(filepath, new_ext, *considered_exts):
"""replace extension of filepath with new_ext
filepath: a file path
new_ext: extension the returned filepath should have (e.g ".ext")
considered_exts: Each is a case insensitive extension that should be considered a
single extension and replace... | 4e1abee01270921d01de1e75614612dcec8485d7 | 3,656,793 |
def textarea(name, content="", id=NotGiven, **attrs):
"""Create a text input area.
"""
attrs["name"] = name
_set_id_attr(attrs, id, name)
return HTML.tag("textarea", content, **attrs) | da85bdeb2d819eaa2e8109036087700afd270a21 | 3,656,794 |
import os
def get_score_checkpoint(loss_score):
"""Retrieves the path to a checkpoint file."""
name = "{}{:4f}.pyth".format(_SCORE_NAME_PREFIX, loss_score)
return os.path.join(get_checkpoint_dir(), name) | 65e147968c738a0b893e5fc25bebbdb0d75c52de | 3,656,795 |
def StretchContrast(pixlist, minmin=0, maxmax=0xff):
""" Stretch the current image row to the maximum dynamic range with
minmin mapped to black(0x00) and maxmax mapped to white(0xff) and
all other pixel values stretched accordingly."""
if minmin < 0: minmin = 0 # pixel minimum is 0
if maxm... | 5f511b4a8bd053d503618767fee06597f1688619 | 3,656,796 |
def detection(array, psf, bkg_sigma=1, mode='lpeaks', matched_filter=False,
mask=True, snr_thresh=5, plot=True, debug=False,
full_output=False, verbose=True, save_plot=None, plot_title=None,
angscale=False, pxscale=0.01):
""" Finds blobs in a 2d array. The algorithm is desi... | 13b9024538b9edff362b409328ebd6cdbbf5fd5b | 3,656,797 |
def get_database_uri(application):
""" Returns database URI. Prefer SQLALCHEMY_DATABASE_URI over components."""
if application.config.get('SQLALCHEMY_DATABASE_URI'):
return application.config['SQLALCHEMY_DATABASE_URI']
return '{driver}://{username}:{password}@{host}:{port}/{name}'\
.form... | 6b04a9518798aa3392cdf41667e5edf1fdaa5125 | 3,656,798 |
from typing import OrderedDict
def get_s_vol_single_sma(c: CZSC, di: int = 1, t_seq=(5, 10, 20, 60)) -> OrderedDict:
"""获取倒数第i根K线的成交量单均线信号"""
freq: Freq = c.freq
s = OrderedDict()
k1 = str(freq.value)
k2 = f"倒{di}K成交量"
for t in t_seq:
x1 = Signal(k1=k1, k2=k2, k3=f"SMA{t}多空", v1="其他",... | d4453ec1e52ee2c19448855e0011b6ac31d5755b | 3,656,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.