content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def full_invoiceitem(faker):
"""Returns a dict for an `InvoiceItem`."""
full_item_dict = {
"service": "Some Material",
"qty": 5.0,
"unit_price": 12.3,
"vat": 19.0,
"description": faker.sentence(nb_words=5),
}
return full_item_dict | 307c430ea0611cf5afef0672b098f1abc73f6504 | 636,285 |
import os
def scan_dir(path, ending):
"""Recursively scan the folder"""
file_list = []
dir_list = []
for curr_dir, _, local_files in os.walk(path):
# filter local files
local_files = [os.path.join(curr_dir, x) for x in local_files if x.endswith(ending)]
# append to global list
file_list += local_files
i... | ac35c541c223b3945e7cce82d45abee9fb29187d | 636,286 |
from typing import List
import inspect
def _get_failing_lines(code, lineno: int) -> List[str]:
"""Get list of strings (lines of code) from lineno to lineno+3.
Ideally we'd return the exact line where the error took place, but there
are reasons why this is not possible without a lot of work, including
... | 9256aefe6fcb950cd0b4bf822dcb3c306ac17023 | 636,287 |
import re
def parseWordsFromText(text):# {{{
"""
从文档数据中解析出单词
忽略小于3个字符的单词, 字符统一转变为小写
"""
wordsList = re.split(r'\W*', text)
return [word.lower() for word in wordsList if len(word) > 2] | 2d93283383381dadda3e08b85bb9b6522a83fee8 | 636,288 |
import numbers
def is_identically_zero(x):
"""
Check if argument is exactly the number zero. True for the number zero;
false for other numbers; false for :class:`~torch.Tensor`s.
"""
return isinstance(x, numbers.Number) and x == 0 | 1902dd9d3af0985fee78115e16d99b93107e5c22 | 636,289 |
def isDate(anw):
"""
функция для определения соответствия ответа пользователя параметрам даты
:param anw: ответ пользователя
:return: true - если это дата, false - в ином случае.
"""
anw = anw.split('.') # преобразование строки ответа пользователя в список
a = all(x.isdigit() for x in anw) ... | 9499edcfe4a3873efcea5d202191cafe2071cf7d | 636,290 |
def generate_extern(component, key, alias, suffix, specify_comp=True):
"""
This function generates a type trait label for C++
"""
if specify_comp:
return "TIMEMORY_{}_EXTERN_{}({}, {})".format(
key.upper(), suffix.upper(), alias, "::tim::component::{}".format(component))
else:
... | 1ca357381bc697e2bc5e4c6fe0c32a7a50489305 | 636,291 |
import json
def _load_predictions_dicts(filepath):
"""Returns list of predictions dicts."""
predictions_dicts = json.load(open(filepath))
return predictions_dicts | 553c0eb7ad076433cc5d88272f3f77845277a71e | 636,292 |
import imghdr
def fileTypeChanged(file_one, file_two):
"""
Return: True if the file types of the two provided files do not match
"""
try:
one_type = imghdr.what(file_one)
two_type = imghdr.what(file_two)
return one_type != two_type
except:
pos = file_one.rfind('.')... | c396afbbdd83959ee6b80b359b65373d6617751b | 636,293 |
def train_test_split(df_ml):
""" Split log data into train and test by well ID """
test_wells = set(['B03', 'B05', 'B06'])
train_wells = set(df_ml.HACKANAME.unique()) - test_wells
print('Train well: ', train_wells)
print('Test wells: ', test_wells)
mask_train = df_ml.HACKANAME.isin(train_wells... | cb397c984b94b08922e9fbef6f061bbc91f08d70 | 636,294 |
def _extract_first_argument(args: tuple, kwargs: dict):
"""
Returns the tuple (X, _args, _kwargs) where X is the first argument (
found in either args or kwargs), and _args, _kwargs are the same (with X
removed)
>>> _extract_first_argument((1,2,3), {'d': 4})
(1, [2, 3], {'d': 4})
>>> _extra... | 72ce272e241f1d9a74bda4075859a847d33066aa | 636,295 |
def simple_hello(name="you"):
"""Returns string with greeting."""
return "Hello {}!".format(name) | f4b016d3cc145a3adfca1cf67f5791da2a6ff473 | 636,296 |
import inspect
def generate_kwargs_dictionary(func, params):
""" Given a function with keyword parameters and a dictionary return a subset of the
dictionary that only contains keys that match keyword arguments
"""
kwargs={}
for key in params:
if key in inspect.getfullargspec(func)[0]:... | 8b15df0e5e9907e1c0aefac19d1156b9fc6da0e3 | 636,297 |
def parse_summary_file(summary_file):
""" Parse a summary file generated by this pipeline
and return the metrics as a dictionary {"metric":val}
summary_file : str; the path to the summary file
"""
metrics = {}
with open(summary_file,"r") as IN:
for line in IN:
contents = lin... | 1004c7cfc517f8ad8c254c4fef04eaea6f72fb73 | 636,298 |
def get_raw_cc(raw_group, unit_id):
"""
Get Raw CC unit
"""
pos = raw_group.df['cc_unit'] == unit_id
cc_unit = raw_group.df.loc[pos]
cc_unit = cc_unit.groupby('time')[['load', 'HTINPUT']].sum()
cc_unit = cc_unit.reset_index()
cc_unit['heat_rate'] = cc_unit['HTINPUT'] / cc_unit['load']
... | eb15f4723c4103e86765f533d184d5186a0a72c0 | 636,299 |
def html_post_line(mark_value, post_filename, title, post_url_done=False, class_name=None):
""" Build post reference line
See: https://jekyllrb.com/docs/liquid/tags/#link
Called by gen_posts_by_vote() directly
Called indirectly by gen_posts_by_tag() via html_posts()
"""
opt_tag = ""... | 1aebd1e4fc0c99b9c797c3e63a0483b650c62b72 | 636,300 |
def find_shortest(array: list[int]) -> int:
""" Find the shortest element in an array.
find_shortest
=============
The `find_shortest` function takes an array and finds the shortest element
in it.
Parameters
----------
array: list[int]
An array/list of integers
Returns
-------
... | 46d4de53f22e0dcf8c5d3a200c082df0041cbeef | 636,302 |
from optparse import OptionParser
def parse_cmd_line_args():
"""
Parse command line parameters
"""
parser = OptionParser()
parser.add_option("-f", "--force_recompute", dest="force_recompute",
default=False, action='store_true',
help="Force a recomputati... | 3bd01ad0a091e3bafdc4fdd399b304fccf3433d1 | 636,303 |
def PrintStabilizationMatrix(Tau, params):
"""Auxiliary function to print the stabilization matrix"""
print("The Stabilization term matrix is:\n")
dim = params.dim
for i in range(0, dim + 2):
for j in range(0, dim + 2):
print("Tau[", i, ",", j, "]=", Tau[i, j], "\n")
return 0 | 6809f13b03242c4d5e0b5875aa6db58f9f38993f | 636,304 |
def _user_keyed_dict(reader):
""" create a dict of the rows of the csv, keyed by the "user" value """
return {row['user']: row for row in reader} | 344f8fcd8e61a7f8cb45762210a80f2fd7e78d0d | 636,305 |
def bsub(a, b):
"""binary subtract"""
return bin(int(str(a),2)-int(str(b),2)) | 5b5fd2fd8d24e5c8def9098a18dfb54d662eaabe | 636,306 |
def sign(x):
"""Sign function.
:return -1 if x < 0, else return 1
"""
if x < 0: return -1
else: return 1 | 64d85692c0a26fc1918024c95c9c554d92a3d2e7 | 636,307 |
def get_results_from_dict_of_sets(list_of_elements, dict_of_sets):
"""
We have a list of elements that are in a dict of elements, and every element have a set with results.
We want to extract the results corresponding to our elements.
"""
results = set()
for element in list_of_elements:
... | 38e1d243d149cfdf42712acc8a71f26436c60b69 | 636,308 |
import os
def _fix_path(path):
"""Expands ~, normalizes slashes, and converts relative paths to absolute."""
if not path:
return path
return os.path.abspath(os.path.expanduser(path)) | 34929fdeafa0537f2caa780df51e4b742acafaf9 | 636,309 |
from sqlite3 import dbapi2 as sqlite
import os
import time
def svn_rev_info(path):
"""Fetch information about the current revision of an Subversion checkout.
@param path: directory of the Subversion checkout
@return:
- tag (name for the repository),
- rev (current Subversion revision iden... | 2dd6d345ac5371d0fe23aec2287aef3ad02225e1 | 636,310 |
def largest_factor(n):
"""Return the largest factor of n*n-1 that is smaller than n.
>>> largest_factor(4) # n*n-1 is 15; factors are 1, 3, 5, 15
3
>>> largest_factor(9) # n*n-1 is 80; factors are 1, 2, 4, 5, 8, 10, ...
8
"""
factor = n - 1
while factor > 0:
if (n*n-1) % factor ... | deaad22f8a5c11a696c8410b8d179b0dc38c8a93 | 636,311 |
import argparse
def get_arg_link() -> str:
"""It takes a link from from command line arg."""
parser = argparse.ArgumentParser()
parser.add_argument('post_link')
arg = parser.parse_args()
return arg.post_link | 77dab5439ea0db140e8ee01dc53b52832a770652 | 636,312 |
def filter_names(_fin='filters.txt'):
""" Only these filter names should be used
:param _fin:
:return:
"""
with open(_fin, 'r') as f:
f_lines = f.readlines()
return [l.split()[0] for l in f_lines] | 62ac06b00f2d23e0e1a94732ebdf14308db36b1b | 636,313 |
import torch
def compute_pairwise_overlaps(masks, masks_target=None, mask_thresh=None, eps=1e-6):
"""Find overlaps between masks"""
B, N, P = masks.shape
if masks_target is None:
masks_target = masks
if mask_thresh is not None:
masks = (masks > mask_thresh).to(torch.float32)
ma... | 9bb4145c5177110dae4acc9ab3f7adcc894cfb92 | 636,314 |
def boolNot(num):
""" return True if num is not 0 """
return num != 0 | 445aee860bf58c174cae51faa48b0aa55c70f553 | 636,315 |
from typing import List
import os
import logging
def get_tokens(token_file: str) -> List[str]:
"""
Get a list of GitHub tokens from the supplied file. Assumes one token each line, and ignores blank line.
:param token_file: path to the token file
:return: A list of GitHub tokens
"""
if not os.p... | b02b70498ee0b34cc87b3299b4277478ca9a9185 | 636,317 |
def initial_state(particle,self):
"""
Set the state of the particles to the state of the
base model.
"""
self.states[particle,:] = self.base_model.agents2state()
return self.states[particle] | c9e4649d87de06c80883688dbfdb0d8794a695d0 | 636,318 |
def get_mbean_name(location, existing_names, alias_helper):
"""
Return the mbean name for the specified location.
For unpredictable single folders:
1. if an existing folder name is present, use that name as the mbean name.
2. set the location's token to the mbean name.
:param location: the l... | c973073fd02c82179326d089ec4680012f7fd724 | 636,319 |
import os
def bw_to_config_f1(x, **kwargs):
"""Generate the config.ini file for files: bigWig
Parameters
----------
x : str
path to the bigwig file
Keyword arguments
-----------------
color=None,
min_value=0,
max_value='auto',
nbins=700
Example... | b4b4557404927a38dcfe75071389ccf5199358df | 636,321 |
def _stanza_handler(element_name, stanza_type, payload_class, payload_key,
usage_restriction):
"""Method decorator generator for decorating <message/> or <presence/>
stanza handler methods in `XMPPFeatureHandler` subclasses.
:Parameters:
-... | 8614952f9101f3613a2f8a0e6de6b2fe58c22c44 | 636,322 |
import functools
def memoize(func):
"""Memoize a function by storing a dictionary of {inputs: outputs}."""
memo = {}
@functools.wraps(func)
def memoizer(*args):
try:
return memo[args]
except KeyError:
memo[args] = func(*args)
return memo[args]
... | 9bc34ad2b05cc8baa65f564a56f7d6b8c21c8756 | 636,323 |
def rearrange(dict_origin, new_dict = None):
""" Introduce hierarchy based on tag directives and clean up dict.
Responds to group tag
"""
if new_dict is None:
new_dict = {}
for key, value in dict_origin.items():
if isinstance(value, list):
new_dict['items'] = []
accum_list = new_dict['items']
for... | 5937349dcc5fcf6b5a797941ce5ba0079a15df14 | 636,324 |
def error_500():
"""Respond to the 500 error test."""
return ('Internal server error', 500) | 2206666b3b640d024f230f9379cc97abfb047073 | 636,325 |
def get_item_from_gcp_response(key_field, key_name, items):
"""
Get item from GCP REST response JSON list by name.
items = [{ 'key_field': 'key_name', 'key_field_value': 'value'}]
:param key_field: item dictionary key
:param key_value: item dictionary value
:param items: list of items(dictionari... | befec2b2059e08c9979e36373bb929ba838450a8 | 636,327 |
import ftplib
import socket
def list_ftp(site, username = None , password = None, dir = None):
"""
lists contents of typical FTP download site. returns two lists, the first is of
filenames, the second is of full filepaths (including filenames) that one could
patch through to the "download_url" functio... | 3e917e6137e62c2f59d2b6927b686bfa853fe30d | 636,328 |
import re
def _FormatNameAsConstant(name):
"""Formats a name to be a C++ constant of the form kConstantName"""
name = '%s%s' % (name[0].upper(), name[1:])
return 'k%s' % re.sub('_[a-z]',
lambda m: m.group(0)[1].upper(),
name.replace('.', '_')) | 9ac8d9ca9438e5c4732b37f39e7432bb95fc72d5 | 636,332 |
def is_boxcar(die1, die2):
"""Return true if face values of die total 12."""
BOXCARS = 12
return True if (die1 + die2 == BOXCARS) else False | aa5cbd48e52f9a470d51fbe758907131b427080b | 636,333 |
def calc_statistic(data):
"""
Calculation and construction of statistical model in the percentage ratio: count of requests,
methods, parametres for each level etc.
:param data: dictionary that must contain key 'paths' and assigned with this key values
:type data: dict
:return: statistical model
:rtype: dict
... | 031d980c9fa630a2011291b597c372a6a6d76074 | 636,334 |
def is_a_conv_layer_label(layer_label):
""" Returns true if a convolutional layer. """
return 'conv' in layer_label or 'res' in layer_label | aa25733ece3ef837f77bbe2adc61c208e6dfa380 | 636,335 |
from pathlib import Path
from typing import List
import glob
import subprocess
def zip_file_generate(path: Path, prefix: str):
"""Convert gerbers into a .zip file."""
def glob_paths_get(path: Path, file_pattern: str) -> List[Path]:
"""Return a list of Path that match a file pattern."""
# prin... | 27609fb17918a6e779e0b6fb4193b4ed5b2cbadd | 636,337 |
import inspect
import re
def get_argname_in_call(call_name, arg_no):
"""
Utility function for extracting the name of an argument in a function
call.
Caveat: the function call is obtained as a string, and the arguments
obtained by splitting that string with respect to comma.
This can easily le... | af23eb892831fcaab974a33f48d827341878134c | 636,338 |
import math
import random
def randint_sample(min, max, size):
""" Generate sample of random integers number inclusively """
width = max - min + 1
return [math.floor(random.random() * width + min) for _ in range(size)] | d59047b4c6317fff45c0aaa460887f8d6fbb0665 | 636,339 |
import argparse
def parse_arguments():
"""
Parse the arguments from the user
"""
parser = argparse.ArgumentParser(
description = "MetaWIBELE-prioritize: prioritize importance of protein families based on binary annotation\n",
formatter_class = argparse.RawTextHelpFormatter,
prog = "filter_prioritization.py"... | 1da47db807319a6d87a0b0f0890ed944b2ca8b05 | 636,340 |
def findSlowness(edge):
"""Retrieve fastest cell neighboring an edge."""
assert hasattr(edge, 'leftCell') and hasattr(edge, 'rightCell')
if edge.leftCell() is None:
slowness = edge.rightCell().attribute()
elif edge.rightCell() is None:
slowness = edge.leftCell().attribute()
else:
... | 4a105baed21171967c96c2d4ea5f9e261adee25e | 636,341 |
import typing
import pathlib
def is_path_obj(obj: typing.Any) -> bool:
"""Is given object ``obj`` a pathlib.Path object?
"""
return isinstance(obj, pathlib.Path) | 52e44eb1e2b6dc448f6fd828f8e5e2ef758a0bb6 | 636,344 |
def table_to_csv(table_name):
"""
DESCRIPTION: Turn table name into filename, i.e., add .csv
INPUT: table name (filename without extension)
OUTPUT: filename (with extension)
"""
csv_filename = str(table_name) + '.csv'
return csv_filename | 5114f5b5a86644b38fa16f22ff065c804f8222f5 | 636,345 |
def __isInBounds(x: int, y: int, nRows: int, nCols: int) -> bool:
""" Check if x and y is within bounds """
return (x >= 1 and x <= nCols and y >= 1 and y <= nRows) | 36a8640dda0304bb4e8223f1263b35798b673144 | 636,346 |
import unicodedata
def is_wide(char):
"""is_wide(unicode_char) -> boolean
Return True if unicode_char is Fullwidth or Wide, False otherwise.
Fullwidth and Wide CJK chars are double-width.
"""
return unicodedata.east_asian_width(char) in ("F", "W") | f2b0399c25c6d6b7fcdc8d577e0440fa7f7992e5 | 636,347 |
def vrh(kclay, kqtz, vclay):
"""
Voigt-Reuss-Hill average to find Kmatrix from clay and qtz components.
From Smith et al, Geophysics 68(2), 2003.
Works for any two components.
Args:
kclay (float): K_clay.
kqtz (float): K_quartz.
vclay (float): V_clay.
Returns:
... | 7a3461d1643b5ea35e90ebfbd565ea50efaf4034 | 636,348 |
import os
def _full_path(file_):
""" Figure out the location of an atomic datafile.
Files are all located in adas_data, which is at the same level
as the package directory, so to get there we must go up one.
"""
# __file__ is the location of atomic_data.py
module_path = os.path.dirname... | 9bbb60407632a5ad05dd60b1d06f0fee27e1db71 | 636,349 |
import numpy
def find_homography(src, dst):
"""
各座標系の対応する4点以上の位置から
射影変換行列を作成します
:param src:
:param dst:
:return:
"""
# X = (x*h0 +y*h1 + h2) / (x*h6 + y*h7 + 1)
# Y = (x*h3 +y*h4 + h5) / (x*h6 + y*h7 + 1)
#
# X = (x*h0 +y*h1 + h2) - x*h6*X - y*h7*X
# Y = (x*h3 +y*h4 + h... | d0ff638d308cf02ee0508ebdb54296b052511c7e | 636,350 |
def efd_name(csc, topic):
"""Get a fully qualified EFD topic name.
Parameters
----------
csc : str
The name of the CSC.
topic : str
The name of the topic.
"""
return f"lsst.sal.{csc}.{topic}" | 077ada0d1285741a748a6053720d57d2863702ca | 636,351 |
from datetime import datetime
def month_start(src_time):
"""Return the beginning of the month of the specified datetime"""
return datetime(src_time.year, src_time.month, 1) | ced437ee7c2246bf22a6282725e1c618cbe4c79b | 636,352 |
import subprocess
import os
def start_standing_subprocess(cmd):
"""Starts a non-blocking subprocess that is going to continue running after
this function returns.
A subprocess group is actually started by setting sid, so we can kill all
the processes spun out from the subprocess when stopping it. Thi... | 328992917afc082655c46238c2f7ff982f03c2f7 | 636,354 |
def get_reg_value(reg_key, value):
"""Helper method to retrieve a specific value"""
try:
return reg_key.value(value)
except:
return None | ba9e2e3d7b4cb5ba5e263b460c4bfbeb0762b835 | 636,355 |
import string
def base62_encode(num: int) -> str:
"""
Encode a positive number using 62 characters 0-1a-zA-Z
"""
charset = string.digits + string.ascii_letters
size = len(charset)
result = ''
while True:
num, rem = num // size, num % size
result += charset[rem]
if n... | fcf113d30f3ab037b09e83c678c802bcf15d2aa9 | 636,356 |
import re
def extract_path(path_string):
"""Convert a path string to a list of names"""
return re.findall(r"[^/\\]+", path_string) | 85f6894688f458aaa4d8bf168f9a667c8ef2cc01 | 636,357 |
def complemento_base (base):
"""
(str)-> (str)
Programa para complementar la base dada
>>> complemento_base('T')
'AT'
>>> complemento_base('G')
'CG'
>>> complemento_base('C')
'GC'
:param base: base a complementar
:return: base complementada
"""
comp_base = ''
... | 8aa638c4b9f09e799c7b4ffef3d761b415609cfa | 636,358 |
def defaultTransformation(mol):
"""
defaultTransformation() returns the mol it receives as parameter.
For testing, corrsponds to a .sdf copy action without any molecule transformation
"""
return mol | 6f83888da21366eded67d9c8e917aeba4ffbac84 | 636,359 |
def equal_size(list1, list2):
"""
Function to equalise the size of two lists.
...
Attributes
----------
list1: list
list2: list
"""
if len(list1) > len(list2):
s = len(list1)-len(list2)
list1 = list1[:-s]
return list1, list2
if len(list2) >... | 6a046f241703977437eb40bd41c6825013b6223d | 636,360 |
from typing import List
import re
def parse_csv(text: str) -> List[str]:
"""Parse comma separated **double quoted** strings in behave steps
Args:
text: double quoted comma separated string
Returns:
List of string tokens
"""
return re.findall(r"\"(.+?)\"\s*,?", text) | 76c2a38fa61d3f298ae26d9eddd0652d8ff94fd5 | 636,361 |
import torch
from typing import cast
import warnings
def predict_segmentation(
logits: torch.Tensor, mutually_exclusive: bool = False, threshold: float = 0.0
) -> torch.Tensor:
"""
Given the logits from a network, computing the segmentation by thresholding all values above 0
if multi-labels task, comp... | f2a3b9ae91e8d3b3d881bf0d4f898548ef09940c | 636,362 |
def _GetMetaDict(items, key, value):
"""Gets the dict in items that contains key==value.
A metadict object is a list of dicts of the form:
[
{key: value-1, ...},
{key: value-2, ...},
...
]
Args:
items: A list of dicts.
key: The dict key name.
value: The dict key value.
R... | 09255e96666a6a29cce3926428834a560d1ba019 | 636,363 |
import math
def round_down_to_multiplicity(multiplicity: int, num: int):
"""
Function to round a number to the nearest multiplicity given the multiplicity
:param multiplicity: multiplicity for rounding
:param num: input number to be rounded
:return: number rounded down to nearest multiplicity
... | 4ecee2a0341c197a9e263116ee4ed61227ae2d2e | 636,364 |
import six
def sort_db_results(results):
"""Deterministically sort DB results.
Args:
results: List[Dict], results from a DB.
Returns:
List[Dict], sorted DB results.
"""
sort_order = []
if len(results) > 0:
sort_order = sorted(six.iterkeys(results[0]))
def sort_ke... | 3cdd879082d60829b3686ac6e2e7a5c7f758c655 | 636,365 |
def Add(xs, **unused_kwargs):
"""Adds two tensors."""
return xs[0] + xs[1] | 40cd7ba1e7d9d76a93deab2bd45fb60b3b116264 | 636,367 |
def last_answers(data):
"""Modifies the given data object so that only the last answers of
students are contained in the data.
:param data: The object containing data.
:type data: :class:`pandas.DataFrame`.
"""
data = data.sort(
['user_id', 'place_id', 'inserted']
).groupby(
... | cf734596107c883c6390303080fba5da6070c305 | 636,368 |
import os
def get_ndt_dir():
""" Gets cross platform ndt directory path. Makes sure it exists. """
ndt_dir = os.path.expanduser("~/.ndt")
if not os.path.exists(ndt_dir):
os.makedirs(ndt_dir)
return ndt_dir | 0f49aa132da0e34eb85e5e94f3fcdc6e19b5f1c0 | 636,369 |
def create_row(size):
"""Returns a single, empty row with the given size. Each empty spot is
represented by the string '-'.
>>> create_row(5)
['-', '-', '-', '-', '-']
"""
return ['-' for i in range(size)] | 6a9a01efab2bae00f016b58324e187f734f904cd | 636,370 |
def get_section_num(courseware_num, level=3, sep=".", template="{:d}"):
"""根据等级获取课件的标号"""
return sep.join(list((map(lambda x: template.format(x), courseware_num[:level])))) | 98b0aa5efd3ea88173938c3654f3d61fe0f014da | 636,371 |
import os
def path_exists(path: str) -> bool:
"""
Checks specified path exists.
:param path: Path to check
:type path: str
:return: True if path exists else False
:rtype: bool
"""
return os.path.exists(path) | 2c78985e58df2ef2aff0ad9a6a09feba908bab55 | 636,373 |
def load_slide_urls():
"""Create a hierarchical mapping to slide PDF urls based on text file."""
with open("tutorials/slide_links.txt") as f:
lines = filter(bool, f.read().split("\n"))
slide_links = {}
for line in lines:
day, topic, url = line.split()
if day not in slide_links:
... | 9e5aca8db9c665bc1508051f76055143954f4593 | 636,374 |
def has_valid_token(client):
"""Does the session have a valid token?"""
return client.authorized | 9ede665bb18a25fb05e30f8d640456f73e64c751 | 636,375 |
import re
def get_version(string):
""" Retrieve the ``__version__`` attribute for Layabout. """
flags = re.S
pattern = r".*__version__ = '(.*?)'"
match = re.match(pattern=pattern, string=string, flags=flags)
if match:
return match.group(1)
raise RuntimeError('No version string could ... | 36aa18a6750fc5d17e1da13ba6768afe7b52960d | 636,376 |
import time
def benchmark_model(model, all_dataset, transformers, metric, test=False):
"""
Benchmark custom model.
model: user-defined model stucture
For user define model, it should include function: fit, evaluate.
all_dataset: (train, test, val) data tuple.
Returned by `load_dataset` function.
tra... | b15e6d2f1b613f3fb28567c367a1451f40453db6 | 636,377 |
def unpack_string_from(data, offset=0):
"""Unpacks a zero terminated string from the given offset in the data"""
result = ""
while data[offset] != 0:
result += chr(data[offset])
offset += 1
return result | b3b8f5524458eae767c1041c450709925aa111d0 | 636,378 |
import pandas
def sequences_from_gff3_metadata( file ):
"""GFF3 files from the Ensembl ftp site list sequences and their lengths in the file metadata.
This function parses this information and returns it as a pandas dataframe.
It's use may be specific to the Ensembl files."""
result = []
for line ... | 2fedb09d715f94f68621c11363dd5565cca00d70 | 636,380 |
def index(array: list, n: int) -> int:
""" This function find the N-th power of the element in the array with the index N. """
for k, i in enumerate(range(len(array))):
if i == n:
return (array[i] ** n)
return -1 | 2339899c83a6549b077a73d7da8eab0af7a76e67 | 636,381 |
def load_coin_value(file_name):
"""
load the starting value of a coin for a given file_name
"""
try:
with open(file_name + 'spy.txt', 'r') as f:
file_content = f.readline()
whitespace = file_content.find(" ")
file_content = file_content[1:whitespace]
r... | f68429441760ef19e4dd4bbe143c482deb04ce9c | 636,382 |
def sv_score_parser(filename):
"""
parse score into notes
"""
with open(filename, "r") as file_handle:
lines_score = file_handle.readlines()
list_note = []
for ls in lines_score:
note = ls.split('\t')
list_note.append([float(note[0]), int(note[1]), float(n... | bccebd44b93cde13e41f0e471f422414330dbfb5 | 636,383 |
def string_to_bytestr(string):
"""
Convert a string to a bytes object. This encodes the object as well which
will typically change ord on each element & change the length (i.e. 1 char
could become 1/2/3 bytes)
"""
return string.encode('utf-8') | cbb067ecec4fde4cb4b1ed9a7ee0959557e5ba8c | 636,385 |
def get_nextsong(client, status):
""" Return next song dict
"""
next_id = status["nextsongid"]
song = client.playlistid(next_id)[0]
url = song["file"]
if "name" in song:
artist, title, album = song["name"].split(" - ")
else:
artist = song["artist"]
album = song["alb... | db6658f2f50ccc6c8c118b1cc6ae0e2d09b569e6 | 636,386 |
def code() -> str:
"""
Example G-code module, an arrow.
Please simulate first, before milling.
"""
return ("""
G91
G0 X0 Y2
G0 X0 Y-4
G0 X0 Y2
G0 X-20 Y0
G0 X40 Y0
G0 X-5 Y-5
G0 X5 Y5
G0 X-5 Y5
G0 X5 Y-5
""") | 938b29301916f12464c93984caf2ab791b691a17 | 636,387 |
def to_capital(word: str):
"""
Make the 'word' parameter capitalized
:param word: string to be capitalized
:return: capitalized string
"""
return word.capitalize() | a764b1765ee1f90272ec6671d362a1b7edd07d72 | 636,388 |
import json
def secret_json():
""" Create secret as a JSON dictionary """
secret_string = '{"secrets.yaml":"foo","place/cert.pem":"bar"}'
return json.loads(secret_string) | 7df52462db8633c59efa923b94002ad4688df4d4 | 636,389 |
def get_count_and_move(s: str, pos: list) -> int:
"""
Extract a repeat {count} from s[pos[0]:]
Args:
s (str): the string to extract from.
pos (list): pos[0] points to the next char in s to start extracting.
Returns:
int: the repeat count that was extracted.
pos[0]: sinc... | a1eba48975c62dd1330930a9208f39aa79e56af4 | 636,390 |
def string_to_score(string, ignore_case=False):
"""字符串转换成数字分值:基于数据的前6个字节(48位二进制)进行转换"""
if ignore_case:
string = string.lower()
pieces = list(map(ord, string[:6]))
while len(pieces) < 6:
pieces.append(-1)
score = 0
for p in pieces:
# 给每一个ASCII值加上1,使得0作为空字符的填充值
sc... | 3078964aee0a04ea3cb1d99d415d83ed6d11d1ab | 636,391 |
def get_true_pos_rate(predictions, targets):
"""True positive rate/sensitivity
parameters:
predictions: ndarray of model predictions(0 or 1)
targets: ndarray binary targets"""
n_true_pos = (predictions * targets).sum()
n_pos = targets.sum()
return n_true_pos / float(n_po... | 9914d3acb0dbfe6993fb0375ed3c8f92e2347a05 | 636,392 |
def listwise_delete(data, inplace=False, verbose=False):
"""Delete all rows from a DataFrame where any missing values exist.
Deletion is one way to handle missing values. This method removes any
records that have a missing value in any of the features. This package
focuses on imputation, not deletion. ... | f30fda1c3ca5390f77f75d711ebc4c9fe6c79b76 | 636,393 |
import torch
def to_device(m, x):
"""Function to send tensor into corresponding device
:param torch.nn.Module m: torch module
:param torch.Tensor x: torch tensor
:return: torch tensor located in the same place as torch module
:rtype: torch.Tensor
"""
assert isinstance(m, torch.nn.Module)
... | 4aefa9553f1c865ccc8e83dfad2cf8768ca96db3 | 636,394 |
def naorthreshold(lmbda, mu, costofbalking):
"""
Function to return Naor's threshold for optimal behaviour in an M/M/1 queue. This is taken from Naor's 1969 paper: 'The regulation of queue size by Levying Tolls'
Arguments:
lmbda - arrival rate (float)
mu - service rate (float)
costo... | d43c11a8c0fa98102cfeabfc98de6076c0d97f98 | 636,396 |
def _filter_info_warning(lines):
"""$ fio info can issue a RuntimeWarning, but click adds stderr to stdout
so we have to filter it out before decoding JSON lines."""
lines = list(filter(lambda x: 'RuntimeWarning' not in x, lines))
return lines | 513c35a02edcee2f33ec235036f7c2f3d6e70032 | 636,397 |
def is_real(qid, claims, fiction_filter):
"""check for claims that an item is fictional"""
if 'P31' in claims:
for spec in claims['P31']:
if 'id' in spec['mainsnak'].get('datavalue', {}).get('value', {}):
thing = spec['mainsnak']['datavalue']['value']['id']
if... | 56b904aecba8ffcd939cd58cc1cd0e20c590f584 | 636,398 |
import subprocess
def run_clscs_wallet_command(command: str, no_auto_kscsd: bool):
"""Run the given clscs command and return subprocess.CompletedProcess."""
args = ['./programs/clscs/clscs']
if no_auto_kscsd:
args.append('--no-auto-kscsd')
args += 'wallet', command
return subprocess.run... | db68b9036bc7fe19d3c08774ad6684a8eea9407f | 636,399 |
import torch
def _tblr_pred_to_delta_xywh_pred(bbox_pred: torch.Tensor,
normalizer: torch.Tensor) -> torch.Tensor:
"""Transform tblr format bbox prediction to delta_xywh format for ncnn.
An internal function for transforming tblr format bbox prediction to
delta_xywh form... | bdc924322f80b90f502f5a0aea9d1cfa057bc1bc | 636,401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.