content stringlengths 42 6.51k |
|---|
def check_if(s: str, d: dict, voting: str) -> str:
"""
if the name is already in the dict, return the name in the dict
else return the given name ("s")
"""
if voting in d:
d = d[voting]
keys = [d[key] for key in d]+['Lukas', 'Melvin', 'Niclas'] # keys is (ex.) ['Fridrich', 'Luk... |
def sanitize_string(str):
"""
sanitize a string by removing /, \\, and -, and convert to PascalCase
"""
for strip in ["/", "\\", "-"]:
str = str.replace(strip, " ")
components = str.split()
return "".join(x.title() for x in components) |
def process_label_name(label_name):
"""Takes a label name from a dataset and makes it nice.
Meant to correct different abbreviations and automatically
capitalize.
"""
label_name = label_name.lower()
if label_name == "neg":
label_name = "negative"
elif label_name == "pos":
la... |
def sieve_of_eratosthenes(n):
"""
Sieve of Eratosthenes is used for finding prime number upto n.
This function returns a list of prime numbers. And did I mention that it is bloody fast?
Primes upto 13000 are calculated in 0.4 seconds in CPython. And don't even mention PyPy.
"""
from math import sqrt
factors =... |
def get_indexes_from_list(lst, find, exact=True):
"""
Helper function that search for element in a list and
returns a list of indexes for element match
E.g.
get_indexes_from_list([1,2,3,1,5,1], 1) returns [0,3,5]
get_indexes_from_list(['apple','banana','orange','lemon'], 'orange') -> returns [2]... |
def map_to_range(min_1:float, max_1:float, min_2:float, max_2:float, value:float):
"""
This function maps a number of one range to that of another range.
Arguments:
min_1 : float/int : The lowest value of the range you're converting from.
max_1 : float/int : The highest value of the range you're conve... |
def aligned(value, func='vdec', aligned='w'):
"""Align specific size of 'w' or 'h' according to input func.
Args:
value (int): Input value to be aligned.
func (str, optional): Alinged method for specified function. Defaults to 'vdec'.
aligned (str, optional): Aligne `w` or `h`. De... |
def FindKeyInKeyList(key_arg, profile_keys):
"""Return the fingerprint of an SSH key that matches the key argument."""
# Is the key value a fingerprint?
key = profile_keys.get(key_arg)
if key:
return key_arg
# Try to split the key info. If there are multiple fields, use the second one.
key_split = key_... |
def replace_words(story_array, tuples_array):
"""
Creates a list of pairs of indexes and corresponding parts of speech.
Args
arr: The array of words of a story.
arr: An array of tuples of indexes and prompts.
Returns
The story converted with the responspes to the prompts.
"... |
def removeprefix(s, prefix):
"""
Remove a prefix from a string
:param s: string
:param prefix: prefix to remove
:returns: the string with the prefix removed
"""
if hasattr(s, "removeprefix"):
# python >= 3.9
return s.removeprefix(prefix)
if s.startswith(prefix):
... |
def mergedicts(dict1: dict, dict2: dict) -> dict:
"""Deep dicts merge."""
result = dict(dict1)
result.update(dict2)
for key, value in result.items():
if isinstance(value, dict) and isinstance(dict1.get(key), dict):
result[key] = mergedicts(dict1[key], value)
return result |
def editDistance(word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
n = len(word1)
m = len(word2)
# if one of the strings is empty
if n * m == 0:
return n + m
# array to store the convertion history
d = [ [0] * (m + 1) for _ in range(n + 1)... |
def get_cadence(message_fields):
""" get_cadence
return the cadence as float in 1/min from a message.as_dict()['fields'] object
Args:
message_fields: a message.as_dict()['fields'] object (with name 'record')
Returns:
the cadence as float in 1/min, or 0 if not found
"""
for mess... |
def byte2hex(addr):
"""
Convert byte to hex
"""
return "".join(['%02X' % byte for byte in addr]) |
def parent_child_pairs(lineage_string):
"""Turn a ";" separated lineage to a list of tuples for child parent
Given a lineage string of the form
'd__XXX;p__XXX;o__XXX;c__XXX;f__XXX;g_XXX;s__XXX'
prepend 'root' and split it into parent-child pairs
[
('root', 'd__XXX'),
('d__XXX... |
def is_anagram(a, b):
"""
Return True if words a and b are anagrams.
Return Flase if otherwise.
"""
a_list = list(a)
b_list = list(b)
a_list.sort()
b_list.sort()
if a_list == b_list:
return True
else:
return False |
def _broadcast_params(params, num_features, name):
"""
If one size (or aspect ratio) is specified and there are multiple feature
maps, we "broadcast" anchors of that single size (or aspect ratio)
over all feature maps.
If params is list[float], or list[list[float]] with len(params) == 1, repeat
... |
def merge(left, right, compare):
"""
Assumes left and right are sorted lists and compare defines an ordering of the elements
Returns a new sorted (by compare) list containing the same elements as
(left + right) would contain.
Time complexity O(len(L))
"""
result = []
i, j = 0, 0
whil... |
def _decay_seconds(index: int, decay_config) -> float:
"""Return duration in seconds the segment should stay on.
Only called during init to create a lookup table, for speed.
Parameters
----------
index : int
The LED segment index.
Return
------
float
Time in millisecon... |
def getConfigList(option, sep=',', chars=None):
"""Return a list from a ConfigParser option. By default,
split on a comma and strip whitespaces."""
return [chunk.strip(chars) for chunk in option.split(sep)] |
def linearise(entry, peak1_value, peak2_value, range_1to2, range_2to1):
"""
Converts a phase entry (rotating 360 degrees with an arbitrary 0 point) into a float between 0
and 1, given the values of the two extremes, and the ranges between them
Parameters
----------
entry : int or float
... |
def _cmdy_plugin_funcname(func):
"""Get the function name defined in a plugin
We will ignore the underscores on the right except for those
magic method, so that we can have the same function defined for
different classes
"""
funcname = func.__name__.rstrip('_')
if funcname.startswith('__'):
... |
def update_text(s,**kws):
"""
Replace arbitrary placeholders in string
Placeholder names should be supplied as keywords
with the corresponding values being the text to
replace them with in the supplied string.
When placeholders appear in the string they
should be contained within '<...>'.
... |
def pascal_triangle(rows: int) -> list:
"""
https://oeis.org/A007318
>>> pascal_triangle(4)
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
"""
res = [[1]]
for _ in range(rows):
row = res[-1]
res.append([1, *map(sum, zip(row, row[1:])), 1])
return res |
def reverse_text(text):
"""
>>> reverse_text('abracadabra')
'arbadacarba'
"""
l = list(text)
l.reverse()
return ''.join(l) |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
gaps = [x for x in range(len(seq) // 2, 0, -1)]
for gap in gaps:
for i in range(gap, len(seq))... |
def vac2airMorton00(wl_vac):
"""Take an input vacuum wavelength in Angstroms and return the air
wavelength.
Formula taken from
https://www.astro.uu.se/valdwiki/Air-to-vacuum%20conversion
from Morton (2000, ApJ. Suppl., 130, 403) (IAU standard)
"""
s = 1e4 / wl_vac
n = 1 + 0.0000834254 +... |
def intSuffixer(passedInt):
"""Returns string with passed int value and corresponding suffix. Integers > 4 return 'OT' for overtime period."""
intSuffix = chr(passedInt)
if passedInt == 49:
intSuffix += "st"
elif passedInt == 50:
intSuffix += "nd"
elif passedInt == 51:
intSuffix += "rd"
elif passedInt == 52... |
def get_percentage_val(val, percentage):
"""Returns floor of the percentage part of the given value"""
return int(percentage/100.0 * val) |
def get_last(list, nb):
"""This returns the last 'Nb' elements of the list 'list' in the reverse order"""
# Empty list
if not list:
return list
#Not empty list but, NB > len(list).
if nb > len(list):
stnts = list
# last NB elements
else:
last = len(list)
stnt... |
def calculateCost(offers, total_amount_to_buy):
"""
Parameters
----------
offers : list[dict]
total_amount_to_buy : int
Returns
-------
total_cost : int
"""
total_cost = 0
for offer in offers:
if total_amount_to_buy == 0:
break
buy_amount = min(off... |
def is_index(x):
"""Return whether the object x can be used as an index."""
# Can't use isinstance(x, numbers.Integral) since sympy.Integer and
# sage.Integer are not registered under that ABC.
#
# Can't check hasattr(x, '__index__') since then type objects
# would also be considered ints.
#... |
def extract_test_params(grid):
"""
PARAMS
==========
grid: dict
keys are model names given by myself and values are
dictionaries containing model parameters used by scikit learn models
RETURNS
==========
For each parameter list contained in a dictionary for a model, this fu... |
def dummyfunc(word: str):
"""I do things"""
print(f'Hello {word}!')
return 0 |
def smooth_frames(frame_grouping, kernel):
"""apply guassian filter to set of 5 frames
:param frame_grouping: group of n frames
:param kernel: n size kernel to apply to frames
:return guassian filtered frames
"""
if len(frame_grouping) != 5:
raise Exception("Unexpected number of frames i... |
def trihex_cell_type(a, b, c):
"""Given a trihex returns what shape it specifically is."""
n = a + b + c
if n == 0:
return "hex"
if n == 1:
return "tri_up"
if n == -1:
return "tri_down" |
def to_subscription_key(uid, event):
"""Build the Subscription primary key for the given guid and event"""
return str(uid + '_' + event) |
def binary_search_lower_bound(array, target):
"""
Search target element in the given array by iterative binary search
- Worst-case space complexity: O(1)
- Worst-case performance: O(log n)
:param array: given array
:type array: list
:param target: target element to search
:type target:... |
def is_iterable(value):
"""
Checks if `value` is an iterable.
Args:
value (mixed): Value to check.
Returns:
bool: Whether `value` is an iterable.
Example:
>>> is_iterable([])
True
>>> is_iterable({})
True
>>> is_iterable(())
True
... |
def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
"""Converts a text to a sequence of words (or tokens).
# Arguments
text: Input text (string).
filters: Sequence of characters to filter out.... |
def fqrn(resource_type, project, resource):
"""Return a fully qualified resource name for Cloud Pub/Sub."""
return "projects/{}/{}/{}".format(project, resource_type, resource) |
def parenthesis(text: str) -> str:
"""
Return the *text* surrounded by parenthesis.
>>> parenthesis("foo")
'(foo)'
"""
return f"({text})" |
def index_config(config, path, index_structure=True):
"""Index a configuration with a path-like string."""
key = None
sections = path.split('/')
if not index_structure:
key = sections[-1]
sections = sections[:-1]
for section in sections:
if isinstance(config, dict):
... |
def parse_seat(seat):
"""
Parse a string describing a seat in binary representation, and return a dictionary
"""
row = int(seat[0:7].replace("F", "0").replace("B", "1"), 2)
column = int(seat[7:10].replace("L", "0").replace("R", "1"), 2)
return {"row": row, "column": column, "seat_id": row * 8 + ... |
def rpad(string, width):
"""Inserts padding to the right of a string to be at least 'width' wide.
Args:
string: String to pad.
width: Width to make the string at least. May be 0 to not pad.
Returns:
Padded string.
"""
if width > 0 and len(string) < width:
return st... |
def typeOut(typename, out):
"""
Return type with const-ref if out is set
"""
return typename if out else "const " + typename + " &" |
def pick_wm_class_1(tissue_class_files):
"""
Returns the gray matter tissue class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_... |
def pad_string(text: str, length: int) -> bytes:
"""Pad the string to the specified length and convert."""
if len(text) > length:
raise ValueError('{!r} is longer than {}!'.format(text, length))
return text.encode('ascii') + b'\0' * (length - len(text)) |
def create_nonlocal_service_cluster_name(
namespace: str, service: str, color: str, index: int,
) -> str:
"""Create the cluster name for the non-local namespace, service, color."""
return "remote-{0}-{1}-{2}-{3}".format(namespace, service, color, index) |
def _get_ordered_million_reads(sample_name, ordered_million_reads):
"""Retrieve ordered million reads for sample
:param sample_name: sample name (possibly barcode name)
:param ordered_million_reads: parsed option passed to application
:returns: ordered number of reads or None"""
if isinstance(orde... |
def hex_to_string(data):
"""Convert an hex string to a string"""
return bytes.fromhex(data).decode('utf-8') |
def set_digital_out(id, signal):
"""
Function that returns UR script for setting digital out
Args:
id: int. Input id number
signal: boolean. signal level - on or off
Returns:
script: UR script
"""
# Format UR script
script = "set_digital_out(%s,%s)\n"%(... |
def _clean_annotations(annotations_dict):
"""Fix the formatting of annotation dict.
:type annotations_dict: dict[str,str] or dict[str,set[str]] or dict[str,dict[str,bool]]
:rtype: dict[str,dict[str,bool]]
"""
return {
key: (
values if isinstance(values, dict) else
{v... |
def coords_dict_to_coords_string(coords):
"""
Given a dict of long/lat values, return a string,
rounding to 2 decimal places.
"""
longitude, latitude = None, None
for k,v in coords.items():
if "at" in k:
latitude = v
if "ong" in k:
longitude = v
if not... |
def xyxy2xywh(bbox):
"""
change bbox to txt format
:param bbox: [x1, y1, x2, y2]
:return: [x, y, w, h]
"""
return [bbox[0], bbox[1], bbox[2] - bbox[0], bbox[3] - bbox[1]] |
def remove_nbws(text):
""" remove unwanted unicode punctuation: zwsp, nbws, \t, \r, \r.
"""
# ZWSP: Zero width space
text = text.replace(u'\u200B', '')
# NBWS: Non-breaking space
text = text.replace(u'\xa0', ' ')
# White space
text = text.replace(u'\t', ' ').replace(u'\r', ' ')... |
def strip_id(url):
"""Get MP database ID from url."""
url = url.split('/')
return url[-2] |
def create_conda_env_name(env_prefix: str, tool_name: str) -> str:
"""Create the name of preferred conda environment name
The environment name is based on the environment state and the specified prefixes
"""
return "".join([env_prefix, tool_name]) |
def delete_all_vectors(lines):
"""Delete the zero vector, if present"""
remove = set()
for i, l in enumerate(lines):
offset = (ord(l.offset[0]) << 8) + ord(l.offset[1])
if offset < 0x38:
remove.add(i)
return [l for i, l in enumerate(lines) if i not in remove] |
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
... |
def index(queryset, obj):
"""
Give the zero-based index of first occurrence of object in queryset.
Return -1 if not found
"""
for index, item in enumerate(queryset):
if item == obj:
return index
return -1 |
def topic_word_set(topic):
"""topic_word_set. Takes a topic from an LDA model and returns a set of top
words for the topic.
Parameters
----------
topic : (int, [ (str, float)])
A topic from a LDA model. Input should be one element of the list
returned by get_topics.
"""
word... |
def find_mirror_next(seq, max_window_size, mirror_centre):
"""Find the next token that will lead to a mirror pattern.
Searches in the range of `window_size` tokens to the left from the
`mirror_centre` if it's found.
E.g., in [a, b, AND, a] the next token should be 'b' to create a mirror
pattern.
... |
def is_true_string(expression: str) -> bool:
"""DOCTEST.
>>> is_true_string("1")
True
"""
if expression == "1":
return True
if expression == "TRUE":
return True
return False |
def binary_search_iterative(data, target):
"""Return True on target Found"""
low = 0
high = len(data) - 1
while low <= high:
mid = (low+high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
high = mid -1
else:
... |
def name_fields(record):
"""combine fields for the names facet"""
record["names_sim"] = record.get("author_tesim")
if record.get("author_tesim") is not None:
if record.get("names_sim") is not None:
record["names_sim"] = record["names_sim"] + record.get("author_tesim")
else:
... |
def encode_to_charrefs(source_text):
"""Replace non-ascii characters by numeric entities"""
ascii_bytes = source_text.encode('ascii',
errors='xmlcharrefreplace')
return ascii_bytes.decode() |
def compute_redundancy_score(stats, col_name):
"""
# Attempts to determine the redundancy of the column by taking into account correlation and
similarity with other columns
:param stats: The stats extracted up until this point for all columns
:param col_name: The name of the column we should comput... |
def is_truthy(value, default=False):
"""Evaluate a value for truthiness
>>> is_truthy('Yes')
True
>>> is_truthy('False')
False
>>> is_truthy(1)
True
Args:
value (Any): Value to evaluate
default (bool): Optional default value, if the input does not match the true or fals... |
def nb_chiffres(s : str) -> int:
"""Renvoie le nombre de chiffres de s.
"""
nb : int = 0
c : str
for c in s:
if c >= '0' and c <= '9':
nb = nb + 1
return nb |
def get_key_val_of_max(dict_obj):
"""Returns the key-value pair with maximal value in the given dict.
Example:
--------
>>> dict_obj = {'a':2, 'b':1}
>>> print(get_key_val_of_max(dict_obj))
('a', 2)
"""
return max(dict_obj.items(), key=lambda item: item[1]) |
def valid_elements(symbols,reference):
"""Tests a list for elements that are not in the reference.
Args:
symbols (list): The list whose elements to check.
reference (list): The list containing all allowed elements.
Returns:
valid (bool): True if symbols only contains elements from ... |
def divide(value, arg):
"""Divides the value; argument is the divisor. Returns empty string on any error."""
try:
value = float(value)
arg = float(arg)
if not arg:
if value:
return "x/0"
else:
return "0.0"
if arg:
... |
def is_well(keyword):
"""Check if well keyword
Args:
Profiles keyword
Returns:
True if well keyword
"""
return bool(keyword[0] == 'W' or keyword[0:2] == 'LW') |
def assoc_in(d, ks, v):
"""
Associates a value in a nested associative structure, where `ks` is a
sequence of keys and `v` is the new value, and returns a nested structure.
If any levels do not exist, `dict`s will be created.
"""
*ks_, last = ks
d_ = d
for k in ks_:
if k not in ... |
def normalize_lons(l1, l2):
"""
An international date line safe way of returning a range of longitudes.
>>> normalize_lons(20, 30) # no IDL within the range
[(20, 30)]
>>> normalize_lons(-17, +17) # no IDL within the range
[(-17, 17)]
>>> normalize_lons(-178, +179)
[(-180, -178), (179... |
def list_math_multiplication(a, b):
"""!
@brief Multiplication of two lists.
@details Each element from list 'a' is multiplied by element from list 'b' accordingly.
@param[in] a (list): List of elements that supports mathematic multiplication.
@param[in] b (list): List of elements that su... |
def get_shape_from_dim(L, axis_0, axis_1=None):
"""
Constructs a chain shape tuple of length L with constant site dimensions everywhere
:param L: Length of chain
:param axis_0: Dimension of the first leg on each site (axis 0) as integer
:param axis_1: Dimension of the second leg on each site (ax... |
def is_unique(x):
"""[ez]
Args:
x ([type]): [description]
Returns:
[type]: [description]
"""
return len(x) == len(set(x)) |
def extract_body(message_dict):
"""Extracts the body from a message dictionary.
Parameters
----------
message_dict : dict
Returns
-------
str
"""
tagged_parts_list = message_dict["structured_text"]["text"]
body = ""
for part_tag_dict in tagged_parts_list:
part = pa... |
def find_simulation_directories(root):
"""Search for SpEC-simulation output directories under `root`"""
import os
# We can't just do this as a list comprehension because of how os.walk works
simulation_directories = []
# Now, recursively walk the directories below `root`
for dirpath, dirnames,... |
def filter_dict(dict, filter=[]):
""" Only keep entrys with keys given in filter.
If filter is an empty list, an empty dict will be returned.
"""
return {key: dict[key] for key in filter} |
def flatten(list_):
"""Returns a flattened list"""
return [item for sublist in list_ for item in sublist] |
def while_loop(m=2.5, n=100_000_000):
""" using pure while loop """
i = 0
l = []
while i < n:
l.append(m * i)
i += 1
return l |
def give_connected_component(adj_list, vertex):
"""
Returns the connected component
Inputs:
- adj_list: adjacency list of a graph
- vertex: a given vertex
Ouput:
- a set of all vertices reachable from the given vertex
"""
vertices_visited = set([])
to_visit = set([v... |
def read_dict(values_dict, key, default=None):
"""
Reads value from values_dict as a dictionary
If value is a dict, then dict is returned
If value is missing, then default value is returned (or an empty dict if not specified)
Otherwise an error is raised
"""
value = values_dict.get(key)
... |
def splicing(dna, introns):
"""
Deletes introns in dna.
Args:
dna (str): DNA string.
introns (list): list of introns.
Returns:
str: spliced dna.
"""
for intron in introns:
dna = dna.replace(intron, '')
return dna |
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return float(sum(data))/float(n) |
def convert_RCSR_to_dictionary(crystalArray):
"""
creates a dictionary of Crystal objects where the name is the key and the Crystal is the value
"""
dict = {}
for crystal in crystalArray:
dict[crystal.name] = crystal
return dict |
def distance(color_one: tuple, color_two: tuple) -> float:
"""Finds the distance between two rgb colors.
Colors must be given as a 3D tuple representing a point in the
cartesian rgb color space. Consequently the distance is calculated
by a simple cartesian distance formula. Returns a float representing... |
def find_first_missing(arr):
"""
Question 22.2: Find the first positive
integer not present in the input array
"""
idx = 0
while idx < len(arr):
if 0 < arr[idx] <= len(arr) and arr[idx] != arr[arr[idx] - 1]:
tmp = arr[arr[idx] - 1]
arr[arr[idx] - 1] = arr[idx]
... |
def twos_comp(val, bits):
"""compute the 2's complement of int value val"""
if (val & (1 << (bits - 1))) != 0: # if sign bit is set
val = val - (1 << bits) # compute negative value
return val # return positive value as is |
def replace_list_element(l, before, after):
"""Helper function for get_cluster_idx
"""
for i, e in enumerate(l):
if e == before:
l[i] = after
return l |
def _undecorate(func):
"""internal: Traverses through nested decorated objects to return the original
object. This is not a general mechanism and only supports decorator chains created
via `_create_decorator`."""
if hasattr(func, "_pv_original_func"):
return _undecorate(func._pv_original_func)
... |
def vec2str(a, fmt='{}', delims='()', sep=', '):
"""
Convert a 3-sequence (e.g. a numpy array) to a string, optionally
with some formatting options. The argument `a` is also allowed to
have the value `None`, in which case the string 'None' is returned.
The argument `delims` can be used to specify d... |
def testfunc(arg1, kwarg1=None):
"""testfunc docstring"""
return "testfunc: %s, %s" % (arg1, kwarg1) |
def get_testname(filename):
"""
Return a standardized test name given a filename corresponding to a golden
JSON file, a coding tables file, a fidl file, or an order.txt file.
>>> get_testname('foo/bar/testdata/mytest/order.txt')
'mytest'
>>> get_testname('foo/bar/goldens/mytest.test.json.golden'... |
def shortTermEnergy(frame):
"""
Calculates the short-term energy of an audio frame. The energy value is
normalized using the length of the frame to make it independent of said
quantity.
"""
return sum( [ abs(x)**2 for x in frame ] ) / len(frame) |
def int_thru_bool(arg):
"""
Convert an object to a 0 or a 1.
Arguments
---------
arg : object
a value to test for truthiness.
Returns
-------
int
An integer 1 or 0, depending on the truthiness of the input argument.
"""
return int(bool(arg)) |
def relative_weight(A, B):
"""Formula should be speaking for itself!"""
return A / (A + B) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.