content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def columns_not_to_edit():
"""
Defines column names that shouldn't be edited.
"""
## Occasionally unchanging things like NIGHT or TILEID have been missing in the headers, so we won't restrict
## that even though it typically shouldn't be edited if the data is there
return ['EXPID', 'CAMWORD', 'O... | 430430c121d784727808b8e7c98d96bd846dc65f | 704,443 |
def substitute_variables(model_params_variables, model_data_raw):
"""
:param model_params_variables:
:param model_data_raw:
:return:
"""
model_data_list = []
for argument_raw in model_data_raw:
argument_split_raw = argument_raw.split(",")
argument_split = []
for par... | bb34bc44f9f4c633d5396fde31bf8ece5cd163c6 | 704,444 |
import tempfile
import subprocess
def get_html_docker(url: str) -> str:
"""Returns the rendered HTML at *url* as a string"""
cmd = ['docker',
'container',
'run',
'--rm',
'zenika/alpine-chrome',
'--no-sandbox',
'--dump-dom',
str(url)
... | 2980e35337f572daca7a16f2694620ca5c02aa90 | 704,445 |
def domain_domain_pair_association(domain_type_dict, opposite_type_dict={'T': 'AT', 'AT': 'T'}):
"""
Compute domain domain association.
domain_type_dict is a {domain_name:{T:[gene_ids], AT:[gene_ids]} ... }
"""
domain_domain_dict = {}
for domain, type2genes in domain_type_dict.items():
... | 1dea69154132af8e39b4119a307e38bde8269160 | 704,447 |
import asyncio
def mock_coro(return_value=None, exception=None):
"""Return a coro that returns a value or raise an exception."""
fut = asyncio.Future()
if exception is not None:
fut.set_exception(exception)
else:
fut.set_result(return_value)
return fut | d06d037bab143e288534e3e7e98da259f7c1cefc | 704,448 |
import requests
import json
def request_records(request_params):
"""
Download utility rate records from USURDB given a set of request
parameters.
:param request_params: dictionary with request parameter names as
keys and the parameter values
:return:
"""
records = requests.get(
... | 7323657186cc87a291e47c3a71cd2e81b4ec8a73 | 704,449 |
def _handle_sort_key(model_name, sort_key=None):
"""Generate sort keys according to the passed in sort key from user.
:param model_name: Database model name be query.(alarm, meter, etc.)
:param sort_key: sort key passed from user.
return: sort keys list
"""
sort_keys_extra = {'alarm': ['name', ... | aef2d996d9d18593ec129c4a37bf8150b3e9c0fe | 704,450 |
def calc_glass_constants(nd, nF, nC, *partials):
"""Given central, blue and red refractive indices, calculate Vd and PFd.
Args:
nd, nF, nC: refractive indices at central, short and long wavelengths
partials (tuple): if present, 2 ref indxs, n4 and n5, wl4 < wl5
Returns:
... | f347b6caf167c19451bb2f03e88b5846c6873250 | 704,451 |
import subprocess
import click
def git_status_check(cwd):
"""check whether there are uncommited changes in current dir
Parameters
----------
cwd : str
current working directory to check git status
Returns
-------
bool
indicating whether there are uncommited changes
""... | 11960967a2e0461ee21861a8aaa856233b0275d9 | 704,452 |
import os
from pathlib import Path
from datetime import datetime
def update_ssh_config(sshurl, user, dryrun=False):
"""
Add a new entry to the SSH config file (``~/.ssh/config``).
It sets the default user login to the SSH special remote.
Parameters
-----------
sshurl : str
SSH URL of... | 50feb2753eb5095090be7b440bb60a7a0478204b | 704,454 |
def in_range(x, a1, a2):
"""Check if (modulo 360) x is in the range a1...a2. a1 must be < a2."""
a1 %= 360.
a2 %= 360.
if a1 <= a2: # "normal" range (not including 0)
return a1 <= x <= a2
# "jumping" range (around 0)
return a1 <= x or x <= a2 | 8855ea29e44c546d55122c7c6e4878b44a3bc272 | 704,455 |
def trip_direction(trip_original_stops, direction_stops):
"""
Guess the trip direction_id based on trip_original_stops, and
a direction_stops which should be a dictionary with 2 keys: "0" and "1" -
corresponding values should be sets of stops encountered in given dir
"""
# Stops for each directi... | a418c90775039b1d52b09cb2057d71f97361e0d9 | 704,456 |
def add_common_arguments(parser):
"""Populate the given argparse.ArgumentParser with arguments.
This function can be used to make the definition these argparse arguments
reusable in other modules and avoid the duplication of these definitions
among the executable scripts.
The following arguments a... | c8e3eba16c33f0fcf12caf3a31b281dcee858648 | 704,457 |
import os
def is_valid_path_and_ext(fname, wanted_ext=None):
"""
Validates the path exists and the extension is one wanted.
Parameters
----------
fname : str
Input file name.
wanted_ext : List of str, optional
Extensions to check
Return
------
bool
"""
if ... | fea067c87a2f867703c234c2fdab418c7e0ab862 | 704,458 |
def attr_names(obj):
"""
Determine the names of user-defined attributes of the given SimpleNamespace object.
Source: https://stackoverflow.com/a/27532110
:return: A list of strings.
"""
return sorted(obj.__dict__) | ecbc0321d0796925341731df303c48ea911fcf57 | 704,459 |
import random
def weighted_choice(choices):
"""
Pick a weighted value off
:param list choices: Each item is a tuple of choice and weight
:return:
"""
total = sum(weight for choice, weight in choices)
selection = random.uniform(0, total)
counter = 0
for choice, weight in choices:
... | c32ff27b9892bb88db2928ec22c4ede644f6792c | 704,461 |
import argparse
def parse_args(args):
"""
Parse the arguments.
"""
parser = argparse.ArgumentParser(description='Simple training script for training a RetinaNet network.')
parser.add_argument('--data-path', help='Data for prediction', type=str, required=True)
parser.add_argument('--target-pat... | 1071d2fdeb2eec7a7b149b295d504e4796dd3aa7 | 704,462 |
from typing import List
from typing import Dict
def aggregate_collate_fn(insts: List) -> Dict[str, List[str]]:
"""aggragate the instance to the max seq length in batch.
Args:
insts: list of sample
Returns:
"""
snts, golds = [], []
for inst in insts:
snts.append(inst['snt'])
... | 8d986d508fd2e5a5c91947563aec2b862ab13361 | 704,463 |
def get_layout(data, width_limit):
"""A row of a chart can be dissected as four components below:
1. Label region ('label1'): fixed length (set to max label length + 1)
2. Intermediate region (' | '): 3 characters
3. Bar region ('▇ or '): variable length
This function first calculates the width of... | dbb8bfa2c537f3b05713bf3abdc106ec74bc7ac9 | 704,466 |
def get_number_of_classes(model_config):
"""Returns the number of classes for a detection model.
Args:
model_config: A model_pb2.DetectionModel.
Returns:
Number of classes.
Raises:
ValueError: If the model type is not recognized.
"""
meta_architecture = model_config.WhichOneof("model")
meta... | d87605b6025e1bc78c7436affe740f7591a99f68 | 704,467 |
def shorten_build_target(build_target: str) -> str:
"""Returns a shortened version of the build target."""
if build_target == '//chrome/android:chrome_java':
return 'chrome_java'
return build_target.replace('//chrome/browser/', '//c/b/') | 03af53f1fcacae9a4e0309053075806d65275ce9 | 704,468 |
def apply_shift(x, shift, out):
"""
Translates elements of `x` along axis=0 by `shift`, using linear
interpolation for non-integer shifts.
Parameters
----------
x : ndarray
Array with ndim >= 1, holding data.
shift : float
Shift magnitude.
out : ndarray
Array wit... | 86e58c536cbc2fb43bb049aab6d0d4d733308bbd | 704,469 |
from typing import Tuple
import random
def draw_two(max_n: int) -> Tuple[int, int]:
"""Draw two different ints given max (mod max)."""
i = random.randint(0, max_n)
j = (i + random.randint(1, max_n - 1)) % max_n
return i, j | 9ebb09158c296998c39a2c4e8fc7a18456428fc6 | 704,471 |
def versionPropertiesDictionary(sql_row_list):
"""
versionPropertiesDictionary(sql_row_list)
transforms a row gotten via SQL request (list), to a dictionary
"""
properties_dictionary = \
{
"id": sql_row_list[0],
"model_id": sql_row_list[1],
"version": sql_row_list[2]... | ab8cdd166bf8a187945c44fd416c3a4cf4634d02 | 704,472 |
import os
def moduleName(file):
"""Extract a module name from the python source file name, with appended ':'."""
return os.path.splitext(os.path.split(file)[1])[0] + ":" | 4f5035e80ddd3df7a8a93585bebf25e2e3300b49 | 704,474 |
def ms2str(v):
"""
Convert a time in milliseconds to a time string.
Arguments:
v: a time in milliseconds.
Returns:
A string in the format HH:MM:SS,mmm.
"""
v, ms = divmod(v, 1000)
v, s = divmod(v, 60)
h, m = divmod(v, 60)
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}" | 5d50aa072584e5ad17d8bd3d08b0b0813aced819 | 704,475 |
import operator
def regroup(X, N):
"""
Regroup the rows and columns in X.
Rows/Columns that are N apart in X are adjacent in Y.
Parameters:
X (np.ndarray): Image to be regrouped
N (list): Size of 1D DCT performed (could give int)
Returns:
Y (np.ndarray): Regoruped image
"""
#... | d4492e71a42a69d86d0e2a1c21bf05d13dfe13d7 | 704,476 |
def uint_to_two_compl(value: int, length: int) -> int:
"""Convert int to two complement integer with binary operations."""
if value >> (length - 1) & 1 == 0: # check sign bit
return value & (2 ** length - 1)
else:
return value | (~0 << length) | a0b7bd5192a3f12119ea7ec1a58ca785c37369bf | 704,477 |
def is_index(file_name: str) -> bool:
"""Determines if a filename is a proper index name."""
return file_name == "index" | 7beb5779b61e25b4467eb7964478c78d44f28931 | 704,480 |
import hashlib
def hash_short(message, length=16):
""" Given Hash Function"""
return hashlib.sha1(message).hexdigest()[:length / 4] | bd071674ce5caf382dc73d27835f43409a6a49d2 | 704,481 |
def get_substrings(source: str):
"""Get all substrings of a given string
Args:
string (str): the string to generate the substring from
Returns:
list: list of substrings
"""
# the number of substrings per length is the same as the length of the substring
# if the characters are... | 79f1db4184c51235a9d6beb8437f1647bc993958 | 704,482 |
def search_tag(resource_info, tag_key):
"""Search tag in tag list by given tag key."""
return next(
(tag["Value"] for tag in resource_info.get("Tags", []) if tag["Key"] == tag_key),
None,
) | 5945631a3de7032c62c493369e82dd330ef2bc47 | 704,483 |
def get_spending_features(txn, windows_size=[1, 7, 30]):
"""
This function computes:
- the cumulative number of transactions for a customer for 1, 7 and 30 days
- the cumulative average transaction amount for a customer for 1, 7 and 30 days
Args:
txn: grouped transactions of custome... | b648df3d1217074edec455a416e0eb698d8069ee | 704,484 |
import six
def _expand_expected_codes(codes):
"""Expand the expected code string in set of codes.
200-204 -> 200, 201, 202, 204
200, 203 -> 200, 203
"""
retval = set()
for code in codes.replace(',', ' ').split(' '):
code = code.strip()
if not code:
continue
... | 52056db88bf14352d4cda2411f25855457defbd7 | 704,485 |
def _get_minimum_columns(
nrows, col_limits, families, family_counts, random_state
):
"""If ``col_limits`` has a tuple lower limit then sample columns of the
corresponding element of ``families`` as needed to satisfy this bound."""
columns, metadata = [], []
for family, min_limit in zip(families, c... | 56a0abc58a6e6c3356be08511e7a30da3c1c52e3 | 704,487 |
def _paths_from_ls(recs):
"""The xenstore-ls command returns a listing that isn't terribly
useful. This method cleans that up into a dict with each path
as the key, and the associated string as the value.
"""
ret = {}
last_nm = ""
level = 0
path = []
ret = []
for ln in recs.split... | afa0fbe3e5c1773074569363a538587664a00a2f | 704,488 |
import torch
def make_complex_matrix(x, y):
"""A function that takes two tensors (a REAL (x) and IMAGINARY part (y)) and returns the combine complex tensor.
:param x: The real part of your matrix.
:type x: torch.doubleTensor
:param y: The imaginary part of your matrix.
:type y: torch.doubleTe... | faae031b3aa6f4972c8f558f6b66e33d416dec71 | 704,489 |
def scale3(v, s):
"""
scale3
"""
return (v[0] * s, v[1] * s, v[2] * s) | 4993c072fb66a33116177023dde7b1ed2c8705fd | 704,490 |
from typing import SupportsAbs
import math
def is_unit(v: SupportsAbs[float]) -> bool: # <2>
"""'True' if the magnitude of 'v' is close to 1."""
return math.isclose(abs(v), 1.0) | 0b31da2e5a3bb6ce49705d5b2a36d3270cc5d802 | 704,491 |
def atom_eq(at1,at2):
""" Returns true lits are syntactically equal """
return at1 == at2 | 43aab77292c81134490eb8a1c79a68b38d50628d | 704,492 |
import math
def k2(Ti, exp=math.exp):
"""[cm^3 / s]"""
return 2.78e-13 * exp(2.07/(Ti/300) - 0.61/(Ti/300)**2) | 6c1f471b31767f2d95f3900a8811f47dc8c45086 | 704,493 |
import math
import torch
def magnitude_prune(masking, mask, weight, name):
"""Prunes the weights with smallest magnitude.
The pruning functions in this sparse learning library
work by constructing a binary mask variable "mask"
which prevents gradient flow to weights and also
sets the weights to z... | 4bac89da952338e133ac0d85735e80631862c7da | 704,494 |
async def async_unload_entry(hass, config_entry):
"""Handle removal of an entry."""
return True | 28005ececbf0c43c562cbaf7a2b8aceb12ce3e41 | 704,496 |
import json
def is_valid_json(text: str) -> bool:
"""Is this text valid JSON?
"""
try:
json.loads(text)
return True
except json.JSONDecodeError:
return False | 3013210bafd5c26cacb13e9d3f4b1b708185848b | 704,497 |
from pathlib import Path
def get_config_path(root: str, idiom: str) -> Path:
"""Get path to idiom config
Arguments:
root {str} -- root directory of idiom config
idiom {str} -- basename of idiom config
Returns:
Tuple[Path, Path] -- pathlib.Path to file
"""
root_path = Path... | 86d65f11fbd1dfb8aca13a98e129b085158d2aff | 704,498 |
def minor_min_width(G):
"""Computes a lower bound for the treewidth of graph G.
Parameters
----------
G : NetworkX graph
The graph on which to compute a lower bound on the treewidth.
Returns
-------
lb : int
A lower bound on the treewidth.
Examples
--------
Thi... | 649ea7fe0a55ec5289b04b761ea1633c2a258000 | 704,499 |
def normalize_email(email):
"""Normalizes the given email address. In the current implementation it is
converted to lower case. If the given email is None, an empty string is
returned.
"""
email = email or ''
return email.lower() | 6ee68f9125eef522498c7299a6e793ba11602ced | 704,500 |
def parse_read_options(form, prefix=''):
"""Extract read options from form data.
Arguments:
form (obj): Form object
Keyword Arguments:
prefix (str): prefix for the form fields (default: {''})
Returns:
(dict): Read options key - value dictionary.
"""
read_options = {
... | 660e836172015999fe74610dffc331d2b37991c3 | 704,501 |
import argparse
def create_arguement_parser():
"""return a arguement parser used in shell"""
parser = argparse.ArgumentParser(
prog="python run.py",
description="A program named PictureToAscii that can make 'Picture To Ascii'",
epilog="Written by jskyzero 2016/12/03",
formatter... | ce53083d1eb823063b36341667bee0666e832082 | 704,502 |
import torch
def normalize_gradient(netC, x):
"""
f
f_hat = --------------------
|| grad_f || + | f |
x: real_data_v
f: C_real before mean
"""
x.requires_grad_(True)
f = netC(x)
grad = torch.autograd.grad(
f, [x], torch.ones_like(f), create... | ff1b8b239cb86e62c801496b51d95afe6f6046d4 | 704,503 |
import os
def get_path_with_arch(platform, path):
"""
Distribute packages into folders according to the platform.
"""
# Change the platform name into correct formats
platform = platform.replace('_', '-')
platform = platform.replace('x86-64', 'x86_64')
platform = platform.replace('manylinu... | c627d01837b7e2c70394e1ec322e03179e859251 | 704,504 |
def join_2_steps(boundaries, arguments):
"""
Joins the tags for argument boundaries and classification accordingly.
"""
answer = []
for pred_boundaries, pred_arguments in zip(boundaries, arguments):
cur_arg = ''
pred_answer = []
for boundary_tag in pred_boundari... | 9801ca876723d092f89a68bd45a138dba406468d | 704,505 |
import operator
import math
def unit_vector(vec1, vec2):
""" Return a unit vector pointing from vec1 to vec2 """
diff_vector = map(operator.sub, vec2, vec1)
scale_factor = math.sqrt( sum( map( lambda x: x**2, diff_vector ) ) )
if scale_factor == 0:
scale_factor = 1 # We don't have an actu... | 79e2cff8970c97d6e5db5259801c58f82075b1a2 | 704,506 |
def my_map(f, lst):
"""this does something to every object in a list"""
if(lst == []):
return []
return [f(lst[0])] + my_map(f, lst[1:]) | 20016cd580763289a45a2df704552ee5b5b4f25e | 704,507 |
import struct
import ipaddress
def read_ipv6(d):
"""Read an IPv6 address from the given file descriptor."""
u, l = struct.unpack('>QQ', d)
return ipaddress.IPv6Address((u << 64) + l) | c2006e6dde0de54b80b7710980a6b0cb175d3e19 | 704,508 |
def generate_level08():
"""Generate the bricks."""
bricks = bytearray(8 * 5 * 3)
colors = [2, 0, 1, 3, 4]
index = 0
col_x = 0
for x in range(6, 111, 26):
for y in range(27, 77, 7):
bricks[index] = x
bricks[index + 1] = y
bricks[index + 2] = colors[col_... | c1535d8efb285748693f0a457eb6fe7c91ce55d4 | 704,509 |
import os
def user_prompt(
question_str, response_set=None, ok_response_str="y", cancel_response_str="f"
):
"""``input()`` function that accesses the stdin and stdout file descriptors
directly.
For prompting for user input under ``pytest`` ``--capture=sys`` and
``--capture=no``. Does not work wit... | 086a56fd16b89cb33eff8f8e91bb5b284ae6d8c4 | 704,510 |
def int2bin(n, count=16):
"""
this method converts integer numbers to binary numbers
@param n: the number to be converted
@param count: the number of binary digits
"""
return "".join([str((n >> y) & 1) for y in range(count-1, -1, -1)]) | 70ce01844c8e32eb24750c4420812feda73a89dd | 704,511 |
def intstr(num, numplaces=4):
"""A simple function to map an input number into a string padded with
zeros (default 4). Syntax is: out = intstr(6, numplaces=4) -->
0006
2008-05-27 17:12 IJC: Created"""
formatstr = "%(#)0"+str(numplaces)+"d"
return formatstr % {"#":int(num)} | 8637a1f6146d1ff8b399ae920cfbfaab83572f86 | 704,512 |
def rename_duplicate_name(dfs, name):
"""Remove duplicates of *name* from the columns in each of *dfs*.
Args:
dfs (list of pandas DataFrames)
Returns: list of pandas DataFrames. Columns renamed
such that there are no duplicates of *name*.
"""
locations = []
for i, df i... | c816804a0ea9f42d473f99ddca470f4e527336f9 | 704,513 |
def checkH(board, intX, intY, newX, newY):
"""Check if the horse move is legal, returns true if legal"""
tmp=False
if abs(intX-newX)+abs(intY-newY)==3:
if intX!=newX and intY!=newY:
tmp=True
return tmp | f1ce66457a54dea4c587bebf9bd2dd0b56577dc4 | 704,514 |
import re
def get_info(prefix, string):
"""
:param prefix: the regex to match the info you are trying to obtain
:param string: the string where the info is contained (can have new line character)
:return: the matches within the line
"""
info = None
# find and return the matches based on ... | ed41100910df8ec3e0060ecd1196fb8cc1060329 | 704,516 |
from datetime import datetime
def convert_moz_time( moz_time_entry ):
""" Convert Mozilla timestamp-alike data entries to an ISO 8601-ish representation """
# [ https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PRTime ]
## result = datetime.fromtimestamp( moz_time_entry/1000000 ).s... | ba15a7ed86d9b608799384e9663d36c1cff36fae | 704,519 |
def is_nonnegative_length(G, l):
""" Checks whether a length function, defined on the arcs, satisfies the non-negative condition.
Args:
G: An instance of Graph class.
l: A dictionary that defines a length function on the edge set.
Returns:
A boolean, True if the length function sat... | c99aaf07b65f9a192b6421b4b3ccf73c98917500 | 704,521 |
import os
def get_verified_absolute_path(path):
"""Verify and return absolute path of argument.
Args:
path : Relative/absolute path
Returns:
Absolute path
"""
installed_path = os.path.abspath(path)
if not os.path.exists(installed_path):
raise RuntimeError("No valid pa... | 2d7c6dcb6066c81b3506837534a72aa814e1faa6 | 704,522 |
def unflatten_tensor(input, feat_size, anchors):
"""
Un-flattens and un-permutes a tensor from size
[B x (W x H) x C] --> [B x C x W x H]
"""
bsize = input.shape[0]
if len(input.shape) >= 3: csize = input.shape[2]
else: csize = 1
input = input.view(bsize, feat_size[0] * anchors.shape[... | 9e7b603071312ea35fa214b3e5a6f586d652c760 | 704,523 |
import curses
import math
def get_colour_depth():
"""
Returns the maximum number of possible values per color channel,
that can be used with the availible number of
colours and colour pairs in the terminal.
"""
nr_colours = curses.COLORS
return int(math.pow(nr_colours, 1. / 3.)) | 3bd47ee65a7db72d87ac7cc965a43e37724e148a | 704,524 |
import six
import traceback
def failure_format_traceback(fail):
"""
:param fail: must be an IFailedFuture
returns a string
"""
try:
f = six.StringIO()
traceback.print_exception(
fail._type,
fail.value,
fail._traceback,
file=f,
... | fdcbdf9f7617f401d511c9ce9b58420367419250 | 704,525 |
def bytes_to_int(b: bytes) -> int:
"""
Convert bytes to a big-endian unsigned int.
:param b: The bytes to be converted.
:return: The int.
"""
return int.from_bytes(bytes=b, byteorder='big', signed=False) | eb08ae0b2663047557b8f102c6c6ed565aae8044 | 704,526 |
import numpy
def cos_distance_numpy_vector(v1, v2):
"""get cos angle (similarity) between two vectors"""
d1 = numpy.sum(v1 * v1)
d1 = numpy.sqrt(d1) # magnitude of v1
d2 = numpy.sum(v2 * v2)
d2 = numpy.sqrt(d2) # magnitude of v2
n1 = v1 / d1
n2 = v2 / d2
return numpy.sum(n1 *... | fdbc02c5cba377c561843dd57e9ca13a2e9c6960 | 704,528 |
def cell_to_se2_batch(cell_idx, mapmin, mapres):
"""
Coversion for Batch input : cell_idx = [batch_size, 2]
OUTPUT: [batch_size, 2]
"""
return (cell_idx[:,0] + 0.5) * mapres[0] + mapmin[0], (cell_idx[:,1] + 0.5) * mapres[1] + mapmin[1] | 72a91b5b3a90014322ad8754848e5f85751d3b3a | 704,529 |
def pyav_decode_stream(
container, start_pts, end_pts, stream, stream_name, buffer_size=0
):
"""
Decode the video with PyAV decoder.
Args:
container (container): PyAV container.
start_pts (int): the starting Presentation TimeStamp to fetch the
video frames.
end_pts (i... | 5b012899c047dcd3ee90d793c68ebdd1d2f413c1 | 704,530 |
import sqlite3
def encode_data_for_sqlite(value):
"""Fix encoding bytes."""
try:
return value.decode()
except (UnicodeDecodeError, AttributeError):
return sqlite3.Binary(value) | fe59a2b0dde5ff7c41acc02c4de6724cc75553fb | 704,531 |
def ext_binary_gcd_env(a, b):
"""Extended binary GCD.
Given input a, b the function returns
d, s, t such that gcd(a,b) = d = as + bt."""
u, v, s, t, r = 1, 0, 0, 1, 0
while (a & 1 == 0) and (b & 1 == 0):
a, b, r = a >> 1, b >> 1, r + 1
alpha, beta = a, b
#
# from here on we ma... | c189fbdd27dcff14bec9093924067f247ea38f88 | 704,532 |
import inspect
import sys
def get_all():
"""Returns all activation functions."""
fns = inspect.getmembers(sys.modules[__name__])
fns = [f[1] for f in fns if len(f)>1 and f[0] != "get_all"\
and isinstance(f[1], type(get_all))]
return fns | 52772f2aac04a9d68f9c6470a19d99afb79f7f7f | 704,533 |
def calculateMid(paddle):
"""Calculates midpoint for each paddle, much easier to move the paddle this way"""
midpoint = int(paddle[0][1] + paddle[1][1]) / 2
return midpoint | 83fbba67945d158807bd9c3aebcab63342ce7599 | 704,534 |
def bits_list(number):
"""return list of bits in number
Keyword arguments:
number -- an integer >= 0
"""
# https://wiki.python.org/moin/BitManipulation
if number == 0:
return [0]
else:
# binary_literal string e.g. '0b101'
binary_literal = bin(number)
bit... | 6f27715dbccefe56d77c800a44c4fa5e82d35b50 | 704,535 |
def join_and_keep_order(left, right, remove_duplicates, keep='first', **kwargs):
"""
:type left: DataFrame
:type right: DataFrame
:rtype: DataFrame
"""
left = left.copy()
right = right.copy()
left['_left_id'] = range(left.shape[0])
right['_right_id'] = range(right.shape[0])
result = left.merge(right=right, **... | a3044f7de9c1f8ffb50cf1e57997307ee0e3d840 | 704,536 |
def crop_images(x, y, w, h, *args):
"""
Crops all the images passed as parameter using the box coordinates passed
"""
assert len(args) > 0, "At least 1 image needed."
cropped = []
for img in args:
cropped.append(img[x : x + h, y : y + w])
return cropped | e8f78246c0bfeb3d370b8fe01e264b2f7e0e1c49 | 704,537 |
import time
import json
def WriteResultToJSONFile(test_suites, results, json_path):
"""Aggregate a list of unittest result object and write to a file as a JSON.
This takes a list of result object from one or more runs (for retry purpose)
of Python unittest tests; aggregates the list by appending each test resu... | cb53b65bf5c8ceb1d0695e38c4ebeedd4916fe14 | 704,538 |
def split_person_name(name):
"""
A helper function. Split a person name into a first name and a last name.
Example.
>>> split_person_name("Filip Oliver Klimoszek")
("Filip Oliver", "Klimoszek")
>>> split_person_name("Klimoszek")
("", "Klimoszek")
"""
parts = name.split(" ")
return " ".join(parts[:-1... | 86b7c7cec1e7772437f41f11437834cfa34051c7 | 704,539 |
def readFile(file):
"""Reads file and returns lines from file.
Args:
string: file name
Returns:
list: lines from file
"""
fin = open(file)
lines = fin.readlines()
fin.close()
return lines | 52c62e6c97caad053cd6619935d8d3674cc3b8cb | 704,540 |
def format_price(raw_price):
"""Formats the price to account for bestbuy's raw price format
Args:
raw_price(string): Bestbuy's price format (ex: $5999 is $59.99)
Returns:
string: The formatted price
"""
formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric... | a3b0adc94421334c3f1c4fe947329d329e68990e | 704,541 |
import os
def get_directory(directory=None):
"""Get directory to work with."""
# Set variable fdir = current directory, if user didn't specify another dir
if not directory:
fdir = os.getcwd()
# Set variable fdir = directory chosen by the user, if a dir is specified
else:
fdir = os.... | 9b83f5502cea6ff908b7528c2ae480d9072ccd79 | 704,542 |
def replicated_data(index):
"""Whether data[index] is a replicated data item"""
return index % 2 == 0 | 26223e305d94be6e092980c0eb578e138cfa2840 | 704,543 |
def get_user_roles_common(user):
"""Return the users role as saved in the db."""
return user.role | cf25f029325e545f5d7685e6ac19e0e09105d65a | 704,544 |
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001):
"""
The analysis on the single-variable dependency in the neural network.
The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case.
Args:
Y_idx: index of Y to acce... | 12186469b27bebea4735372e2b45f463bbfbaff1 | 704,545 |
import pandas
import numpy
def prepare_and_store_dataframe(test_df: pandas.DataFrame, current_datetime: str, prediction: numpy.ndarray,
eval_identity: str, df_output_dir: str):
"""Prepares a dataframe that includes the testing data (timestamp, value), the detected anomalies and the... | a2aa5d9ffb9ec495abb96ddebc820dd351392b1a | 704,546 |
def isfloat(s):
"""
Checks whether the string ``s`` represents a float.
:param s: the candidate string to test
:type s: ``str``
:return: True if s is the string representation of a number
:rtype: ``bool``
"""
try:
x = float(s)
return True
except:
r... | 2233d0a06b9ff0be74f76ef2fce31c816f68584c | 704,547 |
def percentage_to_float(x):
"""Convert a string representation of a percentage to float.
>>> percentage_to_float('55%')
0.55
Args:
x: String representation of a percentage
Returns:
float: Percentage in decimal form
"""
return float(x.strip('%')) / 100 | 6c1aeac99278963d3dd207d515e72b6e1e79f09f | 704,548 |
def _escape_special_chars(content):
"""No longer used."""
content = content.replace("\N{RIGHT-TO-LEFT OVERRIDE}", "")
if len(content) > 300: # https://github.com/discordapp/discord-api-docs/issues/1241
content = content[:300] + content[300:].replace('@', '@ ')
return content | 816fc3ba15150c3e254a17d1a021d1ddee11e49f | 704,550 |
from typing import OrderedDict
import inspect
def build_paramDict(cur_func):
"""
This function iterates through all inputs of a function,
and saves the default argument names and values into a dictionary.
If any of the default arguments are functions themselves, then recursively (depth-first) ad... | b62daf5ffe7b9211d898d26dc754875459dbe1ba | 704,551 |
def get_channel_members_names(channel):
"""Returns a list of all members of a channel. If the member has a nickname, the nickname is used instead of their name, otherwise their name is used"""
names = []
for member in channel.members:
if member.nick is None:
names.append(member.name)
... | 955ea4013841fe8aac52f0474a65e221795db571 | 704,553 |
import hashlib
def get_checksum(file_name: str) -> str:
"""Returns checksum of the file"""
sha_hash = hashlib.sha224()
a_file = open(file_name, "rb")
content = a_file.read()
sha_hash.update(content)
digest = sha_hash.hexdigest()
a_file.close()
return digest | 6bb506accc6aa7826976a2d8033116dcff2f4a55 | 704,554 |
def compress_vertex_list(individual_vertex: list) -> list:
"""
Given a list of vertices that should not be fillet'd,
search for a range and make them one compressed list.
If the vertex is a point and not a line segment, the returned tuple's
start and end are the same index.
Args:
indivi... | a98f8b101219215f719b598ed8c47074a42ecb13 | 704,555 |
import argparse
def add_rnaseq_args():
"""
Arguments for RNAseq pipeline
"""
parser = argparse.ArgumentParser(
description='RNA-seq pipeline')
parser.add_argument('-b', '--build-design', dest='build_design',
action='store_true',
help='Create design for fastq files')
par... | 327e79e26b44933b82f3b31a607112db0e650ce8 | 704,556 |
def week_of_year(datetime_col):
"""Returns the week from a datetime column."""
return datetime_col.dt.week | c1bf4e0cd5d4aeddf2cff9a1142fcb45b17d1425 | 704,557 |
def normalize(df, df_ref=None):
"""
Normalize all numerical values in dataframe
:param df: dataframe
:param df_ref: reference dataframe
"""
if df_ref is None:
df_ref = df
df_norm = (df - df_ref.mean()) / df_ref.std()
return df_norm | 56c96f43c98593a5cf21425f23cfd92a7f6d6fe3 | 704,558 |
def findCongressPerson(name, nicknames_json):
"""
Checks the nicknames endpoint of the NYT Congress API
to determine if the inputted name is that of a member of Congress
"""
congress_json = [x['nickname'] for x in nicknames_json if x['nickname'] == name]
if len(congress_json) > 0:
return... | d03dc1f55c970379b283f78cfd23e393e494bd48 | 704,559 |
def _validate_positive_int(value):
"""Validate value is a natural number."""
try:
value = int(value)
except ValueError as err:
raise ValueError("Could not convert to int") from err
if value > 0:
return value
else:
raise ValueError("Only positive values are valid") | ddc2087d69c96fa72594da62192df58555b25029 | 704,560 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.