content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
def _is_sub_partition(sets, other_sets):
"""
Checks if all the sets in one list are subsets of one set in another list.
Used by get_ranked_trajectory_partitions
Parameters
----------
sets : list of python sets
partition to check
other_sets : list of python sets
partition to ... | b2a1d60245a8d2eca1f753f998ac1d69c8ff9d08 | 646,120 |
import json
def load_json(filename):
"""Load dictionary from JSON file."""
with open(filename, 'r') as f:
mybooks = json.load(f)
return(mybooks) | 3edd21661886ea783e1e9d9c4f4c65561e35f060 | 646,551 |
import csv
def load_label(filename):
"""
process the .csv label file
Args:
filename: /path/to/file/of/csvlabel/ (csv)
Return:
dirname_label_map: a hashmap {dirname <--> label} (dict: str->list[int])
Example:
{..., INDEX10097: [3, 7] ,}
"""
dirname_label_map = {}
... | e932f36a82969f2ac9bb65406d09a20895671a8f | 495,883 |
async def simple_json(req) -> dict:
"""Returns simple json."""
return {
"message": "Hello, world!"
} | df01ded04586c8242ec8cb959557de28b9acef12 | 262,355 |
def id_from_string(hpo_string: str) -> int:
"""
Formats the HPO-type Term-ID into an integer id
Parameters
----------
hpo_string:
HPO term ID.
(e.g.: HP:000001)
Returns
-------
int
Integer representation of provided HPO ID
(e.g.: 1)
"""
idx = ... | 17de4c0b651d5f003dec21c29eac21f0b31ae607 | 449,569 |
def transverseWidgets(layout):
"""Get all widgets inside of the given layout and the sub-layouts"""
w_lists = []
for i in range(layout.count()):
item = layout.itemAt(i)
if item.layout():
# if type(item) == QtGui.QLayoutItem:
w_lists.extend(transverseWidgets(item.layou... | 57c6d12e901f5248eb3e08b3d6f8e131d4e16a64 | 85,428 |
import re
def rx(pat):
"""Helper to compile regexps with IGNORECASE option set."""
return re.compile(pat, flags=re.IGNORECASE) | 7cae6aeff40dff0242c39c0961aace7cd042a0b6 | 594,134 |
def is_callable(x):
"""Tests if something is callable"""
return callable(x) | 72584deb62ac5e34e69325466236792c5299a51b | 2,064 |
def _find_exon(subexon_table, subexon_id_cluster):
"""Return a list with the 'ExonID's of a particular subexon."""
return subexon_table.loc[subexon_table['SubexonIDCluster'] ==
subexon_id_cluster, 'ExonIDCluster'].unique(
).tolist() | 09a2963d000f9ca31a03fe7ffe79d75c37d0bfde | 198,519 |
def linear(input_value: float) -> float:
"""Simple linear activation function.
Args:
input_value (float): Input value to map.
Returns:
float: Mapped value.
"""
return input_value | 7431612e2836b10c2a1d6433e27d8fec569b2612 | 376,937 |
def test(pre=None, post=None):
"""Decorator to execute tests and print useful information
The method being tested must have an <assert>
pre is a function without arguments to execute before the test starts
post is a function without arguments to execute after the test has finished
"""
def inner(func):
def wr... | 2e2358244475f4ce64a81ecc924172216aeb9821 | 564,339 |
import re
def parse_error(err):
"""
"Parse" error string (formats) raised by (simple)json:
'%s: line %d column %d (char %d)'
'%s: line %d column %d - line %d column %d (char %d - %d)'
"""
return re.match(r"""^
(?P<msg>.+):\s+
line\ (?P<lineno>\d+)\s+
column\ (?P<colno>\d+)\s+... | ca00993ce96abe1c64c5564862b47086f1dee300 | 326,376 |
def bar_label_formatter(x, pos):
"""Return tick label for bar chart."""
return int(x) | b1e6d1534d1a5b403d7ca037eb8f445771c26683 | 55,142 |
def party_planner(cookies, people):
"""This function will calculate how many cookies each person will get in the party
and also gives out leftovers
ARGS:
cookies: int, no of cookies is going to be baked
people: int, no of people are attending this party_planner
Returns:
tuple of cookies per ... | b4d4545710f689f2b048ba4a1637647b80aac451 | 72,866 |
def ode_schnakenberg(t, y, a_prod, b_prod):
"""Derivatives to be called into solve_ivp
This returns an array of derivatives y' = [A', B'], for a given
state [A, B] at a time t. This is based on the classical
Schnakenberg system.
Params:
t [float] - the time at which the derivative is eval... | a4e403e55a3f8c89efb71a677a93c0b3178325b1 | 261,880 |
def _resolve_subkeys(key, separator='.'):
"""Resolve a potentially nested key.
If the key contains the ``separator`` (e.g. ``.``) then the key will be
split on the first instance of the subkey::
>>> _resolve_subkeys('a.b.c')
('a', 'b.c')
>>> _resolve_subkeys('d|e|f', separator='|')
... | f7b749a0645a71048aaa3ffa693540c97772653a | 661,489 |
def lowercase_set(sequence):
""" Create a set from sequence, with all entries converted to lower case.
"""
return set((x.lower() for x in sequence)) | 23f55bd4ad1c9ec19b9d360f87a3b310ad619114 | 662,890 |
def invert_y_and_z_axis(input_matrix_or_vector):
"""Invert the y and z axis of a given matrix or vector.
Many SfM / MVS libraries use coordinate systems that differ from Blender's
coordinate system in the y and the z coordinate. This function inverts the
y and the z coordinates in the corresponding mat... | d220e7b8e6868663a75896826ad559195bd0f994 | 491,493 |
def tabular_tex(
body_df,
footer_df,
notes_tex,
render_options,
custom_index_names,
custom_model_names,
left_decimals,
sig_digits,
show_footer,
):
"""Return estimation table in LaTeX format as string.
Args:
body_df (pandas.DataFrame): the processed dataframe with par... | 5858b6334f33cf68bbd737a15117fec6e16c1c76 | 75,143 |
def _get_opt_first_name(a):
""" Get the first of an action's option names. """
return a.option_strings[0] | bbd5f42ea152ab839156d5a026621b93639e8ba9 | 544,625 |
def get_region(context):
"""
Return the AWS account region for the executing lambda function.
Args:
context: AWS lambda Context Object http://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html
Returns:
str : AWS Account Region
"""
return str(context.invoked_functi... | 220a63aef52d97ec8bd5bc6803b7a33803cdaf2f | 671,349 |
import re
def valid_uuid(possible_uuid):
"""
Checks that a possible UUID4 string is a valid UUID4.
"""
regex = re.compile('^[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12}\Z', re.I)
match = regex.match(possible_uuid)
return bool(match) | d20d764362d82fb05dd6554710e471c56786c074 | 175,077 |
from typing import Dict
from typing import Any
from typing import Optional
def _get_driver_kwargs(
platform_details: Dict[str, Any], variant: Optional[str], _async: bool = False
) -> Dict[str, Any]:
"""
Parent get driver method
Args:
platform_details: dict of details about community platform ... | 2f29f4290a0b41b9e032976cde5aa70622cf266b | 130,301 |
def delete_node(manager, handle_id):
"""
Deletes the node and all its relationships.
:param manager: Neo4jDBSessionManager
:param handle_id: Unique id
:rtype: bool
"""
q = """
MATCH (n:Node {handle_id: {handle_id}})
OPTIONAL MATCH (n)-[r]-()
DELETE n,r
"""
... | 124281e6d0d3c2fa1f6deab05c22c2540e56b603 | 239,723 |
def get_speakers(items):
"""Returns a sorted, unique list of speakers in a given dataset."""
speakers = {e[2] for e in items}
return sorted(speakers) | 451c10463a34f40839bec6cf8b017dfa4018b342 | 610,064 |
def hhmmss_to_sec(hhmmss):
"""Parses a HH:MM:SS-string and returns the corresponding number of seconds after midnight.
Args:
hhmmss (str): HH:MM:SS-string
Returns:
int: number of seconds after midnight.
"""
h, m, s = hhmmss.split(':')
return int(h) * 3600 + int(m) * 60 + int(s) | 5ceb6b1d3ac1809ebb8b54227a7a99f6575d9c19 | 233,832 |
def get_metadata_namespaces(metadata):
"""
Utility function to get all the namespaces from a metadata document and return them as a set()
:param metadata: the metadata document
:type metadata: schema.Edmx
:return: the namespace
"""
metadata_namespaces = set()
for reference in metadata.Re... | 7532e38a50500fe40d4ea0c72b84ef2b5032a3fa | 276,946 |
def p(n, d):
""" Helper to calculate the percentage of n / d,
returning 0 if d == 0.
"""
if d == 0:
return 0.0
return float(n) / d | 2b009b7059af7e2897a9e4d92246f8c0c883e7e1 | 568,844 |
def PowersOf(logbase, count, lower=0, include_zero=True):
"""Returns a list of count powers of logbase (from logbase**lower)."""
if not include_zero:
return [logbase ** i for i in range(lower, count+lower)]
else:
return [0] + [logbase ** i for i in range(lower, count+lower)] | 708e46dbff1b838fdfb0c9ca2c354ccc21bd453d | 285,113 |
def remove_end_same_as_start_transitions(df, start_col, end_col):
"""Remove rows corresponding to transitions where start equals end state.
Millington 2009 used a methodology where if a combination of conditions
didn't result in a transition, this would be represented in the model by
specifying a trans... | f4b3ddca74e204ed22c75a4f635845869ded9988 | 3,243 |
def get_diff(throw, target):
"""
Determines the difference between a throw and a target
E.g. between '111344' and '111144'
Here, the difference is 1, dice to keep is '11144', to remove is '3'
"""
diff = 0
remove = []
keep = []
for i, j in zip(throw, target):
if i != j:
... | 6c0dfe395cc7fbfbf5f2e745cde9a61d81b045f8 | 55,518 |
import re
def GetSizeAnnotationToDraw(annotationList):#{{{
"""Get the size of annotation field"""
maxSize = 0
for anno in annotationList:
m1 = re.search("nTM\s*=\s*[0-9]*", anno)
m2 = re.search("group of [0-9]*", anno)
m3 = re.search("[^\s]+", anno)
pos1 = 0
pos2 =... | f45ff9153718c5fedb254fa3716d2d66fc7d60f2 | 67,387 |
def expected(vertices: int, colors: int) -> int:
"""Compute expected colorings with chromatic polynomial."""
return (colors - 1)**vertices + (-1)**vertices * (colors - 1) | 6b1c8fc638b792a0c1ac2c2b59b8ce3973b44d58 | 348,556 |
def _getWordCategory(word, words_category_index):
"""
Retrieves the category of a word
:param word:
:param words_category_index:
:return:
"""
if word in words_category_index:
return words_category_index[word]
else:
return None | f9fd5701d4df5582ced02f51773fdcb158521114 | 587,419 |
def strip_transient(nb):
"""Strip transient values that shouldn't be stored in files.
This should be called in *both* read and write.
"""
nb.metadata.pop('orig_nbformat', None)
nb.metadata.pop('orig_nbformat_minor', None)
nb.metadata.pop('signature', None)
for cell in nb.cells:
cell... | 560a06532273c2a983692c17e898351c4a78130b | 73,315 |
def linear_segment(x0, x1, y0, y1, t):
"""Return the linear function interpolating the given points."""
return y0 + (t - x0) / (x1 - x0) * (y1 - y0) | de8bb06a7b294e0f0eb62f471da553a58e65fc49 | 44,109 |
def clsn(obj):
"""Short-hand to get class name. Intended for use in __repr__ and such."""
if isinstance(obj, str):
return obj
else:
return obj.__class__.__name__ | e030359e86cf07db8e6869c219575c74c620de6a | 650,096 |
import json
def parse_entanglement_header(header):
"""
Parse the entanglement header encoded as a JSON string.
Args:
header(str): JSON encoded entanglement header
Returns:
list((path, int)): The deseralized entanglement header
"""
return json.loads(header) | 11f6a7948f7ceacfa2f7780dd6e54759e1b3a41a | 230,325 |
def get_valid_base_urls(order=None):
"""
Return a list of valid base URLs from where the user analysis transform may be downloaded from.
If order is defined, return given item first.
E.g. order=http://atlpan.web.cern.ch/atlpan -> ['http://atlpan.web.cern.ch/atlpan', ...]
NOTE: the URL list may be ou... | 8d1bcd1fcd9a7774e19d903a178fabdc69da4b6b | 269,661 |
def perm_conjugate(p, s):
"""
Return the conjugate of the permutation `p` by the permutation `s`.
INPUT:
two permutations of {0,..,n-1} given by lists of values
OUTPUT:
a permutation of {0,..,n-1} given by a list of values
EXAMPLES::
sage: from sage.combinat.constellation impo... | a30fe25812709db4944cd7e00d21a9c889e15f0a | 441,160 |
import lzma
def compress_lzma(data: bytes) -> bytes:
"""compresses data via lzma (unity specific)
The current static settings may not be the best solution,
but they are the most commonly used values and should therefore be enough for the time being.
:param data: uncompressed data
:type data: byte... | 06a476a2753be7d591051b9707cf5dbf58556086 | 692,205 |
from typing import Counter
def contains_duplicate(items):
""" Returns True if items contains a duplicate (or more) element """
counter = Counter(items)
for freq in counter.values():
if freq > 1:
return True
return False | 769eb5e52a7e32aa2645917118678de796c9e893 | 134,676 |
import hashlib
def _text_checksum(text):
"""Calculate a digest string unique to the text content"""
return hashlib.sha1(text).hexdigest() | eebdb85139b2b7e9cba8adea3d396458ab6aba3d | 395,664 |
def _xyz_to_uv(x: float, y: float, z: float) -> tuple[float, float]:
"""Convert the color from CIEXYZ coordinates to uv chromaticity coordinates."""
if x == y == 0:
return 0, 0
d = x + 15 * y + 3 * z
return 4 * x / d, 9 * y / d | 70bf86e81fcd298873bd094bdccf0e9856c360b7 | 358,872 |
from typing import OrderedDict
def process_condition(row):
"""
row: a string of the form 'a=b;c=d;...' where each RHS can be converted to float.
Returns: a dictionary derived from row, plus the key 'Device' with value device.
"""
d = OrderedDict()
if "=" not in row:
return d
condit... | 7783e5e906eb6f6fd2b0c3e2f2271597b34a822b | 286,866 |
import time
def repeat_execution(fct, every_second=1, stop_after_second=5,
verbose=0, fLOG=None, exc=True):
"""
Runs a function on a regular basis. The function
is not multithreaded, it returns when all execution
are done.
@param fct function to run
@... | 832c95cbb9285a68708dd90e8dbd7b8e7c09a6d1 | 39,418 |
def window_neighborhood(radius=1.0):
"""Window neighborhood kernel function.
Parameters
----------
radius : float (default = 1.0)
radius of the window.
Returns
-------
neighborhood_fun : (d : int) => float in [0,1]
neighborhood function.
"""
def neighborhood_fun(d):... | 7d1c3b3cdf87e75d8304b32fdf3ee2646ffe8f2e | 514,563 |
import math
def long2net(arg):
"""Convert long to netmask"""
if (arg <= 0 or arg >= 0xFFFFFFFF):
raise ValueError("illegal netmask value", hex(arg))
return 32 - int(round(math.log(0xFFFFFFFF - arg, 2))) | 1f17505290c1a48f4cb4b84c39ffedf47614702a | 244,299 |
def mock_get_env_vars(env_vars_exists):
"""Mock the call to os.getenv in get_credentials"""
expecteds = ('partner_id', 'shop_id', 'key', 'sandbox')
credentials = dict().fromkeys(expecteds)
if env_vars_exists:
for expected in expecteds:
credentials.update({expected: 'XXX'})
retu... | 8cead493f0b26f05fe96511dbf642101393916df | 402,651 |
import re
def normalize_ipv4(ip):
"""
Remove the network mask from the ip address.
e.g. 0.0.0.0/24 -> 0.0.0.0
"""
regex = r'(\d+)[.](\d+)[.](\d+)[.](\d+)[/](\d+)'
if not re.findall(regex, ip):
return ip
p = re.split(regex, ip)
return "%s.%s.%s.%s" % (p[1], p[2], p[3], p[4]) | 97091617bf527b2a125715e04fe47604ad95f4ee | 550,381 |
def get_port_from_usb( first_usb_index, second_usb_index ):
"""
Based on last two USB location index, provide the port number
"""
acroname_port_usb_map = {(4, 4): 0,
(4, 3): 1,
(4, 2): 2,
(4, 1): 3,
... | 37a236ac3a6a16a67f55b123c1c650e8ff0b685c | 125,771 |
def solved(values):
"""Checks if a sudoku puzzle is solved or unsolvable, returns -1 if unsolvable, 1 if solved and 0 if not solved"""
for u in values:
if len(values[u]) < 1:
return -1
elif len(values[u]) > 1:
return 0
return 1 | 9ef2dd1fd07f60e8e36b8bafeb59ff68f8032727 | 536,192 |
def _slugify(text: str) -> str:
"""Turns the given text into a slugified form."""
return text.replace(" ", "-").replace("_", "-") | 78a034e07215e7964ebf1fc66162942d7b4ae85e | 668,870 |
import re
def Language_req(description):
"""Create a function that captures the language requirements from the job description"""
description = description.lower()
matches = re.findall(r"\benglish\sand\sgerman\b|\bgerman\sand\senglish\b\benglisch\sund\sdeutsch\b|\benglish\b|\benglisch\b|\bgerman\b|\bdeuts... | cb6ce14d3cba497f668c701d16c13fdfd78f5dc5 | 8,314 |
def bulk_data(json_string, bulk):
"""
Check if json has bulk data/control messages. The string to check are in
format: ``{key : [strings]}``.
If the key/value is found return True else False
:param dict json_string:
:param dict bulk:
:returns: True if found a control message and False if no... | 3b2cf4dde75951b48688bb516475e778eac28ce2 | 540,406 |
def create_perturbable_texels(texels_map, mask_map, initial_value=0., sign_grad=True):
"""
Creates perturbable texels using mask to define perturbable area. Will also initialize
perturbable area to some value. If no mask is specified for texel, we treat the entire
texel as not perturbable. G... | 467aca12b8308e362857409e0092a8cbf74b94a2 | 390,590 |
def strMakeComma(categories):
"""
Make comma seperate string i.e: a, b, c
"""
result = ""
for catg in categories:
result += catg["name"] + ", "
if len(result) > 0:
result = result[:len(result) - 2]
return result | fb829e331b494ca373167191f59d787ae1762343 | 496,627 |
import torch
def texture_loss(img_pred, img_gt, mask_gt):
"""
Input:
img_pred, img_gt: B x 3 x H x W
mask_pred, mask_gt: B x H x W
"""
mask_gt = mask_gt.unsqueeze(1)
return torch.nn.L1Loss()(img_pred * mask_gt, img_gt * mask_gt) | 54c9894e63b355829cea374ae96ae959c8612070 | 298,246 |
import re
def get_task_path_and_exc(file_path):
"""Get the task path and exception from the file by using its file path"""
with open(file_path, 'r') as f:
for line in f:
reg = re.search('Task (.*) with id (?:[0-9a-f\-]+) raised '
'exception:', line)
... | 30b94c1c0b72055aef83325b2f27f2810586b03e | 619,617 |
import sqlite3
def get_win_rate(num_moves=None, num_trials=None):
"""Get the win rate for a specified configuration of num_moves and num_trials
Args:
num_moves (int, optional): The value for num_moves which printed trials must match. Defaults to None.
num_trials (int, optional): The value for... | 466d2bf1a6c3dd1d737564b0731d3067acdab417 | 125,474 |
def check_incompatible(dict_in, inc_list):
"""
Check any conflicting keys in the dictionary
"""
for incomp in inc_list:
c = 0
for k in dict_in:
if k in incomp:
c += 1
if c > 1:
return incomp
return | 42d596a3dbf69c4d8696eb0ec8ea62a096130c7e | 631,701 |
import math
def PSucLB(sigma,n,d,param):
""" Compute the lower bound given by Theorem 2 in the paper.
param corrersponds to Rmax in the paper.
"""
sigma = sigma**2
return .5 + (d*sigma)/(2*n*param) - math.exp(-param/(2*sigma))*(1+(2*sigma)/param) | d4135229648c11a75b969d3df29baac52536e124 | 150,828 |
def normalize_windows(win_data):
""" Normalize a window
Input: Window Data
Output: Normalized Window
Note: Run from load_data()
Note: Normalization data using n_i = (p_i / p_0) - 1,
denormalization using p_i = p_0(n_i + 1)
"""
norm_data = []
for w in win_data:
norm_win = [(... | 101d142e28a742b7c7814292977eaf3904f8eb91 | 536,392 |
def euclidean_distance_nosqrt(x1, x2):
""" 欧氏距离,不对结果开方
Args:
x1: [B, N] or [N]
x2: same shape as x1
Returns:
[B] vector or scalar
"""
return (x1 - x2).pow(2).sum(-1) | cd9fd3a4e567d7a2923eb4f4f0ef60482be7f2ea | 482,278 |
def fibonacci_loop(n):
"""Calculate the nth Fibonacci number using a loop"""
nn = n - 2 #Already done 1st and second vals
fib = [1, 1]
while nn > 0:
tmp = fib[0]
fib[0] = fib[1]
fib[1] +=tmp
nn -= 1
#If even, return the first val, else, the second
return fib[n%2] | 5356a1a904cc45621a8165065d4733a7961fb518 | 71,795 |
def split(walker, number=2):
"""Split (AKA make multiple clones) of a single walker.
Creates multiple new walkers that have the same state as the given
walker with weight evenly divided between them.
Parameters
----------
walker : object implementing the Walker interface
The walker to ... | 2b6941dd5976b31733bbd93cc60243635f639bce | 558,927 |
def get_layer(model, name):
""" Gets a layer from a model.
# Arguments:
model: A keras model
name: A string, name of a layer in the model
# Returns:
A keras layer
"""
assert name in model.layers
for l in model.layers:
if l.name == name:
return l | b8054684d1822f2186ab5ea612ec0c4a44ffa6e1 | 393,483 |
def constructor_is_method_name(constructor: str) -> bool:
"""Decides wheter given constructor is a method name.
Cipher is not a method name
Cipher.getInstance is a method name
getS is a method name
"""
found_index = constructor.find(".")
method_start_i = found_index + 1
return ... | ee410e1c8df218235fe60ba028dd61bb93cda67b | 110,019 |
def onedim_conversion(length_or_speed: float, mm_per_pixel: float):
"""
:param length_or_speed: in [px] or [px/s]
:param mm_per_pixel: in [mm/px]
:return: length i [mm] or speed in [mm/s]
"""
return length_or_speed * mm_per_pixel | 0eb707b0946fb917a7f93df62819a15b28135170 | 634,235 |
def split_paragraphs(string):
"""
Split `string` into a list of paragraphs.
A paragraph is delimited by empty lines, or lines containing only
whitespace characters.
"""
para_list = []
curr_para = []
for line in string.splitlines(keepends=True):
if line.strip():
curr_... | 4e321d263beecf37efe1da34c503da314a97b894 | 113,500 |
import string
def shift_letter(letter: str, amount: int) -> str:
"""Shift a letter forward in the alphabet by a certain amount."""
sv_alfabet = string.ascii_lowercase + "åäö"
new_position = (amount + sv_alfabet.index(letter)) % len(sv_alfabet)
return sv_alfabet[new_position] | f91213198b6bac7dd78ade0340bbb201ea2a5c6d | 379,223 |
def unknown_char(char_name, id_ep):
"""Transforms character name into unknown version."""
if "#unknown#" in char_name:#trick when re-processing already processed files
return char_name
return f"{char_name}#unknown#{id_ep}" | 061683efd275335e58129225fe4bc9dabc044c9b | 694,707 |
def weighted_sum(pdf, col_name):
"""
Return weighted sum of Pandas DataFrame col_name items.
"""
return (pdf[col_name] * pdf['s006']).sum() | e9954ca2ee7e09f58abbf2420da9824a2e079d3a | 603,321 |
def event_url(event):
"""
Returns the URL for a Pyvo event.
"""
return "https://pyvo.cz/{event.series.slug}/{event.slug}/".format(event=event) | 91ed2424748f16aedda40c11a5f6e24eabef71f5 | 386,553 |
def format_counts(counts):
"""Formats the contents of the counts dictionary into a string suitable
for output.
Args:
counts - dictionary containing the attendance statistics
Returns:
string containing the counts formatted for output
"""
fstr = ("Attendance Figures:\n"
... | 9161a38ea65ddf99a4141b6528342ffd9b1cb67b | 99,572 |
def list_of_first_n(v, n):
"""Given an iterator v, return first n elements it produces as a list."""
if not hasattr(v, 'next'):
v = v.__iter__()
w = []
while n > 0:
try:
w.append(v.next())
except StopIteration:
return w
n -= 1
return w | ac98423187b1a45f5c1e5e47b215245ecb30ef6c | 612,768 |
from typing import Dict
def wrap_single_element_in_list(data: Dict, many_element: str):
"""Make a specified field a list if it isn't already a list."""
if not isinstance(data[many_element], list):
data[many_element] = [data[many_element]]
return data | 1c1c2b1ff5e65af37f86c7ee1d4dd7a38ab0faf4 | 122,928 |
def sum_word(word: str) -> str:
"""Sum the ordinal values of a word."""
return str(sum([ord(char) for char in word if char.isalnum()])) | c3ac1c488fb6f1e09a2e5cae8f60d9677bdbadce | 198,701 |
def findpeptide(pep, seq, returnEnd = False):
"""Find pep in seq ignoring gaps but returning a start position that counts gaps
pep must match seq exactly (otherwise you should be using pairwise alignment)
Parameters
----------
pep : str
Peptide to be found in seq.
seq : str
Sequ... | 3af5afa60fd29f28fd5d3d7ebfbd727c60db3948 | 680,968 |
def find (possible):
"""Returns `(key, index)` such that `possible[key] = [ index ]`."""
for name, values in possible.items():
if len(values) == 1:
return name, values[0] | 6fb98eb6baf4756210f0e8fa38783a3498cf3093 | 663,651 |
def is_valid_color(color, threshold):
""" Return True if each component of the given color (r, g, b, a) is
above threshold
"""
if color[0] > threshold and color[1] > threshold and color[2] > threshold:
return True
return False | 3391779e0977225f7340f50a823610b4dd22876b | 49,158 |
def _translate(num_time):
"""Translate number time to str time"""
minutes, remain_time = num_time // 60, num_time % 60
str_minute, str_second = map(str, (round(minutes), round(remain_time, 2)))
str_second = (str_second.split('.')[0].rjust(2, '0'), str_second.split('.')[1].ljust(2, '0'))
str_time = s... | af49424d3b9c6dfb660955b604c33e9a31e1c3de | 31,992 |
def trim_bst(root, min, max):
"""Select a range from a binary search tree between ``min`` and ``max``.
Arguments:
root (binary search tree):
The root of a binary search tree. A binary tree is either a 3-tuple
``(data, left, right)`` where ``data`` is the value of the root node
... | 47e65cd44cd22ea70214ec5036fc066aa225b074 | 301,800 |
from typing import List
def cast_trailing_nulls(series: List) -> List:
"""
Cast trailing None's in a list series to 0's
"""
for i, x in reversed(list(enumerate(series))):
if x is None:
series[i] = 0
else:
return series
return series | 3a7f7d53dcb7ed9b892b9b423c3650a339af26e2 | 627,957 |
def delete_default_service_account(context, api_names_list):
""" Delete the default service account. """
resource = [
{
'name': '{}-delete-default-sa'.format(context.env['name']),
# https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/delete
'actio... | fcc76629f92cd860dc42d01acb1ca99423c17c95 | 324,362 |
def parse_timedelta_from_api(data_dict, key_root):
"""Returns a dict with the appropriate key for filling a two-part timedelta
field where the fields are named <key_root>_number and <key_root>_units.
Parameters
----------
data_dict: dict
API json response containing a key matching the key_r... | 467130e50d3d5d0a224eed83822d352713ef11c2 | 623,095 |
def check_point(point):
"""Validates a 2-d point with an intensity.
Parameters
----------
point : array_like
(x, y, [intensity])
Coordinates of the point to add. If optional `intensity` is not
supplied, it will be set to `None`.
Returns
... | c2e56e2fa3fd0750570eb46b24dffbd1c30f9a6b | 264,313 |
from typing import List
import html
import re
def get_links(text: str) -> List[str]:
"""Extract all the links in the given text string
Args:
text (str): The text provided
Returns:
List[str]: List of http links
"""
return [
html.unescape("".join(item).strip("."))
f... | 7cfb541ff2e702b6999f034ef8fb51a4ed6b38f7 | 390,138 |
def parse_punishment(argument):
"""Converts a punishment name to its code"""
punishments = {
"none": 0,
"note": 1,
"warn": 1,
"mute": 2,
"kick": 3,
"ban": 4
}
return punishments[argument.lower()] | 9ca9ad052c5636dd58f1b375296137de8b55712b | 700,136 |
import re
def parse_str(num):
"""
Parse a string that is expected to contain a number.
:param num: str. the number in string.
:return: float or int. Parsed num.
"""
if not isinstance(num, str): # optional - check type
raise TypeError('num should be a str. Got {}.'.format(type(num)))
... | 42b46e054c24d946536e99e427052e1777f5561e | 294,652 |
def _calculate_configuration(*, bin_dir_path):
"""Calculates a configuration string from `ctx.bin_dir`.
Args:
bin_dir_path: `ctx.bin_dir.path`.
Returns:
A string that represents a configuration.
"""
path_components = bin_dir_path.split("/")
if len(path_components) > 2:
... | b10ee4abc083a0199302379229796d5c7be3eb6a | 340,585 |
def ask(message):
"""Ask user a question"""
if not message.endswith('?'):
message += ' ?'
message += ' Y/N: '
while True:
inp = input(message).lower()
if inp == 'y':
return True
elif inp == 'n' or inp == '':
return False
else:
p... | cf79e5a0ccdddd26fd6a52ab2e5c016ed6b69208 | 328,092 |
def swegen_link(variant_obj):
"""Compose link to SweGen Variant Frequency Database."""
url_template = (
"https://swegen-exac.nbis.se/variant/{this[chromosome]}-"
"{this[position]}-{this[reference]}-{this[alternative]}"
)
return url_template.format(this=variant_obj) | d55d177290297306b8367fff386984c4f8ab1bf6 | 205,910 |
import re
def xxd_output_to_bytes(input_cc_file):
"""Converts xxd output C++ source file to bytes (immutable)
Args:
input_cc_file: Full path name to th C++ source file dumped by xxd
Raises:
RuntimeError: If input_cc_file path is invalid.
IOError: If input_cc_file cannot be opened.
Returns:
... | 644f8e92b1318e38ff4ee7415585ee21588eb9a3 | 375,028 |
def camel_to_snake_case(value: str) -> str:
"""Converts strings in camelCase to snake_case.
:param str value: camalCase value.
:return: snake_case value.
:rtype: str
"""
return "".join(["_" + char.lower() if char.isupper() else char for char in value]).lstrip("_") | 200892fb89e4b4e54ba47afb52d119021dad139a | 314,667 |
def factorial(number):
"""
This recursive function calculates the factorial of a number
In math, the factorial function is
represented by (!) exclamation mark.
Example:
3! = 3 * 2 * 1
= (6) * 1
3! = 6
"""
if not isinstance(number, int):
raise Exception... | 797d4e79c132ad9a4644da4504326ebd49479acb | 206,486 |
def get_email(obj):
""" Returns the email address for a user """
return obj.user.email | 30b4ec834e46b31384d79b448fc96417d29fe10d | 545,068 |
def reduce_score_to_chords(score):
"""
Reforms score into a chord-duration list:
[[chord_notes], duration_of_chord]
and returns it
"""
new_score = []
new_chord = [[], 0]
# [ [chord notes], duration of chord ]
for event in score:
new_chord[0].append(event[1]) # Append new note... | cbc363b4f7318bf1cf7823281ace8da61fac2195 | 676,537 |
def fscr_score(ftr_t_1, ftr_t, n):
"""Feature Selection Change Rate
The percentage of selected features that changed with respect to the previous time window
:param ftr_t_1: selected features in t-1
:param ftr_t: selected features in t (current time window)
:param n: number of selected features
... | f7598633d4082a416d4a9676292b7f26d2f36ea9 | 66,976 |
import json
import yaml
def loadModel(catalog_path, schema_path):
"""Loads the dbt catalog and schema. The schema selected is the one that will be used to generate the ERD diagram.
Args:
catalog_path (Path): Path to dbt catalog
schema_path (Path): Path to dbt schema
Returns:
dict... | 00e9f60d47ef7846673121eeaea02fa6f2f9625a | 164,915 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.