content stringlengths 42 6.51k |
|---|
def oddify(n):
"""Ensure number is odd by incrementing if even
"""
return n if n % 2 else n + 1 |
def fn_SortByKey(d_Dict: dict) -> list:
"""
:
: Returns a list of values in a dictionary in order of their keys.
:
:
: Args:
: dict d_Dict : An unsigned integer!
:
: Returns:
: List of values sorted by key
:
:
"""
return [y[1] for y in sorted([(k, v) ... |
def key_int_to_str(key: int) -> str:
"""
Convert spotify's 'pitch class notation' to
and actual key value
"""
switcher = {
"0": "C",
"1": "C#",
"2": "D",
"3": "D#",
"4": "E",
"5": "F",
"6": "F#",
"7": "G",
"8": "G#",
"9"... |
def hauteur(arbre):
"""Renvoie la hauteur de l'arbre"""
if arbre is None:
return 0
return 1 + max(hauteur(arbre.get_gauche()), hauteur(arbre.get_droite())) |
def _n_onset_midi(patterns):
"""Computes the number of onset_midi objects in a pattern
Parameters
----------
patterns :
A list of patterns using the format returned by
:func:`mir_eval.io.load_patterns()`
Returns
-------
n_onsets : int
Number of onsets within the pat... |
def bytes_to_size_string(b: int) -> str:
"""Convert a number in bytes to a sensible unit."""
kb = 1024
mb = kb * 1024
gb = mb * 1024
tb = gb * 1024
if b > tb:
return "%0.2fTiB" % (b / float(tb))
if b > gb:
return "%0.2fGiB" % (b / float(gb))
if b > mb:
return "%... |
def select_and_combine(i, obj, others, combine_func, *args, **kwargs):
"""Combine `obj` and an element from `others` at `i` using `combine_func`."""
return combine_func(obj, others[i], *args, **kwargs) |
def calculate_average_price_sl_percentage_long(sl_price, average_price):
"""Calculate the SL percentage based on the average price for a long deal"""
return round(
((sl_price / average_price) * 100.0) - 100.0,
2
) |
def bits2int(bits):
"""
convert bit list to int
"""
num = 0
for b in bits:
num <<= 1
num += int(b)
return num |
def to_string(obj):
"""Process Sigma-style dict into string JSON representation"""
import json
return json.dumps(obj) |
def rk4(x, v, a, dt,accell):
"""Returns final (position, velocity) tuple after
time dt has passed.
x: initial position (number-like object)
v: initial velocity (number-like object)
a: acceleration function a(x,v,dt) (must be callable)
dt: timestep (number)"""
x1 = x
v1 = v
a1 = a(x1... |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check_n... |
def get_frame_name_and_description(header, i, always_call_first_primary=True):
"""
This function ...
:param header:
:param i:
:param always_call_first_primary:
:return:
"""
planeX = "PLANE" + str(i)
# Return the description
if planeX in header: description = header[planeX]
... |
def increment_pair(pair):
"""
Increments pair by traversing through all
k for a given j until 1 is reached, then starting
back up with the next highest value for j
E.G. [1,2]-->[2,3]-->[1,3]-->[3,4]-->[2,4]-->...
"""
k, j = pair
k -= 1
if k > 0:
return [k, j]
else:
... |
def r2h(rgb):
"""
Convert an RGB-tuple to a hex string.
"""
return '#%02x%02x%02x' % tuple([ int(a*255) for a in rgb ]) |
def pulse_train(time, start, duration, repeat_time, end):
""" Implements vensim's PULSE TRAIN function
In range [-inf, start) returns 0
In range [start + n * repeat_time, start + n * repeat_time + duration) return 1
In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0
... |
def getSmallerAndBiggerElement(element1, element2):
"""Returning a tuple of smaller and bigger element, if the same length the first is listed first.
>>> getSmallerAndBiggerElement([1,2], [3,4])
([1, 2], [3, 4])
>>> getSmallerAndBiggerElement([1,2,3], [3,4])
([3, 4], [1, 2, 3])
>>> getSmallerAndBiggerElem... |
def to_set(value):
"""Convert a value to set."""
if type(value) == set or type(value) == list:
return set(value)
else:
return set([value]) |
def _variable_status(value, declarations):
"""Check that an environment variable exists."""
required = False
for decl in declarations:
if decl.required:
required = True
break
if value is not None:
return "PRESENT"
if required and value is None:
retu... |
def ChromeOSTelemetryRemote(test_config):
"""Substitutes the correct CrOS remote Telemetry arguments.
VMs use a hard-coded remote address and port, while physical hardware use
a magic hostname.
Args:
test_config: A dict containing a configuration for a specific test on a
specific builder.
"""
... |
def pair(k1, k2):
"""
Cantor pairing function
"""
z = int(0.5 * (k1 + k2) * (k1 + k2 + 1) + k2)
return z |
def remove_unused_fields(d):
"""
Remove from the dictionary fields that should not be in the final output.
"""
copy = dict(d)
copy.pop("title", None)
return copy |
def fibonacci(n: int) -> list:
"""
Returns a list of the Fibonacci Sequence
up to the n'th number (input)
"""
lst = []
for i in range(n + 1):
if i == 0:
lst.append(0)
elif i == 1:
lst.append(1)
elif i > 1:
x = lst[-1] + lst[-2]
... |
def is_triangle(side_a, side_b, side_c):
"""Returns True if the input satisifes the sides of a triangle"""
return side_a + side_b > side_c and side_a + side_c > side_b and side_b + side_c > side_a |
def _noise_free_model_of_recovery(sulphur):
"""This method returns a metal recovery for a given sulphur %."""
return 74.81 - 6.81/sulphur |
def fix_url(url: str) -> str:
"""Prefix a schema-less URL with http://."""
if '://' not in url:
url = 'http://' + url
return url |
def str_if_not_none(value):
"""Return the string value of the argument, unless
it is None, in which case return None"""
if value is None:
return None
else:
return str(value) |
def lyrics_processing(lyrics):
"""Preprocess the lyrics"""
lyrics_a = lyrics.replace(r"\n", " ")
lyrics_b = lyrics_a.replace(r"\r", " ")
text_list = list(lyrics_b.rsplit())
words_count = len(text_list)
return words_count |
def parse_dict_json(dict):
"""
Helper function that convers Python dictionary keys/values into strings
to be dumped into a JSON file.
"""
return {
outer_k: {str(inner_k): inner_v for inner_k, inner_v in outer_v.items()}
for outer_k, outer_v in dict.items()
} |
def row_to_dict(row, field_names):
"""Convert a row from bigquery into a dictionary, and convert NaN to
None
"""
dict_row = {}
for value, field_name in zip(row, field_names):
if value and str(value).lower() == "nan":
value = None
dict_row[field_name] = value
return d... |
def sum_series(n, x=0, y=1):
"""Function that uses a required parameter and two optional parameters."""
for i in range(n - 1):
x, y = y, x + y
return x |
def word_split(phrase, list_of_words, result=None):
"""word_split(str,list) -> list
If a phrase can be split into a list of words it returns the list.
>>> word_split('themanran',['the','ran','man'])
['the', 'man', 'ran']
>>> word_split('ilovedogsJohn',['i','am','a','dogs','lover','love','John'])
... |
def ringIsClockwise(ringToTest):
"""
determine if polygon ring coordinates are clockwise. clockwise signifies
outer ring, counter-clockwise an inner ring or hole.
"""
total = 0
i = 0
rLength = len(ringToTest)
pt1 = ringToTest[i]
pt2 = None
for i in range(0, rLength - 1):
... |
def email_parser(raw_email):
"""parse email and return dict
@raw_email str
"""
import email
msg = email.message_from_string(raw_email)
# print msg.keys()
return {
'subject': msg.get("subject"),
'from': msg.get('from'),
'to': msg.get('to'),
'date': msg.get('Dat... |
def get_uris_for_oxo(zooma_result_list: list) -> set:
"""
For a list of Zooma mappings return a list of uris for the mappings in that list with a high
confidence.
:param zooma_result_list: List with elements of class ZoomaResult
:return: set of uris from high confidence Zooma mappings, for which to... |
def set_md_table_font_size(row, size):
"""Wrap each row element with HTML tags and specify font size"""
for k, elem in enumerate(row):
row[k] = '<p style="font-size:' + str(size) + '">' + elem + '</p>'
return row |
def is_health_monitor_alarm(alarm):
""" Check that the alarm target is the cloudwatch forwarder """
is_health_alarm = False
if len(alarm["OKActions"]) > 0:
action = alarm["OKActions"][0]
is_health_alarm = "cloudwatch_forwarder" in action
return is_health_alarm |
def matched_requisition(ref, requisitions):
"""Get the requisition for current ref."""
for requisition in requisitions:
if requisition["reference"] == ref:
return requisition
return {} |
def merge_dicts(dict1, dict2):
""" Merge two dictionaries.
Parameters
----------
dict1, dict2 : dict
Returns
-------
dict_merged : dict
Merged dictionaries.
"""
dict_merged = dict1.copy()
dict_merged.update(dict2)
return dict_merged |
def if_elif_else(value, condition_function_pair):
"""
Apply logic if condition is True.
Parameters
----------
value : anything
The initial value
condition_function_pair : tuple
First element is the assertion function, second element is the
logic function to execute if a... |
def arquivo_existe(nome):
"""
-> verifica se existe um arquivo para salvar os dados dos participantes do jogo. dando assim o return
para o programa principal seguir.
"""
try:
a = open(nome, 'rt')
a.close()
except FileNotFoundError:
return False
else:
return Tr... |
def isBin(s):
"""
Does this string have any non-ASCII characters?
"""
for i in s:
i = ord(i)
if i < 9 or 13 < i < 32 or 126 < i:
return True
return False |
def _path_in_ignore_dirs(source_path: str, ignore_dirs: list) -> bool:
"""Checks if the source path is to be ignored using a case sensitive match
Arguments:
source_path: the path to check
ignore_dirs: the list of directories to ignore
Return:
Returns True if the path is to be ignored... |
def listsdelete(x, xs):
"""Return a new list with x removed from xs"""
i = xs.index(x)
return xs[:i] + xs[(i+1):] |
def calculate_hamming_distance(input_bytes_1, input_bytes_2):
"""Finds and returns the Hamming distance (number of differing
bits) between two byte-strings
"""
hamming_distance = 0
for b1, b2 in zip(input_bytes_1, input_bytes_2):
difference = b1 ^ b2
# Count the number of differenc... |
def describe_call(name, args):
""" Return a human-friendly description of this call. """
description = '%s()' % name
if args:
if isinstance(args, dict):
description = '%s(**%s)' % (name, args)
elif isinstance(args, list):
description = '%s(*%s)' % (name, args)
ret... |
def add_zeros(element):
"""This changes the format of postcodes to string with the needed zeros
Args:
element: individual row from apply codes
Returns:
parameter postcode value with zeros
"""
#postinumeroihin etunollat jos on ollut integer
element=... |
def ris_itemType_get(ris_text_line_dict_list):
"""
params: ris_text_line_list_dict, [{},[],[],[], ...]
return: itemType_value, str.
"""
#
itemType_list = []
for ris_element in ris_text_line_dict_list:
if isinstance(ris_element, dict):
if "itemType" in ris_element.keys():
... |
def convert_type(string):
""" return an integer, float, or string from the input string """
if string is None:
return None
try: int(string)
except: pass
else: return int(string)
try: float(string)
except: pass
else: return float(string)
return string.s... |
def make_lr_schedule(lr_base, lr_sched_epochs, lr_sched_factors):
"""Creates a learning rate schedule in the form of a dictionary.
After ``lr_sched_epochs[i]`` epochs of training, the learning rate will be set
to ``lr_sched_factors[i] * lr_base``. The schedule is given as a dictionary
mapping epoch number to... |
def _is_valid_input_row(row, conf):
"""
Filters blank rows and applies the optional configuration filter
argument if necessary.
:param row: the input row
:param config: the configuration
:return: whether the row should be converted
"""
# Filter blank rows.
if all(value == None for v... |
def from_path_get_project(path):
"""
To maintain an organization of webposts beyond a top-level
grouping, we keep track of a "project" for each post
:param: path of the post
:type path: string
"""
folder_list = path.split("/")
# All posts are under the "projects/" folder
# We assume ... |
def hex8_to_u32le(data):
"""! @brief Build 32-bit register value from little-endian 8-digit hexadecimal string
@note Endianness in this function name is backwards.
"""
return int(data[0:8], 16) |
def color_command_validator(language, inputs, options, attrs, md):
"""Color validator."""
valid_inputs = set()
for k, v in inputs.items():
if k in valid_inputs:
options[k] = True
continue
attrs[k] = v
return True |
def bubble_sort(ls):
"""
Bubble sort the simplest sorting algorith.
Time:O(n^2); Auxiliary space: O(1)
"""
size = len(ls)
while size > 1:
i = 0
while i < size - 1:
if ls[i] > ls[i+1]:
temp = ls[i+1]
ls[i+1] = ls[i]
ls[i... |
def extract_dtype(descriptor, key):
"""
Work around the fact that we currently report jsonschema data types.
"""
reported = descriptor["data_keys"][key]["dtype"]
if reported == "array":
return float # guess!
else:
return reported |
def get_factors(x):
"""Returns a list of factors of given number x."""
factors = []
#iterate over range from 1 to number x
for i in range(1, x + 1):
#check if i divides number x evenly
if (x % i == 0):
factors.append(i)
return factors |
def format_subrank(parent_rank, number):
"""Formats the name for ambiguous subranks based on their parent and
number."""
return '{}_Subrank_{}'.format(parent_rank, number) |
def sum_proper_divisors(x):
"""
Calculate the sum of x's proper divisors.
"""
s = 1
for i in range(2, x // 2 + 1):
if x % i == 0:
s += i
return s |
def pig_latinify(word):
"""
Describe your function
:param :
:return:
:raises:
"""
result = ""
return result |
def gerling(rho, C0=6.0, C1=4.6):
"""
Compute Young's modulus from density according to Gerling et al. 2017.
Arguments
---------
rho : float or ndarray
Density (kg/m^3).
C0 : float, optional
Multiplicative constant of Young modulus parametrization
according to Gerling et... |
def numeric_range(numbers):
"""Calculates the difference between the min and max of a given list
Args:
numbers: A list of numbers
Returns:
The distance of the minimax
"""
numbers = sorted(list(numbers))
return (numbers[len(numbers) - 1] - numbers[0]) if numbers else 0 |
def format_user_input(user_input):
"""re-formats user input for API queries"""
lower_user_input = user_input.lower()
search_query = lower_user_input.replace(" ", "%20")
return search_query |
def dqn_params(buffer_size=int(1e6),
gamma=0.99,
epsilon=0.9,
epsilon_decay=1e-6,
epsilon_min=0.1,
batch_size=64,
lr=0.01,
update_freq=5,
tau=0.01):
"""
Parameters
----------
buffer_si... |
def test_if_duplicated_first_value_in_line_items_contents(lst):
"""Takes components and amounts as a list of strings and floats, and returns true if there is at least one repeated component name."""
first_value = lst[0::2]
duplicated_first_value = [x for x in first_value if first_value.count(x) > 1]
ret... |
def _icd10cm_code_fixer(code):
"""Fixes ICD10CM codes"""
new_code = code[0:3]
if len(code) > 3:
new_code += '.' + code[3:]
return new_code |
def normalize_string(string):
"""
Standardize input strings by making
non-ascii spaces be ascii, and by converting
treebank-style brackets/parenthesis be characters
once more.
Arguments:
----------
string : str, characters to be standardized.
Returns:
--------
str : s... |
def bitstr(n, width=None):
"""return the binary representation of n as a string and
optionally zero-fill (pad) it to a given length
"""
result = list()
while n:
result.append(str(n%2))
n = int(n/2)
if (width is not None) and len(result) < width:
result.extend(['0'] * (width - len(... |
def size2str(num, suffix='B'):
"""Convert size from bytes to human readable string."""
for unit in ('', 'K', 'M', 'G', 'T'):
if abs(num) < 1024.0:
return '{:3.1f} {}{}'.format(num, unit, suffix)
num /= 1024.0
return '>1000 TB' |
def dict(*args, **kwargs):
"""
Takes arguments and builds a dictionary from them. The actual arguments
can vary widely. A single list of (key, value) pairs, or an unlimited
number of (key, value) pairs may be passed. In addition, any number of
keyword arguments may be passed, which will be adde... |
def match_dim_specs(specs1, specs2):
"""Matches dimension specs used to link axes.
Axis dimension specs consists of a list of tuples corresponding
to each dimension, each tuple spec has the form (name, label, unit).
The name and label must match exactly while the unit only has to
match if both spec... |
def find_unbalanced_program(program_tree, aggregated_weights):
"""Find the node in the tree that is unbalanced."""
# Find all the nodes that are candidates to be unbalanced.
# I.e. all nodes that have child nodes
parent_nodes = set(parent_node for parent_node in program_tree.values() if parent_node)
... |
def MPInt(value):
"""Encode a multiple precision integer value"""
l = value.bit_length()
l += (l % 8 == 0 and value != 0 and value != -1 << (l - 1))
l = (l + 7) // 8
return l.to_bytes(4, 'big') + value.to_bytes(l, 'big', signed=True) |
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function value at the mid-point of the interval.
f0: derivative va... |
def to_16_bit(letters):
"""Convert the internal (little endian) number format to an int"""
a = ord(letters[0])
b = ord(letters[1])
return (b << 8) + a |
def num_to_str(num):
"""Convert an int or float to a nice string.
E.g.,
21 -> '21'
2.500 -> '2.5'
3. -> '3'
"""
return "{0:0.02f}".format(num).rstrip("0").rstrip(".") |
def evaluate_part_one(expression: str) -> int:
"""Solve the expression from left to right regardless of operators"""
answer = 0
operator = None
for elem in expression.split():
if elem.isdigit():
if operator is None:
answer = int(elem)
elif operator == "+":... |
def _index_digit(s):
"""Find the index of the first digit in `s`.
:param s: a string to scan
Raises a ValueError if no digit is found.
"""
for i, c in enumerate(s):
if c.isdigit():
return i
raise ValueError('digit not found') |
def get_inline_function(binary2source_entity_mapping_simple_dict):
"""find inline functions by its mapping"""
function_number = 0
source_function_number = 0
inline_source_function_number = 0
inline_function_number = 0
binary_number = 0
for binary in binary2source_entity_mapping_simple_dict:
... |
def lambda_handler(event, context):
"""
Lambda function that verifies a Cognito user creation automatically.
"""
event['response']['autoConfirmUser'] = True
if 'email' in event['request']['userAttributes']:
event['response']['autoVerifyEmail'] = True
if 'phone_number' in event[... |
def get_value(obj, name):
"""Get value from object by name."""
if isinstance(obj, dict):
return obj.get(name)
return getattr(obj, name, obj) |
def not_none(passed, default):
"""Returns `passed` if not None, else `default` is returned"""
return passed if passed is not None else default |
def is_overlapped(peaks, chrom, start, end):
"""
check if the promoter of a gene is overlapped with a called peak
:param peaks:
:param chrom:
:param start:
:param end:
:return:
"""
for temp_list in peaks[chrom]:
if (temp_list[0] <= start and start <= temp_list[1] ) or (temp_l... |
def heat_flux_to_temperature(heat_flux: float, exposed_temperature: float = 293.15):
"""Function returns surface temperature of an emitter for a given heat flux.
:param heat_flux: [W/m2] heat flux of emitter.
:param exposed_temperature: [K] ambient/receiver temperature, 20 deg.C by default.
:return tem... |
def calculate_stations_adjoint(py, stations_path, misfit_windows_directory, output_directory):
"""
get the files STATIONS_ADJOINT.
"""
script = f"ibrun -n 1 {py} -m seisflow.scripts.shared.get_stations_adjoint --stations_path {stations_path} --misfit_windows_directory {misfit_windows_directory} --output... |
def pad(data, blocksize=16):
"""
Pads data to blocksize according to RFC 4303. Pad length field is included in output.
"""
padlen = blocksize - len(data) % blocksize
return bytes(data + bytearray(range(1, padlen)) + bytearray((padlen - 1,))) |
def hash_string(value, length=16, force_lower=False):
""" Generate a deterministic hashed string."""
import hashlib
m = hashlib.sha256()
try:
m.update(value)
except TypeError:
m.update(value.encode())
digest = m.hexdigest()
digest = digest.lower() if force_lower else digest
... |
def numberFormat(value: float, round: int = 2) -> str:
"""Formats numbers with commas and decimals
Args:
value (float): Number to format
round (int, optional): Number of decimals to round. Defaults to 2.
Returns:
str: String representation of formatted number
"""
num_format... |
def transform(subject_number, loop_size):
"""
>>> transform(17807724, 8)
14897079
>>> transform(5764801, 11)
14897079
"""
value = 1
loop = 0
while loop < loop_size:
value *= subject_number
value %= 20201227
loop += 1
return value |
def format_class_name(value):
"""
Example:
octree::OctreePointCloudVoxelCentroidContainer<pcl::PointXYZ> -> OctreePointCloudVoxelCentroidContainer_PointXYZ
"""
if "<" in value:
before = format_class_name(value[:value.find("<")])
inside = format_class_name(value[value.find("<") + ... |
def sorted_distances(distances):
"""
This function sorted the distances between same relationship of two shapes Author: @Gautier
======================================= Parameter: @distances: dictionnary of distances between all two shapes,
like this {"smallTriangle-middleTriangle_11":[0.5], "smallTrian... |
def create_story(story_list):
"""Create string of text from story_list."""
story = ' '.join(story_list)
print(story)
return(story) |
def string_to_list(string_list):
"""
string_list -> is a string in a list shape
e.g. '[1,2,False,String]'
returns list of parameters
"""
parameters = []
string_parameters = string_list.strip('[]').split(',')
for param in string_parameters:
try:
parameters.append(int(... |
def non_decreasing(values):
"""True if values are not decreasing."""
return all(x <= y for x, y in zip(values, values[1:])) |
def format_keyword(name):
"""
Get line alignment by 8 chars length
Parameters
----------
name : str
String for alignment
Returns
-------
out : str
8 chars length string
"""
return "{name: <8}".format(name=name.upper()) |
def _agg_scores_by_key(scores, key, agg_mode='mean'):
"""
Parameters
----------
scores: list or dict
list or dict of {'precision': ..., 'recall': ..., 'f1': ...}
"""
if len(scores) == 0:
return 0
if isinstance(scores, list):
sum_value = sum(sub_scores[key] for su... |
def infer_plot_type(model, **kwargs):
"""Infer the plot type. """
try:
model.h([0, 0])
return "binary_ones"
except:
# Error with 2d input vector.
pass
try:
model.h([0])
return "line"
except:
# Error with 1d input vector.
pass
retu... |
def _get_ordered_motifs_from_tabular(data, index=1):
"""backend motif extraction function for motif_counts, motif_freqs and pssm
assumed index 1 are motif strings; motif returned in order of occurrence"""
chars = []
for entry in data:
if not entry[index] in chars:
chars.append(en... |
def consistent_shapes(objects):
"""Determines whether the shapes of the objects are consistent."""
try:
shapes = [i.shape for i in objects]
return shapes.count(shapes[0]) == len(shapes)
except:
try:
lens = [len(i) for i in objects]
return lens.count(lens[0]) =... |
def tofloat(v):
"""Check and convert a value to a floating point number"""
return float(v) if v != '.' else None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.