content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def most_common_errors(interp):
"""More concise version of `most_confused`. Find the single most common
error for each true class.
Parameters
----------
interp: fastai ClassificationInterpretation
Returns
-------
dict[str, str]: Map true class to its most common incorrectly predicted
... | 7217b1418befd9eb95ee16202fa86ca0bd4d6043 | 686,872 |
import torch
def load_pretrained_net(net_name, chk_name, model_chk_path, test_dp=0):
"""
Load the pre-trained models. CUDA only :)
"""
net = eval(net_name)(test_dp=test_dp)
net = torch.nn.DataParallel(net).cuda()
net.eval()
print("==> Resuming from checkpoint for %s.." % net_name)
chec... | ae2a1c04493062ef5f24c745b51c0107269512a2 | 686,873 |
def iter_copy(structure):
"""
Returns a copy of an iterable object (also copying all embedded iterables).
"""
l = []
for i in structure:
if hasattr(i, "__iter__"):
l.append(iter_copy(i))
else:
l.append(i)
return l | e9eb1000abb428ad15006fe18791861e75b17691 | 686,874 |
import platform
def host_target():
"""
Return the build target for the current host machine, if it is one of the
recognized targets. Otherwise, return None.
"""
system = platform.system()
machine = platform.machine()
if system == 'Linux':
if machine == 'x86_64':
return... | 04dc33e4876081b8fed694e54c8aa6aea4874bc3 | 686,875 |
def tag_predicate(p):
"""
Given a full URI predicate, return a tagged predicate.
So, for example, given
http://www.w3.org/1999/02/22-rdf-syntax-ns#type
return
rdf:type
"""
ns = {
"http://www.w3.org/1999/02/22-rdf-syntax-ns#":"rdf:",
"http://www.w3.org/2000/01/r... | bfe1cf2ea83f4faee77299b0e7929571b550b59a | 686,876 |
def chunk(arr:list, size:int=1) -> list:
"""
This function takes a list and divides it into sublists of size equal to size.
Args:
arr ( list ) : list to split
size ( int, optional ) : chunk size. Defaults to 1
Return:
list : A new list containing the chunks of the original
... | 0aa82c11fdc63f7e31747c95e678fdcac4571547 | 686,877 |
def elimina_enter(lines):
"""
Elimina CR/LF do final de cada linha. Todas as linhas da lista deve possuir
o caracter CR/LF
"""
newLines = []
for line in lines:
newLines.append(line[0:len(line)-1])
return newLines | aa822c8adeaa7f1f6d0bdf1cfb769b3f46e35eca | 686,878 |
def listify(x):
"""Convert item to a `list` of items if it isn't already a `list`."""
if not isinstance(x, list):
return [x]
return x | e68cca5c56fb8537a8340682618aa509a5d54bd2 | 686,879 |
import re
import fnmatch
def compile_endpoints(*blacklist):
"""Compiles a list endpoints to a list of regexes"""
return [re.compile(fnmatch.translate(x)) for x in blacklist] | 74c3b76258c940866fc89188fa1fac147f2a1844 | 686,880 |
def _process_app_path(app_path):
""" Return an app path HTML argument to add to a Bokeh server URL.
Args:
app_path (str) :
The app path to add. If the app path is ``/`` then it will be
ignored and an empty string returned.
"""
if app_path == "/":
return ""
... | 1306e6a356159eddc64603a7ec293446cfbb3c67 | 686,881 |
def get_result_class(cls):
"""
For the given model class, determine what class we should use for the
nodes returned by its tree methods (such as get_children).
Usually this will be trivially the same as the initial model class,
but there are special cases when model inheritance is in use:
"""
... | c6f70f38693662c3a2990c180639bec343b48339 | 686,882 |
def find_missing_number(array):
"""
:param array: given integer array from 1 to len(array), missing one of value
:return: The missing value
Method: Using sum of list plus missing number subtract the list of the given array
Complexity: O(n)
"""
n = len(array)
expected_sum = (n + 1) * (n +... | e70ee9bbe7aa9924ddd0e3059c43ed920621ebe9 | 686,884 |
import time
import os
def add_datetime_suffix(filename):
"""
Adds datetime suffix to the given filename.
"""
datetime = time.ctime(time.time())
datetime = datetime.replace(' ', '_')
base, ext = os.path.splitext(filename)
filename = '%s_%s%s'%(base,datetime,ext)
return filename | 27a66927db135e82c1181a2706cef339f9f0eddb | 686,885 |
def get_lat(ref, lat):
"""A Helper function for get_GPS to convert from degrees to decimal."""
if ref == "N":
return lat[0] + (lat[1] / 60) + (lat[2] / 3600)
return -(lat[0] + (lat[1] / 60) + (lat[2] / 3600)) | 240b292a0fcfc3d7a4a8dbd16219dcd008bf7e06 | 686,886 |
def prune_nones_list(data):
"""Remove trailing None values from list."""
return [x for i, x in enumerate(data) if any(xx is not None for xx in data[i:])] | ae596bdbfede7d86ef8b318a63eb1b8b53cf08bf | 686,887 |
def with_complete_history_between(
start_date,
end_date,
# Required keyword
return_expectations=None,
):
"""
All patients for which we have a full set of records between the given
dates
"""
return "with_complete_history_between", locals() | b038da227aff0399f3983e5fcde62ad8fa55b1b7 | 686,888 |
def bound_value(lb=None, ub=None):
"""
builds a function that limits the range of a value
"""
def _f(value):
limited = value if lb is None else max(lb, value)
if ub is not None:
limited = min(ub, limited)
return limited
return _f | 5de2dda7cc14ca538d556a5a6bf81a6b7bb9faf8 | 686,889 |
def _convert_power_variables(experiment_settings, data_parameters):
""" `create_noisy_features` auxiliary function. Scales some power-related settings by
as much as the features were scaled.
:param experiment_settings: [description]
:param data_parameters: [description]
:return: noise and power cut... | 70f2a8c164ba0523b636438515c123a2e5a36d3d | 686,890 |
def is_likely_in_str(line, index):
"""
Return `True` if the `index` is likely to be within a string, according
to the handling of strings in typical programming languages. Index `0`
is considered to be within a string.
"""
cur_str_char = None
escaped = False
def in_str():
... | a1b18144e1c47d744612a7e73e34a238a4a9efe2 | 686,891 |
def get_clean_path_option(a_string):
""" Typically install flags are shown as 'flag:PATH=value', so
this function splits the two, and removes the :PATH portion.
This function returns a tuple consisting of the install flag and
the default value that is set for it.
"""
option, default = a_string.... | 56954c706de0d01077a6c6e023e997d66517e5a1 | 686,893 |
import pandas as pd
def get_pre_post_mean_per_bird(df, variable):
"""
Get conditional mean for each bird
Parameters
----------
df : dataframe
variable : str
target column name to calculate the mean
Returns
-------
df_mean : dataframe
new data frame with the compute... | c343e53f3aa690f292e4e3392c093debe83dc512 | 686,894 |
def proc_add_next_y(df, y_column, number, cont_vars):
"""
Adds the n-next value of the y column
:param df:
:param y_column:
:param number:
:param cont_vars:
:return:
"""
# https://riptutorial.com/pandas/example/24907/shifting-or-lagging-values-in-a-dataframe
c_name = "y"
df[c... | e085332e9ab517da636ba6909a982cdb24de68d7 | 686,895 |
def get_workspace(engine):
"""Gets and returns the MATLAB workspace
Parameters
----------
engine : MATLAB engine
A MATLAB engine object
Returns
-------
Dictionary
Dictionary containing key-value pairs for each variable and its value from the MATLAB workspace
"""
ret... | 6a10af3975f3f19802d3a7341a6e96302f0b342d | 686,896 |
from typing import Tuple
from typing import List
import re
def parse_command(input: str) -> Tuple[str, List[str]]:
"""
Parse the command.
:param input: The input to parse.
:returns: Tuple of command, and a list of parameters to the command.
"""
input = input.strip() # Strip whitespace at sta... | b6e8375940538452096ab13fcede5cd7ce242348 | 686,897 |
def id_2_addr(hue_id):
""" Convert a Phillips Hue ID to ISY Address """
return hue_id.replace(':', '').replace('-', '')[-14:] | da1a085be4fc07b827f34dd8d5d556d218dd2a6c | 686,898 |
import os
import sys
def get_occambin_path():
""" Deduces the full path to the occam bin directory.
"""
home = os.getenv('OCCAM_HOME')
if home is None:
sys.stderr.write('OCCAM_HOME not set!\n')
return None
return os.path.join(home, 'bin') | 41414942c06ffa4a0333e146a13bb8fb3e574a08 | 686,899 |
def merge(novel_adj_dict, full_adj_dict):
"""
Merges adjective occurrence results from a single novel with results for each novel.
:param novel_adj_dict: dictionary of adjectives/#occurrences for one novel
:param full_adj_dict: dictionary of adjectives/#occurrences for multiple novels
:return: full_... | 90d77279aba293b7358bbb7e4b774769cf03588c | 686,900 |
from typing import List
import os
def find_executable(name: str, flags=os.X_OK) -> List[str]:
"""
Finds executable `name`.
Similar to Unix ``which`` command.
Returns list of zero or more full paths to `name`.
"""
result = []
extensions = [x for x in os.environ.get("PATHEXT", "").split(os... | 8adb7079dcba79ac5dcbe323efb48108007951dc | 686,901 |
def jinja2_lower(env, s):
"""Converts string `s` to lowercase letters.
"""
return s.lower() | 95c63c2a1eabc07ebe3a4440155588813d89a166 | 686,902 |
def compute_cycle_length_with_denom(denom):
"""
Compute the decimal cycle length for unit fraction 1/denom (where denom>1)
e.g. 1/6 has decimal representation 0.1(6) so cycle length is 1, etc
"""
digit_pos = 0
# Remaining fraction after subtracting away portions of earlier decimal digits
fr... | 50194cd7ffc699a59d48356f310679dfcc24c273 | 686,903 |
def binary_to_ascii(binary_item):
"""
Convert a binary number to an ASCII char.
"""
str_number = str(binary_item)
if str_number == '':
return -1
decimal_number = int(str_number, 2)
decoded = chr(decimal_number)
return decoded | b310ce04dc932832e326d8164a003300246f12b6 | 686,905 |
def get_ukcp18_kwargs():
"""
From UKCP18 metadata.
Returns
-------
dict with UKCP18-appropriate values of keyword arguments for par_est_xr and eto_xr method functions.
"""
ukcp18rcm_kwargs = {
'freq': 'D',
'z_u': 10,
'dt_index_name': 'time',
}
return ukcp18rc... | 924a64cd3a93de6d01524b6a6c2a848af9fb5db9 | 686,906 |
import socket
def get_local_hostname():
"""
get hostname of this machine
"""
return str(socket.gethostname()) | bcc60e18742955ccda7fb064eb942caaca497db2 | 686,907 |
import torch
def fast_scaled_gramian(x, logvar):
"""
Calculates scaled distance (x-x')Σ'^{-1}(x-x')
for every pair (x,x') in batch. Note asymmetry between x,x'.
Parameters
----------
x: torch.Tensor
Matrix containing observations as rows, [B,D]
logvar: torch.Tensor
... | 359b9a5f3efb7534e5fe6e044cb46bfa2c8ec590 | 686,909 |
import os
def is_xdist_root():
"""True if xdist master or xdist not used"""
return os.getenv("PYTEST_XDIST_WORKER", "root") == "root" | 2dd377cd7af761f8bd616b6c5f65cd3a4abeda81 | 686,910 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_aws_iam package"""
reload_params = {"package": u"fn_aws_iam",
"incident_fields": [],
"action_fields": [u"aws_iam_access_key_filter", u"aws_iam_group", u"aws_iam_group_filter", u"aws_iam_password"... | 88fd4d622290a3d3f46fca658304313dbd78179b | 686,911 |
def insertion_sort(collection: list) -> list:
"""A pure Python implementation of the insertion sort algorithm
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
Examples:
>>> insertion_sort([0, 5, 3, 2... | 675577a4d26a5ba4a0709b04d139fdee9f63e428 | 686,912 |
def comment_to_reply(last_comment, player1, player2):
""" Return string based on last comment.
@param (string, string) last_comment:
@param Player player1:
@param Player player2:
@rtype: string
"""
if "attack" in last_comment.body:
damage = player1.attack(last_comment.body.split()[-... | 822bf36f558f58c866669c6232e256dadd5531d0 | 686,913 |
import shutil
def read_binary(shared_dir, output_file):
"""
Read back binary file output from container into one string, not an
iterable. Then remove the temporary parent directory the container
mounted.
:param shared_dir: temporary directory container mounted
:param output_file: path to outp... | ed79ea0bddccc4c24ee7bb412ce4526e2a90ad7c | 686,914 |
def gluNewTess( baseFunction ):
"""Get a new tessellator object (just unpacks the pointer for you)"""
return baseFunction()[0] | f4c817f7dca3f1f232a09dfe3cda797856db94df | 686,915 |
def number_of_lines(filename=""):
"""returns number of lines in a file"""
lines = 0
with open(filename, mode='r', encoding='utf-8') as a_file:
for i, l in enumerate(a_file):
lines += 1
return lines | ddc16356dcac6372bbbeab05742eabe47a44fa0b | 686,916 |
import inspect
import types
def _repr_obj(obj, show_modules: bool = False, depth: int = 0) -> str:
"""Return a pretty representation of an object."""
rep = f"{obj.__class__.__name__} ("
if show_modules:
rep = f"{obj.__class__.__module__}.{rep}"
tab = "\t"
params = {
name: getattr... | 03d359423540821f83fb89d612a75d5f508ceb01 | 686,917 |
def hex_rgb(argument):
"""Convert the argument string to a tuple of integers.
"""
h = argument.lstrip("#")
num_digits = len(h)
if num_digits == 3:
return (
int(h[0], 16),
int(h[1], 16),
int(h[2], 16),
)
elif num_digits == 4:
return (
... | c00eb26193b923956ae7bd99466021fc63354dc1 | 686,918 |
import json
import base64
def b64_json_enc(data):
"""
encode data to b64 encoded json
:data: data to encode
:returns: encoded str
"""
json_str = json.dumps(data)
return base64.b64encode(json_str.encode()).decode() | e5ecc8d05ff5f49872010daa500a210cddb91700 | 686,919 |
def detectCapitalUse(word):
"""
:type word: str
:rtype: bool
"""
return word.isupper() or word.islower() or word.istitle() | c08ae993cf1fd616e2e07c6c8f0b1646b9d915cd | 686,920 |
import re
def is_valid_project_id(project_id):
"""True if string looks like a valid Cloud Project id."""
return re.match(r'^(google.com:)?[a-z0-9\-]+$', project_id) | 46532d10a8a0ed304204d858445b935ff4f4bfe9 | 686,921 |
def ep2string(EP, area=1.0):
"""Format energy efficiency indicators as string from primary energy data
In the context of the CTE regulations, this refers to primary energy values.
"""
areafactor = 1.0 / area
eparen = areafactor * EP['EPpasoA']['ren']
epanren = areafactor * EP['EPpasoA']['nren']... | 5e0ed0c753f879332a5f670efb5b8179852fa274 | 686,922 |
import json
def __read_nb__(filename):
"""returns the notebook as a dictionary"""
with open(filename) as f:
notebook = json.load(f)
f.close()
return notebook | c740574c58e317be7534459ed39ecdfe1f065acf | 686,923 |
def prompt_yes_or_no(message):
""" prompt_yes_or_no: Prompt user to reply with a y/n response
Args: None
Returns: None
"""
user_input = input("{} [y/n]:".format(message)).lower()
if user_input.startswith("y"):
return True
elif user_input.startswith("n"):
return False
... | 4178f3a9596a17f2529cb6acb959be628ad6d953 | 686,926 |
from random import shuffle
def k_fold_split(X, Y, k=10, shuffleDataset=True):
"""
Split both list X and Y into k folds
random will shuffle the data before, so two calls would not return the same folds
ex: print(k_fold_split(["A", "B", "C", "D", "E", "F", "G"], ["a", "b", "c", "d", "e", "f", "g"], k=3... | 0effb1cc05696fbd83423bf20520cc052835d42a | 686,927 |
import os
def update_config_without_sections(config_path, update_dict):
"""helper function to edit cfg files that look like tracking.cfg
update_dict: i.e. {'nframes': 10, 'video-filename': 'video.avi'}
"""
if config_path == None:
return None
if not os.path.exists(config_path):
pri... | 9ce20727830e3db6a2e403fecc9d6548bc134884 | 686,928 |
def indent(num_spaces):
"""Gets spaces.
Args:
num_spaces: An int describes number of spaces.
Returns:
A string contains num_spaces spaces.
"""
num = num_spaces
spaces = ''
while num > 0:
spaces += ' '
num -= 1
return spaces | 99784b1371330d2c1998c396b4235216044744d3 | 686,929 |
def preprocess_trip_data(daily_results):
"""Cleans the tabular trip data and calculates average speed.
Removes rows with duplicated tripid, locationid columns from the data. These
rows are times where the OneBusAway API was queried faster than the bus
location was updated, creating duplicate info. Buse... | fd64425468f755b30b376c1addf387ddb9e4a358 | 686,930 |
import time
def exampleWorker(in_str, in_num):
""" An example worker function. """
print('Got:', in_str, in_num)
t1 = time.time()
while True:
if time.time() - t1 > 10:
break
return in_str + " " + str(in_num) + " X" | a1e25a6cb43428fcda6dbe06c7013b8f0d3f1411 | 686,931 |
def fn_3poly_dr(x, a, b, c, d):
"""direvative of fn_3poly"""
return b + 2 * c * x + 3 * d * x **2 | ce4277282d09ff667a3d9f7a2a0937f99382cc4c | 686,933 |
def is_not_empty(s):
"""判断字符是否为空字符串"""
return s and len(s.strip()) > 0 | 3862e388d385bc9ba154dd3e376fd5100a31bf21 | 686,934 |
def words_to_count(words):
"""str -> str"""
result = ""
words = words.strip().split()
for word in range(len(words)):
result += str(len(words[word])) + " "
return result.strip() | 58cdadd67ce6c2d064ad092fd235a84a3f460109 | 686,935 |
def calculation(m, d, n):
"""
Calculates m**d mod(n) more efficiently
"""
value = 1
for _ in range(d):
value = (value * m) % n
return value | 11395a27aecc6f3b91820266ed273d2c251631b2 | 686,936 |
import random
def random_color():
"""随机颜色"""
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127)) | e30bd7f896db6412ab74adf1849ce55fb1cf1a09 | 686,937 |
def importance_sampling_ratio(state_action_sequence, target_policy):
"""Importance-sampling ration for a given state-action sequence"""
target_product = 1
for state, action in state_action_sequence:
if target_policy[state] != action:
# The numerator is 0 so the ratio is 0
ret... | f379f71c6d7eb8a4389723c5df1e9511d8c15744 | 686,938 |
def IsInClassroomHub(map_d, hub_id):
"""hub_map_tools.IsInClassroomHub(map_d, hub_id)
INPUTS:
- map_d -- dictionary containing the map of teachers to hub IDs
- hub_id -- hub ID to check against classroom hubs
OUTPUTS:
- True -- if the hub_id matches any classroom hub ID in the hub map,
... | e64cc5e680ee055467b2cbbbea74cc078ba571d8 | 686,939 |
def _get_proxy_type(type_id):
"""
Return human readable proxy type
Args:
type_id: 0=frontend, 1=backend, 2=server, 3=socket/listener
"""
proxy_types = {
0: 'frontend',
1: 'backend',
2: 'server',
3: 'socket/listener',
}
return proxy_types.get(in... | ecf513205f0118264e723169292a0385564bc480 | 686,940 |
def print_number_and_permutations(permutations):
"""
Given a newline-separated list of combinations,
return the number of combinations as well as the
original list.
"""
number = len(permutations.split("\n"))
return("%s\n%s" % (number, permutations)) | a040dff9c8c46912001ea29c0d35eb2f8ab2f9d6 | 686,941 |
def is_white(r, g, b):
"""
Check if an RGB code is white.
:param r: Red byte.
:param g: Green byte.
:param b: Blue byte.
:return: True if the pixel is white, False otherwise.
"""
if r == 255 and g == 255 and b == 255:
return True
else:
return False | 7d409033b7d30eec6f10be68960115f94b260dc3 | 686,942 |
def set_simulation(config, components, exclude):
"""Choose which components to simulate, and which parts to exclude."""
sim_config = """
simulation:
components: [{components}]
exclude: [{exclude}]
""".format(components=", ".join(components),
exclude=", ".join(exclude))
return config + sim... | 2f4a5061f63d4bbcd556e3cd66a2ef9d12ed0f81 | 686,943 |
def steeringLoss():
"""gives the steering loss for a flight"""
return 200 | 6a2624baf23c29ce6ff0d806bb9a6b95c40dde68 | 686,944 |
import torch
def calc_bbox_iou_matrix(pred: torch.Tensor):
"""
calculate iou for every pair of boxes in the boxes vector
:param pred: a 3-dimensional tensor containing all boxes for a batch of images [N, num_boxes, 4], where
each box format is [x1,y1,x2,y2]
:return: a 3-dimensional ma... | 709fc44f5d9645dc80ef4234d640c5ff53a8b335 | 686,946 |
def solution3(nums):
"""
Efficient idea from other guy
---
:type nums: list[int]
:rtype: list[int]
"""
output = []
lookup = set() # Use hashable container to reduce the complexity
for num in nums:
if num in lookup:
output.append(num)
else:
lo... | 7dd30ffe72a0ee21f01d2610a43b00f73be78455 | 686,947 |
def as_retryable(error):
"""
Given an exception, mark it as retryable when serializing
into HTTP error response.
"""
error.retryable = True
return error | 4500eb130047f0610be8bf4200fd957239d6e86b | 686,948 |
def get_locations(twitter_data: dict) -> dict:
"""
Returns a dictionary where keys are users' accounts and the values are their locations.
"""
locations_dct = dict()
for user in twitter_data['users']:
if user['location']:
locations_dct.update({user['screen_name']: user['location'... | 716ddb8bc4ec7f529cb2dbabbd423c0d8960c949 | 686,949 |
def propagateParents(currentTerm, baseGOid, GOdict, parentSet):
"""
Propagates through the parent hierarchy of a provided GO term to create a set of all higher order parents.
Each term's recursive_parents attribute will be filled with all recursively found parent terms.
Parameters
----------
c... | ac59e11ca95a58f8dd52f62af5679add375ee823 | 686,950 |
import re
def strip_html_whitespace(html_text):
""" Whitespace in between the HTML elements obtained is a bitch. Clean up
"""
html_text = html_text.replace("\r", "")
html_text = html_text.replace("\n", "")
html_text = html_text.replace("\t", " ")
html_text = re.sub(">\s*", ">", html_text)
... | d092c8c00a70a2405ad17616abbd9406d2d38982 | 686,951 |
import sys
def is_linux():
""" Checks if host platform is linux
"""
return sys.platform.startswith('linux') | c66c98a3e94685d35494404be94e1eef10593936 | 686,952 |
import timeit
def run_trials_pq_n(clazz, N, factor):
"""Run a single trial."""
stmt = '''
from {0} import PQ
one_run(PQ({1}), {1}, {2})'''.format(clazz,N,factor)
return min(timeit.repeat(stmt=stmt, setup = 'from ch04.timing import one_run',
repeat=5, number=10))/10 | 350a9266c4b66bd1b774ef476aef952c72c2781a | 686,954 |
import os
def _thumbnail_div(subdir, full_dir, fname, snippet):
"""Generates RST to place a thumbnail in a gallery"""
thumb = os.path.join(full_dir, 'images', 'thumb', fname[:-3] + '.png')
link_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
ref_name = os.path.join(subdir, fname).replac... | 487af9b6ea47aaec32ed029e75694229145883b8 | 686,955 |
def parse_theta_params(theta_spec: dict):
"""
Parses the theta parameters that the method will take later on
:param theta_spec: theta specification on the inputs file
:return: list
"""
params = []
for num, param in enumerate(theta_spec["prior"]):
params.append(
(
... | 24721ddcafe45733f0422fa053284b09badb57d7 | 686,957 |
import json
def load_config(config_file="config.json"):
"""
Load configration information from a .json file.
In the future:
The DISCORD_TOKEN should be read from an environment variable and the
channel ids should be pulled down from webhooks.
"""
conf = json.load(open(config_file))
... | f1a246c9ee1e337abe0cdff5668dc0b47db699dc | 686,958 |
from math import log
def Diversity(vec):
"""
###########################################################################
Calculate diversity.
:param vec: kmer vec
:return: Diversity(X)
###########################################################################
"""
m_sum = sum(vec)
... | 5d3657aa396caf79e55cc2e982b00209bab334cf | 686,959 |
def accuracy(model, documents_cv, n=1):
"""Computes accuracy of the model.
:param model: Prediction model.
:param documents_cv: List of documents.
:param n: Number of "suggested" options.
"""
n_cv = len(documents_cv)
tpn = sum([1 for i in range(n_cv)
if documents_cv[i].label i... | ce384db4aa60eefefc7f3fcaef0a7b07b4536b95 | 686,960 |
def partition(rows, question):
"""
Partitions a dataset.
For each row in the dataset,
check if it matches the question.
If so, add it to 'true rows',
otherwise, add it to 'false rows'.
PARAMETERS
==========
rows: list
A list of lists to store the rows
of the datase... | d13bb3c4d5d4eaee7f9b617d3ce79a6cd8c1f6b1 | 686,962 |
def _unpack_proportions(values):
"""List of N-1 ratios from N proportions"""
if len(values) == 1:
return []
half = len(values) // 2
(num, denom) = (sum(values[half:]), sum(values[:half]))
assert num > 0 and denom > 0
ratio = num / denom
return (
[ratio]
+ _unpack_prop... | 3c6275d33a2c75af2de7ca9f74be548903fd99be | 686,963 |
import torch
import math
def pose_error(R0: torch.Tensor, t0: torch.Tensor, R1: torch.Tensor, t1: torch.Tensor):
"""Compute the rotation and translation error.
Adapted from PixLoc (author: Paul-Edouard Sarlin) https://psarlin.com/pixloc/
Args:
* R0: The [3 x 3] first rotation matrix.
* t0:... | b1079781a3426ded29496bcff02097fb7f0a08ab | 686,964 |
import pickle
def dump_data(filename, data):
"""
Сериализация
"""
with open(filename, "wb") as fout:
pickle.dump(data, fout, pickle.HIGHEST_PROTOCOL)
return True | c082aae72053cda4cfe08407d6cbe11387c83800 | 686,965 |
def adl(file_name, is_weight=False, default_weight=0, bonus_key=""):
"""The function returns adjacency list representation of a graph.
bonus_key if set, will be added to all nested dictionaries.
Input data format:
With weights:
1 2,4 3,111
2 4,55 5,7
Output:
{1: {2: 4, 3: 111... | 69d3cc5cd2acba15bfeb52045fc0996d95c29061 | 686,966 |
def check_replace(val, replace_rules):
"""Replaces string in val by rules in dictionary replace_rules
For example:
REPLACE_RULES = {
"1,-1": ["i", "[", "]", "l", "7", "?", "t"],
"q,": ["qg","qq","gg","gq"]
}
Arguments:
val {str} -- input string
replace_rules {d... | e5f0b23094b5b9534661b0283e47abac85641a5d | 686,967 |
def bubble_sort(l):
"""
:param l - a list
:return a sorted list
"""
for i in range(len(l)-1, -1, -1):
for j in range(0, i):
if l[j] > l[j+1]:
l[j], l[j+1] = l[j+1], l[j]
return l | ad8089dce25448524a930ff5beb81e5f06934bf2 | 686,968 |
def playlist_password(playlist_name, limit):
"""
# Takes in a string representing playlist name
# and an integer character limit. Generates and
# returns a string by defined rules that has a
# length less than or equal to the character limit.
>>> playlist_password("World's Best Lasagne", 10)
... | f41bf8dae69690e039b6a34868f14de016724976 | 686,969 |
import re
def extract_stop_words(body: str) -> set:
"""Parse stop words in a text body as delimited by whitespace.
:param body: the body of the text to parse
:returns: a set of "stop-words"
"""
return {word for word in re.findall(r'\w+', body)} | 2f9193e2daeadaa67af9c9e60e13d185fecec98c | 686,971 |
def seq_type(request):
"""
Enumerate via fixture sequence types of coordinates to test with
AxisAlignedBoundingBox.
``request`` is a special parameter name required by pytest.
"""
return request.param | 90c24e79016cc5577f06f442b40135f539f53b73 | 686,972 |
def root_dataset(request):
"""Specify a root dataset to use."""
return request.config.getoption("--root-dataset") | 505e7ee62e3cfb648caeb0f6bbce85214615608e | 686,973 |
import requests
def request_json(url, **kwargs):
"""Send a GET request to one of the API endpoints that returns JSON.
Send a GET request to an endpoint, ideally a URL from the urls module.
The endpoint is formatted with the kwargs passed to it.
This will error on an invalid request (requests.Request... | d4c2c4693f5820ae39aa6a57bddfe7fdf1928303 | 686,974 |
def total_energy(data):
"""Takes the data collated in load_data and calculates the total energy
of the arrays for the day.
total_energy(load_data(date)) -> string
"""
tot_energy = 0
#interates through all of the array values and adds them to the tot_energy
for line in data:
for inde... | 80feb1f99df7bf00c63bcce01316b2098a0bfb5b | 686,975 |
def str_to_bool(parameter):
"""
Utility for converting a string to its boolean equivalent.
"""
if isinstance(parameter, bool):
return parameter
if parameter.lower() in {'false', 'f', '0', 'no', 'n'}:
return False
elif parameter.lower() in {'true', 't', '1', 'yes', 'y'}:
r... | 59aa60d1363b8c1f6aedc7e7d264dbec9b7fc242 | 686,976 |
import re
def parse_vocab_version(typename):
"""Parses a controlled vocabulary version from an instance ``xsi:type``
value.
Args:
typename: The ``xsi:type`` value found on a controlled vocabulary
instance.
Returns:
The version portion of a controlled vocabulary type insta... | ec059f10a921cdc513ce51b142148236a58023c8 | 686,977 |
def min_txns_and_spend(df, min_txns=5, min_spend=200):
"""At least 5 transactions and spend of GBP200 per month."""
def helper(g):
txns = g.resample('M', on='transaction_date').transaction_id.size()
debits = g[g.amount > 0]
spend = debits.resample('M', on='transaction_date').amount.sum()... | e17611092cfea41517b3783a94a4687d8ff1f2bb | 686,978 |
from typing import Callable
def is_class_view(handler: Callable) -> bool:
"""
Judge handler is django.views.View subclass
"""
return hasattr(handler, "view_class") | 3aa82680667166af4c539021fdb9350cd73f437a | 686,979 |
def default_filter(files):
"""Function to filter folders based on content
Parameters
----------
files : list
A list containing strings of filenames in directory
Returns
-------
bool : a flag indicating whether the list contains '1.mkv', '2.mkv'
and 'Labels.json'
... | e5134a1507e2393bc86e2d918276a8ad3d031708 | 686,980 |
import re
def bump_version(version, bump='patch'):
"""
Increases version number.
:param version: str, must be in version format "int.int.int"
:param bump: str, one of 'patch, minor, major'
:returns: version with the given part increased, and all inferior parts reset to 0
"""
# split the v... | 598256cc32216821fa9bfd10a7146a9df4e5ed23 | 686,981 |
def env_override_admin_key(monkeypatch, generated_admin_key):
"""Override Data Catalog admin key using os.environ
"""
gen_key = generated_admin_key
monkeypatch.setenv('CATALOG_ADMIN_TOKEN_KEY', gen_key)
return gen_key | 2524b40952502f51c13c65fd8483b22743c6152f | 686,982 |
def get_profile(config):
"""Return the set profile name."""
return config.get('profile', 'name') | 7f1f2aef4848405a78f18672ea41a19d1351ea1d | 686,983 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.