content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import torch
def unnormalize(img, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
"""
Convert a normalized tensor image to unnormalized form
:param img: (B, C, H, W)
"""
img = img.detach().cpu()
img *= torch.tensor(std).view(3, 1, 1)
img += torch.tensor(mean).view(3, 1, 1)
... | 496ced9481afa5ef8a9a097f36bcf6b7d83157ad | 654,629 |
def addImageCharacteristics(img_char, img_type, height, width):
"""Adds the image characteristics (made from getImageCharacteristics
function) to the global image characteristic variables
:param img_char:
:param img_type:
:return:
"""
if img_type == "original":
height.append(img_cha... | f17c71e338269afde3cdd218a66fb5f635554926 | 654,630 |
from typing import Any
import os
import subprocess
import pickle
def unpickle_sh(file_name: str) -> Any:
"""Unpickle `base_name`.pkl if present or run `base_name`.pkl.sh first. """
if not os.path.isfile(file_name):
subprocess.call([file_name + '.sh'])
with open(file_name, 'rb') as file:
re... | 1901a13d34cb2ce478e8a5ecf06e60ceb05520f3 | 654,631 |
import os
def is_python_filename(name: str) -> bool:
"""
Returns True if string looks like a python filename.
"""
return os.path.exists(name) and name.endswith(".py") | 64458304958a3027dd86025bb6d462f224c37fd8 | 654,632 |
def enumerate(s, start=0):
"""Returns a list of lists, where the i-th list contains i+start and
the i-th element of s.
"""
return list(list([i+start, s[i]]) for i in range(0, len(s))) | a75a8dbbfdea4701a7fe5ca5dbadf0949ae273ff | 654,633 |
from typing import Counter
def num_reviews_with_token(profTokenDict):
""" Returns a Counter with the number of reviews a given token appears in.
"""
counter = Counter()
for profCounts in profTokenDict.values():
for revCtr in profCounts:
counter += Counter(revCtr.keys())
return counter | 0f247f93174b72482278220c163cba057a9caec9 | 654,634 |
def cache_dir(tmp_path_factory):
"""Return temporary location of DATALAD_REGISTRY_DATASET_CACHE."""
return tmp_path_factory.mktemp("cache_dir") | 648d8c9a47974490c83d2004bed6ca86b1f4a706 | 654,635 |
def map_genomes(gold_standard, bin_id_to_list_of_sequence_id):
"""
This script maps a predicted bin to the genome that maximizes precision
@attention: In case of reads, read ids might not be paired read id and cause error: ReadID/1 ReadID/2
@param sequence_id_to_genome_id:
@param anonymous_sequenc... | b802efe8c06dbec36ea983e0726d98eefedcdaa8 | 654,637 |
def test_help():
"""
Help text for argparse describing available sdk tests.
"""
return """Specify an individual test for execution
TESTS:
Enable - Verify ability to enable, check state and disable baxter
Messages - Verify messages being published and ability to subscribe
Services - ... | bda0d85a433e78e8f5c813ac440e10bc7b81b478 | 654,638 |
def cp_polinomial(T, C1, C2, C3, C4, C5):
"""Capacidad calorifica a presion constante de compuestos inorganicos y organicos en el
estado ideal como una ecuación polinomial [J/(mol.K)]"""
return (C1 + C2*T + C3*T**2 + C4*T**3 + C5*T**4) / 1000 | a8f758007d5754428fc64b096eaa15c01a6a8837 | 654,639 |
import os
def GetLocalFileSize(filename):
"""File size of local file in bytes"""
attr = os.stat(filename)
return attr.st_size | 5fc85306b4417e6538ad9963c0336b85766569fb | 654,640 |
def sample_constraint(value):
"""
The value must be within the range of 1-255.
"""
return 1 <= value <= 0xFF | b71c87699742d609ccdff105be70dd72243e9d36 | 654,641 |
def line(a, t, l):
"""
Linear interpolation between a and b
0 <= t <= 1
"""
return a + t * l | 123d3108e44058a039cbd7c2954029e91c1a154a | 654,642 |
import numpy
def baum_welch_test( chmm, t, e, tt, et, _method, itr ):
""" return convergence line on both training (t,e) and testing datasets (tt,et) for dataset likelihood and viterbi"""
train = numpy.zeros( itr+1 )
test = numpy.zeros( itr+1 )
for i in range(itr):
print(i+1,'/',itr)
... | af7eed54c5cc1b500f5761ab57efd2aa91f49383 | 654,643 |
import os
def load_onnx(model_name):
"""Read the ONNX file."""
onnx_path = '%s.onnx' % model_name
if not os.path.isfile(onnx_path):
print('ERROR: file (%s) not found! You might want to run yolo_to_onnx.py first to generate it.' % onnx_path)
return None
else:
with open(onnx_pat... | dfcc277726f8e0517c5aef27db528ad217d0b046 | 654,644 |
def combinations(s, K):
"""
On entry: s sequence of items; K size of the combinations
Returns: list of all possible K-combinations without replacement of
s.
"""
N = len(s)
assert K<=N, 'Error K must be less or igual than N'
S = [[] for i in range(K+1) ]
for n in range(1,N+1):
... | c0d048e7978283b2f86b09b3b1a7fe1790b7fa93 | 654,645 |
import torch
def load_checkpoint(filepath, gpu):
""" Load checkpoint """
if gpu == False:
# Cpu device
checkpoint = torch.load(
filepath, map_location=lambda storage, loc: storage)
else:
# GPU device
checkpoint = torch.load(filepath)
model = checkpoint['mo... | dcc72dc45f373bdea3384833aec2cd3c936ab8a5 | 654,646 |
def most_common_words_without_stopwords(text, top=50):
"""
Returns the frequency of the documents top n words in the text
:type text: Text
:param text: The text to be analysed
:type text: Text
:param top: int
:type top: Top n n-grams to evaluate
:returns Returns list of frequencies
"... | 788a0a260b92f160343fbeeefcff6cfbdc863901 | 654,647 |
def with_file(filename, callback):
"""Call `callback` with the opened file `filename`. Return result of call.
See http://softwareengineering.stackexchange.com/questions/262346/should-i-pass-in-filenames-to-be-opened-or-open-files
"""
with open(filename, 'r') as f:
return callback(f) | ee82f7c0c54ecd52e1ff0ec738a4fd75b8efddd7 | 654,648 |
import os
def get_tagsfile(cfg):
"""Generates tagdata filename."""
tagsfile = cfg.get('tags_filename',
os.path.join(cfg['datadir'], os.pardir, 'tags.index'))
return tagsfile | 9abad0df233d5256b2462c8c0d2a7648c653442e | 654,650 |
def get_node(data_path):
"""Return Blender node on a given Blender data path."""
if data_path is None:
return None
index = data_path.find("[\"")
if (index == -1):
return None
node_name = data_path[(index + 2):]
index = node_name.find("\"")
if (index == -1):
return ... | 50856db9efc76482fef30882147a0b0437c1e59e | 654,651 |
import torch
def preprocess_label_for_tfm(y, v, max_len):
""" pre-processing steps for PLUS-TFM fine-tuning """
labels = torch.zeros(max_len, dtype=torch.long)
valids = torch.zeros(1, dtype=torch.uint8)
weights = torch.zeros(max_len, dtype=torch.bool)
labels[1:len(y) + 1] = y
valids[0] = 1 if... | 9b3169aa08c9064c0a9d4e0a1fbfdd9b8e1145b3 | 654,652 |
from typing import Tuple
def _safe_path(path: str, extensions: Tuple[str, ...]) -> str:
"""Returns safe filename based on given extensions.
Args:
path (str): filepath
extensions (tuple[str, ...]): a list of allowed extensions
Raises:
`ValueError` if path is invalid
"""
if... | 782b295a717f2083d60cfdb367c48eece00f7bb6 | 654,653 |
def grid_to_str(grid):
"""
Convert grid - our internal representation into an 81-char sudoku
string
"""
return ''.join(str(grid[ndx].pop()) for ndx in range(0, 81)) | e1030bdbcf4d9ed805682e6c55eb4bccc3bbac98 | 654,654 |
import os
def get_content_length(data_or_fp):
"""Try to get the content length from the given string or file
pointer. If the length can't be determined the return value
is None.
"""
try:
return len(data_or_fp)
except TypeError:
try:
return os.fstat(data_or_fp.filen... | ead6b30482add55acf61828c776e27a138ac8455 | 654,655 |
def ymdhms2jd(datetime):
"""
Datetime(ymdhms) to Julian date
"""
days_to_month = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] # ignore index=0
year, month, day = datetime[0:3]
# year = year + 1900 if year < 1000 else year # in case of abbr.
# leap_year
years_from_1600 =... | 8351bc7477e20ae1b193a8fc3e416403d569c968 | 654,657 |
def inclusion_tag_current_app(context):
"""Expected inclusion_tag_current_app __doc__"""
return {} | 5251b9e721d97302b7f48d4ec395ff7fe6c1c03a | 654,658 |
import numpy as np
def solve_equations(coeff, values):
"""
Solving linear equations
Parameters
----------
coeff : coefficients of the variables in the equation
values : value of the equations
Returns
----------
1 numpy matrix
"""
inversed = np.linalg.inv(coeff)
soln... | 284f1d3e3c4305b1bf6fc6f3318a686ce7452247 | 654,659 |
def trim(peaks, troughs):
"""
Trims the peaks and troughs arrays such that they have the same length.
Args:
peaks (numpy array): list of peak indices or times
troughs (numpy array): list of trough indices or times
Returns:
peaks (numpy array): list of peak indices or times
... | b07cf06a8175baf9fc5de82d6f432370242b7b6b | 654,660 |
def removeSmartQuote(txt):
"""
removeSmartQuote(txt):
Changes typographic quotation marks back to straight ones
"""
return txt.replace(chr(0x201c), '"').replace(chr(0x201d), '"').replace(chr(0x2018), "'").replace(chr(0x2019), "'") | 505282e7bf68582fa55ee788fa75c49d997eac85 | 654,661 |
def is_balanced(node):
"""Check if a BST is balanced; returns (True/False, height of tree)."""
# First we ensure the left subtree is balanced; then ensure the right subtree
# is balanced too; and ensure the diff betw heights of left & right subtree <=1
if node is None:
return True, 0
balanc... | f4db8d2d0ce7e773118a30ce19c19d41097f10b7 | 654,662 |
def _interp_1d_array(da, indices, weight0, inInterpDim): # {{{
"""
iterpolate a data array in 1D with the given indices and weights
"""
if inInterpDim not in da.dims:
return da
indices0 = {}
indices1 = {}
for dim in da.dims:
if dim in indices.keys():
indices0[di... | 768d2d300de9c0e03dda1ecddde5e9c6e926dc26 | 654,663 |
import os
import torch
def load_checkpoint(checkpoint_file, model, optimizer=None):
"""Loads the checkpoint from the given file."""
err_str = "Checkpoint '{}' not found"
assert os.path.exists(checkpoint_file), err_str.format(checkpoint_file)
# Load the checkpoint on CPU to avoid GPU mem spike
chec... | bb1e4517253fa96749591a62e073117eb9e86ba3 | 654,664 |
def Mobius(z):
"""Distort the resulting image by a Mobius transformation."""
return (z - 20)/(3*z + 1j) | 0f1c2fad7ff42199ea5699f2796437e6648ce076 | 654,665 |
import numpy
def str_to_maze(str):
"""Return a maze array from a string representation."""
maze = numpy.array([list(ln.strip()) for ln in str.splitlines()
if len(ln.strip()) > 1])
return maze | 40884f82fb7599bcb47c2cfdedf281257321046d | 654,666 |
from io import StringIO
import csv
def export_csv(items, fields):
"""
Generate the data with csv.writer and stream the response.
Use StringIO to write to an in-memory buffer rather than
generating an intermediate file.
"""
data = StringIO()
w = csv.writer(data)
w.writerow(fields) # ... | b5cd56939930049cc031f1b5e5bb7864c8c4267d | 654,667 |
import logging
def get_rpc_head(xml_dict):
"""Get the rpc head.
Args:
xml_dict: An OrderedDict. Recording the xml's structure.
Returns:
xml_head: The xml head str.
feature_name: The child node name of config|filter.
xml_type: The type of xml.
if xml_type is config,g... | 5d30f9e3ca41bcea354e8bee477995fef5ebbd7b | 654,668 |
def check_input_format(input_s):
"""
:param input_s: str, input string by user.
:return: bool, check if the input string is in legal format or not.
"""
if len(input_s) < 7 or len(input_s) > 8:
return False
for i in range(len(input_s)):
if i % 2 == 0:
if not input_s[i].isalpha():
return False
else:
... | 29b46aa7351204b126c626b5e723866cfb9d7e06 | 654,669 |
def compliment_bools(v1, v2):
"""Returns true if v1 and v2 are both bools and not equal"""
return isinstance(v1, bool) and isinstance(v2, bool) and v1 != v2 | 010630626e56400599e067206c7ad2a56b6758dc | 654,670 |
from typing import Optional
import os
def get_package_docs_type(
package_dir: str,
) -> Optional[str]:
"""
Identify a package's documentation generation type.
:param package_dir: the directory of the package
:return: the docs type ('doxygen', 'sphinx') or None if it failed
"""
if os.path.... | db6c1c418031dd1d0498675f39aeeb2fab00c39d | 654,671 |
from datetime import datetime
def first_day_n_years(date, n=0):
"""
geet the first day of the n th previous year from a datetime object
:param date: the datetime object
:param n: the n th year, 0 means this year, positive future years, negative previous years
:return: a datetime of the first day... | 63113243ddc4dcd7b653422e18b3b404fb49a070 | 654,673 |
import os
def catch_log(driver, nombre):
"""
Funcion para guardar los logs que ocurren en ciertas pruebas
Esta funcion solo sirve en chrome
:param driver: driver Selenium
:type driver: driver
:param nombre: nombre de la capa
:type nombre: String
:return: String con el nombre del txt ... | 5bc24b56d758d7cb8cd1a12ae16b8ba66e88db0d | 654,674 |
import glob
import os
def get_single_bru_file(dir):
""" return None of no *.bru file in this dir """
matches = glob.glob(os.path.join(dir, "*.bru"))
if len(matches) == 0:
return None
if len(matches) > 1:
raise Exception("there are multiple *.bru files in {}: {}".format(
d... | 07980143ad0878e32a9b214c79ac2b6392355271 | 654,675 |
import itertools
import random
def nbackseq(n, length, words):
"""Generate n-back balanced sequences
:param n: int
How many characters (including the current one) to look back
to assure no duplicates
:param length: int
The total length of the sequence to produce
:param words: ... | c55cfb2ef1ce9a14177c1b9bebdc2ed2f5a49150 | 654,677 |
def check_for_genesis_block(blockchain):
"""Check if a chain has the genesis block.
:param blockchain: the blockchain object
:return: <Boolean> True if the genesis block is found.
"""
success = True
if not blockchain.chain:
print("Blockchain is empty")
success = False
return ... | 256ef3c0d73e66de71e25e3a6ee7a9e51ff6f94a | 654,678 |
def main(*, data, decimals):
"""entrypoint function for this component
Usage example:
>>> main(
... data = pd.Series(
... {
... "2019-08-01T15:20:12": -25.054,
... "2019-08-01T15:44:12": None,
... "2019-08-03T16:20:15": -0.2514,
... ... | c83f95003b9e09e1023f879a32564cc00bf9c5c3 | 654,679 |
import math
def human_size(size):
"""Return human readable string for Bytes size
"""
if size <= 0:
return "0M"
measure = ['B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
expo = int(math.log(size, 1024))
mant = float(size/math.pow(1024, expo))
return "{0:.1f}{1:s}".format(mant, measur... | d9d29ca3b6266e2c22f810d81cd344592edcb495 | 654,680 |
def sec_2_index(secs, fr=2048, offset=0):
"""
:param numpy.ndarray secs: time in seconds to be converted
:param float fr: dampling frequency
:param float offset: offset in seconds
:return: time in samples
:rtype: numpy.ndarray
"""
return (secs*fr - offset*fr).astype(int) | b3e55fcc06ead6260ffa2a0fe93e7cfb144f5407 | 654,681 |
def convert_arg_to_int(cmd_args):
"""Convert str to int as much as possible
:param cmd_args: the sequence of args
:return the sequence of args
"""
args = []
for arg in cmd_args:
if isinstance(arg, str): # Int will cause TypeError
try:
arg = int(arg, 0)
... | 2b63400165e3b073bc66b83686701f80494dd0e3 | 654,683 |
def listHasItems(listOfLists):
"""
Some of the batched calls return lists of lists. This means that a return
value of [ [], [], [], ], say from @ref
python.Manager.getRelatedEntities, is hard to easily detect using a
boolean cast, as the outer list is not empty. This function checks that some
item in the o... | b37d1abcfb31aa6e46e187bc2e2d364f1da1697b | 654,684 |
def create_get_connectivity_service_list_by_id(): # noqa: E501
"""Create get-connectivity-service-list by ID
Create operation of resource: get-connectivity-service-list # noqa: E501
:rtype: GetConnectivityServiceListRPCOutputSchema
"""
return 'do some magic!' | 73c176fbc725d73d0a1a0f00c9b40a0ab240dcb8 | 654,685 |
import re
def strip_escape(text: str) -> str:
"""Remove terminal ascii escape sequences from *text*.
Args:
text: text to strip escape sequences from
Returns:
text stripped of escape sequences
"""
# These are all valid escape sequences... they're probably not
# inclusive
... | 578a49a32fc3538dea66bf67e8cd364dc622c78d | 654,686 |
import json
from typing import OrderedDict
def load_ordered(fp, **kwargs):
"""
Convenience wrapper for json.load() that loads the JSON while preserving the original element ordering/sequence.
"""
return json.load(fp, object_pairs_hook=OrderedDict, **kwargs) | 1e705c0ebac645902f781449a07f96b5276d9b90 | 654,687 |
from typing import Union
from pathlib import Path
def _check_data_dirs(
data_directory: Union[str, Path] = Path("../data/")
) -> Path:
"""
Validates data directory exists. If it doesn't exists, it creates it and creates 'raw/' and 'interim/' directories.
"""
# set directory's values
_data_dire... | 10258b7efc2a8621ee44c8930e337b568aeb824c | 654,688 |
def brute_force_partition(S):
"""
Brute force partition algorithm
This function finds the optimal partition of the
subset of the real numbers, S, by computing every
possible subset of S and comparing every possible
partition for the optimal one.
This algorithm takes exponential time, since
computing t... | fa922a22ffb389de38d100d8444da1b74876b9f5 | 654,689 |
import os
from pathlib import Path
def reduce_imagej_csv(path, parts, scorer=None, split=False, full_joint_name=True):
"""Read a (typically) `Results.csv` file created by the ImageJ `Measure` tool and store as
a minimal csv. The ImageJ csv must be in the same directory as the images it was created from.
M... | c5bee959baaaf8f939df1d4b40dc851ef5ac27f1 | 654,690 |
import textwrap
def wrap(text, width=100):
"""
Intelligently wrap text.
Wrap text without breaking words if possible.
Parameters
----------
text : str
Text to wrap.
width : int, optional
Number of characters to wrap to, default 100.
"""
split_text = text.spli... | b099b45651664d523ac6b612f736ff68e9be07af | 654,691 |
def compute_score_interpretability_method(features_employed_by_explainer, features_employed_black_box):
"""
Compute the score of the explanation method based on the features employed for the explanation compared to the features truely used by the black box
"""
score = 0
for feature_employe in featur... | 650d387f6c46b98086f2cca30e462472ae0aea09 | 654,692 |
def create_host_filter(factory, groupID, hostID, securityProfileID, enumType):
"""Create a host filter"""
EnumHostFilter = factory.EnumHostFilterType(enumType)
HostFilterTransport = factory.HostFilterTransport(
hostGroupID=groupID,
hostID=hostID,
securityProfileID=securityProfileID,... | 6730e3dd693ec373a8eae057ec16c76934fa76d3 | 654,693 |
def values_to_deltas(past_values):
"""Turn a deque holding past gauge values into a list of deltas.
These should be evenly distributed in time.
"""
deltas = []
prev_val = None
for (ival, (_, val)) in enumerate(past_values):
if ival > 0:
deltas.append(val - prev_val)
p... | e2df50dee53c5c05ddf569d200367cbea0c23ce8 | 654,694 |
import argparse
def add_deseq_pair_args():
"""
Run RNAseq compare
"""
parser = argparse.ArgumentParser(description='hiseq deseq_pair -a dirA -b dirB -f gene -o outdir')
parser.add_argument('-a', '--dirA', required=True,
help='deseq_dir (a.vs.b) for groupA')
parser.add_argument('-b', '-... | b637d3b985ada137cb5a5121f09fddb0c93c1b7c | 654,695 |
def in_green(s: str) -> str:
"""Return string formatted in red."""
return f"\033[92m{str(s)}\033[0m" | 52d9650874d3939a6d7410ede593f9c16a4fb450 | 654,696 |
def convert_string(string, chars=None):
"""Remove certain characters from a string."""
if chars is None:
chars = [',', '.', '-', '/', ':', ' ']
for ch in chars:
if ch in string:
string = string.replace(ch, ' ')
return string | 131a5c472f96709da98e042a988e026edc41cd2e | 654,698 |
def read_candidates(candidate_path):
"""Read parent candidates from file.
Row number identifies the node and space separated numbers on each row
identify the candidate parents.
"""
C = dict()
with open(candidate_path, "r") as f:
f = f.readlines()
for v, row in enumerate(f):
... | 33e51ad300327d033a53c06b4143340b96e7b77f | 654,699 |
import os
import json
def read_repos(repos_dir, file_name, start_id, end_id):
"""
Read repos from file. Filter repos by given repo id range if specified.
"""
repos_file_path = os.path.join(repos_dir, file_name)
# load available repo
if os.path.isfile(repos_file_path):
with open(repos_... | 097a909810efd0782d83193073b2e2b6c0aa4d7d | 654,700 |
from typing import Dict
def master_name(tf_vars: Dict) -> str:
"""Construct master name for provided Terraform deployment."""
return f"det-master-{tf_vars.get('cluster_id')}-{tf_vars.get('det_version_key')}" | 4f375768b1b3678d1c3384cdf9bfcc0e3c681430 | 654,701 |
import json
def load_json(path):
"""Load JSON file into Python object."""
with open(path, "r") as file_data:
data = json.load(file_data)
return data | f7420ef1d933c85450815ecaee4f7277b766ebe0 | 654,702 |
def welcome():
"""List all available api routes."""
return (f"Welcome to Surf's Up!: Hawai'i Climate API<br/>"
f"Available Routes:<br/>"
f" The latest year of preceipitation data:<br/>"
f"/api/v1.0/precipitaton <br/>"
f" List of all weather observation stations:<b... | a50b5937f69e37194e0222d861e11b308c48c090 | 654,703 |
import sys
import os
def run(command,echoCommand=True,throwOnNonZero=True):
""" Run a command, but do not capture its output. Raise exception on non-zero status """
if echoCommand:
print( command )
sys.stdout.flush()
result = os.system(command)
if throwOnNonZero and 0 != result:
... | ed40f9cfbbf7da5e9b8a3335bb4d3bb7c9c5f2d8 | 654,704 |
import numpy
def cot(arg):
"""
Cotangent
"""
return 1 / numpy.tan(arg) | 784bfe1877f8284dfd77b5b40dc55b6fd22188dd | 654,705 |
from typing import Union
import json
def make_json_encoded(param: Union[str, list, dict]):
"""
converter for user input to turn into json encoded field
"""
if isinstance(param, str):
return param
elif isinstance(param, (list, dict)):
return json.dumps(param)
else:
raise... | 2080f99bbc43f540d5c6f1bfc2bd4eb4181b3778 | 654,707 |
def bint(x):
"""Convert a bit sequence to an int.
>>> assert bint([0]) == 0
>>> assert bint([1]) == 1
>>> assert bint([0,0]) == 0
>>> assert bint([1,0]) == 1
>>> assert bint([0,1]) == 2
"""
return int("0b"+"".join(str(i) for i in x)[::-1], 2) | 1489fa95c0c85055fe31cc6ced9a1cded0216095 | 654,708 |
import sys
def FromUnicode(val):
"""Make sure a value is a non-unicode string
This allows some amount of compatibility between Python 2 and Python3. For
the former, it converts a unicode object to a string.
Args:
val: string or unicode object
Returns:
non-unicode version of val
... | b25c3ddf3f3f3a97271a08948de0c3d32c0b284b | 654,709 |
import re
import os
import errno
def which(prog, search_path=None):
"""
Search for a file in the given list of directories or fallback to PATH.
Args:
prog (str): the file to search
search_path (list): list of directories to search
Returns:
the first path found
Example:
... | 362c5e70bf3489126a86c9c45f47e717875ff0ce | 654,710 |
def cria_posicao (x,y):
"""Esta funcao cria uma posicao com as condicoes descritas no enunciado do projeto"""
if not (type(x) == int and x >= 0 and type(y) == int and y >= 0):
raise ValueError ("cria_posicao: argumentos invalidos")
else:
return (x,y) | bfe4c8eaa35ca0e629bd13abe0dbce91b448075d | 654,711 |
def tmap(*args, **kwargs):
"""Like map, but returns a tuple."""
return tuple(map(*args, **kwargs)) | 1e218555fe6ebe6e82a7536878808e0f29860ac5 | 654,712 |
def replace_comma_in_text(text):
"""
Parameters
----------
text: str of nominal values for a single mushroom species from primary_data_edited.csv
Returns
-------
replace commas outside of angular brackets with semicolons (but not inside of them)
Example
-------
text = "[a, b], ... | 16b74464d53a57c33e67584e59aedab8e9b1ddcb | 654,714 |
def _preprocess(j):
"""preprocess the file out into nodes ways and relations"""
node_storage = {}
nodes_reused = {}
way_storage = {}
ways_reused = {}
relation_storage = {}
for elem in j["elements"]:
# on our first pass, we go through and put all the nodes into storage
eid = e... | 761e6431239affc8e742e1b606bd5ba39db3065e | 654,715 |
def DNSServiceRef_hash(self):
"""
make pybonjour.DNSServiceRef hashable, i.e. zmq.Poller compatible
"""
return hash(self.fileno()) | 9829f34055199c5a13ee8b784b94c10c9aca7d19 | 654,716 |
def _solve_method_3(N, queries):
"""Me manually trying to mimic/perform/do the "slope" method."""
arr = [0] * N
for query in queries:
a, b, k = query[0], query[1], query[2]
arr[a-1] += k
arr[b] -= k
largest = -1
for i in arr:
if i > largest:
largest = i
... | 8d9493c2cff20dc3112c505971aa482be87ec2e3 | 654,717 |
def replace_illegal_chars(filename):
"""
把非法文件名字符替换为合法字符
"""
params = (
('\\', '\'),
('/', '/'),
(',', ':'),
('*', '*'),
('?', '?'),
('"', "'"),
('<', '<'),
('>', '>'),
('|', '|')
)
for param in params:
filename = f... | bb76d77bc91750b55e42fe4f204658da1ecc18a9 | 654,718 |
import random
async def predict(item):
"""
Predict AirBnB rental prices using app data and home features.
### Request Body
Currently just accepting text input, will be updated to accept
### Response
'{prediction}$ per night is an optimal price.'
"""
# input will be a dictionary, (item :... | efe8a98618e21f4e5c2704830702cc0058ec1b49 | 654,719 |
import re
def make_clean_input(pattern):
"""
Enforces that entities or words have parentheses around them and have trailing spaces
>>> make_clean_input("@num{3}")
'(@(num ) ){3}'
>>> make_clean_input("num{3}")
'(num ){3}'
Entities can sometimes have underscores
>>> make_clean_input("@... | ba22c9b07114d7f0cf8c75593553f4b2ca603fa5 | 654,720 |
import re
def get_trim_string(string: str) -> str:
"""
"""
string = re.sub(
r'\s+', '', string)
return string | 9f509a8ee7c2844783ba163c771c329d505a5c5b | 654,721 |
def unprocessed_collate(batch):
"""
A dummy function to prevent Pytorch's data loader from converting and stacking batch data.
:param batch:
:return:
"""
return batch # List of data tuples (sequence, timeline, label) | 4edf04b483f984aeb34d73a2adc7488b5313dcfb | 654,722 |
def get_genome_ids_by_taxon(csv):
"""Parse CSV file with genome IDs grouped by taxonomic groups of interest.
"""
genome_ids_by_taxon = {}
with open(csv) as infh:
for i in infh:
if not i.startswith('Taxon') and not i.startswith('\n'):
si = i.strip().split(',')
... | 7f518339cfba0638c3853a12d951a81f8153504f | 654,723 |
def get_access_headers(app):
"""
Function to retrieve and format the Authorization Headers
that can be passed to various microservices who are expecting that.
:param oidc: OIDC object having authorization information
:return: A formatted dictionary containing access token
as Authorization header... | 444dbbca079cc5ec1e1d0229c873970700c14fa2 | 654,724 |
def strip_unimportant(source: str) -> str:
"""
Strips unimportant information like footnotes, alternative names, or weird
spaces.
"""
stripped = ""
for char in source:
# remove footnotes like RTX 3080[155]
if char == "[" or char == "(":
break
# remove weird sp... | 7b9fca2d5e923e9e071a7755d7b2b01b788d8e06 | 654,726 |
from typing import List
def justify_stringlist(j: List[str], right=False) -> List[str]:
"""
CONSOLE FUNCTION: justify all str in a list to match the length of the longest str in that list. Determined by
len() function, i.e. number of chars, not by true width when printed, so it doesn't work well with JP/CN chars.
... | 05e59bdc6038985d90c12687902bf16f30d1b3b8 | 654,727 |
import time
async def server_mode_test(client):
"""Test concurrent performance in server mode using commonly queued
operations on the Table and View."""
table = client.open_table("data_source_one")
start = time.time()
view = table.view()
schema = await table.schema()
size = await table.siz... | 88fde0a8ff7545634f70b59e18c50ec4c311a2e0 | 654,728 |
def _match_file_path(path, level, v):
"""Helper function to match part."""
if v == "*" or v is True:
try:
path[level]
return True
except IndexError:
return False
else:
return path[level] == v | f76da0139a4ccdeee0cf1cb72203abca62252035 | 654,729 |
def add_to_date(x, year=0, month=0, day=0):
"""This method...
.. note: Should I return nan?
"""
try:
return x.replace(year=x.year + year,
month=x.month + month,
day=x.day + day)
except:
return x | 4e6c86a7ae54c520e9dd9ab59e89052821b9670e | 654,730 |
from typing import Container
from typing import Any
from typing import Callable
def is_not_in(disallowed: Container[Any]) -> Callable[[Any], bool]:
"""
:param disallowed: A Container of disallowed values
:return: A predicate that checks if a value is not within the disallowed values
"""
def predic... | 1d1ac652b527bad589fb83c246bb5a97125772b5 | 654,731 |
def pascal_triangle(rows: int) -> list:
"""
https://oeis.org/A007318
>>> pascal_triangle(4)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
"""
res = [[1]]
for _ in range(rows):
row = res[-1]
res.append([1, *map(sum, zip(row, row[1:])), 1])
return res | c9430efd4649cd20fc4dcfbbc3c7468c0859c91f | 654,733 |
def clamp(val: float, minimum: float = 0.0, maximum: float = 1.0) -> float:
""" Fix value between min an max"""
if val < minimum:
return minimum
if val > maximum:
return maximum
return val | b6406df3470acb47da9e03cdb4c2ba9d830e9e32 | 654,734 |
def find_value(sheet, row):
"""Finds the best available value.
Parameters
---------
sheet : workbook.sheet
An Excel sheet.
row : int
The row where the value is located.
Returns
-------
string
The cell value that wasn't 'N/E' (not eligible).
"""
# We f... | b4273720b4d4a6191f4f6f1979494f00ce24a3ba | 654,735 |
def get_select_indexes(selects, attributes):
""" Gets the indexes for all select statements.
Args:
selects: select values
attributes: attributes in the tables
Returns:
indexes: look up indexes for select values
"""
if selects[0] != '*':
indexes = []
split_se... | 62925dd988384dd61f749fbdf51aea10bff31be1 | 654,736 |
from typing import Tuple
def int_to_rgb(x: int) -> Tuple[int, int, int]:
"""Return a RGB tuple from integer."""
red = (x >> 16) & 0xFF
green = (x >> 8) & 0xFF
blue = x & 0xFF
return red, green, blue | 09f28d6e69a496ee624dbb8a10a39e068f8169f8 | 654,737 |
import base64
def is_base64(s):
"""Function to check whether a string is base64 encoded or not
Parameters
----------
s
String to check
"""
try:
return base64.b64encode(base64.b64decode(s)) == s
except Exception:
return False | 677aa804f7a76b74f1624796b7eff0ae173a0bf8 | 654,738 |
import re
def re_match_strings(target, strings):
"""
Whether or not the string 'target' matches
any one string of the strings which can be regular expression string
"""
return any(name == target or re.match(name, target)
for name in strings) | d87cd118912aeeabe592b6943ac8ce68c0054c63 | 654,739 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.