content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def newB(m, point):
"""find the y-intersection that the function/point pair passes through"""
b = (point[1] - (m * point[0]))
return b | 4a29d40da37277fecd296dc082dc2e15a4afcff2 | 640,949 |
import torch
from typing import Tuple
def orthonormalize(
vecs: torch.Tensor,
eps: float = 1e-9
) -> Tuple[torch.Tensor, torch.Tensor]: # pragma: no cover
"""
:param vecs: tensor of shape [n, m] with n <= m
:return: (base, expand)
base.shape[1] == m
expand.shape[1] == m
base.... | 5d25a49960977495afb3f3a89eb0dbd6e94ffaa1 | 640,951 |
import math
def CORMSE(X,Y):
""" caculate the RMSE of X and Y """
num=len(X)
if len(X)!=len(Y) or len(X)==0:
print ("list X and list Y have different length!")
RMSE=9999.0
return RMSE
else:
wucha=0.0
for i in range(num):
wucha=wucha+ math.pow((X[i]... | 1f0504e9fd9f934b8b9fc62b0e51ce50946e5c1d | 640,953 |
import shlex
import subprocess
def run_command(cmd):
"""Run a command"""
lexed = shlex.split(cmd)
proc = subprocess.Popen(lexed)
proc.communicate()
return proc.returncode | 9535e1faea91ab265c6a958b9428a2aed23544f7 | 640,954 |
import filecmp
from typing import Tuple
from typing import Set
import os
def dircmp_recursive(dircmp_obj: filecmp.dircmp) -> Tuple[Set[str], Set[str], Set[str]]:
"""
Compare the content of two directories, recursively.
:param dircmp_obj: the filecmp.dircmp object.
:return: three sets:
- the set ... | c00e3fc9b09de6b58a26d1f1ae41fc501d1c3d0b | 640,955 |
def char2idx(data):
"""char2idx function creates look-up table for the corresponding ids for the labels"""
tag2idx = {t: i for i, t in enumerate(data)}
return tag2idx | 8db15a972c8cc5e59d94e5a859b069017123b54c | 640,956 |
def cfact(n: int) -> int:
"""
>>> cfact(5)
120
"""
if n == 0: return 1
return n*cfact(n-1) | 05d500016eec41019efe7e7215083cfd6df14cc2 | 640,957 |
import math
def computeStartsOfInterval(maxVal: int, intervalLength=1024, min_overlap_part=0.33):
"""
Divide the [0; maxVal] interval into a uniform distribution with at least min_overlap_part of overlapping
:param maxVal: end of the base interval
:param intervalLength: length of the new intervals
... | baea88e231439b5d0cb57eb433126f000301b445 | 640,958 |
def bc_dict_seq2id(bc_index_fpath, col_seq=None):
""" dict[barcode_seq] = barcode_id """
if col_seq is None:
col_seq = 0
out = dict()
with open(bc_index_fpath, 'rt') as fin:
# next(fin) # remove header
# out = list(map(lambda row: row.strip().split(), fin))
# out = {row[... | 0bdeae8ed69036ffeaf6f33ce274f45473dac317 | 640,960 |
def checkPrefix(mainList, inputGTParams):
""" Compares two input GTs to see if they have the same prefix. Returns the index in the internal list of GTs of the match
or -1 in case of no match. """
if inputGTParams.find("_") == -1:
raise Exception("Invalid GT name. It does not contain an _, it cannot ... | 14dc18bb48bbb27e701914f65aac1c1cc1f626b7 | 640,961 |
def currency(value):
"""
Returns a string currency representation of a float
"""
return '${:,.2f}'.format(value) | c9ce50794d1e5c9ede66018b9ded5a25b7e69eaf | 640,962 |
def tensor_to_complex_np(data):
"""
Converts a complex torch tensor to numpy array.
Args:
data (torch.Tensor): Input data to be converted to numpy.
Returns:
np.array: Complex numpy version of data.
"""
data = data.numpy()
return data[..., 0] + 1j * data[..., 1] | bcd49b30eb05d209accfd5f4711807e9322139aa | 640,963 |
def load_password(kp, title):
"""
:param kp: объект PyKeePass
:param title: название записи
:return: записи с указанным названием
"""
entries = kp.find_entries(title=title)
passwords = ''
for ent in entries:
passwords += 'log: ' + ent.username + ', pass: ' + ent.password + '\n'
... | 67331ac1690d47eb3cabd6c97c50449473655520 | 640,965 |
def should_reduce_batch_size(exception: Exception) -> bool:
"""
Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory
Args:
exception (`Exception`):
An exception
"""
_statements = [
"CUDA out of memory.", # CUDA OOM
"cuDN... | 799d2c23ed39bd9579ecbdcd48a6308772f8d9b6 | 640,966 |
def substlab(template, lab_path, lab_file):
"""Read template and substitute labs"""
with open(template, 'r') as temp:
t = temp.readlines()
i = t.index('%TEMPLATE_INSERT\n')
t.insert(i+1, '\\subimport{{{0}/}}{{{1}}}\n'.format(lab_path.replace('\\', '/'), lab_file))
return t | d0e2213dfafbc5dd649dbd8ed68851d5ca3a4879 | 640,967 |
import torch
def is_tensor(data):
"""Checks if data is a torch tensor."""
return type(data) == torch.Tensor | f3b8c07bfbdf76bb80ee0db90ca8a4136e037854 | 640,968 |
import imp
def load_module_file(module_name, file_path):
"""Load module given name and path."""
with open(file_path, 'r') as f:
return imp.load_module(module_name, f, "%s.py" % module_name,
(".py", "r", imp.PY_SOURCE)) | 472fd95e03767d329ad0bb19af3d21a554c9a8eb | 640,969 |
def validate_generic(input_string):
"""
Always return true, we can't really validate a format that a developer
defined in an arbitrary way.
:param input_string: The string to validate
:return: True
"""
return True | 2d657ba26b5def4b5e5da209658e868664c0ffd7 | 640,971 |
def numeric_range(numbers):
"""Calculates the difference between the min and max of a given list
Args:
numbers: A list of numbers
Returns:
The distance of the minimax
"""
numbers = sorted(list(numbers))
return (numbers[len(numbers) - 1] - numbers[0]) if numbers else 0 | 011f8184b3ac429711d154009c843a6b2e32b1d3 | 640,972 |
def equals(arg1, arg2):
"""
check if two object equal
>>> equals('a', 'b')
"""
if arg1 == arg2:
return True
if (arg1 is None) or (arg2 is None):
return False
return arg1.__eq__(arg2) | 713fef4b874a06cc6b1c74407f31bb881a9b9bb0 | 640,973 |
import inspect
def get_kwarg_names(func):
"""
Return a list of valid kwargs to function func
"""
sig = inspect.signature(func)
kwonlyargs = [p.name for p in sig.parameters.values()
if p.default is not p.empty]
return kwonlyargs | 05e4dbfdfd1d98bf1b4f04cb7689d485e584ac93 | 640,974 |
def map_postorder(lamark_ast, visit_func):
"""Maps a function over a LaMark AST. The visit_func takes in one node
and returns a node. The returned node replaces the original node in
the AST. Returning None leaves the node unchanged.
"""
new_children = []
for node in lamark_ast.get_children... | 39646adee2b29301962ad03add43e38fbf0cf63a | 640,976 |
def DoesDatabaseExist(client_vm, connection_string, database_name):
"""Returns whether or not the specifid database exists on the server.
Args:
client_vm: client vm which will run the query
connection_string: database server connection string understood by psql
database_name: name of database to check ... | 506648e807517d2fa53e684f4ad6fd526925e364 | 640,977 |
def _synapse_error_msg(ex):
"""
Format a human readable error message
"""
if isinstance(ex, str):
return ex
return '\n' + ex.__class__.__name__ + ': ' + str(ex) + '\n\n' | 75e7ec392a9fed55f641cd722bfe210898d16185 | 640,978 |
def prices_from_returns(returns):
"""
Calculate the pseudo-prices given returns. These are not true prices because
the initial prices are all set to 1, but it behaves as intended when passed
to any PyPortfolioOpt method.
:param returns: (daily) percentage returns of the assets
:type returns: pd... | be8ea9a9f17bd9a625c4cda8eb11d9313fa334d1 | 640,980 |
import re
def preprocess(text):
"""
remove unwanted characters fom a string
"""
text = re.sub(r"\n|\t|”|“|'|\xa0|[Bb]y", " ", text)
text = re.sub(r'"', " ", text)
text = re.sub(r" +", " ", text)
return text | d11660ddb718e72f98bed40ebd9dd39bd4bdd4d1 | 640,981 |
def do_complicated_mathematics() -> int:
"""Do complicated mathematics.
Returns:
int: The result
"""
return 1 + 1 | fbfddd15fd63dcac7bc7e6e12fa6f66ed0d254cf | 640,982 |
def new_duplicate_dict(d):
""" Create a duplicate of the given dictionary """
d1 = {}
for p in d.keys():
d1[p] = d[p]
return d1 | 64879b5e916d16a40f6f07bd92f1c24b09cbf224 | 640,983 |
import os
def get_local_files(array_of_files):
"""Get local files"""
localArr = []
for i in array_of_files:
if os.name == "posix":
temp = os.getcwd() + "/" + str(i)
else:
temp = os.getcwd() + "\\" + str(i)
localArr.append(temp)
return localArr | d8e7a70b7aa6b38584aa610ea4e7cb800982ce12 | 640,984 |
def cleanup_url(url: str) -> str:
"""Cleans up the text to be a valid URL.
Returns:
str: The cleaned up URL.
"""
url = url.replace(" ", "-")
if url.startswith("http://") or url.startswith("https://"):
return url
else:
return f"https://{url}" | b3eed31d45f7bfaa975c60212949dd8fe0e43729 | 640,985 |
def results(person, result, rate):
"""
Checks if the current person is in the dict, if not adds them with their current rate
if they are, adds the current rate to the current person
:param person: the current person
:param result: the output result
:param rate: the current tax rate
:return: ... | 05cfff6046b90a9cbc1ab4352d69125d44505201 | 640,986 |
def generate_four_vertices_from_ref_vertex(ref, img_sz):
"""
Generate four vertices from top-left reference vertex.
:param ref:
:param img_sz:
:return:
"""
pt_tl = [int(img_sz[0] * ref[0]), int(img_sz[1] * ref[1])]
# pt_tr = [int(img_sz[0]), pt_tl[1]]
pt_tr = [int(img_sz[0] - pt_tl[0... | a61329cf209af818d08cd60af98f39693dfc3901 | 640,987 |
import argparse
def udaq_argparser():
"""Function to get arguments from string and parse them into single python dictionary.
"""
parser = argparse.ArgumentParser()
# Define parser mandatory arguments.
parser.add_argument('--port', type=str, help='path to serial device port e.g. /dev/ttyUSB0')
... | 2353049ef909c290184e5dd1f843a2563b713da0 | 640,988 |
from typing import Optional
from datetime import datetime
def _date_repr(val: Optional[datetime]) -> str:
"""Print a datetime in a compact format."""
if val is None:
return str(val)
return val.isoformat() | c6b65e0184529fa1eb366300609f97f8f55f95fb | 640,989 |
def prefix(symbol: str, value: float, accuracy=2):
"""
Input: symbol to add, value
Output rounded value with scientific prefix as string
"""
if value >= 900000000:
prefix = " G"
value = value / 1000000000
elif value >= 900000:
prefix = " M"
value = value / 100000... | a1b75e340a45c63d7194b9cb2277723daa913952 | 640,990 |
import hashlib
def hash_object(*objects, hasher=None):
"""Hash the given object(s) and return the hashlib hasher instance
If no hasher argument is provided, then automatically created
a hashlib.md5()
"""
if hasher is None:
hasher = hashlib.md5()
for obj in objects:
if... | 7e072d27d625f47dde75f5119a5bb1f8e57202fb | 640,991 |
import math
def shannon_entropy(p):
"""Computes the Shannon Entropy at a distribution in the simplex."""
s = 0.
for i in range(len(p)):
try:
s += p[i] * math.log(p[i])
except ValueError:
continue
return -1.*s | e5e8bdf40a04e7c532c464e2438626d4b98a2cfb | 640,993 |
import torch
def Ax(A, x):
"""Returns the Matrix-vector product Ax.
Arguments:
A (function or torch.Tensor): Matrix-vector product function or
explicit matrix.
x (torch.Tensor): A vector.
"""
if callable(A):
Ax = A(x)
else:
Ax = torch.mm(A, x)
... | 21e20f8db65bfa7e1bd571bc5861d27c1e5a8be5 | 640,994 |
def get_etr_d_t(q_out_H_hs_d_t, q_max_H_hs):
"""圧縮機の圧縮効率 (5)
Args:
q_out_H_hs_d_t(ndarray): 熱源機の平均暖房出力 (kW)
q_max_H_hs(float): 熱源機の最大暖房出力 (W)
Returns:
float: 圧縮機の圧縮効率
"""
tmp = (q_out_H_hs_d_t * 1000 / q_max_H_hs)
return -0.9645 * tmp * tmp \
+ 1.245 * tmp \
... | c4233f27798ac22b900d10e7c08655138b816280 | 640,995 |
def create_pad(size, pad_id):
"""
Create a padding list of a given size
Args:
size: nd list shape
pad_id: padding index
Returns:
- padding list of the given size
"""
if len(size) == 1:
return [pad_id for _ in range(size[0])]
else:
return [create_pad(... | 31593a5ac6f4aa7991b0b3025ff0a3b84be89c4f | 640,996 |
def get_file_data(path):
"""
read data from a given file
:param path: file path
:return: file data
"""
data = ""
try:
_file = open(path, 'r')
data = _file.read()
_file.close()
except EnvironmentError as e:
print("File operation failed, Error: %s" % e)
... | 75ce2aa918288e91a3a321c27f72146074296a58 | 640,997 |
def roi_center(roi):
"""Return center point of an ``roi``."""
def slice_center(s):
return (s.start + s.stop) * 0.5
if isinstance(roi, slice):
return slice_center(roi)
return tuple(slice_center(s) for s in roi) | ae6f9fc6af535ed1643481fb7b38f4dd8aa6de72 | 640,998 |
import numpy
def schechterL(luminosity, phiStar, alpha, LStar):
"""Schechter luminosity function."""
LOverLStar = (luminosity/LStar)
return (phiStar/LStar) * LOverLStar**alpha * numpy.exp(- LOverLStar) | 9dcdaaeb534c8ffecbff0a48d744d8c41ae7c7a0 | 640,999 |
import textwrap
def ssplit(str_, length=420):
"""
Splits a into multiple lines with a maximum length, without
breaking words.
:param str_: The string to split.
:param length: Maximum line length.
"""
buf = list()
for line in str_.split('\n'):
buf.extend(textwrap.wrap(line.rstr... | 8f4100e73e57ad896bf1d754ccf78d2be7366fcd | 641,000 |
import pickle
def load_pickle(fpath):
""" Given a file path pointing to a pickle file, yields the object pickled in this file"""
with open(fpath, 'rb') as fp:
return pickle.load(fp) | 494eea7152c12d435f35e2def6abc7020126e446 | 641,001 |
import pickle
def read_magnitude_catalogue(pkl_data_fname):
"""Function to read magnitude catalogue output by get_event_moment_magnitudes() into python.
Arguments:
Required:
pkl_data_fname - The filename of the python dict containing the magnitudes information.
This is an outp... | 96d79d76810fb58904afac726fd5fe2c3c78a394 | 641,002 |
from typing import Counter
def get_fine_regions(columns, min_samples=50):
"""
Select regions that have at least ``min_samples`` samples.
Remaining regions will be coarsely aggregated up to country level.
"""
# Count number of samples in each subregion.
counts = Counter()
for location in co... | 40a1ec404b689091532ed452568cadc944eb863b | 641,003 |
def check_consecutive(labels):
""" Check that the input labels are consecutive and start at zero.
"""
diff = labels[1:] - labels[:-1]
return (labels[0] == 0) and (diff == 1).all() | 9c567e857d4814a299935320fdbfff2f454eca2a | 641,004 |
import typing
import os
import stat
import mimetypes
def detect_filetype(path: str, stat_: typing.Optional[os.stat_result] = None) -> str:
"""Given a file path, work out what type the file is."""
# pylint: disable=R0912
# Pylint complains that this function has too many branches.
# I cannot think of a... | 862f1f64ea15044eb959a4f7906ff398c42d62bf | 641,005 |
def validate_ids(data, field='id', unique=True):
"""
By this method we just return uniq list
Actually we use it for {issue_id:xxx order: xxx}
We don't really know what to do if we got
2 different order for the same issue.
Of course frontend should prevent it.
But I decided not raise an Exception for this case.
... | 54781f1ecb2f469852720770f5236f814f0bcea3 | 641,006 |
def merge_dicts(*args, **kwargs):
"""Outputs a merged dictionary from inputs. Overwrites data if there are conflicts from left to right.
:param args: (dict), tuple of input dictionaries
:param kwargs: dict, input kwargs to merge
:return: dict, combined data.
"""
data = {}
for input_dict in ... | fb35fbeda9606019c6fd67b6b47a77af704e1aab | 641,007 |
import random
def random_tour(num_of_cities):
"""
Returns a random valid tour
"""
tour = list(range(num_of_cities))
random.shuffle(tour)
return tour | f6e8edf4b57cbaa8a4402e27639f3b6b8467198f | 641,008 |
def word_freq(words):
"""
Return dictionary
"""
index = {}
for word in words:
if word in index:
index[word] += 1
else:
index[word] = 1
return index | 1c8a2e16e9324f75e2ea1b95ce24afcef9968df6 | 641,009 |
def cli(ctx, history_id, purge=False):
"""Delete a history.
Output:
An error object if an error occurred or a dictionary
containing: ``id`` (the encoded id of the history), ``deleted`` (if the
history was marked as deleted), ``purged`` (if the history was
pur... | 4976507579406617de4d30c1e89ab4de97aa2a4d | 641,010 |
def is_path_cyclic(node, visited):
"""
@type G: Graph
@param G: our Graph
@type node: Vertex
@param node: the vertex we are currently visiting
@type visited: set
@param visited: set of visited paths
@rtype: bool
@return: if a path is cyclic
"""
stack = [node]
while sta... | 672ed6fdf6edb5c40528b3bf92f7a9870eef5b14 | 641,012 |
def dash_to_underscore(obj):
"""
Convert dashes to underscores in an input model object
:param obj: The object to convert
:return:The converted object
"""
if isinstance(obj, list):
ret_obj = []
for item in obj:
ret_obj.append(dash_to_underscore(item))
elif isinsta... | c00f25a321541839191cbdd077aba54fda26b133 | 641,013 |
import six
def clear_dict_empty_lists(to_clear_dict):
"""
Removes entries from a nested dictionary which are empty lists.
param to_clear_dict dict: python dictionary which should be 'compressed'
return new_dict dict: compressed python dict version of to_clear_dict
Hints: recursive
"""
ne... | 4f2e7461fab27487dcd493e4af886d4ca7332b26 | 641,014 |
def gcContent(seq):
"""calculate G/C content of sequence"""
gc = seq.count("C") + seq.count("G")
gcPercent = 100 * (float(gc) / len(seq))
return int(round(gcPercent)) | 4eaae2012000faf68b353bf301aae57a121f4898 | 641,015 |
def per_hour_to_per_second(per_hour):
"""
Transform a per hour rate to a per second rate.
:param per_hour: quantity per hour
"""
return per_hour / 3600 | f4f15c972f59b09b7a5af6b667bfd8721da40a27 | 641,016 |
from pathlib import Path
import pandas
def read_repos(fn: Path, sheet: str) -> dict[str, str]:
"""
make pandas.Series of email/id, Git url from spreadsheet
Parameters
----------
fn : pathlib.Path
path to Excel spreadsheet listing usernames and repos to duplicate
sheet : str
na... | 7a9e582dfead8ed8dbe55f52572521443c0b98fe | 641,017 |
def decide_produced(desc):
"""Based on the provided description, determine the ActivityProducedBy."""
if 'Production' in desc:
return desc.split('Production')[0].strip()
return 'None' | f219c63cc6ea30dffaa35d004c544f889499de51 | 641,018 |
from typing import Counter
def preprocess(text):
"""
Converts any puctuation into tokens, creates a counter dictionary of the data,
and trims the data dictionary of words with occurrances less than five
Input:
* text: a text file containing words
Output:
* returns a trimmed counter dictionary of tokeniz... | 6799256a0ddaa254c0298bf36218fdac0566da8e | 641,019 |
def shekel_gradient(point, p, matrix_test, C, b):
"""
Compute Shekel gradient at a given point with given arguments.
Parameters
----------
point : 1-D array with shape (d, )
A point used to evaluate the gradient.
p : integer
Number of local minima.
matrix_test : 3-D arra... | 8d6628243de1f40aea3ab6b45211579e3633924d | 641,021 |
import shlex
import os
def _is_dryrun( cmd ):
"""
If the environment defines COMMAND_DRYRUN to an empty string or to the
value "1", then this function returns True, which means this is a dry
run and the command should not be executed.
If COMMAND_DRYRUN is set to a nonempty string, it should be a ... | 9170477e47ba4d06c15da6a909f8d8974de93894 | 641,022 |
import re
def __valid_word(word, stopword, language):
"""
Check if the word is in the stopword list
Return a boolean
word = string
stopword = stopword object (cf stopwords.py)
language = string (french or english)
"""
# print(word)
# print(language)
# print(word not in stopword... | ef1850a9b01a26708fdacacf9536cc24ad6f6323 | 641,023 |
import re
def clean_fieldname(text: str) -> str:
""" Sanitizes input and yields safe ascii strings. """
if text == 'root':
return '_root'
return re.sub(r"(^[^A-Za-z_]|[^A-Za-z0-9_])", "_", text) | 00928f5c014df2513cbc38341f4c0715bb044fe9 | 641,024 |
def ignore_filter(topics):
"""filter topics starts with !"""
result = [t for t in topics if not t['title'].startswith('!')]
for topic in result:
more_topics = topic.get('topics', [])
topic['topics'] = ignore_filter(more_topics)
return result | 8e330ddc56b2b2638288059d679050eefa11441c | 641,025 |
import random
def get_jumbled_text(text):
"""
Return jumpled version of text.
"""
text = text.split(" ")
jumbled = ""
while len(text) > 0:
word = random.choice(text)
del text[text.index(word)]
jumbled += (word + " ")
return jumbled.strip() | 5ae662e14a03ce1dd7f17be329785ec52511e16b | 641,026 |
def point_in_rectangle(point, rectangle):
"""
Determine if the given point is inside the rectangle
Args:
point(tuple): tuple of points x and y
rectangle
Returns:
bool: True if point in the rect, False otherwise
"""
left_sides = 0
for i in rang... | 3404e13413ff0568fc2933df419b19cc0adc46d5 | 641,027 |
import time
import os
def is_younger(path, age, default=False):
"""
Args:
path (str | Path): Path to file
age (int | float | None): How many seconds to consider the file too old
default (bool): Returned when file is not present
Returns:
(bool): True if file exists and is y... | e8d45b102819decdb4232bc164a383467c2d8e0e | 641,028 |
import math
def get_conv_output_shape(in_shape, kernel, stride=1, padding=0, dilation=1, out_channels=32):
""" infer output shape after 1 layer of conv
reference: https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d
"""
_, h, w = in_shape
out_h = math.floor(
(h + 2 * padding - dilation... | 8882e9363e66b82c692abf3470645ebddd6d6252 | 641,029 |
import re
def parsePWDResponse(response):
"""
Returns the path from a response to a PWD command.
Responses typically look like::
257 "/home/andrew" is current directory.
For this example, I will return C{'/home/andrew'}.
If I can't find the path, I return L{None}.
"""
match = r... | 5e74777bf5d5fb882f9ca20d3e0ac6dac97ae19e | 641,030 |
import time
from datetime import datetime
def get_tlim(*times):
"""
Create mask for user-defined time range.
"""
time_list = []
for dt in times:
# Convert start date into timestamp
dt = time.mktime(dt.timetuple())+dt.microsecond/1e6
# Convert timestamp back local datetime
... | e77ed39e832989c82041bae500acf5d21fccca06 | 641,031 |
def p_dictent(p, key, value=3):
"""dictent : test COLON test"""
return key, value | 87de4a98725f0cc337c05e720af4b1c3d3d632bc | 641,033 |
from argparse import ArgumentParser
from argparse import RawTextHelpFormatter
import os
def get_parser():
"""Build parser object"""
parser = ArgumentParser(description='First level analysis',
formatter_class=RawTextHelpFormatter)
parser.add_argument('bids_deriv_dir', action='... | b4aca0eddc6f64a57d0d45b8ac8c75bfecc2750d | 641,034 |
from typing import List
def filter_ipas(sentence: str, ipas_lst: List[str]) -> List[str]:
"""
filters the list of ipas passed.
"""
return [sentence for item in ipas_lst if item in sentence] | a357e608ef2cf7c850d1036fb5b8ba9507f68e9c | 641,035 |
def check_subsequence(short, long) -> bool:
"""
Checking string subsequence recursively
@param short: This substring is searching
@param long: Here we search in
@return: False or None
"""
try:
return check_subsequence(short[1:], long[long.index(short[0])+1:])
except ValueError: ... | 19c023082bb99bef36563b722f1cc9b18f800825 | 641,036 |
def first(s):
"""Return the first element of a recursive list s."""
return s[0] | 20ac0a269fc9e99bca137867254019605df343b2 | 641,037 |
def get_reference_token(client, name):
"""Get slack reference token given name
Args:
client (SlackClient): slack client
name (str): member name to search for
Returns:
(str): slack reference token
"""
for member in client.api_call('users.list')['members']:
if member... | 438a5cbd81d2ecd698f7a9ae8913ab5102f390da | 641,038 |
from typing import Dict
import json
def get_unambiguous_roots(base_forms_file: str) -> Dict[str, Dict[str, str]]:
"""Get the list of words repleaceable with an unambiguous lemma.
This is a dictionary having the ISO 3-letter code of each language as
a key, and as values dictionaries mapping words with the... | 879ed6678655a731940cac8457d347ce9de8c4ac | 641,039 |
def levenshtein(a: str, b: str) -> int:
"""Find the levenshtein distance between two strings"""
if not len(a):
return len(b)
if not len(b):
return len(a)
if a[0] == b[0]:
return levenshtein(a[1:], b[1:])
return 1 + min(
levenshtein(a[1:], b),
levenshtein(a, b... | a5396e19c298a9a05f2141ec2448413aa32eb7ca | 641,040 |
import re
def _convert_to_regex(input_format: str):
"""Return regex of input_format."""
return re.compile(input_format.replace("(", "\\(")
.replace(")", "\\)")
.replace("<artiste>", "(.+)")
.replace("<track>", "(\\w+)")
.r... | d93687b03684b96a9e0d6d0b2ce957e8079f47ba | 641,041 |
def replace_white_space_in_column_names_with_and_underscore(df):
""" Takes one parameter, the dataframe. """
with_replacement = [i.replace(' ', '_') for i in df.columns]
df.columns = with_replacement
return df | fbba5483cc86f66401f6b4c5d2c3d68c30218981 | 641,042 |
def which_one(iterable):
"""Index of the first True value in an iterable."""
it = enumerate(iterable)
i, x = next(it)
while not x:
i, x = next(it)
return i | 9efa3d85717fec7ff7c19b9c5d0d9fe831ff19b0 | 641,043 |
def df_matches_slab(slab, df_coord, ):
"""
"""
#| - df_matches_slab
num_atoms = slab.get_global_number_of_atoms()
num_rows = df_coord.shape[0]
same_num = True
if num_atoms != num_rows:
same_num = False
# #####################################################
all_atoms_indice... | 1c4855e8bf83a5d9cc9c734573dff5a88be909e2 | 641,044 |
import sys
def GetGitCommand():
"""Returns a git command that does not need to be executed using shell=True.
On non-Windows platforms: 'git'. On Windows: 'git.bat'.
"""
return 'git.bat' if sys.platform == 'win32' else 'git' | ac99b22ab2129f066f412c5bc6e38c16c6abd36b | 641,045 |
def readFile(path):
"""
读取文件的所有内容为字符串
"""
content=""
with open(path,encoding="utf-8") as f:
content=f.read()
f.close()
return content | 8ee6c611ee95e7a57080b262fb7b7f8cabad4d7e | 641,046 |
import operator
def apply_constraints(params, constraints):
"""
Ensure that `params` meet `constraints`
`constraints` is a list of (parameter, constraint function, constraint parameter) tuples
"""
if constraints is None:
return True
operator_map = {
"<": operator.lt,
... | ee9052474453d54154d5057e9090b084b77fce4a | 641,048 |
def _worst_size(str_len):
""" Given a string length, what's the worst size that we should grow to """
if str_len == 0:
return 0
elif str_len == 1:
return 2
elif str_len % 255 in (0, 1):
return (str_len / 255) * 2 + str_len + (str_len % 255)
else:
return ((str_len / 25... | 926549250f3cd998ea5c0c5287d326f43ccecd35 | 641,049 |
import subprocess
def has_untracked() -> bool:
"""
Return True if untracked file/folder exists
"""
result = subprocess.run('git ls-files -zo --exclude-standard'.split(),
stdout=subprocess.PIPE)
return bool(result.stdout) | f6912d48eb13b170e86e0d4318697bb9fe2487ee | 641,050 |
def check_third_bs(fd1, fd2, fd3, fd4, fd5) -> str:
"""输入5段走势,判断是否存在第三类买卖点
:param fd1: 第N-4段
:param fd2: 第N-3段
:param fd3: 第N-2段
:param fd4: 第N-1段
:param fd5: 第N段
:return:
"""
zs_d = max(fd1['low'], fd2['low'], fd3['low'])
zs_g = min(fd1['high'], fd2['high'], fd3['high'])
t... | 7496a9b990be592a26e82a7b5b4f58889b8ff50a | 641,052 |
from pathlib import Path
import subprocess
import shutil
def rerun_cmd(cmd, outfile, max_ntry=2, subdir_failures='failed_outputs', **run_kwargs):
"""
rerun r0_to_dl1 process given by `cmd` as long as the exit code is 0 and number of try < max_ntry
move the failed output file to subdir failed_outputs
... | 6df2e0f4f4f51543a138e36208bc39353521a517 | 641,053 |
import torch
def rotation_from_axis(axis):
"""
Expects Bx1x3 axis Tensor
The axis is x, y, z with the angle being norm(axis).
Returns a Bx3x3 rotation matix tensor
"""
device = axis.device
# Trick for batch_size broadcasting
theta = torch.norm(axis, p=2, dim=2).view(-1, 1, 1)
axis... | 566a71ff883afb7952221429e6749d3550566898 | 641,054 |
def get_number_of_verb(sentence_token):
"""Return number of verbs in sentence
Args:
sentence_token (tuple): contains length of sentence and list of all the token in sentence
Returns:
int: number of verb in sentence
"""
number_of_verb = 0
for word in sentence_token[1]:
i... | 7f9d404e204612ef8a5379566bde802997fc30ef | 641,055 |
def partextras(labels):
"""Return a dictionary of extra labels for use in prompts to the user
Intended use is in strings of the form "(l)ocal%(l)s".
"""
if labels is None:
return {
"l": "",
"o": "",
}
return {
"l": " [%s]" % labels[0],
"o": "... | 27a6b819b25c532971e223aaa783d3f6c3c745a8 | 641,056 |
def chunkify(files_list, chunksize=1000):
"""
Create a list of chunks.
Each chunk is a list itself, with size `chunksize`.
Arguments:
files_list: list: A list of Path objects
chunksize: int: Size of each chunk
Return:
chunks: list: A list of lists. Each nested list has size
... | 6040bd067a96490c3da627ee0883df20ec663083 | 641,057 |
def _trunk(port_data):
"""Return trunk for specific ifIndex.
Args:
port_data: Data dict related to the port
Returns:
trunk: True if port is in trunking mode
"""
# Initialize key variables
trunk = False
# Determine if trunk for Cisco devices
if 'vlanTrunkPortDynamicSta... | eebbe1fcaaeeaa1295ce1aaf9f8a42eddf583c79 | 641,058 |
def get_inline_math(block):
"""This function will get inline math code and append it to the text
"""
text = ""
lists = block.get("properties")["title"]
for list in lists:
if list[0] == "⁍":
text += "$$"+list[1][0][1]+"$$"
else:
text += list[0]
return t... | 9f268c0474752035fc326c19fcd60e3787ced2f0 | 641,059 |
def construct_index_dict(field_names, index_start=0):
"""This function will construct a dictionary used to retrieve indexes for cursors.
:param - field_names - list of strings (field names) to load as keys into a dictionary
:param - index_start - an int indicating the beginning index to start from (default ... | 45f0193d0053c9ea01a35e248782fc414f06cdb1 | 641,060 |
from typing import BinaryIO
import hashlib
def get_md5(f: BinaryIO) -> str:
"""Make an MD5 hash of the page's contents."""
BLOCKSIZE = 65536
hasher = hashlib.md5()
buf = f.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = f.read(BLOCKSIZE)
return hasher.hexdigest() | 91e9729df86d1c3ab33f129a3c864580ddf5ced1 | 641,061 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.