content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
def log(df: pd.DataFrame, columns: List[str]) -> pd.DataFrame:
"""Apply log-transformation to numerical columns.
By defintion of the log operation, no negative values are supported.
A 1 is added to all values to make the transform work for 0 values as well.
"""
df[columns]... | bf0bccc83f3fd084a58072fb3545d933ab8c8130 | 3,609,300 |
def Pearson(endog, exdog):
"""
The def calculates the Pearson coefficient
:param endog: The dependent variable. DataFrame
:param exdog: The independent variable. Series
:return: pearson; Pearson coefficient
"""
pearson = exdog.corrwith(endog)
return pearson | cbb1e36c91cd969758b0d456d627fcb6798353de | 3,609,301 |
def gaussfitfun2D(fitparam, dummy, image):
"""
Calculate residuals of 2D Gaussian fit of 2D data
========== ===============================================================
Input Meaning
---------- ---------------------------------------------------------------
fitparam Vector with ini... | 870b34ff2d542c92ad4740c9fd2763a90dc94528 | 3,609,302 |
def test():
"""
UCI_HOUSING test set creator.
It returns a reader creator, each sample in the reader is features after
normalization and price number.
:return: Test reader creator
:rtype: callable
"""
global UCI_TEST_DATA
load_data(paddle.dataset.common.download(URL, 'uci_housing',... | 8eb79d335b4559ac151fb711b251e64135d80fe9 | 3,609,303 |
def destos_to_binfmt(key):
"""
Returns the binary format based on the unversioned platform name,
and defaults to ``elf`` if nothing is found.
:param key: platform name
:type key: string
:return: string representing the binary format
"""
if key == 'darwin':
return 'mac-o'
elif key in ('win32', 'cygwin', 'uw... | 89e1233f494a80ea4b0dd9ef2053352e462e3b3d | 3,609,304 |
from operator import inv
def _system_mat2d(fmatin, cmat, fmatout):
"""Computes a system matrix from a characteristic matrix Fin-1.C.Fout"""
fmatini = inv(fmatin)
out = bdotdm(fmatini,cmat)
return bdotmd(out,fmatout) | 1038f17962f2d2e0ef8a12340d47b36f31d86000 | 3,609,305 |
def get_status():
"""Show a status of the repository."""
return Command().command(_get_status).require_migration().require_clean() | c5af186f1cd29cb201ba6d62e781d06941327f15 | 3,609,306 |
def infection_rate_symptomatic_80x10():
"""
Real Name: b'infection rate symptomatic 80x10'
Original Eqn: b'Susceptible 10*Infected symptomatic 10x80*contact infectivity symptomatic 10x80*(self quarantine policy SWITCH self 10\\\\ * self quarantine policy 10+(1-self quarantine policy SWITCH self 10))/non con... | d450bf2292ee2cf2bbe134cdac7d2a68eda6f754 | 3,609,307 |
def calculPriority(im, taillecadre, masque, dOmega, normale, data, gradientX, gradientY, confiance):
"""Permet de calculer la priorité du patch"""
C = calculConfiance(confiance, im, taillecadre, masque, dOmega)
D = calculData(dOmega, normale, data, gradientX, gradientY, confiance)
index = 0
maxi = 0... | c714366ed54a199cfdcbb31fbfb17d6d68617b2f | 3,609,308 |
def levenshtein_distance(a: str, b: str):
"""
Calculates Levenshtein distance between two strings using dynamic programming.
Complexity: O(len(a) * len(b))
"""
m = len(a)
n = len(b)
d = np.zeros((m + 1, n + 1), dtype=np.uintc)
for i in range(m + 1):
d[i, 0] = i
for j in range... | 446e18ab093fadda70e22715b2f63eafbc53aae9 | 3,609,309 |
def to_int(s, default=None):
"""Attempts to convert the provided string to an integer.
:param s: The text to convert
:param default: Default value to return if cannot be converted
:returns: The integer if converted, otherwise the default value
"""
try:
return int(s)
except ValueErro... | 9f8214efc65035b433af22e9872cb4fe1e4e1cf7 | 3,609,310 |
def rotation_y(angle: float) -> Mat33:
"""create matrix for rotation around y axis"""
return trimesh.transformations.rotation_matrix(angle, Y_HAT)[0:3, 0:3] | 5a512a6db805dff2c6bc6c5c30c153e72dbd967a | 3,609,311 |
def find_chunks(input_list,key):
"""
Find consecutive chunks in list
will return a list comprimised of dictionaries [{value:number_of_interval},..]
"""
result_list = []
section = {}
input_list = map (lambda x: x[key], input_list) # Flatten list
for key, iter in groupby(input_list): # OH... | b91157e1942a2a6f692c87167e48f82068644441 | 3,609,312 |
from pathlib import Path
async def fetch_entity(
entity_id: str = Path(None, description="ID of the entity to retrieve")
):
"""Retrieve a single entity by its ID. The entity will be returned in
full, with data from all datasets and with nested entities (adjacent
passport, sanction and associated entit... | b48ffc708e263ff2d40afefdf4a2dbb9a2b232bf | 3,609,313 |
def classify_flare(value):
"""Convert GOES X-Ray flux into a string flare classification.
You should use the 1-8 Angstrom band for classification [1]
(B_AVG in the NOAA data files).
A 0.001 W/m**2 measurement in the 1-8 Angstrom band is classified as an X10 flare..
This function currently only wor... | 0b78b06a6676de3f6164b82b8f5800b3ce3df978 | 3,609,314 |
import inspect
import functools
def typeclass(type_variable):
"""Declare a type class of a single method over a single type variable."""
def decorator(default_implementation):
sig = inspect.signature(default_implementation)
names = [
p.name for p in sig.parameters.values()
... | 78d107599b4a40cc1b99015f65a61fcc16580265 | 3,609,315 |
def create_recording(recording_folder_path: str, subject: str) -> Recording:
"""
Returns a recording
Gets a XSens recorind folder path, loops over sensor files, concatenates them, adds activity and subject, returns a recording
"""
raw_recording_frame = XSensRecordingReader.get_recording_frame(
... | cb219895bc131a7356ef522848c10fd696f3457f | 3,609,316 |
def get_first_key(obj, key):
"""Return the value of the first key matching the given key.
Recursively searches the obj.
obj should contain at least one dict. Can be a nested dict or list of dicts
or whatever.
Returns None if not found
"""
if type(obj) is dict and key in obj:
re... | 034069fc0a9d73a78d387d6a78dae1ceea7c87b9 | 3,609,317 |
def make_rawruntimeerrorproblem_for_file(filepath):
"""Constructs a RawRuntimeErrorProblem from the given filepath."""
with open(filepath, 'r') as f:
source = f.read()
target = 0
target_lineno = 0
return process.make_rawruntimeerrorproblem(
source, target, target_lineno=target_lineno) | 94b7210ec0043b457486400aa162e681cf73cb12 | 3,609,318 |
def registerUser():
"""Register a new user in the database at endpoint: "https://cicsoft-web-api.herokuapp.com/user/register"
Request Payload:
{
"first_name": <User's first name>,
"last_name": <User's last name>,
"umass_email": <User's official @umass.edu email addre... | 3326c76e26b94b420670b3edfb7f02d8f526bb7e | 3,609,319 |
def k_means_clustering(data,K):
"""
K-means clustering is an algorithm that take a data set and
a number of clusters K and returns the labels which represents
the clusters of data which are similar to others
Parameters
--------------------
data: array-like, shape= (m_samples,n_samp... | 5ac448435856013680a0c62735763fb7698c6d50 | 3,609,320 |
from typing import Tuple
def filter_phase_delay(
sos: np.ndarray, N: int = 2048, fs: float = None
) -> Tuple[np.ndarray, np.ndarray]:
"""
Given filter spec in second order sections of an IIR filter, return
phase delay in samples, extracted from the phase response
Note for FIR filters, phase delay... | ef0468b194f9a718ac3367339c0f26ddf5889c4c | 3,609,321 |
from typing import Union
from datetime import datetime
def diff_yyyy_mm_dd(a: Union[str, datetime.date], b: Union[str, datetime.date]) -> int:
"""
Returns the amount of days between date A and date B
>>> diff_yyyy_mm_dd("2020-02-01", "2020-03-01")
29
>>> diff_yyyy_mm_dd("2020-02-14T10:20:30", "20... | c4492cd18683b2f41fb520ae5cee3b285497c64e | 3,609,322 |
import types
def get_entityset_ranges(my_core, meshset, geom_dim):
"""
Get a dictionary with MOAB Ranges that are specific to the
types.MBENTITYSET type
inputs
------
my_core : a MOAB Core instance
meshset : the root meshset for the file
geom_dim : the tag that specifically denotes th... | 53c11eecdb6017316e46151b5eeb75e0f5bf2c2a | 3,609,323 |
def select_year_and_fill_gaps(load_df, model_year, acceptable_gap_hours):
"""Selects relevant year then fills in all NaNs with data from other years"""
model_year_missing_data = columns_with_missing_data_in_model_year(
load_df, model_year, acceptable_gap_hours
)
missing_data_countries = set(load... | 5710b4e54519f140ef0819ed1ffd76f95d6f1e8b | 3,609,324 |
from re import T
def index():
""" Module's Home Page """
try:
module_name = deployment_settings.modules[module].name_nice
except:
module_name = T("Person Registry")
def prep(jr):
if jr.representation == "html":
if not jr.id:
jr.method = "search_si... | d3eff879cf1f270794947645d45d807931c2f985 | 3,609,325 |
def CountPixels(image, N_levels):
"""Returns a tupil (pixel count, normalized pixel count)
N_levels: number of intensity levels, N_levels = 2 ** bpp (bits per pixel)
"""
pixel_count = np.zeros((N_levels, 1));
for i in range(N_levels):
pixel_count[i] = np.sum(image == i);
... | f1b10248cc4a341301b68dd73e1a1c9b846b1739 | 3,609,326 |
def duo_auth_enroll_status(integration_key: str, secret_key: str, host: str, user_id: str, activation_code: str) -> dict:
"""
Anonymous enrollment of a new device
:param integration_key: The Duo integration key
:type integration_key: str
:param secret_key: The Duo secret key
:type secret_key: ... | 3402561a55faf15a47db52f0ee08036dc21912c6 | 3,609,327 |
def ascii_to_morse(text):
""" """
code = ""
for letter in text:
code += MORSE_ALPHABET[letter.upper()] + " "
print code
return code | 6e86fe2df7ef2bf37b41bc7b5a8ec69fb7f12b50 | 3,609,328 |
def tablefragment(m,tabname):
"""
main function to transfer the set of numbers/names (=m provided by UpperLimitTable) into a LaTeX table
@param m Set of names/numbers provided by UpperLimitTable.py
@param tabname Table name used as label in LaTeX
"""
tableline = ''
tableline += '''
\\begin{table}
\\... | 5eade6e31b51d3f1d76d41fb8655fedf3bc17a55 | 3,609,329 |
def rigids_from_quataffine(a: quat_affine.QuatAffine) -> Rigids:
"""Converts QuatAffine object to the corresponding Rigids object."""
return Rigids(Rots(a.rotation),
Vecs(a.translation)) | 9d440fd4dfe3d754a51c3d7605cd30744d037313 | 3,609,330 |
def safe_sub(_x: int, _y: int) -> int:
"""Returns the difference of _x minus _y, asserts if the subtraction results in a negative number
:param _x: minuend
:param _y: subtrahend
:return: difference
"""
if _x < _y:
revert("Difference between two numbers should be positive")
return _x... | 63c39965c9657070ecbffc8f79a74e07e04ee92b | 3,609,331 |
def sample_frames_uniformly(x: jnp.ndarray,
n_sampled_frames: int) -> jnp.ndarray:
"""Sample frames from the input video."""
if x.ndim != 5:
raise ValueError('Input shape should be [bs, t, h, w, c].')
num_frames = x.shape[1]
if n_sampled_frames < num_frames:
t_start_idx = num... | 8cbcf1e615b23bf18e1595286776fb6a9575d173 | 3,609,332 |
import os
def read(fname):
"""Utility function to read the README file into the long_description."""
return open(os.path.join(os.path.dirname(__file__), fname)).read() | 82c261e5d7379035ebe9eb6ef0b7c4c6e2c6a4ae | 3,609,333 |
def generate_hierarchical_model_parameters(parameter,
n_subjects,
design,
mu_mean,
mu_sd,
mu_lower,
... | d229010db8853bcadc431a2df7b3664f4f9bd2bc | 3,609,334 |
def semester_view(year, half):
""" Возврат к странице после смены текущего семестра """
session['sem'] = year * 2 + half - 1
next_url = request.args.get('next', url_for('home'))
return redirect(next_url) | d36ec860957f0ea8cdb02d67dedf3fd127d1332f | 3,609,335 |
def im_detect_all(model, im, box_proposals=None, timers=None):
"""Process the outputs of model for testing
Args:
model: the network module
im_data: Pytorch variable. Input batch to the model.
im_info: Pytorch variable. Input batch to the model.
gt_boxes: Pytorch variable. Input batch to ... | cd59b6144a50cf00a3319ca41e7b21b0eed93d46 | 3,609,336 |
import hmac
def getHMAC(key, value):
"""Return the HMAC of **value** using the **key**."""
# normalize inputs to be bytes
key = key.encode('utf-8') if isinstance(key, str) else key
value = value.encode('utf-8') if isinstance(value, str) else value
h = hmac.new(key, value, digestmod=DIGESTMOD)
... | 3e3e1acf3569432140a99bb3baff9abee2b7724e | 3,609,337 |
def ignore_xyr(circles):
"""Change all x and y to 0.0 and r to 1.0
This is useful for those tests whose actual (x, y, r) data can change.
"""
return [circ.Circle(level=c.level, ex=c.ex) for c in circles] | 662e7f87b3bc062afe74af91ec54a1437e3edaaa | 3,609,338 |
def create_model(num_classes, feature_size, bert_config):
"""Creates a BERT classifier model."""
# TODO(jereliu): Point to a locally implemented BERT for v2.
return bert_models.classifier_model(
bert_config=bert_config,
num_labels=num_classes,
max_seq_length=feature_size,
) | c2435f1e1d79479aef098aba30dd6e24214d334a | 3,609,339 |
import scipy
def compute_yvalues_quantiles(gp, xcandidate, M=10):
"""
Quantiles of the gaussian process at xcandidate
"""
ndim = gp.X_train_.shape[1]
if ndim == 1:
xcandidate = np.array(xcandidate).reshape(-1, 1)
else:
xcandidate = np.atleast_2d(xcandidate)
m, s = gp.predic... | d512e2ce00b665918c8f50dd4a54e22224740dbd | 3,609,340 |
def equal_dicts(d1, d2, compare_keys=None, ignore_keys=None):
"""Check whether two dicts are same except for those ignored keys.
"""
assert not (compare_keys and ignore_keys)
if compare_keys == None and ignore_keys == None:
return d1 == d2
elif compare_keys == None and ignore_keys != None:
... | c2d4a3dace8504750ee8003db06abcecdef928b6 | 3,609,341 |
def HandleHttpError(func):
"""Decorator that catches HttpError and raises corresponding HttpException."""
@functools.wraps(func)
def CatchHTTPErrorRaiseHTTPException(*args, **kwargs):
try:
return func(*args, **kwargs)
except apitools_exceptions.HttpError as error:
msg = GetErrorMessage(error)... | 497ef2362efd50aca03f0f1935c70248951e0701 | 3,609,342 |
def softmax_loss(x, y):
"""
Softmax loss function, vectorized version.
y_prediction = argmax(softmax(x))
:param x: (float) a tensor of shape (N, #classes)
:param y: (int) ground truth label, a array of length N
:return: loss - the loss function
dx - the gradient wrt x
"""
... | d64ff40d131091d5a0eb0557ea8c70a4cebf53f5 | 3,609,343 |
def _get_esquinidad(estado):
"""
- Récord: 2048>512
- Corre muy rápido: (13.8 us +- 613 ns) / estado
- Favorece la esquina superior izquierda
"""
esquinidad = 0
m, n = estado.shape
for i in range(m):
for j in range(n - 1):
if estado[i, j] < estado[i, j + 1]:
... | 1b001a7aa74e8ca9ddc2148cd8aeb06bda4d53dc | 3,609,344 |
import logging
def korteriomand_response(json_return: dict, registritunnus: str) -> dict:
""" Modifying the response from korteriomandid WFS
:param json_return: response to look at, will be json format
:param registritunnus: registritunnused to match
:return: dictionary w/ the data added
"""
... | 422c5f3499a9250f783054b1cfb7b584dcf53bc8 | 3,609,345 |
def query_handler():
"""Create query handler test fixture."""
class QueryGetter:
def __init__(self):
self.query_handler = QueryHandler()
def search(self, variation='', disease='', therapy='', gene='',
statement_id='', detail=False):
response = self.qu... | b9ddc541bc2ea87dc3ff778f57346e1d8a2288ed | 3,609,346 |
def update_vurl(request, vid, *args, **kwargs):
"""update_vurl(vid) returns ..."""
s = api.read_vurl(request, vid, *args, **kwargs)
return render_to_response('update/vurl.html', s) | 57184b5d03256313ab3e6e79e9bc67cc16c3046d | 3,609,347 |
from typing import Dict
from typing import Any
def get_json_headers() -> Dict[str, Any]:
"""
Get the headers required to make a request to Spotify's API
"""
token = get_access_token()
headers = {
'Authorization': f'{token["token_type"]} {token["access_token"]}',
'Content-Type': 'ap... | 85224d17fecf29aa54b6ab0cf72655bb6bf86d3e | 3,609,348 |
def parse_Church_HOT201_222_Tricho16S_seq_assoc_v2__xls(spreadsheet_fp):
"""
This spreadsheet has 'net tow' in the cast_num column. These will be changed to '0'.
The cruise_name column has only numbers. 'HOT' will be prepended to them.
The depth column is missing some values. For now use 175.
The co... | 78c4c26d293311a098066090280a7be54e1d96ef | 3,609,349 |
def getPerimeterOfDictWithPolygons(dictionary):
""" getPerimeterOfDictWithPolygons(dictionary)
Getting a dictionary with all polygons inside returns
a new polygon with the perimeter
In process
Parameters
----------
dictionary : Array
List of dictionaries with all coordinates inf... | 0578a00c72f6bcdb47453be97a66e468f4893a51 | 3,609,350 |
def RSI(close, period=14):
"""
Calculates Relative Strength Index.
This indicator measures the magnitude of recent price changes.
Commonly used in technical analysis to evaluate overbought or oversold conditions in the price of a stock.
A stock is considered overbought when the RSI is above 70% and ... | 475e1d9abc8c0880ba02df4c590d4e6979a473c7 | 3,609,351 |
from functools import reduce
def summarize_proposals(datas):
"""
同一とみなせるプロポーザル(トークタイプが異なる)を集約したリストを返す
"""
def f(acr, data):
xs = list(filter(lambda x: is_same_proposal(x, data), acr))
if len(xs) == 0:
data['talk_types'] = [data['talk_type']]
del data['talk_type'... | defb99e83ed88bc4dd6ac90c1317aeae7d412b43 | 3,609,352 |
import numpy
def coord_space(acs, rev=False):
"""Generate transformation matrix to coordinate space defined by 3 points.
New coordinate space will have:
acs[0] on XZ plane
acs[1] origin
acs[2] on +Z axis
:param numpy column array x3 acs: X,Y,Z column input coordinates x3
:par... | 21774226a13e6422f3786412a0beb0460b464a42 | 3,609,353 |
from typing import Tuple
from typing import Optional
from typing import Union
from typing import List
def iplot_gate_map(
backend: IBMQBackend,
figsize: Tuple[Optional[int], Optional[int]] = (None, None),
label_qubits: bool = True,
qubit_size: Optional[float] = None,
line_width... | 3b3c1a459250947214d20ef03c9d0e9524e4aea4 | 3,609,354 |
def get_partitions(num_items, buckets, prefix):
"""
Given a number of items and a number of buckets, return all possible combination of divider locations.
Result is a list of lists, where each sub-list is set of divider locations. Each divider is placed after
the 1-based index provided (or, alternately... | 503d7afcb544e231c00a83ed77adfe95c4283d16 | 3,609,355 |
def split_cfg_comma(s):
"""The simplest and dumbest Context-Free Grammar parser.
Just cares about commas and parenthesis depth."""
elems = [""]
depth = 0
for c in s:
if depth == 0 and c == ",":
elems.append("")
else:
if c == "(":
depth += 1
... | 821033e6acc10618cd5927ae645136d71894ef57 | 3,609,356 |
def read_data(connection, block_number, num_bytes=0x10):
""" Read binary data from a block
"""
apdu = [0xFF, 0xB0, 0x00, block_number, num_bytes]
data, sw1, sw2 = connection.transmit(apdu)
if (sw1, sw2) == SUCCESS_STATUS:
return data
raise NFCError("Failed to read data from block.", "re... | fd746c56d6c8a04f092040dd3e93abf88ac4eab5 | 3,609,357 |
from typing import Mapping
def compare_hashes(
test: Mapping[str, str], reference: Mapping[str, str]
) -> Mapping[str, str]:
"""
Compares two mappings, notionally from object name to hashed value of
object.
Returns a dictionary containing new keys, missing keys, and keys with
mismatched hash ... | be74f69ac6e82be87413cbaaf36ff2a10624468e | 3,609,358 |
from pathlib import Path
def blocking_setup(url: str, dar: "Path") -> "Party":
"""
Set up a ledger for a test in a completely blocking fashion.
Used by the tests that test the thread-safe variants of the dazl API where
avoiding contamination of the current async context is more important than
the... | 788970e30665789905a2184fe3f7925d92516206 | 3,609,359 |
def visualize_latents(X: Tensor, edge: int) -> Image:
"""Visualize sampled points from latent space. It forms image square
lattice of size edge x edge.
:param X: Datapoints sampled from latent space.
:param edge: Number of images along both X and Y axis.
:return: Image object with painted datapoint... | c4718efaef4158f9878bd72aa742d9acf5d7c6a7 | 3,609,360 |
from typing import Tuple
import os
async def make_pipe() -> Tuple[PipeSendStream, PipeReceiveStream]:
"""Makes a new pair of pipes."""
(r, w) = os.pipe()
return PipeSendStream(w), PipeReceiveStream(r) | d60b60ff374f5a3114ce5688172b6035b25b74e1 | 3,609,361 |
def normalize_rate(rate):
"""
Function to change any string 'n/a' values in rate limit information to
None values.
:param rate: dictionary
:return: dictionary
"""
for key in rate.keys():
if rate[key] == "n/a":
rate[key] = None
return rate | 1539cd2059724be8b474d2b81b761164837274c8 | 3,609,362 |
def is_natural(value):
"""
Is the given value a Nat?
:param value: value to check
:type value: Any
:return: True if the value is a Nat, False otherwise
:rtype: bool
"""
return is_int_greater_or_equal_to(0, value) | e18b6143e44445b5b46021981801a05ac77f89f6 | 3,609,363 |
def farthest_point_sample_np(xyz, num_point):
"""
Using FPS to sample N points from a given point cloud.
Input:
xyz: point cloud data, [N, C]
num_point: number of samples
Return:
centroids: sampled point cloud index, [num_points]
"""
N, C = xyz.shape
centroids = np.ze... | abda3dbf285635a87ab3bb60b5cbbb829ca35c52 | 3,609,364 |
def get_redis_pool(redis_conf, redis_sentinel_conf):
"""
@param redis_conf: 针对整个redis配置都更改的情况
@return: redis连接池
"""
if redis_sentinel_conf['use_sentinel']:
redis_sentinel = sentinel.Sentinel(
[(redis_conf['host'], redis_conf['port'])],
socket_timeout=5
)
... | 67b1b8c6e9f156d10571534a04befc00ecf11cbc | 3,609,365 |
def crop(ar, crop_width, copy=False, order='K'):
"""Crop array `ar` by `crop_width` along each dimension.
Parameters
----------
ar : array-like of rank N
Input array.
crop_width : {sequence, int}
Number of values to remove from the edges of each axis.
``((before_1, after_1),`... | a680215a69542887516262ef32ab7fa61ddab168 | 3,609,366 |
from typing import Dict
from typing import List
from typing import Tuple
import json
import pickle
def combine_dataset_datapoints(
dataset_dicts: Dict[str, List[Datapoint]], vg_imid2data: Dict[int, Dict], coco_imid2data: Dict[str, Dict], coco_path: str,
) -> Tuple[Dict[str, List[Datapoint]], Dict[str, List[Datapo... | 2938500e9be10597b4bfcabdfc25ed3b697083e8 | 3,609,367 |
def process_measurements(measurements_raw: pd.DataFrame, pref) -> pd.DataFrame:
"""Process the measurements.
Since the data is already as clean as possible, this function just adds a
prefix to the index.
"""
return check_is_df(measurements_raw.copy().rename(lambda i: f"{pref}_{i}")) | 631ae797d09fc7f8d7c3e8edc7838bd1f79f7cc1 | 3,609,368 |
import re
def parse_tf(constants : dict) -> set:
"""Read user configured variables in variables tf and return the entire set
Args:
constants: config read from config.yml
Returns:
all variables defined in variables.tf
"""
magma_root = constants['magma_root']
tf_root = f'{magma_r... | 814dcde6bb7b84c9898387f1eb8c3c7d82cf117d | 3,609,369 |
def _get_user_me():
"""自身のUserの情報を取得する.
:return: 自身のUserの情報
:rtype: Response
"""
user_uuid = request.oauth.user.uuid
user = User.query.get(user_uuid)
if user is None:
return respond_failure('User not found.', _status=404)
return respond_success(user=user.to_json(True)) | 70fb843cffb6fec5d11fd9dcdc8f31b074527a8d | 3,609,370 |
import io
def text_resource_stream(path, locations, encoding="utf8", errors=None,
newline=None, line_buffering=False):
""" Return a resource from this path or package. Transparently decode the stream. """
stream = binary_resource_stream(path, locations)
return io.TextIOWrapper(stream, ... | 39db9efc38d81857d6c31970d41a29c5247c442d | 3,609,371 |
def fillippone_from_vint_time(
twt, v_int_t, stepDepth, startDepth, endDepth, obp_d, n=1):
"""
Calculate Fillippone Pressure with time domain interval velocity
Parameters
----------
twt : 1-d ndarray
two-way-time
v_int_t : 1-d ndarray
Interval velocity in time domain
... | a8e4cf04c4a9669130e309bef25bef921a995ad5 | 3,609,372 |
import json
def echo_callback(container):
"""
Just respond back with whatever is sent in.
"""
payload = container.payload
logger.debug('echo callback payload: {}'.format(
json.dumps(payload, indent=2))
)
return {
# Respond back to the slash command with the same text
... | acf03332ec782f018fe4b894fffd3f5cd9b2b08d | 3,609,373 |
def _update_sheet_with_totals(worksheet, totals_cell_list, coinbase_account) -> None:
"""
Update the worksheet with totals
"""
# Set cell values with totals
totals_cell_list[0].value = coinbase_account['current_value']
totals_cell_list[1].value = coinbase_account['current_unrealized_gain']
t... | 70f5ec018c3fbc23e645abad7d55fffade0d6dbc | 3,609,374 |
def filterdictvals(D, V):
"""
dict D with entries for valeus V removed.
filterdictvals(dict(a=1, b=2, c=1), 1) => {'b': 2}
"""
return {K: V2 for (K, V2) in D.items() if V2 != V} | 5bfafd8d5c383791b2dd3f792c48cf7a6c16a9de | 3,609,375 |
def extract_ace (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an ACE archive."""
cmdlist = [cmd, 'x']
if not outdir.endswith('/'):
outdir += '/'
cmdlist.extend([archive, outdir])
return cmdlist | f4952f9e484e5f31fbe243318bb875ca668de6b6 | 3,609,376 |
def solve2(wires):
"""
A brute-force O(N**2) solution is fine since O(N**2) is really at most
(10**4)**2 = 10**8, or one-hundred-million comparisons.
"""
result = 0
for w1 in wires:
for w2 in wires:
result += int(w1[0] < w2[0] and w1[1] > w2[1])
return result | 963591c2b41c30a1e6c4817dd61dc0f106730a5b | 3,609,377 |
def parse_regions(text):
"""Return a list of (start, end) tuples."""
_regions = []
region_pairs = text.strip().split(",")
for region_pair in region_pairs:
split_pair = region_pair.split("..")
start = split_pair[0]
end = split_pair[1]
_regions.append([start, end])
retu... | 20a0de9fe4f75fbdc9c8f006d675e53f0b305d62 | 3,609,378 |
def parse_segment(segment: str, model: PhonoModel = model_mipa) -> Segment:
"""
@param segment:
@return:
"""
# TODO: make sure to implement context-specific boundaries (^and $)
if segment in ["#", "^", "$"]:
return BoundarySegment()
# look for negation, if there is one
# TODO: ... | 0fd573d54658e549fc4e827df658ec7cae13d134 | 3,609,379 |
import torch
def val(model, dataloader, use_gpu):
"""val. the CNN model.
Args:
model (nn.model): CNN model.
dataloader (dataloader): val. dataset.
Returns:
tuple(int, in): average of image acc. and digit acc..
"""
model.eval() # turn model to eval. mode(enable droupout la... | cc5dce7bae443d475f0271cf9b1b8caa6b3a58cd | 3,609,380 |
import inspect
def _automatic_refresh2(
_mapper: Mapper,
connection: Connection,
target: PeriodicTask,
) -> None:
"""Log task changed."""
def is_changed() -> bool:
for name, attr in inspect(target).attrs.items():
history = attr.history
if name not in ['... | f8e74cd2088b06a5ad482626c410be9d1769d8e4 | 3,609,381 |
def write_oriented_bbox(scene_bbox, out_filename):
"""Export oriented (around Z axis) scene bbox to meshes
Args:
scene_bbox: (N x 7 numpy array): xyz pos of center and 3 lengths (dx,dy,dz)
and heading angle around Z axis.
Y forward, X right, Z upward. heading angle of positive X ... | 43891a1b4c50532fd225e4fddf5c504326d68f15 | 3,609,382 |
import json
def predictSegment(segment, run_id):
"""
Utility func to classify a segment into cats
:param segment: a sequence of text
:param run_id: MLFlow run to use
:return prediction
"""
# Load artifacts from the run and predict
artifacts = loadRunArtifacts(run_id=run_id)
predict... | 54b61b4e96dae399d7f2bc0f428b679e64f43bc3 | 3,609,383 |
from typing import Sequence
from typing import List
def extend_predictions(preds:Sequence, classes:List[str], extended_classes:List[str]) -> np.ndarray:
""" finished, checked,
extend the prediction arrays to prediction arrays in larger range of classes
Parameters:
-----------
preds: sequence,
... | 8b138c7e8bad86afe04fd4a535ba181f80cb01fc | 3,609,384 |
from pathlib import Path
def _replace_relative_links(regex: tp.Match[str]) -> str:
"""Converts relative links into links to master
so that links on Pypi long description are correct
"""
string: str = regex.group()
link = regex.group("link")
name = regex.group("name")
version = submitit.__v... | e0d3d31e9ddc49917de8fb342b4987461bc34d4b | 3,609,385 |
def get_init_text(poll):
"""Compile the poll creation initialization text."""
locale = poll.user.locale
poll.user.current_poll = poll
poll.user.expected_input = ExpectedInput.name.name
anonymity = i18n.t('creation.no_anonymity', locale=locale)
if poll.anonymous:
anonymity = i18n.t('crea... | 9e1891a2f3340f790db8cf3bf52d7e547e5b8a2a | 3,609,386 |
def make_init(items):
"""Construct the `__init__` function.
partof: #SPC-asts.statements
"""
init = empty_init_ast()
for item in items:
init.body.append(item.init_stmt)
mod_node = Module(body=[init])
return ast_to_func(mod_node, "__init__") | 95edba95b00e49c8048141a5c9fc34c34349392e | 3,609,387 |
import time
def FailureCatch(fail_loop_count, err):
""" A failure has occurred, these happen likely due to API's
request to the database returning bad data
"""
print (TextColors.RED
+ '\n\n'
+ '*********************************\n'
+ '* ERROR *\n'
+ '****************************... | 64de88005ed4182d7c16c05f0d9acb0a8ac35d89 | 3,609,388 |
def validationCurve(X, y, Xval, yval):
"""returns the train
and validation errors (in error_train, error_val)
for different values of lambda. You are given the training set (X,
y) and validation set (Xval, yval).
"""
# Selected values of lambda (you should not change this)
lambda_vec = np.a... | a4f469c7df2335ca7a4352284e27249cd8a9f459 | 3,609,389 |
def conv3d_transpose(
inputs,
num_output_channels,
filter_size,
stride,
padding='SAME',
activation_fn=tf.nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
... | 5f0880d487f0874cb10e55ed170caeaad0293d1a | 3,609,390 |
def handle_already_linked(
media_list: list, offline_types: list = ["Offline", "None"]
) -> list:
"""Remove items from media-list that are already linked to a proxy.
Since re-rendering linked clips is rarely desired behaviour, we remove them without prompting.
If we do want to re-render proxies, we... | 4ccd28c924e5ffcf803c0f4de8f5cb95b9baca40 | 3,609,391 |
def calculate_pn_phase( chirpm,symmratio,delta,chi_a,chi_s,f,i):
"""5 and 6 depend on the given freq."""
M = calculate_totalmass(chirpm,symmratio)
if i == 0:return 1.
elif i == 1: return 0.
elif i == 2: return 3715/756 + 55*symmratio/9
elif i == 3: return -16*np.pi + 113*delta*chi_a/3 + \
(1... | e49f606cf01b9c4fbeafd5b2cc66fc4201b59250 | 3,609,392 |
def structure_to_sequence(structure: Structure) -> str:
"""Convert a Bio.PDB.Structure into a sequence.
Parameters
----------
structure
Bio.PDB.Structure
Returns
-------
Sequence
"""
seq = []
for residue in Selection.unfold_entities(structure, "R"):
aa = seq... | 799af0660fc994c29712a4bee6e03ac48ff8e0bf | 3,609,393 |
def batch_neighbors(queries, supports, q_batches, s_batches, radius):
"""Computes neighbors for a batch of queries and supports.
Args:
queries: (N1, 3) the query points
supports: (N2, 3) the support points
q_batches: (B) the list of lengths of batch elements in queries
s_batches... | 03c5a63050b8b124e2bc54fadece1dd9cdfe54f6 | 3,609,394 |
def empty_szlst(nsingle, noneq=False):
"""
Make an empty list of lists corresponding to different charges and :math:`S_{z}` values.
Parameters
----------
nsingle : int
Number of single particle states.
noneq : bool
If True the list contains None objects.
If False the lis... | 23d5a048fea37877c76175907ca47dcb8480f311 | 3,609,395 |
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that contains
only other hashable types (including any lists, tuples, sets, and
dictionaries).
Based on http://stackoverflow.com/questions/5884066/hashing-a-python-dictionary
"""
return hash(make_hashable(... | a2b3682737e91c73b8e7eb3875498d380d2bf1fe | 3,609,396 |
def available_unionization_info():
""" Lists available attributes for `get_unionization_from_` functions
"""
return _UNIONIZATION_ATTRIBUTES | a7615c93c817531ee2dfd400fd2c78910e9d2cd0 | 3,609,397 |
def ask_yesno(question):
"""
Helper to get yes / no answer from user.
"""
yes = {'yes', 'y'}
no = {'no', 'n', 'q', 'quit'} # pylint: disable=invalid-name
done = False
print(question)
while not done:
choice = input().lower()
if choice in yes:
return True
... | c0e0a5681eeb5eef41692225ba865e606b5995d6 | 3,609,398 |
def word_acf(word, text, timesteps):
"""
Calculate word-autocorrelation function for given word
in a text. Each word in the text corresponds to one "timestep".
"""
acf = np.zeros((timesteps,))
mask = [w==word for w in text]
nwords_chosen = np.sum(mask)
nwords_total = len(text)
for t... | c9e678eedb90e7b956cc0a2df8ee427496217ad2 | 3,609,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.