content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def lc_std_loss(lc):
"""
lc: BNK3
"""
B, N, K, _ = lc.shape
lc = lc.reshape(B * N, K, 3)
x = lc[:, :, 0] # BN, K
y = lc[:, :, 1] # BN, K
x_std = torch.std(x, 1)
y_std = torch.std(y, 1)
x_std_mean = x_std.mean()
x_std_std = x_std.std()
x_std_selected = x_... | 93f9bd6bbda2eabc01f755609656ff144c89b669 | 628,412 |
def reg_mlp_weight_init(m):
"""Does not weight init, defaults to whatever pytorch does."""
return m | 9fce388584cc3efd0ab1c130c0dd1e808e81349c | 628,413 |
def ireplace(old, new, text):
"""
case insensitive search and replace function searching through string and returning the filtered string
(based on http://stackoverflow.com/a/4773614)
"""
idx = 0
occur = 0
while idx < len(text):
index_l = text.lower().find(old.lower(), idx)
... | a5bb8403314bf294f64909f95de2c982d9c4321d | 628,415 |
import sys
import csv
def read_data(fn):
"""
Read data from a TSV file
"""
rows = []
with open(sys.argv[2]) as fn:
data = csv.DictReader(fn, delimiter='\t')
cols = data.fieldnames
for row in data:
rows.append(row)
return cols, rows | d72c5e47253836e058569505b68c54cc4d9cf8ec | 628,416 |
def pattern(vals: list) -> str:
"""
Return a regex string from a list of values
"""
return f"^({'|'.join(map(str, vals))})$" | 08a26c2d4abd890a1dc96a58a9814e6f5d02b85f | 628,417 |
def isHidden(path_):
"""Hidden files are files which names starts of dot symbol. This method returns True if file is hidden or False otherwise."""
return path_[0] == '.' | 3314929857660e491467d35190e355ffc67c8b17 | 628,418 |
import inspect
def get_rule_args(clazz):
"""
Gets list of ("param_name", Parameter)
:param clazz:
:return:
"""
params = inspect.signature(clazz).parameters
return [
dict(name=name, required=param.default is inspect.Parameter.empty)
for name, param in params.items()
] | 5b928adfa79fd63c7c992424610a3763283b610d | 628,420 |
import re
def sanitize(name, minlen=2, maxlen=25):
"""Lower-case name and replace all non-ascii chars by `_`."""
if name is None or len(name.strip()) < minlen:
raise ValueError("name must have at least {} chars.".format(minlen))
return re.sub(r'\W|^(?=\d)', '_', name.strip().lower()[:maxlen]) | 0108ae989fa00524d361c0d67285c190bfe88cdb | 628,421 |
def format_headers(headers, excludes=[]):
"""Returns a dictionary after excluding blacklisted headers"""
_h = {}
for k, v in headers.items():
if k not in excludes:
_h[k] = v
return _h | baf656b93fd4bf3f4890b978bb903a972aa041a4 | 628,422 |
import numpy as np
def bss_components_inversion(sources, interferograms):
"""
A function to fit an interferogram using components learned by BSS, and return how strongly
each component is required to reconstruct that interferogramm, and the
Inputs:
sources | n_sources x pixels | ie archi... | 84552e22ce9341336c237e0dda60b7d503a98508 | 628,423 |
def to_root_latex(s):
"""
Converts latex expressions in a string *s* to ROOT-compatible latex.
"""
return s.replace("$", "").replace("\\", "#") | 775459ec73270d22fb4797fa4062711d34b58d58 | 628,424 |
def _lstrip(source: str, prefix: str) -> str:
""" Strip prefix from source iff the latter starts with the former. """
if source.startswith(prefix):
return source[len(prefix) :]
return source | 0782647c439cafe9d1036c8d6541ac5377991e2c | 628,425 |
import os
def check_file_exist_by_os_path(path: str = ""):
"""
Check if the path exist
:param path:
:return:
"""
# If this file object exist.
if os.path.exists(path):
ret = True
else:
ret = False
return ret | 3cfb8e3cae5df04c3c2481082ea23549bf39b2bd | 628,426 |
def format_time(function_name, time, nb_iterations, timeout):
"""
Provides a nicely formatted string given a function name, a time of execution
and the number of iterations.
Args:
function_name (str): The name of the function that was executed.
time (float): The time it took for the fun... | c8d28e1835ce9a8d36a1a1ba2dd436c676a56910 | 628,427 |
def df_column_wise_norm(df):
"""
Column wise norm. Calculates the norm of each column.
The formula is:
df - df.mean / df.max - df.min
"""
df_norm = (df - df.mean()) / (df.max() - df.min())
return df_norm | b8a03a59a3d589ea9d46bee86208b102b44e428e | 628,428 |
def main():
"""
The main function to execute upon call.
Returns
-------
int
returns integer 0 for safe executions.
"""
print("Program to onvert temperature units.")
celsius = float(input("Enter temperature in ℃: "))
fahrenheit = (celsius * 9/5) + 32
print('%.2f ℃ ≈ %0... | fcf0d362cec8f60b8784d9356b4411a7446bd46a | 628,429 |
import os
import re
def find_boost(hint=None, verbose=True):
"""
Find the location of the Boost include directory. This will return
``None`` on failure.
"""
# List the standard locations including a user supplied hint.
search_dirs = [] if hint is None else hint
search_dirs += [
"/... | 26b7f3f2f709238b6112d94df1caa716846d32f6 | 628,430 |
def _index_keys(columns):
"""
Take all the key columns and build a list of possible index
tuples that can arise from them.
For example, given the following schema: "varId|dbSNP,gene"
these are the possible index key lists:
[['varId', 'gene'],
['dbSNP', 'gene']]
"""
keys = [k.split... | ee7cb47b0abe6936ba7f5cfd720a4e92854a0d90 | 628,431 |
import os
def find_all_files(package_path):
"""
Get all the files within the path given.
Ignore certain files like hidden files and `.pyc` files.
:param str package_path: The relative path
:return: a list of relative paths of all the files
"""
paths = []
for dirpath, dirnames, filena... | 23e553f16a9e8f3a992b158de7f3bc88994a14df | 628,432 |
def recognize_server(uid: int) -> str:
"""Recognizes which server a UID is from.
:param uid: A genshin uid
"""
server = {
"1": "cn_gf01",
"2": "cn_gf01",
"5": "cn_qd01",
"6": "os_usa",
"7": "os_euro",
"8": "os_asia",
"9": "os_cht",
}.get(str(u... | 995d04e41f793b202542fd381a591bfc1434568d | 628,433 |
import re
def check_premise_indicators(sentence, premise_list):
"""
function to detect the presence of argument keywords in a sentence
:param full sentence:
:return: 1 if sentence contains keyword
"""
for indicator in premise_list:
if re.search(r"\b" + re.escape(indicator.lower()) + r... | f8e454d767c695f425edbcf196a927880b1bdef7 | 628,434 |
import math
def get_rotated_point(x1, y1, x2, y2, angle):
"""
获得点(x2, y2)绕(x1, y1)顺时针旋转angle度后的点(x3, y3),屏幕坐标系
:param x1:
:param y1:
:param x2:
:param y2:
:param angle: 度
:return:
"""
x3 = int(x1 + (x2 - x1) * math.cos(angle * math.pi / 180) - (y2 - y1) * math.sin(angle * math.... | 230b91f25adc128957fb786ebceaa5c0628c061b | 628,435 |
def posterior(self,observation):
"""Return posterior of success given evidence"""
y = self.indicators.index(observation)
C = self.evidence(observation)
return self.likelihood[0,y] * self.marginals[0] / C | 5c00dbbf0e909d889b15861d2393f2adb0f2721a | 628,436 |
def zigzag(n):
"""
Produce a list of indexes that traverse a matrix of size n * n using the JPEG zig-zag order.
Taken from https://rosettacode.org/wiki/Zig-zag_matrix#Alternative_version.2C_Translation_of:_Common_Lisp
:param n: size of square matrix to iterate over
:return: list of indexes in t... | d20e0466c30301278a5727b5f3975286969c9a11 | 628,437 |
def file_to_str(fname):
"""
Read a file into a string
PRE: fname is a small file (to avoid hogging memory and its discontents)
"""
data = None
# rU = read with Universal line terminator
with open(fname, 'rU') as fd:
data = fd.read()
return data | f89dce69a8f39d6d98a3cc9f70d684a1ac9d52bf | 628,439 |
import time
def timestamp():
"""
Returns a timestamp formatted properly as a string.
"""
return time.strftime("%d-%m-%Y %H:%M:%S: ", time.localtime()) | ae932b909421deb93094604d3cffa603b6427442 | 628,440 |
from typing import Any
def is_primitive_type(arg_type: Any) -> bool:
"""Check if the input type is one of `int, float, str, bool`.
Args:
arg_type (typing.Any): input type to check.
Returns:
bool: True if input type is one of `int, float, str, bool`.
"""
try:
return isinst... | 288b4e425f65b428ca33164fbc5aeb891eb39ad9 | 628,441 |
import requests
from bs4 import BeautifulSoup
def get_html(url):
"""
# get_html
@Description:
get html code by url
based on exception handling and anti-spider design
to realize totally data mining
---------
@Param:
a url str
-------
@Returns:
a Beautifulsoup object
... | da37ba7231fff46579d1d3e1330bef8af783eda4 | 628,442 |
def _parse_range(r):
"""
Parse an integer sequence such as '0-3,8-11'.
'' is the empty sequence.
"""
if not r.strip():
return []
res = []
for piece in r.strip().split(","):
lr = piece.split("-")
if len(lr) == 1 and lr[0].isdigit():
res.append(int(... | 2cbd53453cb98a2c2f4d5799c159ffec762fc009 | 628,443 |
def get_load_zones(conn, subscenarios):
"""
Get the load zones
:param conn: database connection
:param subscenarios: Subscenarios class object
:return:
"""
c = conn.cursor()
load_zones = c.execute(
"""SELECT load_zone
FROM inputs_geography_load_zones
WHERE load_z... | d1cc635f16b170aeeb9f09bdfe008eb86dc99ad1 | 628,444 |
def new_character(c, n):
"""
Find the character in 'n' position after/before character 'c'.
"""
# Range of ordinal values of letters in the alphabet
ref_min, ref_max = (ord('a'), ord(
'z')) if c.islower() else (ord('A'), ord('Z'))
# Number of letters in the range
num_c = ref_max - r... | 0b76b79d02f41c01b528375bcd7d318ec7001cb9 | 628,445 |
def normalize_list_params(params):
"""
Normalizes parameters that could be provided as strings separated by ','.
>>> normalize_list_params(["f1,f2", "f3"])
["f1", "f2", "f3"]
:param params: Params to normalize.
:type params: list
:return: A list of normalized params.
:rtype list
"... | 3c837def00e2c543b33b6829d157e9b3f0699f19 | 628,446 |
def normalize(img, radius=1):
"""
Normalize image to L2 norm of radius
"""
img = img - img.mean(-2, keepdim=True).mean(-1, keepdim=True)
norms = img.pow(2).sum(-2, keepdim=True).sum(-1, keepdim=True).sqrt()
return img / norms * radius | 0dc92bc66d6d9e19d62455e66fbd2cbf09f0535e | 628,447 |
import logging
def set_logger_timesource(dtm_now):
"""Set a custom record factory, with a bespoke source of timestamps.
Used to have records with the same datetime as the most recent packet log record.
"""
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
ct... | 96f8d9da33c2d2d9a0b0107842c17e35ee06bc6d | 628,448 |
import configparser
import itertools
import secrets
def generate_configs(n, addresses):
"""Generate party configurations.
Generates n party configurations with thresholds 0 up to (n-1)//2.
addresses is a list of '(host, port)' pairs, specifying the
hostnames and port numbers for each party. Moreover,... | 97ca22fe20a0d99cc7b58d8cb609efd5fa929e6b | 628,449 |
def get_rerole_stats(rerole_ops):
"""
Gets a summary of information about the rerole operation.
"""
stats = {'base': {}, 'team':{}}
users = {'base': {}, 'team':{}}
for (user, role_spec) in rerole_ops:
to = role_spec[:2]
per_team = role_spec[2]
if len(per_team):
... | 33c922ef88ebec52d522f8c3a0d802e2c745034c | 628,451 |
import os
def list_pngs(video_title: str) -> list:
"""List png frame files for a video.
Args:
video_title: name of video file.
Returns:
List of png file names.
"""
path_to_pngs = os.path.join('frames', video_title)
files = os.listdir(path_to_pngs)
png_files = [f for f in... | 26e9a5b93ef5c35b73b77ea574e1b71e5058e6a4 | 628,452 |
def count_params(model, trainable=True):
""" Count number of parameters in pytorch model (optional: only count trainable params)
"""
if not trainable:
return sum(p.numel() for p in model.parameters())
else:
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 30be6a99ab63b1b2ef71b740009520a39bf1a05c | 628,453 |
def unsqueeze_as(tensor, as_tensor, dim=-1):
"""Expand new dimensions based on a template tensor along `dim` axis.
Args:
Args:
tensor (torch.Tensor): tensor with shape (bs, ..., d1)
as_tensor (torch.Tensor): tensor with shape (bs, ..., n, ..., d2)
Returns:
torch.Tensor: (bs, ... | 05f077733a7fd355f838a65da3b7ff3f33648f35 | 628,454 |
def prepare_params(sort=None, filter=None, params=None):
"""
Prepares the different parameters we want to send as the query in a request
:param sort: str
The sorting (used in list commands issued to the DNSimple API)
:param filter: dict
The filtering (used in list commands issued to the... | b4d97173ba3e4777a843ff332dae1b33c22204ae | 628,455 |
def is_palindromic_phrase(s):
""" (str) -> bool
Return True iff s is a palindrome, ignoring case and non-alphabetic
characters.
>>> is_palindromic_phrase('Appl05-#$elppa')
True
>>> is_palindromic_phrase('Mada123r')
False
"""
result = ''
for i in range(len(s)):
... | ec079e99518ba477228e8d0e39c8ce34ca4f7c89 | 628,456 |
def extract_simple_type_restrictions(properties: dict) -> dict:
"""Extract Simple Type restrictions."""
restrictions = {}
keys = [
"minLength",
"maxLength",
"pattern",
"minimum",
"maximum",
"length",
"totalDigits",
"fractionDigits",
"ex... | ac0ca829c7026de19fec1c8939312421c6e00ddf | 628,457 |
import re
def _de_embed_elements(vistr: str) -> str:
"""De-embed elements <<...>>"""
# pylint: disable=cell-var-from-loop
for element in [
"B",
"append",
]:
vistr = re.subn(f"<(</?{element}>)>", lambda m: m.groups()[0], vistr)[0]
vistr = re.subn("<<([0-9]+)>>", lambda m: "_... | b6cda88c85b8994ae708debe20c2baa4786d44f9 | 628,458 |
import torch
def get_prediction_ids(predictions):
""" Get the label ids from the raw prediction outputs """
tensor = torch.tensor(predictions)
softmax = torch.nn.functional.softmax(tensor, dim=-1)
argmax = torch.argmax(softmax, dim=-1)
return argmax.tolist() | 51b93b23138c1d32cdba27d218ad01a87ebccb93 | 628,460 |
import json
def read_anki_json(conn, json_name):
"""
:param sqlite3.Connection conn:
:param str json_name:
:return dict:
"""
cursor = conn.execute('SELECT {} FROM col'.format(json_name))
record = cursor.fetchone()
if record is not None:
return json.loads(record[0])
else:
... | b9b1fd7cddbe200a7ad7cb9f30cb2550d8c75bfc | 628,462 |
def search(user_input):
"""Takes the user input.
Renders the result of search:
- found meal/product that has the most fitting name
- found table of replacements for that meal (sortable)
- if meal not found: prompt to add"""
return f"Searches the replacement for '{user_input}'" | e138fba3f29d4b09993c7a4bbcd1ef8366fad559 | 628,463 |
def all(iterable):
"""The built-in was unavailable no Python 2.4."""
for element in iterable:
if not element:
return False
return True | 0f1638bf12ccdaa3ee66699365789bc8ab0c5b8c | 628,464 |
def semester(date, *, base=1):
"""
Returns the semester of the given date.
The first semester runs from 1 January to 30 June; the second
from 1 July to 31 December.
Parameters
----------
date : datetime.date
the date from which to determine the semester
base : int, optional
... | 6519ad39e31117d341345555de7753c2e1069d6f | 628,465 |
def mode3():
"""words vs phonems"""
mode = {
'/diy/' : 'phoneme',
'/iy/' : 'phoneme',
'/m/' : 'phoneme',
'/n/' : 'phoneme',
'/piy/' : 'phoneme',
'/tiy/' : 'phoneme',
'/uw/' : 'phoneme',
'gnaw' : 'word',
'knew' : 'word',
'pat' : 'wor... | 61863ef196e558d7c6d49757b2faa083819e30eb | 628,466 |
def check_eq_files(path1, path2, blocksize=65535, startpos1=0, startpos2=0):
""" Return True if both files are identical, False otherwise """
flag = True
with open(path1, 'rb') as f1, open(path2, 'rb') as f2:
buf1 = 1
buf2 = 1
f1.seek(startpos1)
f2.seek(startpos2)
whi... | f81ecb84e25e37eeff5022e8916bc0a1c378a5ae | 628,467 |
def jaccard_index_pair_counts(a, b, c):
"""
Compute the Jaccard index from pair counts; helper function.
Arguments:
a: number of pairs of elements that are clustered in both partitions
b: number of pairs of elements that are clustered in first but not second partition
c: number of pairs of elem... | c0da77d2195055c28c6fc2ec67d00aacfa1ac497 | 628,468 |
def create_lookup(stream, derived_fields, index_field):
"""
Build a lookup table from an indexed field to a set of derived fields.
Ensures that there is a unique relation, raises assertion if violated
:param stream: stream of records
:param derived_fields: list of derived fields assumed to be a func... | 4003e051fe1f816af7e7f7f2df7a438c3092a711 | 628,470 |
def overlap(a, b):
"""
Checks to see if two series intersect, or have identical start/end positions.
"""
# if any start / end is None then it doesn't overlap
if a[0] is None or a[1] is None or b[0] is None or b[1] is None:
return False
# If the casing start/end intersects
records_int... | b597b73497e694352a6882ac9746db1b1c364f5e | 628,471 |
from typing import Counter
def fill_histogram(histograms, indices, hist_idx, normalize=True):
"""
Compute a histogram and fill in the designated entry in the array histograms.
:param histograms: Array that will contains histograms.
:param indices: Array with values from which a histogram should be co... | e4eb4c03c16aa01813526d83324dbf39082bbcb9 | 628,472 |
import requests
import json
def get_dbs():
"""
Get a list of all the PhysioNet databases available.
Parameters
----------
N/A
Returns
-------
dbs : list
All of the databases currently available for analysis.
Examples
--------
>>> dbs = wfdb.get_dbs()
>>> dbs
... | 409b87e9e92ff27bf25df66952278a632d894825 | 628,473 |
def get_C_def_frst_test(e_HP_def_high_test, e_HP_frst_high_test):
"""試験時の着霜期高温条件における除霜効率係数(-)(16)
Args:
e_HP_def_high_test(float): 試験時の着霜期高温加熱条件におけるヒートポンプの除霜運転を含むエネルギー消費効率
e_HP_frst_high_test(float): 試験時の着霜期高温加熱条件におけるヒートポンプの除霜運転を除くエネルギー消費効率
Returns:
float: 試験時の着霜期高温条件における除霜効率係数
"""
... | 2a3a8b69f3e141417c94ee9182581367723e2d9a | 628,474 |
def file_to_string(filename):
""" file contents into a string """
data = ""
try:
with open(filename, 'r') as myfile:
data = myfile.read()
except IOError:
pass
return data | 1b37a5f64aeb97deb1a4e7eee93c9e52ea2db497 | 628,475 |
def partition(data):
"""ignore me, subset of quicksort"""
pivot = data[0]
less, equal, greater = [], [], []
for temp in data:
if temp < pivot:
less.append(temp)
elif temp > pivot:
greater.append(temp)
else:
equal.append(temp)
return less, equal, greater | 842e44126972d06d8ae38ef5da23f478c1551b4f | 628,476 |
def isKtServerRunning(logPath):
"""Check if the server started running."""
success = False
with open(logPath) as f:
for line in f:
if line.lower().find("listening") >= 0:
success = True
return success | 71a2a67fee57c55e28238f00e5c37aa5287610b8 | 628,477 |
import numpy as np
import time
from tqdm import tqdm
def get_halos_per_forest(f_in, Snap_Keys, haloID_field="ID",
forestID_field="ForestID"):
"""
Determines the number of halos in each forest.
The resulting Dictionary is nested with the outer-key given by the ForestID
and the... | 7a00d8d124d6098df80582d056f1986285e5e1f0 | 628,478 |
import numpy as np
def kronecker_generator(SCALE, edgefactor):
"""
Generate an edgelist according to the Graph500 parameters.
In this sample, the edge list is returned in an array with three
rows, where StartVertex is first row, EndVertex is the second row,
and Weight is the third ... | 71fb710238c97cde1f261da251396a1070d043c3 | 628,479 |
def split_numal(val):
"""Split, for example, '1a' into (1, 'a')
>>> split_numal("11a")
(11, 'a')
>>> split_numal("99")
(99, '')
>>> split_numal("a")
(0, 'a')
>>> split_numal("")
(0, '')
"""
if not val:
return 0, ''
for i in range(len(val)):
if not val[i].isdigit():
return int... | 7ba4b35d4727692770b9cd3764f5fdf10bfb6c7c | 628,480 |
def rgb(arg):
"""Convert a comma separate string of 3 integers to RGB values"""
colors = arg.split(',')
if len(colors) == 1:
try:
r = int(colors[0])
except ValueError:
raise ValueError('Colour should be a single integer or ' + \
'3 comma s... | fd8dedbe33026a1c2c9e399ff40485805079b216 | 628,481 |
import math
def hm(hours):
"""Convert hours to hour-minute
If hours is negative, only hour of the tuple is negative.
"""
if math.isinf(hours):
return None
minutes = int(math.ceil(hours * 60))
h, minutes = divmod(minutes, 60)
return (h, minutes) | 5b4473694ed40f0f5a1594f796e42bc92852217e | 628,482 |
def is_nfs_have_host_with_host_obj(nfs_details):
""" Check whether nfs host is already added using host obj
:param nfs_details: nfs details
:return: True if nfs have host already added with host obj else False
:rtype: bool
"""
host_obj_params = ('no_access_hosts', 'read_only_hosts',
... | 8beac82c761ca71456a627c5a34db241daf3059d | 628,483 |
from operator import add
def _binary_bracketings(n):
"""Helper for binary_bracketings.
"""
if n == 1:
return [[]]
elif n == 2:
return [[(0,2)]]
else:
b = {}
for i in range(1, n):
b[i] = _binary_bracketings(i)
B = []
for i in range(1, n):
... | 9c702fa78a97bf9008567a1ba2432974f76412a0 | 628,484 |
from pathlib import Path
def pathlen(path):
"""Return folder level of the path string"""
return len(Path(path).parts) | 0819611deafe9beea2e608ab85f36edb69b35ac9 | 628,485 |
import re
def csv_row(row):
"""Function to clean a row of CSV data before writing it to an output file"""
if row is None or not row: return ''
return '"' + '","'.join(re.sub(r'^None$|\[\s*\]', '', str(s)).replace(', [', ' [') for s in row) + '"\n' | 1e5f3cfd0e3aa13a6186fa30c2e591281fe04e0c | 628,486 |
import re
def normalize_timestamp(ts):
"""Normalize a timestamp
For easier comparison
"""
if ts is None:
return
return re.sub(r'\d(\.\d+)?', '0', ts) | 58561922838381a2575df646d1892831f5b94b3b | 628,487 |
import random
import torch
def get_top_k(x, ratio):
"""it will sample the top 1-ratio of the samples."""
x_data = x.view(-1)
x_len = x_data.nelement()
top_k = max(1, x_len * (1 - ratio))
# get indices and the corresponding values
if top_k <= 1:
if random.random() < top_k:
... | d72ba9402d70facda63dc98cedcd02d6298f8099 | 628,488 |
def execute_chronos_api_call_for_job(api_call, job):
"""Attempt a call to the Chronos api, catching any exception.
We *have* to catch Exception, because the client catches
the more specific exception thrown by the http clients
and rethrows an Exception -_-.
The chronos api returns a 204 No Content... | 04c8cc91e9062699233b4bd2395d8cc3e7e2dfda | 628,489 |
def esval(es, tlist):
"""
Evaluates an exponential series at the times listed in ``tlist``.
Parameters
----------
tlist : ndarray
Times at which to evaluate exponential series.
Returns
-------
val_list : ndarray
Values of exponential at times in ``tlist``.
"""
... | 4dd2d2287c0bdec8efc4740f69522ab08bda1103 | 628,490 |
def google_fixed_width_font(style):
"""check if the css of the current element defines a fixed width font"""
font_family = ''
if 'font-family' in style:
font_family = style['font-family']
if 'Courier New' == font_family or 'Consolas' == font_family:
return True
return False | 9067d72978db4b63244feb3255d80a8d48a37c09 | 628,492 |
def cal_kt(raw_trajs_frequent_pattern, sd_trajs_frequent_pattern):
"""
calculate KT
Args:
raw_trajs_frequent_pattern: frequent patterns of the original trajectory
sd_trajs_frequent_pattern : frequent patterns that generate trajectories
Returns:
KT
"""
concordant_count... | ffb1379be7072afb3d75b0f3fc706967ed0064f2 | 628,493 |
import random
def adj31():
"""Calculate a random 3rd adjective declension (one or two endings)."""
return [random.randrange(2), random.randrange(6), random.randrange(2)] | 6ebb236f8cb00f5aab8be811f9be6fa164b7ab11 | 628,494 |
def EncryptData(Enrico, MessageStr):
"""
heart_rate_data = {
'heart_rate': heart_rate,
'timestamp': now,
}
plaintext = msgpack.dumps(heart_rate_data, use_bin_type=True)
message_kit, _signature = data_source.encrypt_message(plaintext)
kit_bytes = message_kit.to_bytes()
kits.ap... | c67a88b49ebf25872eeb9027040c5eaa4b49a9e9 | 628,495 |
import os
import logging
def locate_dir(path, dir_name):
""" Locates a directory inside the given path.
Args:
path: The path to be searched
dir_name: The directory we are looking for
Returns:
The absolute path of the directory we are looking for, None otherwise.
"""
paths = []
for root, sub... | 922f9548d4f6d8acbef4171056c13b4f0e4f5a5a | 628,497 |
def validWebsite(website):
"""
Checks With a Regex If The URL Entered Is Correct Or Not! (User can use IP Too :)
"""
# web = webNotEmpty(website)
# if web is "valid":
# if not (re.match(r"(^(http://|https://)?([a-z0-9][a-z0-9-]*\.)+[a-z0-9][a-z0-9-]*$)", website)):
# exit(wrong_U... | f5b1133c500e860c63436419b64248bcded736f3 | 628,498 |
import math
def avg(current, previous, bpp):
"""
To compute the Average filter, apply the following formula to each
byte of the scanline:
Average(x) = Raw(x) - floor((Raw(x-bpp)+Prior(x))/2)
:param current: byte array representing current scanline.
:param previous: byte array representing th... | d1034a5acc626922de33dc6f3b9c59b10c0ccbf1 | 628,499 |
import os
import random
import json
def iter_sample_single_jsonl(root, language, partition, num_examples, random_seed=None, excerpt=False):
"""Randomly samples a single extracted and indexed jsonl file.
Args:
root: A directory containing the extracted and indexed master dataset.
language: The... | 78f3c48addfff60320e25e681f67fb75bdd15511 | 628,500 |
import numpy
def get_wcs_rotation(wcs):
"""Returns the rotation of a WCS frame.
Parameters
----------
wcs : ~astropy.wcs.WCS
The `~astropy.wcs.WCS` object.
Return
------
float
The rotation angle, in degrees.
"""
return numpy.degrees(numpy.arctan2(wcs.wcs.cd[1, 0... | 086bb68809f3c0d201aaf4a6ba95004ae3a17b34 | 628,501 |
from typing import List
from typing import Dict
def flatten_list_dict(lst: List[Dict[str, list]]) -> Dict[str, list]:
"""Flatten list of dicts to dict of lists
Parameters
----------
lst : List[Dict[str, list]]
list of dicts of lists
Returns
-------
Dict[str, list]
"""
ret... | 2ca88975b524fc7065e425ab79408095d600e7e4 | 628,502 |
def is_node(relative_link):
"""In directory listings a folder is indeicated by a trailing slash (/)."""
node = not relative_link.endswith('/')
return node | 491e4dae494db206c08dce5cc0a5c1fb8aca1631 | 628,503 |
def evaluate_f1(tp: int, fp: int, fn: int) -> float:
"""F1-score.
*F1-score* $=\dfrac{2TP}{2TP + FP + FN}$
Args:
tp: True Positives
fp: False Positives
fn: False Negatives
"""
try:
return 2 * tp / (2 * tp + fp + fn)
except ZeroDivisionError:
return 0.0 | 8ba6beeb0c8fe8c20e9d12fec462474c8d15de5b | 628,504 |
import re
def FindProperties(data):
"""Finds extra properties for a file.
Finds strings of the form '@PROPS[name name name]'.
Args:
data: The contents of the file being checked.
Returns:
A list of properties from the PROPS line in the file.
"""
match = re.search(r'@PROPS\[([^\]]*)\]', data)
if... | a7a3ae636fdcfb13d17977b9d36535fbd6adab6f | 628,505 |
def construct_version_string(major, minor, micro, dev=None):
"""
Construct version tag: "major.minor.micro" (or if 'dev' is specified: "major.minor.micro-dev").
"""
version_tag = f"{major}.{minor}.{micro}"
if dev is not None:
version_tag += f"-{dev}"
return version_tag | 4734dc4627dbeebb9562ebc800092f3368010af1 | 628,507 |
def get_width(c):
""" 计算字幕宽度
:param c:
:return:
"""
widths = ((126, 1), (159, 0), (687, 1), (710, 0), (711, 1), (727, 0), (733, 1), (879, 0), (1154, 1), (1161, 0),
(4347, 1), (4447, 2), (7467, 1), (7521, 0), (8369, 1), (8426, 0), (9000, 1), (9002, 2), (11021, 1),
(12350,... | 19ee4c59452b5882cfff6babf88bf4637818f44e | 628,508 |
import torch
def get_valid_positive_mask(labels):
"""
To be a valid positive pair (a,p),
- a and p are different embeddings
- a and p have the same label
"""
indices_equal = torch.eye(labels.size(0)).byte()
indices_not_equal = ~indices_equal
label_equal = torch.eq(labels.unsqueeze(1), labels.unsqueeze(0))... | fb17b18129f85c2a33f7c7ddc571622cab52df7c | 628,509 |
def get_detector(header):
"""Get the first detector image string by giving header """
keys = [k for k, v in header.descriptors[0]["data_keys"].items() if "external" in v]
for k in keys:
if "eiger" in k:
return k
# return keys[0] | c8f43ae35c8d11ded23c561cff4206f4f0cca9ee | 628,510 |
def get_slicing_config(config):
"""Util function that generates config for visualization.
Args:
config: EvalConfig that contains example_weight_metric_key.
Returns:
A dictionary containing configuration of the slicing metrics evalaution.
"""
return {'weightedExamplesColumn': config.example_weight_me... | 43baae2073634a700fc42480fa13893e305c9eb7 | 628,511 |
import os
def get_walk_files(path):
"""
填入文件夹位置获取该目录和其子目录下的所有文件列表,获取的相对路径
:param path
return a list of files inside the path
"""
file_name_list = []
for root,dirs,files in os.walk(path):
for file in files:
file_name_list.append(file)
file_name_list = [x for x in f... | 48fda4c05c2816c938fdab3874e0901a610364de | 628,512 |
from typing import Tuple
from typing import Optional
def sort_categories_key(category: str) -> Tuple[str, Optional[str], Optional[int]]:
"""A function which may be used as the key when sorting a list of categories.
This function assumes categories are based on chemical environments and
compositions (up to... | 7b25de52b6902458ccfbf2e62efce8c8e63be61f | 628,515 |
def out_command_infos(info: str) -> str:
"""命令形式输出"""
return f'>>> {info}\n' | 57a302629f0b4f5231621c67905a94a19ae3c4a8 | 628,516 |
def read_resource_usage_file(recipe_dir):
"""Read resource usage from the log."""
resource_file = recipe_dir / 'run' / 'resource_usage.txt'
usage = {}
if not resource_file.exists():
return usage
text = resource_file.read_text().strip()
if not text:
return usage
lines = tex... | f2e6203da4165dd68e6b285838466238c9a085b0 | 628,517 |
import sys
def extract_emp_stat(loaded_df):
"""
Extracts the employment status of each row. The coded values are the following:
-1 - Invalid value
0 - Not applicable (the sample is under the age of 15)
1 - Employed
2 - Unemployed
3 - Not in workforce
:param loaded_df: The dataframe loa... | 5fd699b494ba2cde21b539c3b9071a00204a7e86 | 628,518 |
def seqgetattr( z, attr, default=None ):
"""like getattr (with a specified default), but on sequences returns a sequence of
getattr results. On sequences, the returned sequence is generally a list, but will be a tuple
if the input be a tuple."""
if hasattr( z, '__iter__') and not hasattr( z, '__cdms_in... | 06d15cc81c7cfaa0dfeed0fca817e55372bd2e46 | 628,519 |
def pmd_core_numbers_from_mask(pmd_core_mask):
""" Convert CPU hex mask to a list of CPU core IDs in a list """
pmd_cores = []
binary_mask = bin(int(pmd_core_mask, 16))[2:]
for i, val in enumerate(binary_mask[::-1]):
if val == "1":
pmd_cores.append(i)
return pmd_cores | 9df0b36e9dc89e34cfaeeb0b0eb2562a9bd7551b | 628,520 |
from datetime import datetime
def get_month_options(year):
"""
Get the month options for the given year.
For the previous year, there is data available for each individual month.
However, for previous years only the aggregate statistics is available.
Parameters:
year: (int): The year for... | dc68b71134e9628f61228215d0394ae189aee08f | 628,521 |
def binomial_coefficient_faster(n, r):
"""
A faster way to calculate binomial coefficients
>>> binomial_coefficient_faster(10,5)
252
"""
if 0 <= r <= n:
#initializing two variables as 1
ntok = 1
rtok = 1
#we use the formula nCr = n!/(n-r)!r!
for t in ran... | 1678b9295d68f5d4c49a14e048385a6af202e085 | 628,522 |
import math
def get_utm_zone_epsg(lon: float, lat: float) -> int:
"""
Calculates the suitable UTM crs epsg code for an input geometry point.
Args:
lon: Longitude of point
lat: Latitude of point
Returns:
EPSG code i.e. 32658
"""
zone_number = int((math.floor((lon + 180... | 68688609ad2f445bd808a07576137fa9763fb113 | 628,523 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.