content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def normalize_dir(dir_name):
"""
Removes the '/' from the end of dir_name is it exists.
Returns the normalized directory name
"""
if (dir_name[-1] == os.sep):
dir_name = dir_name[:-1]
return dir_name | c69b79ad31156742f8c22ffc59b4436d738a6ba5 | 24,845 |
def pbc(rnew, rold):
"""
Periodic boundary conditions for an msd calculation
Args:
rnew (:py:attr:`float`, optional): New atomic position
rold (:py:attr:`float`, optional): Previous atomic position
Returns:
cross (:py:attr:`bool`, optional): Has the atom cross a PBC?
rn... | 67260f98371fbb95d2eca5958f75d80c76b89371 | 24,847 |
import requests
def submit_task(task: dict, username: str, password: str) -> str:
"""
Submits a task using the AppEEARS API.
Parameters
----------
task: dictionary following the AppEEARS API task object format
username: Earthdata username
password: Earthdata password
Returns
... | fd75b86b5258f9b4b0abd02f8fb289a7467149df | 24,848 |
from typing import Callable
import math
def get_sigmoid_annealing_function(epoch_checkpoint: int, temperature: float) -> Callable:
"""
Implements sigmoid annealing given a checkpoint (for the turning point - middle) and temperature (speed of change)
"""
def _sigmoid(data):
"""Ordinary sigmoid... | 08b9bf07912a7b79a830acb6896c015aa430c6ee | 24,850 |
def compare_int(entry, num):
"""Return True if the integer matches the line entry, False otherwise."""
if int(entry) == num:
return True
else:
return False | e779829b0d9a8343d3c48e6a66542e8e6ee62494 | 24,851 |
def _prepare_params(params):
"""return params as SmashGG friendly query string"""
query_string = ''
if len(params) == 0:
return query_string
prefix = '?expand[]='
query_string = prefix + '&expand[]='.join(params)
return query_string | 9fc0573961d50536ee28ae576ac030197eae0cf2 | 24,852 |
def load_settings(path='api/settings'):
"""Loads the user settings located under `api/`"""
with open(path, 'r', encoding='utf-8') as file:
return {
l.strip(): r.strip()
for l, r in (l.split('=') for l in file if l.strip())
} | 1a89c3f80f0a8b4013429fbb060b453f5f447aa5 | 24,853 |
def get_mask(source, source_lengths):
"""
Args:
source: [B, C, T]
source_lengths: [B]
Returns:
mask: [B, 1, T]
"""
B, _, T = source.size()
mask = source.new_ones((B, 1, T))
for i in range(B):
mask[i, :, source_lengths[i]:] = 0
return mask | 8466ff5113ca22488b4218f86c43bfea248197d1 | 24,855 |
import glob
def get_all_html_files(directory):
"""
Returns list of html files located in the directory
"""
return glob.glob(directory + "/*.html") | 5e92a8b4fc52ea63e5c65c5eb7b2487556b08a3d | 24,857 |
from datetime import datetime
import sys
def iso2time(iso_val: str) -> datetime:
"""
解析iso字符串时间到datetime类型
Args:
iso_val: 年月日时间字符串, eg: 2020-03-12T11:49:31.392460
Returns:
datetime
"""
if sys.version_info >= (3, 7):
dt_val = datetime.fromisoformat(iso_val)
else:
... | 61107a2ae47322a802d8dd3eae7beaa628965bbf | 24,858 |
def fact(n: int) -> int:
"""
>>> fact(0)
1
>>> fact(1)
1
>>> fact(2)
2
>>> fact(3)
6
>>> fact(4)
24
"""
f = {
n == 0: lambda n: 1,
n == 1: lambda n: 1,
n == 2: lambda n: 2,
n > 2: lambda n: fact(n-1)*n
}[True]
return f(n) | 232ce6d77cf99fedf720d2bf3a14b2c315657619 | 24,860 |
def fraction_word_to_num(number_sentence):
"""transfer english expression of fraction to number. numerator and denominator are not more than 10.
Args:
number_sentence (str): english expression.
Returns:
(float): number
"""
fraction={
'one-third':1/3,'one-thirds':1/3... | 2b9125589db65c43e768c1fe49fc5f8555ee7b84 | 24,862 |
import csv
def load_csv(csv_filename):
"""Load csv file generated py ```generate_training_testing_csv.py``` and parse contents into ingredients and labels lists
Parameters
----------
csv_filename : str
Name of csv file
Returns
-------
list[str]
List of ingredient ... | 704151f36424f9e72ecb1d0dce9f8f7e8f77c1f1 | 24,870 |
def largest_common_substring(query, target, max_overhang):
"""Return the largest common substring between `query` and `target`.
Find the longest substring of query that is contained in target.
If the common substring is too much smaller than `query` False is returned,
else the location `(start, end)` ... | 4e0e1e1ee9d5d37fe5e56601fcedab66621ac9fb | 24,871 |
import os
def only_benchmark_models(path: str) -> bool:
"""
Predicate for list_config_files allowing to list all files
that are benchmarks or models used in benchmarks
"""
dir_path, file_name = os.path.split(path)
return file_name.startswith("eval_") or dir_path.endswith("models") | 470afcc56118a332d01d0b1f164f08f1325f3190 | 24,872 |
def clean_predictions(predictions):
"""
Clean-up the predicted labels by changing impossible combinations (f.e. 'R-S', 'R-E' should be 'R-B', 'R-E').
:param predictions: The predicted labels.
:return: The cleaned predicted labels.
"""
relation_labels = ['R-B', 'R-E', 'R-I', 'R-S']
for line_... | dff5f5c0dca463693850fcc0b43aa841c2c3299a | 24,874 |
def normalize_time(timestamp):
"""Normalize time in arbitrary timezone to UTC"""
offset = timestamp.utcoffset()
return timestamp.replace(tzinfo=None) - offset if offset else timestamp | bd8b7f0417afabe8c58eba3393e7d466c35a70be | 24,875 |
def PopulationDynamics(population, fitness):
"""Determines the distribution of species in the next generation."""
n = list(population)
L = len(population)
f = fitness(population)
for i in range(L): n[i] *= f[i]
N = sum(n)
if N == 0.0: return population
for i in range(L): n[i] /= N
... | b7f928c08e9275c7a314a4be92445588df02abc6 | 24,876 |
def extra(column: list, data_property: str, method):
"""
:param column: table A[column[0]] mapping table B[column[1]]
:param data_property: table A property name
:param method: query method
"""
def e(data_entity):
if isinstance(data_entity, list):
for entity in data_entity:
... | da3c8a2eaf6df1ca026ea48fd7fd36abf3b8b4a2 | 24,877 |
def round_up(n, size):
"""
Round an integer to next power of size. Size must be power of 2.
"""
assert size & (size - 1) == 0, "size is not power of 2"
return ((n - 1) | (size - 1)) + 1 | 02f34fd5f2c059a9ee1b657f099b4699d90dfc01 | 24,878 |
def recombination(temperature):
"""
Calculates the helium singlet and triplet recombination rates for a gas at
a certain temperature.
Parameters
----------
temperature (``float``):
Isothermal temperature of the upper atmosphere in unit of Kelvin.
Returns
-------
alpha_rec_1... | c09e887053794a4c00b0daa3a48a57e563d89992 | 24,879 |
import torch
def batch_quadratic_form(x: torch.Tensor, A: torch.Tensor) -> torch.Tensor:
"""
Compute the quadratic form x^T * A * x for a batched input x.
Inspired by https://stackoverflow.com/questions/18541851/calculate-vt-a-v-for-a-matrix-of-vectors-v
This is a vectorized implementation of out[i] =... | 4e639fc210e944cdc6726c2daab85e486de58134 | 24,880 |
def _codepoint_is_ascii(ch):
"""
Returns true if a codepoint is in the ASCII range
"""
return ch < 128 | 931a3a67956bffd28f73e938e5d312951a2b3b80 | 24,881 |
import re
def valid_email(email):
"""Check if entered email address is valid
This checks if the email address contains a "@" followed by a "."
Args:
email (str): input email address
Returns:
bool: True if the input is a valid email and False otherwise
"""
# Ensure email is a... | a675856a7bb8dae87a77990c9e752b0bb4177c9b | 24,882 |
def _relpath(path, basepath):
"""Generate path part of relative reference.
based on: cpython/Lib/posixpath.py:relpath
"""
path = [x for x in path.split('/')]
basepath = [x for x in basepath.split('/')][:-1]
i = 0
for index in range(min(len(path), len(basepath))):
if path[index] == ... | 6d5b6a24d28791a616de24b2841f0f61ac84e366 | 24,883 |
def get_iou(gt_bbx, pred_bbx):
"""
Calculate the Intersection over Union (IoU) of two bounding boxes.
Based on:
https://stackoverflow.com/questions/25349178/
calculating-percentage-of-bounding-box-overlap-for-image-detector-evaluation
Parameters
----------
gt_bbx : dict
ym... | 20ce6ed931e1a26ed078113191c6de06c4030510 | 24,884 |
def directory_get_basename(path: str) -> str:
"""Returns the last directory in a path."""
p = path
if p.endswith('/'):
p = p[:-1]
elif '.' in p:
p = p[:p.rfind('/')]
return p[p.rfind('/') + 1:] | 69af9336142c88cd705162b2e4522aef2ac95403 | 24,889 |
def _return_quantity(quantity, return_quantity, units_out=''):
"""Helper method to return appropriate unit type
Parameters
----------
quantity : :class:`~vunits.quantity.Quantity` obj
Quantity object to use
return_quantity : bool
If True, returns :class:`~vunits.quant... | de68065aad70134e4e7778e099711013a9930e13 | 24,890 |
def _get_currency_pair(currency, native):
"""
Format a crypto currency with a native one for the Coinbase API.
"""
return '{}-{}'.format(currency, native) | 92c3f43d1661f912a6bb63d14df1a7095eb784f3 | 24,891 |
import six
def sanitize_command_output(content):
"""Sanitizes the output got from underlying instances.
Sanitizes the output by only returning unicode characters,
any other characters will be ignored, and will also strip
down the content of unrequired spaces and newlines.
"""
return six.text_... | 55a42507b24d2fcb3993cfa8abda0cd04e4c7718 | 24,892 |
import os
import argparse
def DirType(d):
""" given a string path to a directory, D, verify it can be used.
"""
d = os.path.abspath(d)
if not os.path.exists(d):
raise argparse.ArgumentTypeError('DirType:%s does not exist' % d)
if not os.path.isdir(d):
raise argparse.ArgumentTypeErr... | a038d70874622a40d36e7e3f6192c156dc4791ed | 24,893 |
def countmatch(str1, str2, countstr):
"""checks whether countstr occurs the same number of times in str1 and str2"""
return str1.count(countstr) == str2.count(countstr) | a25f77cc6b847ff6f9b81af33836b3e4a715b056 | 24,894 |
def get_histogram_limits(filename):
"""Read a histogram file `filename' and return the smallest and largest values in the first column."""
hmin = 0
hmax = 0
with open(filename, "r") as f:
line = f.readline().split("\t")
hmin = float(line[0])
for line in f:
line = line... | 8ceed4f939c40f0266afa9f3218073842578f26f | 24,897 |
def decode_dict(d):
"""Decode dict."""
result = {}
for key, value in d.items():
if isinstance(key, bytes):
key = key.decode()
if isinstance(value, bytes):
value = value.decode()
elif isinstance(value, dict):
value = decode_dict(value)
resul... | 1d2bc6665692a42b8a5a0efd24c1a7fbeeaaaa0b | 24,898 |
from datetime import datetime
def str2timestamp(s, fmt='%Y-%m-%d-%H-%M'):
"""Converts a string into a unix timestamp."""
dt = datetime.strptime(s, fmt)
epoch = datetime.utcfromtimestamp(0)
return (dt - epoch).total_seconds() | 69dd680623da8a61837676b540e1d5c053c8e198 | 24,899 |
def is_cached(o, name):
"""Whether a cached property is already computed.
Parameters
----------
o : object
The object the property belongs to.
name : str
Name of the property.
Returns
-------
bool
True iff the property is already computed.
Examples
----... | eb7b1356ded56dddb4cd917b27461e9108bd7b76 | 24,900 |
def get_food(request):
""" Simple get food request """
return "Hello there, here's some food!" | 0c9942b1e26a5399adbc06ece5d90ebd496ab4cc | 24,902 |
def encode_no_auth(**kwargs):
""" Dummy encoder. """
return {} | 5912dc656233e32fb4a354a32fc4279d105cf5b7 | 24,903 |
import os
def read_file(file_path: str, as_single_line: bool = False) -> str:
"""Read file content.
:param file_path: path to the file.
:param as_single_line: whether or not the file is to be read as a single line.
:return: file content.
"""
with open(file_path, "r") as file:
lines = ... | 21e528d90b5ec403c87c0bcee1e702b49787e160 | 24,904 |
def inverse_dead_zone(motor_output, dead_zone):
"""This is the inverted dead zone code which is important for Talons."""
if abs(motor_output) < .00001: #floating point rounding error workaround.
return 0
elif motor_output > 0:
return (motor_output*(1-dead_zone))+dead_zone
else:
r... | 7129323f47f34a5ae28d91e5b3128af4804aace7 | 24,905 |
import click
def no_going_back(confirmation):
"""Show a confirmation to a user.
:param confirmation str: the string the user has to enter in order to
confirm their action.
"""
if not confirmation:
confirmation = 'yes'
prompt = ('This action cannot be undone! ... | 385c665b4b690e9b80473006b6d1e9536310189f | 24,906 |
def minutes_to_human_duration(minutes_duration):
"""
Convert a duration in minutes into a duration in a cool format human readable
"""
try:
hours,minutes = divmod(minutes_duration,60)
return "%sh %smin" %(hours,minutes)
except TypeError:
return None | 22197c568505e366d5d4f6b020f8b61466deb43a | 24,907 |
def chart_filter(df, year = None, month = None, neighbourhood = None, crime = None):
"""
Filters the given database in order to wrange the database into the proper dataframe
required the graphs to display relevant information. Default value of None will allow
the maps to display every single data poin... | 0958af7abd9d302adc2aff91b081d309a88a505e | 24,908 |
def fibonacciAtIndex(index):
"""
Returns the fibonacci number at a given index.
Algorithm is using 3 variables instead of recursion in order to reduce memory usage and runtime
"""
a1, a2 = 1,1
position = 3
# while position <= index:
while index > 2:
temp = a1
a1 = a2
a2 += temp
# position += 1
index -... | 2dde77a70bfe8d1c32777910521a9b4695ab326e | 24,910 |
def get_lists_moving_avg(lists: list, period: int) -> list:
"""Get the moving average from the given lists.
Notice that all lists must have the same size."""
num_lists = len(lists)
avgs = [sum(vals)/num_lists for vals in zip(*lists)]
if period > len(avgs):
raise Exception(
"Peri... | f25ed2216a1c7695d74a3f6dc7c8a14bed22af69 | 24,911 |
import os
import pickle
def load_object(file_name):
"""Save a Python object by pickling it."""
file_name = os.path.abspath(file_name)
with open(file_name, 'rb') as f:
return pickle.load(f) | 35484a2d794a02970b6f757f1d10374cf646cf00 | 24,912 |
from typing import Tuple
from typing import List
def define_2d_correlations_hists() -> Tuple[List[str], List[float], List[Tuple[str, float, float, str]]]:
""" Define the 2D correlation hists.
Args:
None.
Returns:
(ep_orientation values, assoc_pt values, (ep_orientation, lower_pt_bin_edge,... | 00a0f59fe7c238a271fa75a83085556fc51f4acc | 24,913 |
def _dict_clean_departments(my_dict):
"""Remove internal annotations."""
my_dict['department_name'] = my_dict['department_name'].replace('_archive_', '').replace('_obsolete_', '').replace('_Obsolete_', '').replace('Obsolete_', '')
return my_dict | c5be3a21491f8b82cabe812c03104f1e92d7baef | 24,915 |
def is_valid_environment(env, nova_creds):
"""
Checks to see if the configuration file contains a section for our
requested environment.
"""
if env in nova_creds.keys():
return env
else:
return False | c1a020f8b7ea8515d24f5f2547cd3eb5a182e306 | 24,916 |
import os
from pathlib import Path
def get_files(path, exts):
"""Return sorted list of absolute paths to files in the tree rooted at path.
Only return the files with given extensions.
"""
result = []
for dirpath, _, filenames in os.walk(path):
selected = [fn for fn in filenames if fn.lo... | b629b39f01972924f1b563060ef6703cb7b3b01c | 24,917 |
import numpy as np
def nd_to_3d(ndarray, Rlist, Glist, Blist, G_plus=0):
"""
input an nd image, Rchannels, Gchannels, Bchannels\n
G_plus rise, green color down
return a 3d image
"""
out = np.zeros([ndarray.shape[0],ndarray.shape[1],3])
for r in Rlist: out[:,:,0] += ndarray[:,:,r]
out[... | fcca0a1b168d5f218274b0773854a2713e72ffe0 | 24,918 |
def compress(dates, values):
"""
inputs:
dates | values
-----------+--------
25-12-2019 | 5
25-12-2019 | 6
25-12-2019 | 7
25-12-2019 | 8
25-12-2019 | 9
25-12-2019 | 10
29-12-2019 | 11
29-12-2019 | 12
29-12-2019 | 13
... | d6e34a56e6834916f68af491f4b5793e28594685 | 24,919 |
def _load_image(client, load):
"""Load image from local disk
"""
with open(load, 'rb') as f:
# load returns image list
return client.images.load(data=f)[0] | c3c4f2cf074707126d93f12d8281da3179ddf0da | 24,920 |
def _ParseClassNode(class_node):
"""Parses a <class> node from the dexdump xml output.
Returns:
A dict in the format:
{
'methods': [<method_1>, <method_2>]
}
"""
methods = []
for child in class_node:
if child.tag == 'method':
methods.append(child.attrib['name'])
return {'m... | 2d801173230a065e668b89cac155b31991cee656 | 24,921 |
import select
def _is_readable(socket):
"""Return True if there is data to be read on the socket."""
timeout = 0
(rlist, wlist, elist) = select.select(
[socket.fileno()], [], [], timeout)
return bool(rlist) | 79b258987171e3a5e4d3bab51a9b8c9a59e2415e | 24,922 |
def add_lists(*args):
"""
Append lists. This is trivial but it's here for symmetry with add_dicts
"""
out = []
for arg in args:
out.extend(arg)
return out | a7992b388995dbe23ca4b117d0fe94a8197e81da | 24,923 |
def export_sheet(ss, sheet_id, export_format, export_path, sheet_name):
"""
Exports a sheet, given export filetype and location. Allows export format 'csv', 'pdf', or 'xlsx'.
:param ss: initialized smartsheet client instance
:param sheet_id: int, required; sheet id
:param export_... | 76b49fa0904140571eb84526f6021448db54dea9 | 24,924 |
def rev_slice(i):
"""
"""
return isinstance(i, slice) and i.step is not None and i.step < 0 | 680736407681301f16b93d5871630fcbd9ca9679 | 24,926 |
import sys
def usage():
"""
Defines the usage when called directly
"""
return "{} [state action terminating]".format(sys.argv[0]) | 846faa01af054fcb2f61ed36daaf34e8cd5f9af6 | 24,927 |
def add_tooltips_columns(renderer, tooltips, group):
"""
Args:
renderer (GlyphRenderer): renderer for the glyph to be modified.
tooltips (bool, list(str), list(tuple)): valid tooltips string as
defined in the builder class.
group (DataGroup): group of data containing missing... | f13fd71a4288936575c8157bc8829eed6545e004 | 24,928 |
def adapt_sample_keys(sample_list, key_type):
"""
Converts sample_list to a new format where instead of "scene_id", "object_id" and "ann_id"
there is a "sample_id".
:param key_type:
'kkk' for {scene_id}-{object_id}_{ann_id}
'kk' for {scene_id}-{object_id}
'k' for {scene_id}
:retu... | 8845da67ee9627cf377efc1c7b789eaa4cfb2c65 | 24,930 |
import torch
def get_distance_measure(x: torch.Tensor, p: int = 1):
"""Given input Nxd input compute NxN distance matrix, where dist[i,j]
is the square norm between x[i,:] and x[j,:]
such that dist[i,j] = ||x[i,:]-x[j,:]||^p]]
Arguments:
x {torch.Tensor} -- [description]
Keywor... | 716fd603263aae905720058ec698caf8c8d9e5a3 | 24,931 |
import types
import inspect
def get_pytorch_model(module, model_settings):
"""
Define a DeepSphere-Weather model based on model_settings configs.
The architecture structure must be define in the 'module' custom python file
Parameters
----------
module : module
Imported python m... | a32a01163b71b1610c97adad1b3febfa1d4d5a25 | 24,932 |
def p_testlist_single(p, el):
"""testlist_plus : test"""
return [el], el | 0879bcf4c414acf0f01028e80ece2d5ed4db8489 | 24,933 |
def get_sample_name_and_column_headers(mpa_table):
""" Return a tuple with sample name, column headers, database, and table variant.
Variant is an integer also indicating the number of rows to skip when parsing table.
"""
with open(mpa_table) as f:
first_line = f.readline().strip()
seco... | f37d52124cae2d1a893627390cde731b52f87d32 | 24,936 |
def lingray(x, a, b):
"""Auxiliary function that specifies the linear gray scale.
a and b are the cutoffs."""
return 255 * (x-float(a))/(b-a) | 40562246a2a3ba377344bc593091c49ca290a04b | 24,937 |
def calc_wmark_low_and_totalreserve_pages():
"""Calculate sum of low watermarks and total reserved space over all
zones, and return those two values. Values are in pages.
"""
fzoneinfo = open("/proc/zoneinfo")
wmark_low = 0
totalreserve = 0
keep_reading = True
while keep_reading:
... | e184a82e9a61002eb883e2c8a1e9063bd53a860e | 24,938 |
import torch
def get_criterion(config):
"""
Creates the torch criterion for optimization
"""
if config["name"] == "cross_entropy":
return torch.nn.CrossEntropyLoss()
else:
raise NotImplementedError | 2d1a9cc5983ab64fe2016637c292de3b9551079b | 24,939 |
import subprocess
def isProgramAvailable(programName):
"""Find if program passed in is available.
There's probably a better way to do this that's portable, and in a
sense this is not "safe", but for the scope of this program, this
approach is fine.
Arg:
programName: A string containing a... | 28cb7d06175808ee58b8b479cce1f1a14ba30719 | 24,942 |
def is_magic(attribute):
"""Check if attribute name matches magic attribute convention."""
return all([
attribute.startswith('__'),
attribute.endswith('__')]) | d392a34902ce22127d92bc4d678228d59b97cba9 | 24,944 |
def expand_row(header, row):
"""Parse information in row to dict.
Args:
header (dict): key/index header dict
row (List[str]): sambamba BED row
Returns:
dict: parsed sambamba output row
"""
thresholds = {threshold: float(row[key])
for threshold, key in head... | 79ea16b498f6fd5c7c002bf822a34da65de0d2c9 | 24,945 |
import pickle
def retrieve_model(filename='model.pkl'):
"""
Retrieve probability model pickled into a file.
"""
with open(filename, 'rb') as modfile: return pickle.load(modfile) | 3e05c3c9b3bc2bc3974dab422ced5f53589c2823 | 24,949 |
def aggregator(df, column):
"""
Return multiple aggregate data values, compiled into a list. summ (total), minn (lowest value), maxx (highest value), avg (mean), med (median), mode (most repeated value).
Parameters
----------
df : pandas object
dataFrame from which to pull the values
... | f940270662715859f42e6b9ffc4411c492085651 | 24,951 |
def gen_compare_cmd(single_tree, bootstrapped_trees):
"""
Returns a command list for Morgan Price's "CompareToBootstrap" perl script <list>
Input:
single_tree <str> -- path to reference tree file (Newick)
bootstrapped_trees <str> -- path to bootstrapped trees file (Newick)
"... | df9d2d4c21ca28012107b8af69706d45804e5637 | 24,953 |
def silent_none(value):
"""
Return `None` values as empty strings
"""
if value is None:
return ''
return value | 48b9709dc4bffc659b168f625f4f6be5608a645d | 24,955 |
import os
def GetNumCores():
"""Returns the number of cores on the machine. For hyperthreaded machines,
this will be double the number of actual processors."""
num_cores = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(num_cores, int) and num_cores > 0:
return num_cores
return 1 | a03536917ef9401a693d076e1a2cebde807e90ab | 24,956 |
def _get_filename(params):
""" Return the filename generated from given configuration params. """
def _mem_to_int(mem_type):
return {'local': 0, 'no_local': 1}[mem_type]
def _algo_to_int(algo_type):
return {'standard': 0, 'naive': 1}[algo_type]
def _batch_to_int(batch_type):
re... | 23fd49a2288d6b5386b7863152950f7e3d751246 | 24,957 |
def name(action_name):
"""custom action name, does not override prefix"""
def decorator(action_function):
"""custom action name, does not override prefix"""
action_function.action_name = action_name
return action_function
return decorator | 530e107c0062ee5e5f91d833d0810f6eed27650d | 24,958 |
def determina_netmask_bin(putere):
"""
Determina netmask-ul potrivit
:param (int) putere: numarul de 0-uri din netmask
:return (str) netmask: string reprezentand netmask-ul
"""
ones = 32 - putere
str_bin_netmask = ""
for i in range(0, 32):
if i < ones:
str_bin_netmas... | 93498dc715d18fb8dd6ca593680bc51b648f083d | 24,959 |
def splinter_screenshot_encoding(request):
"""Browser screenshot html encoding."""
return "utf-8" | 17e6055332e7bc63778e1e80ba01c1631b0c876e | 24,960 |
import math
def rms_mean(elements):
"""
A function to calculate the root mean squared mean value of a list of elements
:param elements: a list of elements
:return: root mean squared mean value
"""
return math.sqrt(sum(x * x for x in elements) / len(elements)) | a1178e70f210063c6559fa15789bfd15c1f89b79 | 24,961 |
import subprocess
def run_cmd(command, wait=True):
"""
Execute command with subprocess.
"""
return subprocess.check_call(command, shell=True) | 950716af828f14984c0aea5f797fc0cd46bce554 | 24,963 |
from typing import Any
def maybebool(value: Any) -> bool:
"""
A "maybified" version of the bool() function.
"""
return bool(value) | e40d112291ce7bfb58d94208be662cb5370506d9 | 24,964 |
import random
def digits() -> str:
"""Generate a random 4 digit number."""
return str(random.randint(1111, 9999)) | 8d4f9195e74c2b1b0c31a108a502a028239bea8e | 24,965 |
def parse_probabilities_grep_pos_2_prob(aaseq, pos_2_prob_dict):
"""
the following didn't work as expected since list is not initialized as expected
df[COLUMN_PROB] = df[COLUMN_MODPROB].apply(parse_probabilities, args=([], ))
"""
try:
start_index = aaseq.index("(")
except ValueError:
... | 069e22809c11fede827e89710807a2b0743e486e | 24,966 |
def get_history_object_for(obj):
"""Construct history object for obj, i.e. instantiate history
object, copy relevant attributes and set a link to obj, but don't
save. Any customizations can be done by the caller afterwards.
Many-to-many fields are not copied (impossible without save).
The history m... | 233a9b2d80c80803d1f3e9dbaacbc76290d71f33 | 24,968 |
from typing import Sequence
def crop_to_bbox_no_channels(image, bbox: Sequence[Sequence[int]]):
"""
Crops image to bounding box (in spatial dimensions)
Args:
image (arraylike): 2d or 3d array
bbox (Sequence[Sequence[int]]): bounding box coordinated in an interleaved fashion
(e... | 0d6d4a2c77be0343b7557485e06fd8c33a49e72f | 24,969 |
def find_interval(array, value):
""" Returns the index idxInf and idxSup of array verifying :
array[idxInf] < value < array[idxSup] """
n = [abs(i-value) for i in array]
idx = n.index(min(n))
idxInf=-1
idxSup=-1
if value < array.min() or value > array.max():
idxInf=-1
id... | f6399cc1ae0b496ae9d407d38853ba91bcff3640 | 24,973 |
def mean_std(feature_space, eps=1e-5):
"""
Calculates the mean and standard deviation for each channel
Arguments:
feature_space (torch.Tensor): Feature space of shape (N, C, H, W)
"""
# eps is a small value added to the variance to avoid divide-by-zero.
size = feature_space.size()
a... | 2b228edab0397257b1deacdecae95265d955c76c | 24,976 |
import os
def resolve_template_filepath(paths, template_reference):
"""Resolves a template filepath, given a reference and a collection of
possible paths where it might be found.
This function returns the first matching resolved template filepath, if the
chapter files and their children are ambiguous... | 7aa28d330c4d1f225265c116b726e2b51e571b2b | 24,977 |
def fake_training_fn(request):
"""Fixture used to generate fake training for the tests."""
training_loop, loop_args, metrics = request.param
assert len(metrics) in [1, 3]
return lambda logdir, **kwargs: training_loop(
logdir=logdir, metrics=metrics, **loop_args, **kwargs
) | 8f44f765126f74bdd06e243015fa2d58259e967b | 24,979 |
def some_text(name):
"""
Some method that doesn't even know about the decorator
:param name: string some name
:return: Some ipsum with a name
"""
return "Ipsum {n}, Ipsum!".format(n=name) | 4f76b67f5b3fb34e1bc634ba5374cc5714a2e387 | 24,980 |
import torch
def bbox_transform(boxes, gtboxes):
""" Bounding Box Transform
from groundtruth boxes and proposal boxes to deltas
Args:
boxes: [N, 4] torch.Tensor (xyxy)
gtboxes: [N, 4] torch.Tensor (xywh)
Return:
delta: [N, 4] torch.Tensor
"""
gt_w = gtboxes[:, 2] - gt... | fa2bf83d24206b83508612ac728636905e80ebcc | 24,981 |
import json
def jsonEqual(ja, jb):
"""
jsonEqual(obj1, obj2) -> Boolean
determine two object(can be dumped by json) whether is equal
args:
obj1 = {1:1, {2:2, "a":"a"}}; obj2 = {1:1, {2:2, "a":"a"}}
return: Boolean
True
"""
return json.dumps(ja, sort... | 15affb59b426f7d5b909ec2c999c86a4f3951e22 | 24,982 |
import os
def select_path(directories, filename):
"""Find filename among several directories"""
for directory in directories:
path = os.path.join(directory, filename)
if os.path.exists(path):
return path | a3f5b3afcb6f00d2bb44d7bdb9f90944d40dce05 | 24,983 |
def port_forward(srcport, destport, rule=None):
"""Use firewall rule to forward a TCP port to a different port. Useful for
redirecting privileged ports to non-privileged ports. """
return NotImplemented | 041056ad58efca38b1f681bacd556f002ff7d1de | 24,984 |
from typing import Union
from pathlib import Path
import pickle
def load_picke(ffp: Union[Path, str]):
"""Loads the pickle file"""
with open(ffp, "rb") as f:
return pickle.load(f) | 39145f2c1dd51226f19b89aaeb984a9434ebb06c | 24,985 |
def check_average_ROI_overlap(df_overlap, percentage):
"""" Returns True if the mean overlap in the df is greater than percentage"""
mean_overlap = df_overlap["%_overlap"].mean()
if mean_overlap > percentage:
return True
return False | 3f1d932ba270f64fec85644c5e3613b082cda160 | 24,986 |
import argparse
def set_parser():
""" set custom parser """
parser = argparse.ArgumentParser(description="")
parser.add_argument("-d", "--data", type=str, required=True,
help='path to a folder containing days to be predicted (e.g. the test folder of the test dataset)')
parser.add_argumen... | bf4a04954ec83ad55972acec3f72f936d85c657a | 24,987 |
from typing import List
def replace_words_with_prefix_hash(dictionary: List[str], sentence: str) -> str:
"""
Replace words in a sentence with those in the dictionary based on the prefix match.
Intuition:
For each word in the sentence, we'll look at successive prefixes and see if we saw them before
... | bb46b0dc61eab2be358d44f8fb46782f867e3c30 | 24,990 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.