content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def rn_sub(a, b):
"""
a - b
uses rn_sum and rn_neg to get the difference like a + (-b)
:param a: RN object
:param b: RN object
:return: difference array
"""
return a + (-b)
|
483bdcaab4121139f967057082c362e89409093a
| 680,363 |
def scale_features(X, approach='standard'):
"""Scale feature matrix.
Parameters
----------
X : torch.Tensor
Tensor of shape (n_samples, n_channels, lookback, n_assets). Unscaled
approach : str, {'standard', 'percent'}
How to scale features.
Returns
-------
X_scaled : torch.tensor
Tensor of shape (n_samples, n_channels, lookback, n_assets). Scaled.
"""
n_samples, n_channels, lookback, n_assets = X.shape
if approach == 'standard':
means = X.mean(dim=[2, 3]) # for each sample and each channel a mean is computed (over lookback and assets)
stds = X.std(dim=[2, 3]) + 1e-6 # for each sample and each channel a std is computed (over lookback and assets)
means_rep = means.view(n_samples, n_channels, 1, 1).repeat(1, 1, lookback, n_assets)
stds_rep = stds.view(n_samples, n_channels, 1, 1).repeat(1, 1, lookback, n_assets)
X_scaled = (X - means_rep) / stds_rep
elif approach == 'percent':
X_scaled = X * 100
else:
raise ValueError('Invalid scaling approach {}'.format(approach))
return X_scaled
|
c7e73e5789f9418f5215298da0cee9301e8a0447
| 126,726 |
def isFloat(string):
""" is the given string a float? """
try: float(string)
except ValueError: return 0
else: return 1
|
4605d2975523dab25ec598ee7ed0324c0c200b05
| 677,567 |
import time
def time_strptime(*args, **kwargs):
"""Version of time.strptime that always uses the C locale.
This is because date strings are used internally in the database, and
should not be localized.
"""
return time.strptime(*args, **kwargs)
|
5410a4b4154471834f70818bf2a0a2356bdc25dd
| 29,135 |
def parse_filesize(filesize):
""" Parse a human readable filesize string into a integer.
Only the suffixes 'k' and 'M' are supported. """
try:
if filesize.endswith('k'):
return int(filesize[:-1]) * 1024
if filesize.endswith('M'):
return int(filesize[:-1]) * 1048576
return int(filesize)
except ValueError as error:
# include the original exception
raise ValueError('Invalid size: {}'.format(filesize)) from error
|
9d3a496f07131d0f76fa66d3b5831b7b75555d2d
| 269,988 |
def normalize(img):
"""
Normalize an image array.
Assume the image is stored as an array or matrix of uint8. Since the max
value of uint8 is 255 we use 128 (255 / 2) as the constant in the
formula below.
Args:
img: input image
Returns:
Normalized image
"""
normalized_img = (img - 128) / 128
return normalized_img
|
116519372cb6d083fab056fcb635266fecd1c67d
| 137,904 |
def cmd_limits(targ):
"""
CMD limits for plotting.
zoom1_kw is the top right axis, HB
zoom2_kw is the bottom right axis, MSTO
xlim, ylim is the main axis.
(ylim order doesn't matter, xlim order does)
"""
kw = {'HODGE2': {'xlim': [0., 1.99],
'ylim': [26, 18.5],
'zoom1_kw': {'xlim': [1.29, 1.6],
'ylim': [19.5, 20.67]},
'zoom2_kw': {'xlim': [0.3, 0.74],
'ylim': [19.35, 21.1]}},
'NGC1644': {'xlim': [0., 1.5],
'ylim': [26, 18],
'zoom1_kw': {'xlim': [0.8, 1.2],
'ylim': [19.7, 18.7]},
'zoom2_kw': {'xlim': [0.15, 0.7],
'ylim': [19.5, 21.5]}},
'NGC1718': {'xlim': [0., 1.99],
'ylim': [26, 18.5],
'zoom1_kw': {'xlim': [1.5, 1.9],
'ylim': [20.7, 19.7]},
'zoom2_kw': {'xlim': [0.6, 1.1],
'ylim': [22.23, 20.73]}},
'NGC2203': {'xlim': [0., 1.99],
'ylim': [26, 18.5],
'zoom1_kw': {'xlim': [1.35, 1.62],
'ylim': [19.30, 20.30]},
'zoom2_kw': {'xlim': [0.37, 0.85],
'ylim': [19.87, 21.50]}},
'NGC2213': {'xlim': [0., 1.99],
'ylim': [26, 18.5],
'zoom1_kw': {'xlim': [1.30, 1.62],
'ylim': [20.20, 19.00]},
'zoom2_kw': {'xlim': [0.40, 0.90],
'ylim': [19.80, 21.50]}},
'NGC1795': {'xlim': [0., 1.5],
'ylim': [26, 18],
'zoom1_kw': {'xlim': [0.9, 1.3],
'ylim': [18.30, 20.0]},
'zoom2_kw': {'xlim': [0.25, 0.7],
'ylim': [19.50, 21.50]}}}
return kw[targ]
|
49e37305720aa438f2e62f061d315e2779c3b5fe
| 323,991 |
def train_test_split(filepaths_and_text, train_size):
"""
Split dataset into train & test data
Parameters
----------
filepaths_and_text : list
List of samples
train_size : float
Percentage of entries to use for training (rest used for testing)
Returns
-------
(list, list)
List of train and test samples
"""
train_cutoff = int(len(filepaths_and_text) * train_size)
train_files = filepaths_and_text[:train_cutoff]
test_files = filepaths_and_text[train_cutoff:]
print(f"{len(train_files)} train files, {len(test_files)} test files")
return train_files, test_files
|
5f7007c6c2e46b4863a00369618096918e2dfd24
| 209,255 |
def compute_specificity(cm):
"""
Computes specificity for binary classification problems
:param cm: A Numpy-like matrix that represents a confusion matrix
:return: The specificity of the confusion matrix
"""
print(cm.shape)
print(len(cm.shape))
assert len(cm.shape) and cm.shape[0] == cm.shape[1] and cm.shape[0] == 2
TP = cm[1, 1]
TN = cm[0, 0]
FN = cm[1, 0]
FP = cm[0, 1]
if FP+TN == 0:
return 0
return float(TN)/(FP + TN)
|
4815d74db80be0b953dade3692092634ff7c9b7b
| 118,602 |
import time
def time_helper(seperator = '_', to_sec = False):
"""
return a string like 2020_09_11_22_43_00 (if to_sec is True) or 2020_09_11_22_43 (if to_sec is False)
"""
localtime = time.asctime(time.localtime(time.time()))
if to_sec:
return time.strftime("%Y" + seperator + "%m" + seperator + "%d" + seperator + "%H" + seperator + "%M" + seperator + "%S", time.localtime())
return time.strftime("%Y" + seperator + "%m" + seperator + "%d" + seperator + "%H" + seperator + "%M", time.localtime())
|
eac8b63681fe6ea666aebf5963ed443667421592
| 563,342 |
def sanitize_str(string):
""" Sanitize string to uppercase alpha only """
return filter(str.isalpha, string.upper())
|
e693d61f19ab56103395a798c930a1b9937eafd5
| 693,547 |
def sort_batch_contributions(contributions):
"""Returns the list of contributions sorted by creation date (old -> young)
and score (high -> low).
"""
by_creation = sorted(contributions, key=lambda x: x["created"])
by_score = sorted(by_creation, key=lambda x: x["score"], reverse=True)
return by_score
|
d9cc0125813c158175e58198b64521db613a8e55
| 510,223 |
from typing import List
def serial_order_to_spatial(hole_sequence: List[int],
seq_positions: List[int]) -> List[int]:
"""
Converts a first-phase hole sequence and a list of serial order positions
(at the choice phase) into a list of spatial holes at test.
Args:
hole_sequence: ordered list of spatial hole numbers to be presented
in the first phase of the task, e.g. [3, 1, 4].
seq_positions: list of serial orders, e.g [1, 3] for the first and
third in the sequence.
Returns:
list of spatial hole numbers (e.g. [3, 4] in this example).
"""
return [hole_sequence[i - 1] for i in seq_positions]
|
23a8c158ba0821ea2960091d4b9fa8974f368249
| 620,919 |
def _get_date_from_filename(filename):
""" Returns date (first part of filename) """
return filename.split("/")[-1].split("_")[0]
|
9dd84ef278fbbe48a421a5b708bb09200ef93912
| 661,496 |
import torch
def unbatch(d, ignore=[]):
"""
Convert a dict of batched tensors to a list of tensors per entry. Ignore any
keys in the list.
"""
ignore = set(ignore)
to_unbatch = {}
for k, v in d.items():
# Skip ignored keys.
if k in ignore:
continue
if isinstance(v, torch.Tensor):
# Detach and convert tensors to CPU.
new_v = v.detach().cpu().numpy()
else:
new_v = v
to_unbatch[k] = new_v
# Make sure all entries have same length.
lengths = [len(v) for v in to_unbatch.values()]
if len(set(lengths)) != 1:
raise ValueError("All values must be of same length.")
res = []
for i in range(lengths[0]):
to_append = {}
for k, v in to_unbatch.items():
to_append[k] = v[i]
res.append(to_append)
return res
|
e550883d2260fe6f4794ca28b67c3b16d938c9e2
| 308,386 |
def setdefaults(dct, defaults):
"""Given a target dct and a dict of {key:default value} pairs,
calls setdefault for all of those pairs."""
for key in defaults:
dct.setdefault(key, defaults[key])
return dct
|
fe6c9f2253757369dc12cd8fff087b114f0805b7
| 276,189 |
def parse_im_name(im_name, parse_type='id'):
"""Get the person id or cam from an image name."""
assert parse_type in ('id', 'cam')
if parse_type == 'id':
parsed = int(im_name[:8])
else:
parsed = int(im_name[9:13])
return parsed
|
9b05fc76aa689bda9e0f482bfed6ce2c281d9bbc
| 596,563 |
import json
def get_credentials(credentials_path="credentials.json"):
"""Access database credentials from JSON file
Parameters
----------
credentials_path : str
Location of the credentials JSON file
Returns
-------
credentials : dict
Dictionary containing the database connection details
"""
with open(credentials_path, "r") as f:
credentials = json.load(f)
return credentials
|
9d5c06da334b90691985ab26cf071648600d210f
| 71,636 |
def filter_dictionary(dictionary, field_list):
"""
Takes dictionary and list of elements and returns dictionary with just
elements specified. Also decodes the items to unicode
:param dictionary: the dictionary to filter
:param field_list: list containing keys to keep
:return: dictionary with just keys from list. All values decoded
"""
return_dictionary = {}
for item in dictionary:
if item in field_list:
return_dictionary[item] = dictionary[item]
return return_dictionary
|
40b93742fc04e498865939665363e97cd8ee67b5
| 455,576 |
def get_tile_type(index_i, index_j, tile_arrangement):
"""
Gets the tile type at (`index_i`, `index_j`).
Args:
index_i (int):
Row index.
index_j (int):
Column index.
tile_arrangement (List[List[str]]):
Arrangement of the tiles as a 2D grid.
Returns:
str:
The type of tile, chosen from the list ["Occupied", "Free", "Floor"].
"""
# Validate inputs
if not (0 <= index_i <= len(tile_arrangement) - 1):
raise IndexError
if not (0 <= index_j <= len(tile_arrangement[0]) - 1):
raise IndexError
# Check occupancy
if tile_arrangement[index_i][index_j] == "#":
return "Occupied"
elif tile_arrangement[index_i][index_j] == "L":
return "Free"
else:
return "Floor"
|
025f4524067cce2d99d95ba1e5a131749475c089
| 392,012 |
from typing import OrderedDict
def make_offset_dict(strand):
"""
Helper function for calculating offsets at which chains fall into in a model
:param strand: Model to calculate offsets from, OrderedDict with chain names as keys
:return: Dictionary of offsets
"""
offset_dict = OrderedDict.fromkeys(strand.keys())
temp_length = 0
for chain, items in strand.items():
offset_dict[chain] = temp_length
temp_length += len(items)
return offset_dict
|
8222644ee6bfb28980ac05530cef557439f46532
| 169,017 |
def int_or_float(x):
"""Return `x` as `int` if possible, or as `float` otherwise."""
x = float(x)
if x.is_integer():
return int(x)
return x
|
eacef4f2f88351f0d0a8832afcbebb12be305b26
| 679,662 |
import re
import string
def remove_special_chars(text: str) -> str:
"""
Removes all special characters from a string.
"""
chars = re.escape(string.punctuation)
return re.sub(r"[" + chars + "]", "", text)
|
f73b047ef47ff965aadce56437dd6882c66e07fd
| 140,461 |
def strings_similarity(str1, str2, winkler=True, scaling=0.1):
"""
Find the Jaro-Winkler distance of 2 strings.
https://en.wikipedia.org/wiki/Jaro-Winkler_distance
:param winkler: add winkler adjustment to the Jaro distance
:param scaling: constant scaling factor for how much the score is adjusted
upwards for having common prefixes. Should not exceed 0.25
"""
if str1 == str2:
return 1.0
def num_of_char_matches(s1, len1, s2, len2):
count = 0
transpositions = 0 # number of matching chars w/ different sequence order
limit = int(max(len1, len2) / 2 - 1)
for i in range(len1):
start = i - limit
if start < 0:
start = 0
end = i + limit + 1
if end > len2:
end = len2
index = s2.find(s1[i], start, end)
if index > -1: # found common char
count += 1
if index != i:
transpositions += 1
return count, transpositions
len1 = len(str1)
len2 = len(str2)
num_of_matches, transpositions = num_of_char_matches(str1, len1, str2, len2)
if num_of_matches == 0:
return 0.0
m = float(num_of_matches)
t = transpositions / 2.0
dj = (m / float(len1) + m / float(len2) + (m - t) / m) / 3.0
if winkler:
length = 0
# length of common prefix at the start of the string (max = 4)
max_length = min(
len1,
len2,
4
)
while length < max_length and str1[length] == str2[length]:
length += 1
return dj + (length * scaling * (1.0 - dj))
return dj
|
a4f7a41d5869a1139409ac3dce21ae49b2d3f9d2
| 392,255 |
import re
def rm_brackets(text: str) -> str:
"""
Remove all empty brackets and artifacts within brackets from `text`.
:param str text: text to remove useless brackets
:return: text where all useless brackets are removed
:rtype: str
:Example:
>>> rm_brackets("hey() whats[;] up{*&} man(hey)")
hey whats up man(hey)
"""
# remove empty brackets
new_line = re.sub(r"\(\)", "", text)
new_line = re.sub(r"\{\}", "", new_line)
new_line = re.sub(r"\[\]", "", new_line)
# brakets with only punctuations
new_line = re.sub(r"\([^a-zA-Z0-9ก-๙]+\)", "", new_line)
new_line = re.sub(r"\{[^a-zA-Z0-9ก-๙]+\}", "", new_line)
new_line = re.sub(r"\[[^a-zA-Z0-9ก-๙]+\]", "", new_line)
# artifiacts after (
new_line = re.sub(r"(?<=\()[^a-zA-Z0-9ก-๙]+(?=[a-zA-Z0-9ก-๙])", "", new_line)
new_line = re.sub(r"(?<=\{)[^a-zA-Z0-9ก-๙]+(?=[a-zA-Z0-9ก-๙])", "", new_line)
new_line = re.sub(r"(?<=\[)[^a-zA-Z0-9ก-๙]+(?=[a-zA-Z0-9ก-๙])", "", new_line)
# artifacts before )
new_line = re.sub(r"(?<=[a-zA-Z0-9ก-๙])[^a-zA-Z0-9ก-๙]+(?=\))", "", new_line)
new_line = re.sub(r"(?<=[a-zA-Z0-9ก-๙])[^a-zA-Z0-9ก-๙]+(?=\})", "", new_line)
new_line = re.sub(r"(?<=[a-zA-Z0-9ก-๙])[^a-zA-Z0-9ก-๙]+(?=\])", "", new_line)
return new_line
|
3310e3cc0867f65bc680d6144f82813b469e2c6a
| 440,239 |
def integrate(i, dx):
"""Takes a list of values, i. i is split into n equal intervals of length dx, and contains the
values of an arbitrary function at these points. With this data, this function will approximate
the integral of the function using the trapezoidal rule."""
n = len(i)
sum = i[0]+i[n-1]
for k in range(1,n-1):
sum += 2*i[k]
sum = (dx/2)*sum
return sum
|
6e276f6c8d753c26e96128f5a82cfb512cd84195
| 286,878 |
from typing import Tuple
def parse_pr_url(url: str) -> Tuple[str, int]:
"""Parse the given pull request URL and return its information.
:param str url: the PR URL from Github, formatted as:
https://api.github.com/repos/<account>/<repo>/pulls/<pr_number>
:return: the PR information as (full_repo_name, pr_number)
:rtype: tuple
"""
arr = url.split('/')
full_repo_name = '{}/{}'.format(arr[-4], arr[-3])
pr_num = int(arr[-1])
return full_repo_name, pr_num
|
9ac519e6ba1abcd9a3756e33a8a64669222b397c
| 602,153 |
def readme(root_path):
"""Returns the text content of the README.rst of the package
Parameters
----------
root_path : pathlib.Path
path to the root of the package
"""
with root_path.joinpath('README.rst').open(encoding='UTF-8') as f:
return f.read()
|
4c1fca9ea070e4902b626abc4a751ae13893fa41
| 484,655 |
def is_in_t(pt):
"""Checks if a point is in the template triangle T.
:param pt: The point to be checked.
:type pt: tuple(float,float).
:returns: True if pt is in T.
:rtype: bool.
"""
flag = True
if pt[0] < 0 or pt[1] < 0:
flag = False
if pt[0] + pt[1] > 1:
flag = False
return flag
|
94f1f6baeed3a56d5f28f8cd3ad98a4e51cfdd21
| 223,730 |
from datetime import datetime
def convert_to_date(transaction_date: str):
"""Convert the date-time string(dd/mm/yyyy hh:min_) to date time object"""
if type(transaction_date) == str:
date_, time = transaction_date.split()
dd, mm, yyyy = [int(val) for val in date_.split("/")]
hh, min_ = [int(val) for val in time.split(":")]
return datetime(year=yyyy, month=mm, day=dd, hour=hh, minute=min_)
return transaction_date
|
1f597c20eced07386bd2e936ac95a9d0d110f86d
| 461,054 |
def path2ParentPath(path):
"""
>>> path2ParentPath('/xxx/yyy/zzz/')
'/xxx/yyy/zzz'
>>> path2ParentPath('/xxx/yyy/zzz')
'/xxx/yyy'
>>> path2ParentPath('/xxx/yyy/zzz.gif')
'/xxx/yyy'
"""
return '/'.join(path.split('/')[:-1])
|
cad66ccb11c8d7b7c9ae9117743a8bdd5c39e247
| 327,973 |
def logical_xor(a, b, unsafe=False):
"""logical xor without the bloat of numpy.logical_xor
could be substituted with numpy.logical_xor
!important: if unsafe is set to True, a and b are not checked. This improves speed but is risky.
expects integers [0,1] or bools
"""
if not unsafe:
sum = a*1+b*1
if sum > 2 or sum < 0:
raise Exception(
"The parameters for logical_xor have to be booleans or integers in range [0,1]. got a: " + str(a) + ", b: " + str(b))
return a ^ b
|
bc1981e81412f29fd91b1f5d57405a3d92ac4fa3
| 629,064 |
def to_index(char):
"""
Converts char to class index
:param char: 0-9 =, a-z, A-Z
:return: corresponding class index
"""
if ord(char) < 59:
return ord(char) - 48
elif ord(char) < 95:
return ord(char) - 55
else:
return ord(char) - 61
|
62a5fdb9a164d745dfe813db85d3616f8e306703
| 307,975 |
def _discard_newlines(parm: str, start: int) -> int:
"""Discard any newline characters.
:param parm: The parameter data.
:param start: The start index.
:return: The start index offset to discard any newlines
"""
pos = start
while pos < len(parm):
if parm[pos] not in ("\r", "\n"):
break
pos += 1
return pos
|
658adf55186376380de2ece36d06a97b2711dee6
| 510,140 |
def scheme_false(val):
"""Only False is false in Scheme."""
return val is False
|
aa9c77c53d22b17d925b09a88846ea67ad3107ae
| 578,401 |
from functools import reduce
def get_value_or(dictionary, x_path, default=None):
"""
Try to retrieve a value from a dictionary. Return the default if no such value is found.
"""
keys = x_path.split("/")
return reduce(
lambda d, key: d.get(key, default)
if isinstance(d, dict) else default, keys, dictionary)
|
9679fa8ea18473728348b6213b1d36145e01488a
| 448,037 |
def crop_other_columns(table, required_columns):
"""This function removes the columns that are not in required_columns list
This would help getting rid of columns that are not to be displayed.
Args:
table: Type-pandas.dataframe
required_columns: Type-list of str
Returns:
Returns the table as a dataframe obj after
removing the rest of the columns.
"""
current_columns = table.columns
for column in current_columns:
if column not in required_columns:
table = table.drop([column], axis=1)
return table
|
05e80172a159e51303c58ba70a684875902e1451
| 505,965 |
def makes_false(operator, fact):
"""Returns true iff 'operator' makes 'fact' false"""
return fact in operator.del_effects
|
3f23569945c3370f6cbed92f905dcb38cf72f297
| 300,527 |
def extract_total_individuals_and_the_ones_within_target_for_both_classes(
individuals, target
):
"""
Extract the total number of individuals that pass through the model and the
total number of individuals that exit the model within the given target.
Parameters
----------
individuals : list of ciw.individual.Individual objects
target : float
Returns
-------
int, int, int, int
- The number of class 2 individuals that pass through the model
- The number of class 2 individuals that pass through within the target
- The number of class 1 individuals that pass through the model
- The number of class 1 individuals that pass through within the target
"""
class_2_inds, class_2_inds_within_target = 0, 0
class_1_inds, class_1_inds_within_target = 0, 0
for individual in individuals:
ind_class = len(individual.data_records) - 1
rec = individual.data_records[-1]
if rec.node == 2 and ind_class == 0:
class_1_inds += 1
if rec.waiting_time + rec.service_time < target:
class_1_inds_within_target += 1
elif rec.node == 2 and ind_class == 1:
class_2_inds += 1
if rec.waiting_time + rec.service_time < target:
class_2_inds_within_target += 1
return (
class_2_inds,
class_2_inds_within_target,
class_1_inds,
class_1_inds_within_target,
)
|
e3ed2a5be7f28ad9aec90cd337c68e8f04867b7e
| 219,979 |
import torch
def draw_shape(pos, sigma_x, sigma_y, angle, size):
"""
draw (batched) gaussian with sigma_x, sigma_y on 2d grid
Args:
pos: torch.tensor (float) with shape (2) specifying center of gaussian blob (x: row, y:column)
sigma_x: torch.tensor (float scalar), scaling parameter along x-axis
sigma_y: similar along y-axis
angle: torch.tensor (float scalar) rotation angle in radians
size: int specifying size of image
device: torch.device, either cpu or gpu
Returns:
torch.tensor (1, 1, size, size) with gaussian blob
"""
device = pos.device
assert sigma_x.device == sigma_y.device == angle.device == device, "inputs should be on the same device!"
# create 2d meshgrid
x, y = torch.meshgrid(torch.arange(0, size), torch.arange(0, size))
x, y = x.unsqueeze(0).unsqueeze(0).to(device), y.unsqueeze(0).unsqueeze(0).to(device)
# see https://en.wikipedia.org/wiki/Gaussian_function#Two-dimensional_Gaussian_function
a = torch.cos(angle) ** 2 / (2 * sigma_x ** 2) + torch.sin(angle) ** 2 / (2 * sigma_y ** 2)
b = -torch.sin(2 * angle) / (4 * sigma_x ** 2) + torch.sin(2 * angle) / (4 * sigma_y ** 2)
c = torch.sin(angle) ** 2 / (2 * sigma_x ** 2) + torch.cos(angle) ** 2 / (2 * sigma_y ** 2)
# append dimsensions for broadcasting
pos = pos.view(1, 1, 2, 1, 1)
a, b, c = a.view(1, 1), b.view(1, 1), c.view(1, 1)
# pixel-wise distance from center
xdist = (x - pos[:, :, 0])
ydist = (y - pos[:, :, 1])
# gaussian function
g = torch.exp((-a * xdist ** 2 - 2 * b * xdist * ydist - c * ydist ** 2))
return g
|
4fe11c527ca12f8890c86138021b3cc4eedf8311
| 334,283 |
def post_process_response(token_ids, reader, merge=True):
"""Post-process the decoded sequence.
Truncate from the first <eos> and remove the <bos> and <eos> tokens.
Convert token_ids to words(merge=True) or tokens(merge=False)
Args:
token_ids: Token id sequence.
merge: If true, merge subwords (tokens) into words, otherwise return tokens.
Returns:
token_ids: Truncated token_ids.
response: A word list or a token list.
"""
eos_pos = len(token_ids)
for i, tok_id in enumerate(token_ids):
if tok_id == reader.eos_id:
eos_pos = i
break
token_ids = token_ids[1:eos_pos]
response = reader.tokenizer.convert_ids_to_tokens(token_ids)
if merge:
response = reader.tokenizer.merge_subword(response)
return token_ids, response
|
669ca779442a66a23fb10c053fd1c8c62bd519a6
| 637,038 |
import time
import calendar
def to_timestamp(dt):
"""
Converts a datetime object to a timestamp (seconds since epoch).
:param dt: datetime object (naive or aware)
:returns: timestamp (seconds since epoch)
Native datetime objects will be treated as local time.
.. note::
Epoch is defined as 00:00:00 UTC on 1 January 1970. It is *always* UTC.
"""
if dt.tzinfo is None:
# Treat naive objects as local time.
return time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0
else:
return calendar.timegm(dt.utctimetuple()) + dt.microsecond / 1000000.0
|
49babc122876c32230df7e9e211500ef3d0dafe4
| 518,775 |
def _deduplicate_and_remove_empty_options(zipped):
"""Remove option-bitmap pairs where option is duplicate or empty.
Args:
zipped: list of tuples [(option, bitmap), ...].
Returns:
`zipped` without such elements where `option` is duplicate in the list or
is empty.
"""
stored_options = set()
zipped_unique = []
for (option, bitmap) in zipped:
# remove empty options and duplicate options at once
if option and option not in stored_options:
zipped_unique.append((option, bitmap))
stored_options.add(option)
return zipped_unique
|
277a791c574ab5512aec24323480d514297689cf
| 84,713 |
def skymapweights_keys(self):
"""
Return the list of string names of valid weight attributes. For unpolarized
weights, this list includes only TT. Otherwise, the list includes all six
unique weight attributes in row major order: TT, TQ, TU, QQ, QU, UU.
"""
if self.polarized:
return ['TT', 'TQ', 'TU', 'QQ', 'QU', 'UU']
return ['TT']
|
f7e69f39abfbb35bd12b44a838ce76f3145cdfe7
| 686,834 |
def _flag_awakenings(hypno, thresh):
"""
Mark awakenings as Long or Short depending on threshold in minutes
Parameters
----------
hypno : pd.DataFrame
Hypnogram dataframe obtained through _read_hypno().
thresh : int or float, positive non-zero
Minimum duration in minutes for awakenings to qualify as long.
Returns
-------
hypno : pd.DataFrame
Hypnogram with added columns for type of awakening.
"""
# Sanity checks
assert isinstance(thresh, (int, float)), "Threshold should be a numeric type"
assert thresh > 0, "Threshold should be a positive number (minutes)"
# Seggregate long and short awakenings based on a 2 minute threshold
wake_mask = hypno["Stage"] == "W"
hypno.loc[(wake_mask) & (hypno["Duration"] <= thresh), "Awakening"] = "Short"
hypno.loc[(wake_mask) & (hypno["Duration"] > thresh), "Awakening"] = "Long"
return hypno
|
a270665b50140117c0651b3bf3d8bbbb18725c00
| 90,691 |
import torch
def get_rays_shapenet(hwf, poses):
"""
shapenet camera intrinsics are defined by H, W and focal.
this function can handle multiple camera poses at a time.
Args:
hwf (3,): H, W, focal
poses (N, 4, 4): pose for N number of images
Returns:
rays_o (N, H, W, 3): ray origins
rays_d (N, H, W, 3): ray directions
"""
if poses.ndim == 2:
poses = poses.unsqueeze(dim=0) # if poses has shape (4, 4)
# make it (1, 4, 4)
H, W, focal = hwf
yy, xx = torch.meshgrid(torch.arange(0., H, device=focal.device),
torch.arange(0., W, device=focal.device))
direction = torch.stack([(xx-0.5*W)/focal, -(yy-0.5*H)/focal, -torch.ones_like(xx)], dim=-1) # (H, W, 3)
rays_d = torch.einsum("hwc, nrc -> nhwr", direction, poses[:, :3, :3]) # (N, H, W, 3)
rays_d = rays_d / torch.norm(rays_d, dim=-1, keepdim=True)
rays_o = poses[:, :3, -1] # (N, 3)
rays_o = rays_o[:, None, None, :].expand_as(rays_d) # (N, H, W, 3)
return rays_o, rays_d
|
2e3c25b819753e8e482da49bb33c4d4247a0284a
| 633,071 |
def is_smth_near(profile, v1, rng=2):
"""
Return index of something near if something exists near the target position. Else return None.
:param profile: list(int) - profile
:param v1: int - target place
:param rng: int - how far to search from target
:return: int/None - either a place where we have found something or None
"""
# fill the search space
to_search = [v1]
for i in range(1, rng + 1):
to_search.extend([v1 - i, v1 + i])
# search the search space
for i in to_search:
if 0 <= i < len(profile) and profile[i] != 0:
return i
return None
|
c9f4e4087eca2c893e597f95fccabec7b383149d
| 554,740 |
def fetch_method(name, modules):
""" Get function from list of modules. """
for module in modules:
if hasattr(module, name):
return getattr(module, name)
raise ValueError('Cannot find method ' + name + ' in ' + ', '.join([module.__name__ for module in modules]))
|
8376655e59115bc5d95a0fb32ba54edb52e69188
| 556,643 |
import math
def get_number_format(number_of_pages) -> str:
"""
Get the correct number formatting for pdftoppm's output numbering. E.g. a file with 10-99 pages will have output
images named '01.png, 02.png, 03.png'; a file with 100-999 pages will output '001.png, 002.png, 003.png'. We need
to use the same formatting for reading the images back in (and scanning them)
:param number_of_pages: The total number of pages
:return: A format string (e.g. '{:03}') to use for formatting these page numbers into filenames
"""
formatted_number_length = int(math.log10(number_of_pages)) + 1
return "{:0" + str(formatted_number_length) + "}"
|
db8f3c205e9763566e20c6ae57fbd34cfc04d42f
| 692,167 |
import random
def optimize_order(package_archives):
"""
Shuffle a list of package archives in random order.
Usually when scanning a large group of package archives, it really doesn't
matter in which order we scan them. However the progress reported using
:class:`~humanfriendly.terminal.spinners.Spinner` can be more accurate when
we shuffle the order. Why would that happen? When the following conditions
are met:
1. The package repository contains multiple versions of the same packages;
2. The package repository contains both small and (very) big packages.
If you scan the package archives in usual sorting order you will first hit
a batch of multiple versions of the same small package which can be scanned
very quickly (the progress counter will jump). Then you'll hit a batch of
multiple versions of the same big package and scanning becomes much slower
(the progress counter will hang). Shuffling mostly avoids this effect.
"""
random.shuffle(package_archives)
return package_archives
|
754a132d063721457d7f523788c8a532a799124c
| 545,267 |
def get_bibtex(model_identifier):
"""
A method returning the bibtex reference of the requested model as a string.
"""
return """
@article{https://doi.org/10.48550/arxiv.2203.12601,
doi = {10.48550/ARXIV.2203.12601},
url = {https://arxiv.org/abs/2203.12601},
author = {Nair, Suraj and Rajeswaran, Aravind and Kumar, Vikash and Finn, Chelsea and Gupta, Abhinav},
keywords = {Robotics (cs.RO), Artificial Intelligence (cs.AI), Computer Vision and Pattern Recognition (cs.CV), Machine Learning (cs.LG), FOS: Computer and information sciences, FOS: Computer and information sciences},
title = {R3M: A Universal Visual Representation for Robot Manipulation},
publisher = {arXiv},
year = {2022},
copyright = {arXiv.org perpetual, non-exclusive license}
}"""
|
bb3d4411cdca9dad09f40d19c779f5f87eb7e268
| 218,970 |
def DeserializeAttributesFromJsonDict(json_dict, instance, attributes):
"""Sets a list of |attributes| in |instance| according to their value in
|json_dict|.
Args:
json_dict: (dict) Dict containing values dumped by
SerializeAttributesToJsonDict.
instance: (object) instance to modify.
attributes: ([str]) List of attributes to set.
Raises:
AttributeError if one of the attribute doesn't exist in |instance|.
Returns:
instance
"""
for attr in attributes:
getattr(instance, attr) # To raise AttributeError if attr doesn't exist.
setattr(instance, attr, json_dict[attr])
return instance
|
e89274ccb47a2196303728c9f6d9f6ed5983be8a
| 174,360 |
def is_json(_path) -> bool:
"""Return True if file ends with .json, otherwise False."""
if _path.endswith(".json"):
return True
else:
return False
|
ba2a3ec6b93675dc86d07fbd626fac7c75a14585
| 652,737 |
def remove_object(objs, label, none_val=0):
"""Remove object specified by id value"""
objs[objs==label]=none_val
return True
|
c62df57aebc323f85f318db982cc4de795c30e9a
| 46,822 |
def badge(message: str, badge_template: str) -> str:
"""Create color badge with message using template."""
return badge_template.format(message=message)
|
11fba2049db699ab95e7aa018b9f33d4e452d351
| 550,881 |
def user_unicode(self):
"""Return user's full name."""
return self.get_full_name()
|
409ff8558fa12d9fa375db238bdc4ec970e3037d
| 247,064 |
def get_action_by_name(client, cluster, name):
"""
Get action by name from some object
Args:
client: ADCM client API objects
cluster: cluster object
name: action name
Returns:
(action object): Action object by name
Raises:
:py:class:`ValueError`
If action is not found
"""
action_list = client.cluster.action.list(cluster_id=cluster['id'])
for action in action_list:
if action['name'] == name:
return action
raise ValueError(f"Action with name '{name}' is not found in cluster '{cluster}'")
|
9089b2e5d5b5b131eea0ddd9a16dace9decc5905
| 642,388 |
def count_recursive(contents_per_bag, bag_list):
"""
Count number of nested bags from the given list
:param contents_per_bag: per-bag mapping
:param bag_list: list of bag to inspect
:return: number of bags
"""
nested_bag_qty = 0
for bag in bag_list:
nested_bag_qty += 1
nested_bag_qty += count_recursive(contents_per_bag, contents_per_bag[bag])
return nested_bag_qty
|
d48e317ee73bf0f18021d27bc9857a3ad898759c
| 31,697 |
import yaml
def data_file_read_yaml(filename):
"""
Reads a file as a yaml file. This is used to load data
from fuzz-introspectors compiler plugin output.
"""
with open(filename, 'r') as stream:
try:
data_dict = yaml.safe_load(stream)
return data_dict
except yaml.YAMLError as exc:
return None
|
1ac2aa98d9628aab6637048a8f07f5ffa84aa750
| 650,093 |
import math
def flip_phi(phi):
"""
Correct phi to within the 0 <= to <= 2pi range
:return: phi in >=0 and <=2Pi
"""
Pi = math.pi
if phi < 0:
phi_out = phi + (2 * Pi)
elif phi > (2 * Pi):
phi_out = phi - (2 * Pi)
else:
phi_out = phi
return phi_out
|
5f65525869b46d91ad1c6235eead873866a457ed
| 530,411 |
def get_neighbors(graph, node):
"""Return all neighbors for the given node in the graph
:param graph: The given graph
:type graph: nx.Graph
:param node: The node to analyse
:type node: tuple
:return: List of all neighbors
:rtype: list
"""
return graph.neighbors(node)
|
7fd45eb363fc64ee4f8b66d4505d18770858711a
| 153,773 |
def build_reverse_dictionary(word_to_id):
"""Given a dictionary for converting word to integer id.
Returns a reverse dictionary for converting a id to word.
Parameters
----------
word_to_id : dictionary
mapping words to unique ids
Returns
--------
reverse_dictionary : a dictionary
mapping ids to words
"""
reverse_dictionary = dict(zip(word_to_id.values(), word_to_id.keys()))
return reverse_dictionary
|
e306c09d99ef6a27eec715ddb8585db1a70b9f27
| 354,510 |
def leiaint(inteiro):
"""
--> Função que faz a validação da entrada de dados do tipo inteiro (int)
:param inteiro: Mensagem para entrada de dados do usuário
:return: retorna o valor digitado, caso este tenha sido um número inteiro
:print: Escreve uma mensagem de erro na tela, caso o valor digitado não seja do tipo inteiro
"""
while True:
try:
n = int(input(inteiro))
return n
except (TypeError, ValueError):
print(f'\033[0;31mErro! Digite um número inteiro válido.\033[m')
|
f402e7380ddc5b4dfab17535e5e1823236000a24
| 229,737 |
def linear_regression(x, y):
"""
Calculates a linear regression model for the set of data points.
Args:
x: a 1-d numpy array of length N, representing the x-coordinates of
the N sample points
y: a 1-d numpy array of length N, representing the y-coordinates of
the N sample points
Returns:
(m, b): A tuple containing the slope and y-intercept of the regression line,
both of which are floats.
"""
m = (((x-x.mean())*(y-y.mean())).sum())/((x - x.mean())**2).sum()
b = y.mean() - m*x.mean()
return (m,b)
|
33037a2d57172ff2eb386ed35787cda08eb8f11d
| 692,640 |
def get_bbox(element: dict) -> tuple:
"""Get a bounding box from a manga109 element.
Args:
element (dict): a manga element such as body, face, frame, and text
Returns:
tuple:
a bounding box that comparises four integers -- (xmin, ymin, xmax, ymax)
"""
bbox_attrs = ("@xmin", "@ymin", "@xmax", "@ymax")
xmin, ymin, xmax, ymax = [element[attr] for attr in bbox_attrs]
return (xmin, ymin, xmax, ymax)
|
994e103e22737e11c51c8a0ea9584539ad62c6fb
| 395,919 |
def get_symbol_name(result):
"""Returns the name used by this symbol based on availability"""
if 'longName' in result:
return result['longName']
elif 'shortName' in result:
return result['shortName']
else:
return result['symbol']
|
a45ef6c8feac4cef73470f3b7576e6fc97428cb3
| 86,487 |
def metalicity_nemec(period, phi31_v):
"""
Returns the Nemec formula metalicity of the given RRab RR Lyrae.
The version of the formula used is from Skowron et al. (2016), where I band
phi31 is used, as opposed to the original usage of Kp-passband phi31.
(Nemec et al., 2013) (2)
(Skowron et al., 2016) (5)
Parameters
----------
period : float64
The period of the star.
phi31_v : float64
The V band phi31 of the star.
Returns
-------
metalicity_neme : float64
The Nemec formula metalicity of the star.
"""
return -7.63 - 39.03 * period + 5.71 * phi31_v + 6.27 * phi31_v * period \
- 0.72 * phi31_v ** 2
|
ae9eb84da9be3e6d4610d25ae36ff0b95cd2e6fe
| 451,362 |
import six
def is_str(x):
"""Whether the input is an string instance."""
return isinstance(x, six.string_types)
|
82a0e8ff501cd8264af5feec8e99b0a600cb8cd2
| 191,596 |
def calc_mean_std(feat, eps=1e-5):
"""Calculate mean and std for adaptive_instance_normalization.
Args:
feat (Tensor): 4D tensor.
eps (float): A small value added to the variance to avoid
divide-by-zero. Default: 1e-5.
"""
size = feat.size()
assert len(size) == 4, 'The input feature should be 4D tensor.'
n, c = size[:2]
feat_var = feat.view(n, c, -1).var(dim=2) + eps
feat_std = feat_var.sqrt().view(n, c, 1, 1)
feat_mean = feat.view(n, c, -1).mean(dim=2).view(n, c, 1, 1)
return feat_mean, feat_std
|
a72daff9b7f4a718127eaf0da18e6206797ced27
| 379,108 |
import re
def removePlexShowYear(title):
"""Removes any trailing year specification of the form '(YYYY)' as is often found in Plex show names"""
return re.sub(r'([\s.\-_]\(\d{4}\))$', '', title)
|
8327eab02d7453f8f08371fa273770a45df4bfa8
| 123,173 |
import posixpath
def shift_path_info(environ):
"""Shift a name from PATH_INFO to SCRIPT_NAME, returning it
If there are no remaining path segments in PATH_INFO, return None.
Note: 'environ' is modified in-place; use a copy if you need to keep
the original PATH_INFO or SCRIPT_NAME.
Note: when PATH_INFO is just a '/', this returns '' and appends a trailing
'/' to SCRIPT_NAME, even though empty path segments are normally ignored,
and SCRIPT_NAME doesn't normally end in a '/'. This is intentional
behavior, to ensure that an application can tell the difference between
'/x' and '/x/' when traversing to objects.
"""
path_info = environ.get('PATH_INFO','')
if not path_info:
return None
path_parts = path_info.split('/')
path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p != '.']
name = path_parts[1]
del path_parts[1]
script_name = environ.get('SCRIPT_NAME','')
script_name = posixpath.normpath(script_name+'/'+name)
if script_name.endswith('/'):
script_name = script_name[:-1]
if not name and not script_name.endswith('/'):
script_name += '/'
environ['SCRIPT_NAME'] = script_name
environ['PATH_INFO'] = '/'.join(path_parts)
# Special case: '/.' on PATH_INFO doesn't get stripped,
# because we don't strip the last element of PATH_INFO
# if there's only one path part left. Instead of fixing this
# above, we fix it here so that PATH_INFO gets normalized to
# an empty string in the environ.
if name=='.':
name = None
return name
|
6131be1027cde9e7d1149746e2daad73c79e4e65
| 308,792 |
def prefix(string, string_prefix):
"""
Check to see if a prefix is present in a string
If not, add it
:param string: string - string to check against
:param string_prefix: string - prefix to check
"""
if string.startswith(string_prefix):
return string
else:
return '%s%s' % (string_prefix, string)
|
e65d7373cdf2014be8de6705c628489a6a9c2fbd
| 349,952 |
def ci(request, monkeypatch):
"""Parametrize all tests for CI
Tasks may behave differently depending on whether they are running on a
Continuous Integration (CI) server (where the environment variable `CI`
will be set).
This fixture makes sure all tests exercise tasks in both scenarios.
"""
if request.param is True:
monkeypatch.setenv("CI", "true")
elif request.param is False:
monkeypatch.delenv("CI", raising=False)
return request.param
|
e95a445e2c731146e5c378f8ae5792aa40ed1e4d
| 407,971 |
import random
import string
def deadText(wordCount, wordLength, letterCase=None, printOut=None):
"""Generate random dummy text.
Args:
wordCount (int): The number of words the function will generate.
wordLength (int): The length of each randomly generated word.
letterCase (int, optional): Specify the letter case (1 Lower, 2 Upper, 3 Both). Defaults to 3.
printOut (bool, optional): Print out the generated dummy text. Defaults to False.
Returns:
The randomly generated dummy text.
"""
# final output
meaningless_text = ""
# check if letter case is none
if letterCase is None:
# if letter case is none, set it to default (lower and upper case)
caseMin = 0
caseMax = 51
else:
# if letter case is not none, then use the given
if letterCase == 1:
# if letter case is lower, make the caseMin and caseMax to 1 and 25
caseMin = 0
caseMax = 25
elif letterCase == 2:
# if letter is upper, make the caseMin and caseMax to 26 and 51
caseMin = 26
caseMax = 51
else:
# if letter case is not found, set it to default or lower case and upper case
caseMin = 0
caseMax = 51
# generate a N number of string of random characters based on the wordCount
for i in range(wordCount):
# Generate random characters to be added to the meaningless_text string
# then stop generating then add a space when the wordLength is reached
for i in range(wordLength):
letter = random.randint(caseMin, caseMax)
meaningless_text += string.ascii_letters[letter]
# add a space after every randomly generated word
meaningless_text += " "
# check if printOut is not none
if printOut is not None:
# print out is not none and is true so print out the generated text.
if printOut == True:
print(meaningless_text)
# print out is not none and is false so only return the generated text.
return meaningless_text
|
4853aa56d0189b12030f51c84c4f31015f162264
| 145,599 |
def findXCoordinateFromDirection(direction):
""" Returns delta X, when given a direction value """
if direction in (1, 5):
return 0
elif direction in (2, 3, 4):
return 2
elif direction in (6, 7, 8):
return -2
else:
error_template = "Unexpected direction value of: {0}"
raise ValueError(error_template)
|
a69342e911255e21bde09a75b6d8cbb7229bdf39
| 324,144 |
import collections
def transpose_dict(adict):
"""Transposes a dict of dicts to regroup the data."""
out = collections.defaultdict(dict)
for k,v in adict.items():
for ik,iv in v.items():
out[ik][k] = iv
return out
|
f97c7d664b78aef83f997e57bdcef8f943da3f7e
| 404,917 |
def onboarding_pipeline_patterns_pipeline_pattern_id_get(pipeline_pattern_id): # noqa: E501
"""Get specific pipeline pattern
# noqa: E501
:param pipeline_pattern_id: Pipeline pattern identifier
:type pipeline_pattern_id: str
:rtype: PipelinePattern
"""
return 'do some magic!'
|
453e0a9aa283e5ebe5de087e76305a3f1323942c
| 373,259 |
import re
def cleaning(text):
"""
Cleans the provided text by lowering all letters, removing urls, removing emails,
substituing punctuations with spaces
Args:
text (str): Input string to be cleaned
Returns:
text: cleaned text
"""
text = text.lower()
text = re.sub('http\S+', '' , text)
text = re.sub('\S*@\S+', '', text)
# Sub-ing punctuation with whitespace.
# text = re.sub(r'[<.*?>;\!()/,:&\\]+', ' ', text)
# Removing everything except numbers, capital & small letters
text = re.sub(r'[^0-9A-Za-z\s]', '', text)
# Remove multiple whitespace to single whitespace
# text = re.sub(r'\w+', ' ', text)
# Removing everything except numbers, capital & small letters & hyphens
# text = re.sub(r'[^0-9A-Za-z\-\s]', '', text)
# Example statement for removing words with numbers in them
# re.sub('\w*\d\w*', ' ', clean_text)
# Alternate version of removing all punctuations only
# re.sub('[%s]' % re.escape(string.punctuation), ' ', my_text)
return text
|
beafd409f030f85105e6d3ac0bd50f93b8ccb4cd
| 96,728 |
from typing import OrderedDict
def build_meta_layer(root):
"""
Build the meta layer from the provided root of the XML tree.
:param root: The root element of the XML tree.
:type root: :class:`etree.Element`
:return: An OrderedDict containing the regulation metadata, suitable for direct
transformation into JSON for use with the eRegs frontend.
:rtype: :class:`collections.OrderedDict`:
"""
meta_dict = OrderedDict()
part_to_letter = {'1001': 'A', '1002': 'B', '1003': 'C',
'1004': 'D', '1005': 'E', '1006': 'F',
'1007': 'G', '1008': 'H', '1009': 'I',
'1010': 'J', '1011': 'K', '1012': 'L',
'1013': 'M', '1014': 'N', '1015': 'O',
'1016': 'P', '1017': 'Q', '1018': 'R',
'1019': 'S', '1020': 'T', '1021': 'U',
'1022': 'V', '1023': 'W', '1024': 'X',
'1025': 'Y', '1026': 'Z', '1027': 'AA',
'1028': 'BB', '1029': 'CC', '1030': 'DD',
'1070': '1070', '1071': '1071',
'1072': '1072', '1080': '1080',
'1081': '1081', '1090': '1090',
}
preamble = root.find('{eregs}preamble')
fdsys = root.find('{eregs}fdsys')
eff_date = preamble.find('{eregs}effectiveDate').text
cfr_title_num = int(fdsys.find('{eregs}cfrTitleNum').text)
cfr_title_text = fdsys.find('{eregs}cfrTitleText').text
statutory_name = fdsys.find('{eregs}title').text
part = preamble.find('{eregs}cfr').find('{eregs}section').text
part_letter = part_to_letter[part]
meta_dict[part] = [
{
'cfr_title_number': cfr_title_num,
'cfr_title_text': cfr_title_text,
'effective_date': eff_date,
'reg_letter': part_letter,
'statutory_name': statutory_name
}
]
return meta_dict
|
e9d983e2fc2154015706d491aa95a92382457c36
| 181,397 |
import platform
def is_platform_arm() -> bool:
"""
Checking if the running platform use ARM architecture.
Returns
-------
bool
True if the running platform uses ARM architecture.
"""
return platform.machine() in ("arm64", "aarch64") or platform.machine().startswith(
"armv"
)
|
5e487a5d8a6e3423f9752c1e7b520afd8a2d5f08
| 660,016 |
import torch
def gae_rtg(x, gam, lam):
"""
This function calculates the rewards to go and at the same time the
advantages with GAE. It works even if the length of the episodes
is not the same for all of them.
Args:
x (tuple): Stores the rewards (R) as a list, the value estimates from
the critic (V) as a torch tensor and the total number of
timesteps stored (T) as an int.
gam (float): Value of gamma
lam (float): Value of lamda
Returns:
gae (torch.tensor): The advantages calculated with GAE
rtg (torch.tensor): The rewards to go
"""
R, V, T = x
j = 0
gae = torch.empty(T, 1)
rtg = torch.empty(T, 1)
for r in R:
for i in reversed(range(len(r))):
t = j + i # keep track of where we are at in global coordinates
# calculate GAE
delta_t = - V[t] + r[i] + gam * (V[t+1] if i != len(r)-1 else 0)
gae[t] = delta_t + gam * lam * (gae[t+1] if i != len(r)-1 else 0)
# calculate rewards to go
rtg[t] = r[i] + gam * (rtg[t+1] if i != len(r)-1 else 0)
j += len(r)
return gae, rtg
|
7ca6aef4872b7b6c1c49fc3e219333793d353fa0
| 136,087 |
def get_maximum_norm(p1, p2):
"""Return the inf norm between two points."""
return max(abs(p1[0]-p2[0]), abs(p1[1]-p2[1]))
|
0955c446d251ac561aaa6eb0bba5d63b9c94fc2e
| 240,081 |
def _is_section(tag):
"""Check if `tag` is a sphinx section (linkeable header)."""
return (
tag.tag == 'div' and
'section' in tag.attributes.get('class', [])
)
|
8605d8d95e9344c80e91dd1735bec79072507f7b
| 26,172 |
def aligned(value, func='vdec', aligned='w'):
"""Align specific size of 'w' or 'h' according to input func.
Args:
value (int): Input value to be aligned.
func (str, optional): Alinged method for specified function. Defaults to 'vdec'.
aligned (str, optional): Aligne `w` or `h`. Defaults to 'w'.
Raises:
ValueError: Input `func` not in ['jpegd', 'pngd', 'vdec', 'resize', 'crop', 'crop_and_paste', 'encode']
ValueError: Input aligned not in ['w', 'h']
Returns:
[int]: A aligned value.
"""
if func not in ['jpegd', 'pngd', 'vdec', 'resize', 'crop', 'crop_and_paste', 'encode']:
raise ValueError(
f"Aligned func only support:'jpegd','vdec','resize','crop','crop_and_paste'.")
if aligned not in ['w', 'h']:
raise ValueError(f"Aligned func only support w or h aligned.")
if func == 'jpegd' or func == 'pngd':
if aligned == 'w':
alignment = 128
else:
alignment = 16
else:
if aligned == 'w':
alignment = 16
else:
alignment = 2
formal = ((value + alignment - 1) // alignment) * alignment
return formal
|
239fc41ba4fdc6a292b625b768ed01d3997f78a3
| 456,034 |
def isUniversityEmail(email):
"""
Checks if the person has a university of windsor email
"""
return email.lower().endswith('@uwindsor.ca')
|
e56c66b59a6c938ffb1cc06d809edd306ce9ff6e
| 513,183 |
def _Backward3a_T_Ph(P, h):
"""Backward equation for region 3a, T=f(P,h)
Parameters
----------
P : float
Pressure [MPa]
h : float
Specific enthalpy [kJ/kg]
Returns
-------
T : float
Temperature [K]
References
----------
IAPWS, Revised Supplementary Release on Backward Equations for the
Functions T(p,h), v(p,h) and T(p,s), v(p,s) for Region 3 of the IAPWS
Industrial Formulation 1997 for the Thermodynamic Properties of Water and
Steam, http://www.iapws.org/relguide/Supp-Tv%28ph,ps%293-2014.pdf, Eq 2
Examples
--------
>>> _Backward3a_T_Ph(20,1700)
629.3083892
>>> _Backward3a_T_Ph(100,2100)
733.6163014
"""
I = [-12, -12, -12, -12, -12, -12, -12, -12, -10, -10, -10, -8, -8, -8, -8,
-5, -3, -2, -2, -2, -1, -1, 0, 0, 1, 3, 3, 4, 4, 10, 12]
J = [0, 1, 2, 6, 14, 16, 20, 22, 1, 5, 12, 0, 2, 4, 10, 2, 0, 1, 3, 4, 0,
2, 0, 1, 1, 0, 1, 0, 3, 4, 5]
n = [-0.133645667811215e-6, 0.455912656802978e-5, -0.146294640700979e-4,
0.639341312970080e-2, 0.372783927268847e3, -0.718654377460447e4,
0.573494752103400e6, -0.267569329111439e7, -0.334066283302614e-4,
-0.245479214069597e-1, 0.478087847764996e2, 0.764664131818904e-5,
0.128350627676972e-2, 0.171219081377331e-1, -0.851007304583213e1,
-0.136513461629781e-1, -0.384460997596657e-5, 0.337423807911655e-2,
-0.551624873066791, 0.729202277107470, -0.992522757376041e-2,
-.119308831407288, .793929190615421, .454270731799386,
.20999859125991, -0.642109823904738e-2, -0.235155868604540e-1,
0.252233108341612e-2, -0.764885133368119e-2, 0.136176427574291e-1,
-0.133027883575669e-1]
Pr = P/100.
nu = h/2300.
suma = 0
for i, j, n in zip(I, J, n):
suma += n*(Pr+0.240)**i*(nu-0.615)**j
return 760*suma
|
a3c57b9e767ad48f6481a77dfb6dd87c09a17e95
| 241,082 |
def snake_case(word: str) -> str:
"""Convert capital case to snake case.
Only alphanumerical characters are allowed. Only inserts camelcase
between a consecutive lower and upper alphabetical character and
lowers first letter.
"""
out = ''
if len(word) == 0:
return out
cur_char: str = ''
for i in range(len(word)):
if i == 0:
cur_char = word[i]
if not cur_char.isalnum():
raise Exception('Non legal character in: ' + word)
out += cur_char.lower()
continue
last_char: str = cur_char
cur_char = word[i]
if (last_char.islower() and last_char.isalpha() and
cur_char.isupper() and cur_char.isalpha):
out += '_'
if not cur_char.isalnum():
out += '_'
else:
out += cur_char.lower()
return out
|
004ac0095c18a13512e81611ba8a603e41aa901c
| 409,859 |
def is_hdfs_path(path):
"""
Check if a given path is HDFS uri
Args:
path (str): input path
Returns:
bool: True if input is a HDFS path, False otherwise
>>>is_hdfs_path("/tdk")
False
>>>is_hdfs_path("hdfs://aa:123/bb/cc")
True
"""
return path.startswith("hdfs://")
|
62cc9286f91fbad848541275d79d250bf62b4c99
| 38,690 |
def pprint_positions(position):
"""
custom print for TQSDK positions
Args:
position (tqsdk's position object)
Returns:
str: the formated string
"""
open_cost = 0
if position.pos > 0:
open_cost = position.open_price_long
elif position.pos < 0 :
open_cost = position.open_price_short
s = "Contract: {}, Net Holding: {}, pos long : {}, pos short: {}, open cost (avg): {}".format(position.instrument_id, position.pos, position.pos_long, position.pos_short, open_cost)
return s
|
a168ff19b8294f7e2642e92a781e1059d21dcca2
| 363,881 |
import json
def load_script(script_path):
"""Load script from a JSON file.
Parameters
----------
script_path : str
Path to JSON file.
Returns
-------
script : dict or dict[]
Loaded JSON object.
"""
with open(script_path) as f:
script = json.load(f)
return script
|
be3dcd5411d51de7ad6cbc14e9770ac45d6b8b17
| 223,195 |
def get_tag(tags, key):
""" Returns a specific value in aws tags, from specified key
"""
names = [item['Value'] for item in tags if item['Key'] == key]
if not names:
return ''
return names[0]
|
630a50026b82e2beb8834df5a9b4d4220abafcbd
| 377,382 |
from datetime import datetime
def convert_time(dt):
"""Convert datetime from ISO 8601 format to seconds since midnight."""
dt = datetime.strptime(dt[:19], '%Y-%m-%dT%H:%M:%S')
return dt.hour * 60 * 60 + dt.minute * 60
|
bef7c8b4b31ba2807c3fb687af6ebf1aa895cdfa
| 488,899 |
import hashlib
def generate_hash(algorithm, salt, password):
"""Generate the hash from the algorithm, salt and password."""
hash_obj = hashlib.new(algorithm)
password_salted = salt + password
hash_obj.update(password_salted.encode('utf-8'))
password_hash = hash_obj.hexdigest()
password_db_string = "$".join([algorithm, salt, password_hash])
return password_db_string
|
834cce7caf997b297c44283abaee7787fc01014e
| 502,406 |
import types
def copy_func(f, name=None):
"""
Return a function with same code, globals, closure, and name (or provided name).
"""
fn = types.FunctionType(f.__code__, f.__globals__, name or f.__name__,
f.__defaults__, f.__closure__)
# If f has been given attributes
fn.__dict__.update(f.__dict__)
return fn
|
65be84ec7e46c7f6726248fa627bfd9b800a24af
| 669,850 |
def do_while_loop(evaluator, ast, state):
"""Evaluates "do {body} while (cond)"."""
while True:
res, do_return = evaluator.eval_ast(ast["body"], state)
if do_return:
return res, True
if not evaluator.eval_ast(ast["cond"], state):
break
return None, False
|
d083126f047a02abf1d83bb8a5daf60e5456b42a
| 512,259 |
def _get_top_vars(top, top_vars):
"""Generate a dictionary of values for the defaults directive."""
combining_rule_to_gmx = {"lorentz": 2, "geometric": 3}
default_top_vars = dict()
default_top_vars["nbfunc"] = 1
default_top_vars["comb-rule"] = combining_rule_to_gmx[top.combining_rule]
default_top_vars["gen-pairs"] = "no"
default_top_vars["fudgeLJ"] = 1
default_top_vars["fudgeQQ"] = 1
default_top_vars["nrexcl"] = 3
if isinstance(top_vars, dict):
default_top_vars.update(top_vars)
return default_top_vars
|
01fb2a132ec3c78ea36abc444c667db0f6faabc0
| 201,015 |
def group_cpu_metrics(metrics):
"""Group together each instances metrics per app/space"""
grouped_metrics = {}
for metric in metrics:
grouped_metrics.setdefault(metric['space'], {}).setdefault(metric['app'], []).append(metric['value'])
return [(app, space, metric_values,)
for space, apps in grouped_metrics.items() for app, metric_values in apps.items()]
|
91b91601c359e2b80c31b80fcb80bd5915d5972d
| 41,915 |
def getMenuItemPrice (theDictionary, item):
"""Identifies the price of item.
Assumes items are written in uppercase.
:param dict[str, float] theDictionary:
Dict containing menu items as keys and respective prices as
prices.
:param str item:
The name of item to check the price of.
:return:
The price of item if in theDictionary, else None.
:rtype: float or None
"""
item = item.upper()
if item in theDictionary:
return theDictionary[item]
|
8395b692138dd911ed5c8fdd48d99e2da49f6f1e
| 324,988 |
def internal_dot(u, v):
"""Returns the dot product of two vectors. Should be identical to the
output of numpy.dot(u, v).
"""
return u[0]*v[0] + u[1]*v[1] + u[2]*v[2]
|
3f8700d40bd703540fc67408ff7799d81d1c3f08
| 135,753 |
from typing import Any
def create_null_type(name: str) -> Any:
"""
Creates a singleton instance of a custom nullable-type. This nullable-type acts much in the
same way `None` does. It is a "Falsey" value, returns `None` when called, raises `StopIteration`
when iterated, returns `False` when checking for attributes, and is the only possible instance
of its type.
Use this to create a unique None-like constant where the standard `None` will not work.
Args:
name: The name to give the class of the returned nullable-type object.
Returns:
A nullable-type object.
"""
def stop_iter(*args):
raise StopIteration
return type(
name,
(object,),
{
"__str__": lambda s: name,
"__repr__": lambda s: name,
"__bool__": lambda s: False,
"__nonzero__": lambda s: False,
"__contains__": lambda s: False,
"__len__": lambda s: False,
"__call__": lambda s: None,
"__iter__": lambda s: s,
"next": stop_iter,
},
)()
|
e976a0a14e53ca63bdce3fc16252782960e0b3c5
| 576,789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.