content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def smallest_side(length: int, width: int, height: int) -> int:
"""Multiply the smallest edges of a gift to get its smallest side
Args:
length (int): The length of the gift
width (int): The width of the gift
height (int): The height of the gift
Returns:
int: The area of the... | 23255925c38cd2347c543b0c8575381fe0b3809c | 637,882 |
def calc_average(last, current, share_of_use):
"""
function to calculate the weighted average of schedules
"""
return last + current * share_of_use | bfb64e1d6bab377581565a7339416d53a8c181e3 | 637,883 |
import os
def get_key():
"""
return Goodreads API key
"""
return os.environ['GOODREADS_KEY'] | 7ab30dff87a416f678bb21029cd1977153db04fa | 637,884 |
def strip_command(cmd):
"""Returns the command given stripping first part name and removing any first spaces
'/echo test' -> 'test'
"""
if cmd[0] != '/':
return cmd.lstrip(' ')
first_space = cmd.find(' ')
if first_space == -1:
return ''
return cmd[first_space:].lstrip(' ') | 6e8fd9b4a6cf27f86fe54e414f6c8e790ad01b39 | 637,885 |
def closest_distance(atom1, atom2_list):
"""
Most likely distance between atoms is the smallest distance betwen atom
and all the periodic images of atom2 stored in atom2_list.
:param atom1: pmx.model.Atom
:param atom2_list: collection of pmx.model.Atom or PositionAtom
"""
return min([atom1.d... | d7e4e9f4feec00e9577fcf78967eebdb8e3a30ea | 637,886 |
def _detect_fully_listened_track(remaining_duration,
end_of_track_buffer) -> bool:
"""Performs the detection logic for whether a track was fully listened through
Args:
remaining_duration: The remaining duration of the track in milliseconds
end_of_track_buffer: T... | 7a7a1a04ef5c2bb6f53e81b47842b989d5491028 | 637,887 |
def number(value, minimum=None, maximum=None, cut=False, pad=False):
"""Returns back an integer from the given value"""
value = int(value)
if minimum is not None and value < minimum:
if pad:
return minimum
raise ValueError(
"Provided value of {} is below specified min... | 39c47439abe0a7b2f530caa518c5170cb4e5332b | 637,888 |
import os
def get_all_files(parent_dir, ext=None):
"""Return a list of paths relative to the given dir_path."""
paths = []
for root_dir, dir_paths, file_names in os.walk(parent_dir):
for file_name in file_names:
path = os.path.join(root_dir, file_name)
rel_path = os.path.re... | 929002999067f0a6c6a4cdcdf74a3e63f7ab16f5 | 637,889 |
import torch
def _generate_relative_positions_matrix(length, max_relative_position,
cache=False):
"""Generates matrix of relative positions between inputs."""
if not cache:
range_vec = torch.arange(length)
range_mat = range_vec.repeat(length).view(length... | 8562d6dba70e66b9950c9b52c660e7564836e435 | 637,890 |
from typing import List
def get_filename_from_query(query: List[str]) -> str:
"""Convert a keyword query into filenames to dump the paper.
Args:
query (list): List of string with keywords.
Returns:
str: Filename.
"""
filename = "_".join([k if isinstance(k, str) else k[0] for k in... | e61b2a0ffbfed37df4c77c2829312adc4df94a6f | 637,892 |
def get_object_type(object_id):
"""
Obtain object type
Parameters
----------
object_id : int
object identifier
Returns
-------
object_type : str
type of object
"""
# https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/naif_ids.html
if object_id < -100000:
... | 308e57d50f9f72fce7785ab07461cf98e1672cfb | 637,893 |
def factorial_rec_broken(n):
"""Non stopping recursive factorial function."""
return n * factorial_rec_broken(n-1) | 3a6a6a2da79b142c05044ea2d2ad4ef733e9bc0c | 637,894 |
import sys
def get_root_dir():
"""
获取项目根目录
:return:
"""
base_path = sys._getframe().f_code.co_filename
result = base_path.rsplit('/', 2)
if 1 == len(result): # window平台上路径使用的"\\"
result = base_path.rsplit("\\", 2)
return result[0] | ad7877fedc935e434fa06ed387791357ba5a9080 | 637,895 |
def _to_sRGB(component):
"""
Convert linear Color to sRGB
"""
component = 12.92 * component if component <= 0.0031308 else (1.055 * (component**(1/2.4))) - 0.055
return int(255.9999 * component) | db343553bcb64abe6d6ec72cfde969b3ce0ab263 | 637,896 |
def _import(class_path):
""" Imports a module or class from a string in dot notation. """
bits = class_path.split('.')
mod_name = '.'.join(bits[:-1])
cls_name = bits[-1]
mod = __import__(mod_name, None, None, cls_name)
return getattr(mod, cls_name) | 4d96de56aca59f6aa22c24fc1fe3f006727cc810 | 637,898 |
def trigram_letters(text):
"""Implements the trigram letter idea from Penn & Choma.
Penn, Gerald and Travis Choma. (2006). "Quantitative methods for
classifying writing systems." Proceedings of the North American
Chapter of the Association for Computational Linguistics, pages
117--120.
Args:
text: a s... | fbe038be4db8560fc1b74b2d53ad663acdec1268 | 637,899 |
def is_device_command(self):
"""
Returns true if the command is a Vulkan device command.
:return: boolean indicating if the command is a device command
"""
if len(self.params) == 0:
return False
first_param = self.params[0]
# See: https://cgit.freedesktop.org/mesa/mesa/tree/src/int... | b45f0ac99b062b843bd6179c2c5fed13d2cfcf08 | 637,901 |
import os
import logging
import errno
def mkdir(dirname):
""" Check that a directory can be made then make it
:param dirname: Directory to create
:type dirname: str or os.path
:return: True if successful
:rtype: bool
"""
if not os.path.exists(os.path.dirname(dirname)):
try:
... | d07c75bc92083a98855734d8a17dc05fbbb0b9c3 | 637,902 |
import sys
def indentcount_lines(lines):
""" Minimum indent for all lines in line list
>>> lines = [' one', ' two', ' three']
>>> indentcount_lines(lines)
1
>>> lines = []
>>> indentcount_lines(lines)
0
>>> lines = [' one']
>>> indentcount_lines(lines)
1
>>> indentcount_... | e8760402087cb1a4ad44c13498cc1d9b312c0865 | 637,903 |
def control_change_rate_cost(u, u_prev):
"""Compute penalty of control jerk, i.e. difference to previous control input"""
return (u - u_prev) ** 2 | 09439fa7b2b6afa306e41e85434db3064be0a481 | 637,904 |
def cremona_letter_code(n):
"""
Returns the Cremona letter code corresponding to an integer. For
example, 0 - a 25 - z 26 - ba 51 - bz 52 - ca 53 - cb etc.
.. note::
This is just the base 26 representation of n, where a=0, b=1,
..., z=25. This extends the old Cremona notation (counting f... | afa88dbd202803b8f864ffd6ca624b701a8e631c | 637,905 |
def model_snowmelt(ps = 0.0,
M = 0.0):
"""
- Name: SnowMelt -Version: 1.0, -Time step: 1
- Description:
* Title: Snow Melt
* Author: STICS
* Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002
* Institution: INRA
... | 86aa1da9593a7c20baaba8528ff3220892a4f40d | 637,906 |
def compose( rf1, rf2 ):
"""Combines two reduction functions - normally ones which reduce over different axes -
into one. Each reduction function should take a single MV as an argument and return a MV.
Each should accept an optional keyword argument vid, defaulting to None."""
def rf12( mv, vid=None ):... | 3660e4bf1e6fc84d7e713c9efa62fe02bad620d6 | 637,908 |
def add(x: int, y: int) -> int:
"""Add two numbers.
>>> add(1, 2)
3
Args:
x: An operand.
y: An operand.
Returns:
x + y.
"""
return x + y | d93e4249d3afcef04821b16bad3d7878ac876d0c | 637,909 |
def all_subclasses(cls):
"""Recursively find subclasses of a class.
The subclasses should already be imported for this function to work properly.
Args:
cls (type): Class to inspect.
Returns:
set[type]: The set of subclasses.
"""
return set(cls.__subclasses__()).union(
... | bbb2ea7bd5ca98db05557886e22065bfa5aa7365 | 637,911 |
from pathlib import Path
def api_image_file(
test_image_path: Path,
) -> dict[str, tuple[str, bytes, str]]:
"""Return the dict with file needed to use post requests."""
return {
"file": (
test_image_path.name,
test_image_path.open("rb").read(),
"image/png",
... | 757542bea990c4ae02f071bcd783186efc6c96aa | 637,912 |
import os
import time
import json
from shutil import copyfile
def read_json(file_path):
""" read a file as a string
"""
assert os.path.isfile(file_path)
avail = 'in use'
while avail == 'in use':
time.sleep(.1)
if os.path.exists(file_path.replace('.json','.avail')):
with... | acebb3e39a830baa7d61eec8e412b9998412dccc | 637,913 |
def rolling_apply(df, window, func, shift=1, *args, **kwargs):
"""Calculate rolling apply() to all columns of a pandas dataframe
Function can be used by ApplyFunc module.
:param pd.DataFrame df: input pandas dataframe
:param int window: size of rolling window.
:param func: function to be applied
... | f86aefc605edb252da46c99b3079e659e087063a | 637,914 |
import torch
def output_to_multilabel(out, dim=None):
"""Converts output of an output layer to a class (id) via softmax
and argmax."""
out = torch.sigmoid(out)
out = (out > 0.5)
return out | 65d5ee156f54d2b81bd7a99f7b88154b202f538e | 637,915 |
def get_number_base(bitstring, base):
"""Transfer bitstring to a number in base `base`."""
nr = 0
for place, bit in enumerate(bitstring[::-1]):
nr += base**place * int(bit)
return nr | 1a54f84dd67b245009831258b7e50a28924e7f5b | 637,916 |
def sp_get_dict(sub_dict, param, default):
"""This method yields a standard interface to list of list params.
Parameters:
-----------
sub_dict : dict
Items sub-dictionary of the network dictionary.
param : str
String specifying the parameter to extract.
default : None, int, etc.... | 3bff150b14c4cc6fa4e2376715d904b159ed54c0 | 637,918 |
def eulers_method(f, y, dx, range):
""" The Eulers method for a first order differential equation.
:param f: First order differential equation to approximate the solution for.
:type f: lambda
:param y: The initial condition for the y-value.
:type y: float, int
:param dx: Step size. Smaller ... | a1b31fb2c842c86c89d8e5b7c52188e4cf00d97e | 637,919 |
def prepare_profile_data(results):
"""
Helper function which generates acc and runtime dictionaries which
contain the values for each minimizer.
:param results: The sorted results grouped by row and category
:type results: dict[str, dict[str, list[utils.fitbm_result.FittingResult]]]
:return: d... | dd5fdec51a443e4308838246fe963cad6c760d0c | 637,920 |
def redefines_column(f):
"""Decorator to mark a function as a column_function for all
columns associated with functions with the same name as f.
"""
f._redefines_column = True
return f | 71e3e7100567cbfd7e1e0510b8b064f94974a5cb | 637,921 |
def song_decoder(song):
"""Return decoded song string"""
return ' '.join((song.replace("WUB"," ").strip()).split()) | 26cf4ad6a140d0b66757b2e84b75a91fef04fe07 | 637,922 |
import pickle
def curate_ssl_data(sheet, ast_threshold=30):
"""
Create df of ssl data filtered at ast conc value and nan dropped
returns path
"""
# load premade df
df = pickle.load( open( 'data_handler/files/assay_data/All_lipase_ssl_data.pkl', 'rb' ) )
# filter using AST conc
df = df.... | fa795ec2964c0c143ace5250f0a6d228509c65f8 | 637,923 |
import argparse
def parse_command_line():
"""parse_command_line()"""
"""Read the arguments passed on the command line"""
"""to the script. """
Parser = argparse.ArgumentParser(
description="Plot the spectrum of a source from an ASTRI obs"
)
Parser.add_argument(
"--butterfly",
... | e39dc33ec6c83286db6c7ebfbda985a2762228bd | 637,924 |
def ask_confirmation(action):
"""
Asks the user for confirmation of action.
Parameters
----------
action : str
The action to take place if confirmed.
Returns
-------
str :
The action to be executed if confirmed, aborts otherwise.
"""
confirmation = str(input("P... | 707e2ffdbd6c20b4495561c28a19730fac9e8615 | 637,926 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Gaze estimation using L2CSNet.')
# Gaze360
parser.add_argument(
'--gaze360image_dir', dest='gaze360image_dir', help='Directory path for gaze images.',
default='datasets/Gaze360/... | 26d247074ffacc80fa01b600d85325aba5626697 | 637,927 |
import requests
def buscar_avatar(usuario):
"""
Busca o avatar de um usuário no Github
:param usuario: str com o nome de usuário no github
:return: str com o link do avatar
"""
url = f'https://api.github.com/users/{usuario}'
resp = requests.get(url)
print(resp.status_code)
return ... | 30efe589ab16d0df83ad250eed88574e04260ec2 | 637,928 |
import os
def environ_get(name: str, default=None) -> str:
"""
Get an environment variable, raising an error if it's missing.
"""
val = os.environ.get(name, default)
if val is None:
raise Exception(f"Required environment variable {name!r} is missing")
return val | 0f182c333a02e4cd69644c111bde83048e5040bb | 637,930 |
def overlap(l1, l2, l3, stemlength1, stemlength2):
""" Function: overlap()
Purpose: Handle case that overlap of 1 bp or 2 bps occurs at L2.
A marker is used to indicate whether overlap can be resolved.
Input: Loop and stem lengths of a pseudoknot
... | 95686b0696c4f9348b42697642b64df0643c87f9 | 637,931 |
import argparse
import sys
def get_args():
"""Collect the inputs."""
parser = argparse.ArgumentParser(
description='Visualise the output of Heinz')
parser.add_argument('-i', '--input', required=True, dest='heinz',
metavar='Heinz_output.txt', type=str,
... | a956bb103742c38eee33f5e4edeeaf46a18c063a | 637,932 |
def get_data_minibatched(handlers, flags, data_key, label_key, weight_key):
"""
Handles minibatching the data
"""
data_blob = {'data': [], 'idx_v': []}
if label_key is not None: data_blob['label' ] = []
if weight_key is not None: data_blob['weight'] = []
for _ in range(int(flags.BATCH_SIZE... | 722fda017694758a2bd3e52650c017455fed1905 | 637,933 |
import numpy
def _preprocess_irdata(data, knots, knots_corr=None):
"""Perform preprocessing of IR data"""
data = numpy.array(data)
dim, nsegments, polyorder = data.shape
if knots_corr is None:
knots_corr = numpy.zeros_like(knots)
# First, the basis is given by *normalized* Legendre functi... | 8770ff4df8d2d93b01188843ced810994e6fb8c3 | 637,934 |
from pathlib import Path
import os
def get_src_files():
"""
Returns a list of strings that contains paths to all the source (.py) files
in the 'src' directory and its subdirectories. This is useful for getting a
list of source files to upload to Neptune.
"""
# In order to do the globbing in a ... | c06f5650bd6b5624ece82814529d829ef4cac70b | 637,935 |
def clear_refills_2016(oven_refill_ends):
""" Some of the automatically found refills in 2016 are incorrect and
result e.g. from short oven stops. They are cleared out with this
function based on manual selection and comparison with CALS.
Parameters
----------
oven_refill_ends : list of timesta... | 549284be03e6280304847792f7e5ac1d4ce83736 | 637,937 |
def _get_precip(sel_cim_data):
"""Return total precipitation."""
return sel_cim_data.TotalPrecip_tavg | 22c19a4cfe377e7555ecb1c1384e934b54128216 | 637,938 |
import json
import sys
def dump_json(i):
"""Dump dictionary (json) to a string
Target audience: end users
Args:
dict (dict) : dictionary to convert to a string
(skip_indent) (str): if 'yes', skip indent
(sort_keys) (str): if 'yes', sort keys
Returns:
... | b113e52074b7228d33add1385a4bd0957f564cad | 637,939 |
import subprocess
import threading
def spin_for(seconds: int):
"""Run the spin.py program for `seconds`."""
prog = subprocess.Popen(["python", "test/support/spin.py", f"{seconds}"])
thread = threading.Thread(target=lambda: prog.wait())
thread.start()
return prog | 34485d28e2389a3c308879c28ac2eedcfa44bcfd | 637,940 |
import re
import textwrap
def clean_text(text):
"""清理文本.
去掉首尾空格, 将多个空格合并为一个, 替换换行符为一个空格.
"""
text = re.sub(r'(?<=\s)\s+', '', text.strip())
return textwrap.fill(re.sub(r'\n', ' ', text), 79) | 40e1df570fc0c4a57a67be853546600f72cb40d0 | 637,941 |
def clean_hypothesis(hyp: str) -> str:
"""
Remove extra words after the question mark of the generated question
Parameters
----------
hyp : str
Hypothesis question
Returns
-------
str
the cleaned hypothesis question
"""
_loc = hyp.find("?")
if _loc == -1: #... | d9d8d9b5e8d32bf5325bc2658759bba83292c560 | 637,942 |
import os
import codecs
import traceback
def get_references(file_name, encoding="utf-8"):
""" Get footnote and general references from outside source """
text = ''
if file_name is not None:
if os.path.exists(file_name):
try:
with codecs.open(file_name, "r", encoding=enc... | 4f22c80c90d309fef0ab8947c607ed71145bdbb1 | 637,943 |
def __fix_ada_dictionary__(bayesDict):
"""
If convert AdaBoost's "base_estimator" parameter into string
:param bayesDict:
:return:
"""
for k, v in bayesDict.items():
# if k == 'params': # Param grid does not behave properly,
# listDict = bayesDict[k]
# new_params... | 46c873e1545b7cf2bc4a0a3b01fbfb90ac966cf6 | 637,944 |
import logging
def tokenize(tokenizer, sentences):
"""
Given a list of sentences, convert words to vocab ids (0 -> 30522) in each sentence.
This function is supposed to use BertTokenizer from the transformers library.
"""
logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)... | afa661a9451ff86f71a566dfd953edc601713687 | 637,945 |
import numpy
def reflection_from_matrix(matrix):
"""Return mirror plane point and normal vector from reflection matrix.
>>> v0 = numpy.random.random(3) - 0.5
>>> v1 = numpy.random.random(3) - 0.5
>>> M0 = reflection_matrix(v0, v1)
>>> point, normal = reflection_from_matrix(M0)
>>> M1 = reflec... | 79b761ce9f3937cc14c845b661237f206005f149 | 637,946 |
def divide(arg1,arg2):
"""
divides
"""
return arg1 / arg2 | 044c50da0dd0db843f3cfa3efdbaf9d46f4d30a6 | 637,947 |
def calc_gamma(Ti):
"""Derive gamma from Ti"""
return 1.0 / Ti | 4d292cd554ca7ebfc70bc4bbe1d992ac3416b6d0 | 637,948 |
from functools import reduce
import operator
def bitor(*args):
"""
BITOR num1 num2
(BITOR num1 num2 num3 ...)
outputs the bitwise OR of its inputs, which must be integers.
"""
return reduce(operator.or_, args) | f8d3ca6861e2af4d92765efa964ad4d3fedfc94d | 637,949 |
def after_request(response):
"""Modify response headers including Access-Control-* headers.
:param response: An instance of the response object.
:return: As instance of the response object with Access-Control-* headers.
"""
response.headers.add(
"Access-Control-Allow-Headers", "Content-Type... | e72de487bbf1bce1209bd653c5b0b8c491afa716 | 637,950 |
from typing import OrderedDict
def parse_abundances(i, rows):
""" Parse a list of abundances in a cloudy file (gas or grain).
Parameters
----------
i : int
starting row
rows : list of str
the cloudy output file as a list of rows.
Returns
-------
i : int
Row index of... | 720cdeecaa6ecebccce8e23246ff8725db25d4de | 637,951 |
def GRAVITATIONAL_CONSTANT():
"""
The `GRAVITATIONAL_CONSTANT` function returns the Newtonian constant of
gravitation (unit is m3kg-1s-2) according to the NIST reference on
constants, units and uncertainty.
"""
return 6.67408e-11 | c977d09db8f76eb5e3929a5a4ce18596b1a6b706 | 637,952 |
def drop_empty_rows(rows):
"""Return `rows` with all empty rows removed."""
return [row for row in rows if any(val.strip() for val in row)] | 478270e8a47206da33810f7255c5e12bf4658cc0 | 637,954 |
def preprocess(theorem, chromosome):
"""
convert chromosome to complete Coq script
Args:
theorem (list): a list of string contains theorem or some pre-provided
tactic.
chromosome (list): a list of string.
Returns:
byte: a byte string will be passed to coqtop
"""... | 56582dd43ab13e4ca4ffdbf0471129b8c230666e | 637,955 |
def char_to_word_index(ci, sequence):
"""
Given a character-level index (offset),
return the index of the **word this char is in**
"""
i = None
for i, co in enumerate(sequence.char_offsets):
if ci == co:
return i
elif ci < co:
return i - 1
return i | ecdfafd0c301d98d3f600b34022eb2e605a6e1da | 637,956 |
import os
import json
def create_params_file(server, params):
"""Create a params file."""
params_json_path = os.path.join(server['tmp_dir'], 'params.json')
with open(params_json_path, 'w') as file:
json.dump(params, file)
return params_json_path | 6b2359c8aefad641d1399d777cb568fa8598b97e | 637,957 |
def recommend(userid, model, user_items):
"""Returns recommended items for give userid"""
return model.recommend(userid, user_items) | 07c900de3344c06cb3a4ab3ba8757f4639ccbe36 | 637,958 |
import hashlib
def md5(filename):
"""
Return the MD5 hash of a file.
Parameters
----------
filename : str
The name of the file to check.
Returns
-------
str
The MD5 hash in hexadecimal.
"""
with open(filename) as fin:
return hashlib.md5(fin.read().enc... | b67d2ee63c82b31d589bdb2ec28047ef70831bb0 | 637,959 |
def get_dirs(basedir):
"""
Configuration of subdirectory names relative to the basedir.
"""
return {
'templates': basedir + '/templates', # Mako templates
'content': basedir + '/content', # Markdown files
'output': basedir + '/htdocs',
'static': basedir + '/static',
... | a9431de0d0fc30cfb93dd0ff3c677e5ce40cccdb | 637,960 |
def k_factor_new_formula(elo_diff, underdog_won):
""" Calculates the K-factor """
if underdog_won: return (elo_diff + 16) / 32
else: return (0.5 - elo_diff / 32) | e051bd9be767134475a3fe96eac6dd71b39aa474 | 637,961 |
def card_is_special(given_card):
"""checks if the card is special
>>> given_card=('A', '♥', 11)
>>> card_is_special(given_card)
True
"""
return given_card[0]=='A' or given_card[0]=='7' or given_card[0]=='8' or given_card[0]=='9' | e4fdf1e84a94d503f0dd5fd8f15509c3162d8dbd | 637,963 |
def GetTag(client, messages, tag):
"""Gets a tag by its name."""
get_tag_req = messages.ArtifactregistryProjectsLocationsRepositoriesPackagesTagsGetRequest(
name=tag)
return client.projects_locations_repositories_packages_tags.Get(get_tag_req) | 603e58ae3da88d2ae7e13627c34f81614200e883 | 637,964 |
def grab_col_names(dataframe, cat_th=10, car_th=20):
"""
Veri setindeki kategorik, numerik ve kategorik fakat kardinal değişkenlerin isimlerini verir.
Not: Kategorik değişkenlerin içerisine numerik görünümlü kategorik değişkenler de dahildir.
Parameters
------
dataframe: dataframe
... | 8d121e3780d6455e90e9d0fd49bf2d0e543fc310 | 637,965 |
import re
def get_max_deltas(filename):
"""Returns maximum gap parameters for the specified CoMetGeNe result file.
:param filename: CoMetGeNe result file
:return: tuple representing the gap parameters for genome and metabolic
pathway, respectively
"""
pattern = re.compile("--- delta_G = (... | b090413681f751d4de0db0c9f7eb62748c700e39 | 637,966 |
import time
def staleCheck(keyState):
"""basically same as a heartbeat
"""
if time.time() - keyState.lastalive < keyState.checkAfter:
return "ok"
elif time.time() - keyState.lastalive > 5*keyState.checkAfter:
return "critical"
else:
return keyState.defaultSeverity | 7d28b7a1622d266fef38e4880b8b8c027896693c | 637,967 |
from typing import Iterable
def word_join(
iterable: Iterable[str],
use_repr: bool = False,
oxford: bool = False,
delimiter: str = ',',
connective: str = "and",
) -> str:
"""
Join the given list of strings in a natural manner, with 'and' to join the last two elements.
:param iterable:
:param use_repr... | 9ffcbe4a42f273db1138d4779dc9d23e9b5658f9 | 637,968 |
import torch
def evaluate_acc(confidences: torch.Tensor,
true_labels: torch.Tensor) -> float:
"""
Args:
confidences (Tensor): a tensor of shape [N, K] of predicted confidences.
true_labels (Tensor): a tensor of shape [N,] of ground truth labels.
Returns:
acc (floa... | 12691e29500f9bced16a9b03c4ebc05c81d872af | 637,969 |
def run_2(inp):
"""
>>> t = "\\n".join('-1, +1'.split(','))
>>> run_2(t)
0
>>> t = "\\n".join('+3, +3, +4, -2, -4'.split(','))
>>> run_2(t)
10
>>> t = "\\n".join('-6, +3, +8, +5, -6'.split(','))
>>> run_2(t)
5
>>> t = "\\n".join('+7, +7, -2, -7, -4'.split(','))
>>> run_2(... | ca5317a1ceea5787bef746fbd5b372be7fad3246 | 637,970 |
def public(endpoint):
"""Declare an endpoint to be public, i.e., not requiring auth."""
# Store metadata on this function stating that it is unprotected
endpoint.is_protected = False
return endpoint | a775c79533e790abe01809d70f8ffbc49645ce57 | 637,971 |
def rho_t_func_kh(t):
"""Function for rho_t in FW to get KH"""
return 1/(1 + t) | 641abaaeef8e4d1de20865d27c1b44d148bda094 | 637,972 |
from typing import Counter
from functools import reduce
import operator
def add_dicts(*args):
"""
Adds two or more dicts together. Common keys will have their values added.
For example::
>>> t1 = {'a':1, 'b':2}
>>> t2 = {'b':1, 'c':3}
>>> t3 = {'d':4}
>>> add_dicts(t1, t... | 7f4303d574e123cab80ad5cf84fe59f19980b2c6 | 637,973 |
def Newton_method(f, df, start:float=0.0, step:int=1)->float:
"""
From 2.2.py.
"""
fun = lambda x: x-f(x)/df(x)
if step:
val = fun(start)
for i in range(1,step):
val = fun(val)
return val
else:
return start | 6952845a4d8ad9b979d8c4b4e4382c92f7ac348c | 637,974 |
def preprocess_image(image):
"""Preprocesses an image into the form suitable for machine learning
model input.
Args:
image:
The image to preprocess.
Returns:
The preprocessed image.
"""
return image / 255.0 | c74f5a0b12b3487ff0fca7dd2eafa17ae4b3148a | 637,976 |
def h1_to_h3(html):
"""Convert h1 headers to h3 to match other transcription formats,
used to avoid modeltranslation inserting elements into h1 headers"""
return html.replace("h1", "h3") | dc615595f8a60dbc181fbf8f1db578934f7ef3ac | 637,979 |
def check_static_metrics(expected_metrics, error_message=""):
"""Create a callable to verify that the static provider response contains
the expected values.
To be used with the :meth:`run` function. The callable will raise an
:class:`AssertionError` if the static metrics in the response are different
... | 47ed71eb52f079377be83fe70cb5f2534f480bd3 | 637,980 |
import re
def load_query_model(model, obj = None):
"""
Loads a model. Objective can be changed to either "biomass" (regex
will be used) or a valid reaction ID.
Print is used temporary. A general log will be generated in the
final version.
"""
Model = model
if obj == "biomass":
... | 4f9f077736f48865bdb33daad371dba0649b8319 | 637,981 |
def indent_level(line: str):
"""
インデント用のスペースがいくつあるかを返す
"""
for i, _c in enumerate(line):
if _c != ' ':
return i
return len(line) | 3e1938195d4529b3d37fca2252e0acfd02d02076 | 637,983 |
def format_getmember(args):
""" split query string on , to support GET multiple """
return {key: args.get(key).split(",") for key, val in args.items()} | 4a7d59f7a72c9867763330e4ea21e5f04c330122 | 637,984 |
def remove_old(handle, read_start):
""" The remove old function removes the basepairs that do not have sofclips to save memory.
:param softclip_data: A dictionary with positions and the number of "normal" bases and softclip bases.
:param read_start: An integer representing the place where the read start.
... | 9b86597e1d4d1a2dd8e0c7f1173ffef63b36c6b3 | 637,985 |
def is_same_line(rect1, rect2):
"""
Tries to estimate if two rectangles (rect1 and rect2) are at the
same line based on rect1's height.
"""
if all([rect1, rect2]):
h1 = rect1[1] - rect1[0]
return abs(rect1[0] - rect2[0]) <= h1 / 2
return False | a38a55285b8caec2f8e6f97b8cf8de36b8ecf804 | 637,986 |
import torch
def get_atoms_inside_cell(r, N, pbc):
"""Removes atoms outside of the unit cell which are carried in `r`
to ensure correct periodic boundary conditions. Does that by discarding
all atoms beyond N which are not in the reindexing mapping `pbc`.
Args:
r (torch.float): atomic... | 784937ab8c04a08a8e7fb4417750db69ebec4f5e | 637,987 |
import torch
def get_inv_cam(intri_mat, extri_R, extri_T):
"""
all should be in (nview*batch, x, x)
:param intri_mat:
:param extri_R:
:param extri_T:
:return:
"""
# camera_to_world torch.mm(torch.t(R), x) + T
# world_to_camera torch.mm(R, x - T)
# be aware of that: extri T is... | 53c293b6daa9fea9636043c20349ef3088077930 | 637,988 |
def make_preference_space_MovieLens(path):
""" create preference space for Movielens data set
"""
movies = {}
for line in open(path + '/movies.dat'):
(movieid, title) = line.split('::')[0:2]
movies[movieid] = title
preference_space = {}
for line in open(path + '/ratings.dat'):
(user, movieid, rating, ts... | 0c2058b23db7bf96ee639ae785b77f27995fdb04 | 637,989 |
import re
def replace_strip(text):
"""
Remove newline, carriage return, tabs from string and split by ','
Parameters
----------
:param text: input text </br>
:return: list of words
"""
data = re.sub(r"[\n\r\t]", "", text.lower()).split(",")
data = [item.strip() for item in data]
... | da5317b2310faff2c9a015d32af41473e687a737 | 637,990 |
def merge_dict(first: dict, second: dict) -> dict:
"""Merge 2 dict like `{**first, **second}`. This is because Transcrypt cannot actually treat kwargs."""
result = {}
result.update(first)
result.update(second)
return result | 3be70567833287dd2022fe49a15d5b7be64ac0b2 | 637,992 |
import json
import requests
def unpack_response(response):
"""
Fetches the JSON body of a response and returns a tuple composed of the
response itself with the decoded JSON.
"""
try:
j = response.json()
except json.JSONDecodeError:
j = response.text
if response.status_code... | 53c0fd9afd79d294ab282e46ae9feaecf178992f | 637,993 |
import math
def nextTarget(coords, crosshairX, crosshairY):
"""Find the closest target to the crosshair using euclidean distance"""
nearestTgtId = -1
minDist = 1e9
i = 0
for x in coords:
ed = math.sqrt((crosshairX - (int(x[1]) + (int(x[3]) - int(x[1])) / 2)) ** 2 + (crosshairY - (int(x[2])... | 9d8e6d7e218c370f44a2bdf7996aae1789c7db3c | 637,994 |
def update_file_list(file_content, tag_index, formated_informations):
"""
Return the list file_content with formated_informations inserted at
tag_index position.
file_content : list containing the current file
tag_index : position, in list, of tags to insert bet... | c7fc63e07e7602ce53f1af84ff487549bd66469b | 637,995 |
def format_datetime(date_time):
"""Generate string from datetime object."""
return date_time.strftime("%Y-%m-%d %H:%M:%S") | 9123fe7ae7a5d6d08c60c67faa6dd552a20448d5 | 637,996 |
def get_download_ranges_list(range_left, range_right, parts):
"""
function to get a list of ranges to be downloaded by each thread
"""
l = range(range_left, range_right + 1)
dividend, remainder = divmod(len(l), parts)
ranges_list = list( l[i * dividend + min(i, remainder) : (i+1) * dividend ... | 8a6166773e88b56f673d85fc6a581fc5f401defb | 637,997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.