content stringlengths 42 6.51k |
|---|
def n_values(obj, keys):
"""Extract multiple values from `obj`
Parameters
----------
obj : dict
A grow or data "object"
keys : list
A list of valid key names
Must have at least one element
Returns
-------
tuple
The values for each key in `args`
Notes
... |
def ComptageNil(tree):
"""Compte le nombre de pointeurs nuls de l'arbre tree."""
if tree is None:
return 1
if tree.is_empty():
return 4
number = 0
number += ComptageNil(tree.left)
number += ComptageNil(tree.middle)
number += ComptageNil(tree.right)
return number |
def version_higher_or_equal(v1, v2):
""" Check if v1 is higher than or equal to v2.
"""
t1 = tuple(int(val) for val in v1.split('.'))
t2 = tuple(int(val) for val in v2.split('.'))
return t1 >= t2 |
def get_label_from_dict(settings_dict):
"""Function to get name from dict"""
label = ''
if 'delay' in settings_dict.keys():
label += 'd' + str(settings_dict['delay'])
if 'commissions_const' in settings_dict.keys():
label += '_' + str(settings_dict['commissions_const'] * 100) + '%' + 'com... |
def RevisionKeyName(rev_id, repository_name):
"""Compute the keyname for a revision.
We use a keyname. This allows faster lookups. But more importantly, it
enforces uniqueness. Each revision in a Repository exists at most once.
This is useful, because otherwise we'd have a race condition.
Args:
rev_... |
def retrieve_operations(changeList, new_path, old_path):
"""
get changes in flow table from operation code
:param changeList:
:param new_path:
:param old_path:
:return:
"""
insert_list = []
delete_list = []
delete_list_switches = []
flow_add_operations = []
flow_mod_opera... |
def sort_anagrams_1(strs):
"""
:type strs List[str]
:rtype List[List[str]]
"""
map = {}
for v in strs:
target = ''.join(sorted(v))
print(target)
if target not in map:
map[target] = []
map[target].append(v)
print('building map ', map[target])
result = []
for value in map.valu... |
def base10_to_7(num: int) -> str:
"""
Take a base 10 number and convert it to an ASCII string.
:param num: the base 10 number
:return: the ASCII string
"""
s = ""
while num:
s += chr(num & 0x7F)
num = num >> 7
return s[::-1] |
def are_answers_updated(config_answers, saved_answers):
""" Check if all the saved answers are the answers stored in the configuration and vice versa """
# config_answers is a list of strings
# saved_answers is a list of dictionary with a key "answer" and a key "votes"
return set(s['answer'] for s in sa... |
def conv_outdim(i_dim, k, padding=0, stride=1, dilation=1):
"""Return the dimension after applying a convolution along one axis"""
return int(1 + (i_dim + 2 * padding - dilation * (k - 1) - 1) / stride) |
def alias_map(templ):
"""
aliases map
Expand all the aliases into a map
This maps from the alias name to the proper column name
"""
aliases = dict()
for field in templ:
aliases[field] = field
aliases[field.lower()] = field
for alias in templ[field].get('aliases',[]):
... |
def count(text, character):
"""Return the amount of certain character in the text."""
return text.count(character) |
def author_en_default(val):
"""Returns the author name in the order of (1) given name, (2) family name.
Args:
val (str): name string.
Returns:
str
Examples:
>>> # Example1: with comma
>>> name = "Handai, Taro"
>>> author_en_default(name)
"Taro Handai"
... |
def D_func(J, S, a):
"""
Note
----
[S] : ?
[a] : angstroem
[D] : meV * angstroem**2
[J] : ?
"""
return 2 * J * S * a**2 |
def check_time_horizon(th: int) -> int:
"""
Check the validity of the time horizon provided (in years).
:param th: time horizon (in years), to determine marginal mixes for consequential modelling.
:return: time horizon (in years)
"""
if th is None:
print(
"`time_horizon`, us... |
def _cleaned_url(url):
"""Sanatize the url
Remove and replace illegal whitespace characters from the URL.
"""
return str(url).strip().replace(" ", "%20") |
def cosalpha(a, b, c):
"""
Calculate the cosign of an angle in a triangle a, b, c
:param a: length of the side opposing the angle
:param b: length of the side adjacent to the angle
:param c: length of the side adjacent to the angle
:return: cosign
"""
return (b ** 2 + c ** 2 - a ** 2) / (2 *... |
def template_to_pairs(template):
"""
>>> template_to_pairs("NNCB")
{'NN': 1, 'NC': 1, 'CB': 1}
>>> template_to_pairs("NCNBCHB")
{'NC': 1, 'CN': 1, 'NB': 1, 'BC': 1, 'CH': 1, 'HB': 1}
>>> template_to_pairs("NBCCNBBBCBHCB")
{'NB': 2, 'BC': 2, 'CC': 1, 'CN': 1, 'BB': 2, 'CB': 2, 'BH': 1, 'HC': ... |
def get_num_classes(dataset):
"""
Check number of classes in a given dataset
Args:
dataset(dict): key is the class name and value is the data.
Returns:
int: number of classes
"""
return len(list(dataset.keys())) |
def validate_repo_names(repos):
"""
Checks whether repository name is '{username}/{repo}'
:param repos: list of repository names
:type repos: list
:returns: True if all are OK, repo name of the one that is not
:rtype: bool, string
"""
for r in repos:
s = r.split('... |
def is_pythagorean_triplet(a_num, b_num, c_num):
"""Checks if the 3 input digits (int) form a Pythagorean Triplet"""
res = False
if (a_num**2 + b_num**2) == c_num**2:
res = True
return res |
def little_fermat(base, value_to_pow):
"""Subtracts the base-1 from the power, because a number to the power of the base-1 is always 1 if base is prime
Args:
base: Mod base, for the inverse to check.
value_to_pow: Power to use for Fermat
Returns:
Returns the rest power after Fermat... |
def Triangle(base, height):
"""Return the area of Triangle"""
area = 0.5 * base * height
return area |
def rigid_footing(x, B, delta, G, nu, settlement):
"""
Calculates analytical solution for reaction pressure of settlement controlled rigid footing on linear elastic soil
[@@ref@@]
:param x: x-coordinate
:param B: width footing
:param delta: geometry dependent factor
:param G: shear modulus... |
def mask_shift_set(value, mask, shift, new_value):
"""
Replace new_value in value, by applying the mask after the shift
"""
new_value = new_value & mask
return (value & ~(mask << shift)) | (new_value << shift) |
def _as_dtype(val, dtype):
"""
Convert a value represented using a string variable to the desired output data-type.
:param val: string, representation of the value to convert
:param dtype: string, desired output data-type
:return: input values converted to the output data-type
"""
if dtyp... |
def fullname(o):
"""Get the full name of a class/object."""
klass = o.__class__
module = klass.__module__
if module == "builtins":
return klass.__qualname__ # avoid outputs like 'builtins.str'
return module + "." + klass.__qualname__ |
def digital_sum(number):
"""
This function calculates the sum of digits of a given number.
"""
return sum([int(nb) for nb in list(str(number))]) |
def choices_to_dict(choices_list):
"""
Convert a list of field choices to a dictionary suitable for direct comparison with a ChoiceSet. For example:
[
{
"value": "choice-1",
"label": "First Choice"
},
{
"value": "choice... |
def EucDist(p1, p2):
"""2D Euclidean distance"""
return ( (p2[0]-p1[0])*(p2[0]-p1[0]) + (p2[1]-p1[1])*(p2[1]-p1[1]) )**0.5 |
def _bisect(a, x):
"""
"""
hi = len(a)
lo = 0
while lo < hi:
mid = (lo + hi) // 2
if x < a[mid]:
hi = mid
else:
lo = mid + 1
return lo - 1 |
def camel_split(string):
# test: (str) -> str
"""
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees')))
('the', 'Birds', 'And', 'The', 'Bees')
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees123')))
('the', 'Birds', 'And', 'The', 'Be... |
def get_opposite_emotion(key):
"""
Utility function to get the opposite emotion of a given emotion
:param key: emotion to be processed
:return: opposite emotion, None if no opposite emotion is found
"""
opposite_emotions = {"joy": "anger",
"sad": "joy",
... |
def choose(situation, state):
"""Uses the given rule to decide whether to be 1 or 0 in the next round"""
if situation == 3 and state == 0:
return 1
elif situation in [2, 3] and state == 1:
return 1
elif situation not in [2, 3] and state == 1:
return 0
else:
return sta... |
def prefix_lines(s, p):
"""
Prefix each line of ``s`` by ``p``.
"""
try:
return p + ('\n' + p).join(s.splitlines())
except Exception as e:
import traceback
traceback.print_exc()
import pdb; pdb.set_trace()
raise |
def recur_dict(col_names, elements):
"""Summary
Args:
col_names (TYPE): Description
elements (TYPE): Description
Returns:
TYPE: Description
"""
for element in elements:
if type(element) == dict:
col_names[element.get("key")] = element.get("data... |
def _find_sa_sess(decorated_obj):
"""
The decorators will by default use sqlalchemy.db to find the SQLAlchemy
session. However, if the function being decorated is a method of a
a class and that class has a _sa_sess() method, it will be called
to retrieve the SQLAlchemy session that ... |
def lad_dwelling_density(dwelling_data, urban_rural_lut):
"""Calculate initial/baseline LAD dwelling density
"""
interim = []
unique_lads = set()
for oa in dwelling_data:
unique_lads.add(oa['lad11cd'])
for lad in list(unique_lads):
area_of_lad = 0
dwellings_in_lad = 0
... |
def first_not_none(iterable):
"""Select the first item from an iterable that is not None.
The idea is that you can use this to specify a list of fall-backs to use
for configuration options.
"""
for item in iterable:
if item is not None:
return item
return None |
def rt_lookup(session, vpc_id, rt_name):
"""Lookup the Id for the VPC Route Table with the given name.
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
vpc_id (string) : VPC ID of the VPC to... |
def _get_positive_int(raw_value):
"""Convert the raw value for api/patch into a positive integer."""
value = int(raw_value)
if value < 0:
raise ValueError("negative")
return value |
def xmlSafe(value):
"""Convert the given string to a format that is safe for inclusion in an XML document.
"""
return value.replace('&','&') |
def API_response(*args, **kwargs):
"""Create an API response using provided arguments.
Positional arguments: any number of dicts that will be merged into the response.
Keyword arguments: will be merged into the response."""
r = {"status": "ok"}
for a in args:
if type(a) is dict:
... |
def prettify(M):
"""Turn the set of frozen sets M into a string that looks like a set of sets.
M is assumed to be the power set of some set.
"""
if M == set():
return '{}'
result = "{\n"
for A in M:
if A == frozenset():
result += "{},\n"
else:
... |
def _block_append(string, val):
"""Append val to each line of string."""
return "\n".join(
map(lambda l: l+val, string.split("\n"))
) |
def sign(x):
"""Returns -1 if x < 0, 1 otherwise
Error Conditions:
- raises TypeError if x is not a number
"""
abs(x) # checks type of argument
if x < 0:
return -1
else:
return 1 |
def parse_load_balancer_name(load_balancer_arn):
"""
Parse name out from load balancer ARN
Example:
ARN of load balancer: 'arn:aws:elasticloadbalancing:us-east-1:881508045124:loadbalancer/app/alb-1/72074d479748b405',
Load balancer name: 'alb-1'
return: load balancer name
"""
return load_... |
def mesos_masters_quorum_size(mesos_masters):
"""Calculate the required quorum size from a list of mesos masters"""
return((len(mesos_masters) / 2) +1) |
def conv(x, h):
""" Perform the convolution operation between two input signals. The output signal length
is the sum of the lenght of both input signal minus 1."""
length = len(x) + len(h) - 1
y = [0]*length
for i in range(len(y)):
for j in range(len(h)):
if i-j >= 0 and i-j < ... |
def struct_size(items):
""" Computes the total size of a given (potentially nested) struct.
items -- A list like this:
items := [ [elem, elem-alignment] + ]
elem := elem-size | items
elem-size:= integer
elem-alignment:= integer
Returns a 2-element list whose first element is ... |
def pa_to_torr(pa):
"""pa_to_torr(pa)
Convert pressure in Pascals to Torr
Parameters
----------
pa: number
Pressure, in Pa
Returns
-------
torr: number
Pressure, in Torr
"""
return(0.0075062*pa) |
def _f(coord, a0, a1, a2, a3, a4, a5, a6, a7, a8):
"""Evaluate 2-d function by: a0*x**2*y**2 + a1*x**2*y + ... + a8
Parameters:
coord: (x,y): (float, float)
a0,...,a8: float
"""
x, y = coord
res = a0*x**2*y**2 + a1*x**2*y + a2*x**2 \
+ a3*x*y**2 + a4*x*y + a5*x \
+ a... |
def _map_mobility(
dementia: int,
falls: int,
visual_impairment: int,
visual_supervisation: int,
) -> bool:
"""Maps historic patient's mobility status to True or False."""
if dementia + falls + visual_impairment + visual_supervisation > 0:
return True
else:
return False |
def _process_config(config):
"""
Make sure config object has required values
"""
required_fields = [
"account_sid",
"auth_token",
"from_phone",
"to_phone",
]
for field in required_fields:
if field not in config:
raise ValueError("required... |
def _strip_markup_line(line, sigil):
"""Strip sigil and whitespace from a line of markup"""
return line.lstrip(sigil).rstrip() |
def transform(data, pse):
"""The transformer function."""
__PSE_ASYM_ENC_CLIENT_RECV_SHIFT = 13
output = []
for c in data:
num = ord(c) + __PSE_ASYM_ENC_CLIENT_RECV_SHIFT
while num > 127:
num -= 127
output.append(chr(num))
return "".join(output) |
def acceptable_title(node):
""" Omit projects that have certain words in the title """
omit_titles = ['test', 'photo', 'workshop', 'data']
if any(word in node['title'].lower() for word in omit_titles):
return False
return True |
def find_first_month_and_year(num_months, end_month, end_year):
"""Find the month and year that is num_months prior to end_month, end_year.
Num_months includes the end_month and the first_month."""
excess = num_months - end_month
full_years_prior = excess / 12
months_in_partial_years_prior = ... |
def get_item(d, k):
"""attempts to get an item from d
at key k. if d is a list and the key is the list selector [],
then tries to return the first item from the list.
if the list is empty, returns None."""
try:
return d[k]
except KeyError:
if k.endswith('[]'):
lst = d... |
def reverse_string(string):
"""Recursively returns the string in reverse order"""
if len(string) == 1:
return string
else:
return reverse_string(string[1:]) + string[0] |
def calculate_rates(TP, TN, FP, FN):
"""
Calculates the True and False Positive and Negative rates of the supplied reference and test data
For TPR and TNR, if the denominator is 0, the result is defined as 1, as there were no false positive/negatives
Input:
ref: Numpy boolean array of ... |
def decode_string(string):
"""Decode String Data Type.
The "string" data type encodes binary data as a sequence of undistinguished
octets. Where the range of lengths for a particular attribute is limited to
a subset of possible lengths, specifications MUST define the valid range.
Attributes with le... |
def esc1(string):
"""
Escape single quotes, mainly for use in shell commands. Single quotes
are usually preferred above double quotes, because they never do shell
expension inside. e.g.
::
class HelloWorld(Node):
def run(self):
self.hosts.run("echo '%s'" % esc1(... |
def find_key_position_in_text(queryText, key, parameters):
"""
Search value position of key inside text entered by the user
:param queryText: Text which user enter
:param key: key from request parameters
:param parameters: parameters of request
:return: value position of key in queryText
"""... |
def heaviside(x):
"""Heaviside function. Returns 1 if x>0, and 0 otherwise.
Examples
--------
>>> heaviside(2)
1
>>> heaviside(-1)
0
"""
if x >= 0:
return 1
else:
return 0 |
def make_index_positive(word, index):
"""Return positive index based on word.
"""
if index >= 0:
return index
else:
return len(word) + index |
def _genetate_feature_list(channel_mappings: list):
"""
Generate a list of features from a list of ChannelMap objects (see data.panel.ChannelMap). By default
the ChannelMap marker value is used, but if missing will use channel value instead.
Parameters
----------
channel_mappings: list
... |
def load(conanfile, path, encoding="utf-8"):
""" Loads a file content """
with open(path, 'rb') as handle:
tmp = handle.read()
return tmp.decode(encoding) |
def simple_mean(x, y):
"""Function that takes 2 numerical arguments and returns their mean.
"""
mean = (x + y) / 2
return mean |
def extract_id(urn):
"""Extract id from an urn.
'urn:vcloud:catalog:39867ab4-04e0-4b13-b468-08abcc1de810' will produce
'39867ab4-04e0-4b13-b468-08abcc1de810'
:param str urn: a vcloud resource urn.
:return: the extracted id
:rtype: str
"""
if urn is None:
return None
if ':... |
def hump_to_underscore(name):
"""
Convert Hump style to underscore
:param name: Hump Character
:return: str
"""
new_name = ''
pos = 0
for c in name:
if pos == 0:
new_name = c.lower()
elif 65 <= ord(c) <= 90:
new_name += '_' + c.lower()
... |
def parse_by_line(input_string, prefix_string, offset):
"""breaks input string by lines and finds the index of the prefix_line.
Returns the line that is offset past the prefix_line"""
split_by_line = input_string.splitlines()
prefix_line = split_by_line.index(prefix_string)
return split_by_line[p... |
def create_form_relations(self, repeats_list, form_list,
form_index, prev_form_index):
"""
Edit form names to include the previous form read, so models can reference
each other through foreign keys. If there are nested lists, the function is
recursively called to search th... |
def get_diff(old: dict, new: dict, value: str, statistics=False):
""" Get the difference between old and new osu! user data. """
if not new or not old:
return 0
if statistics:
new_value = float(new["statistics"][value]) if new["statistics"][value] else 0.0
old_value = float(old["stat... |
def VStack_Calc(N, Vcell):
"""
Calculate VStack.
:param N: number of single cells
:type N :int
:param Vcell: cell voltage [V}
:type Vcell:float
:return: VStack [V] as float
"""
try:
result = N * (Vcell)
return result
except TypeError:
print(
... |
def _centroid(gen):
"""Find the centroid of the coordinates given by the generator. The
generator should yield pairs (longitude, latitude).
:return: Pair (longitude, latitude) of the centroid.
"""
n, lon, lat = 0, 0, 0
for pair in gen:
lon += pair[0]
lat += pair[1]
n +=... |
def get_language(file_path):
"""Returns the language a file is written in."""
if file_path.endswith(".py"):
return "python3"
elif file_path.endswith(".js"):
return "node"
elif file_path.endswith(".go"):
return "go run"
elif file_path.endswith(".rb"):
return "ruby"
... |
def clean_list(list_of_subroutines):
"""
Simple function that just removes empty strings from the lsit of subroutines
:param list_of_subroutines: the list of subroutines and functions affected
by adding gr into the decleration
:return: a cleaner version of the list of sub... |
def join_dict(keys, values):
"""
Create a dictionary from a list of
keys and values having equal lengths
"""
if len(keys) == len(values):
adict = dict(zip(keys, values))
return adict
else:
print('Error: Attempting to create a dictionary from '
'a key and val... |
def construct_SN_default_rows(timestamps, ants, nif, gain=1.0):
""" Construct list of ants dicts for each
timestamp with REAL, IMAG, WEIGHT = gains
"""
default_nif = [gain] * nif
rows = []
for ts in timestamps:
rows += [{'TIME': [ts],
'TIME INTERVAL': [0.1],
... |
def preserve_location_hint(config, response):
"""Preserve location hint in client config for subsequent requests"""
if response and response.get("target_location_hint_cookie"):
config["target_location_hint"] = response.get("target_location_hint_cookie").get("value")
return response |
def is_bytes_type(typ):
"""
Check if the given type is a ``bytes``.
"""
# Do not accept subclasses of bytes here, to avoid confusion with BytesN
return typ == bytes |
def f(n):
"""
f(0) = 0
f(1) = 1
f(2) = 1
f(3) = 2
f(4) = 3
f(5) = 5
f(n) = f(n-1) + f(n-2)
"""
if n < 2:
return n
prev_number = 1
current_number = 1
# f(2)
result = 1
for idx in range(3, n+1):
result = current_number + prev_number
pre... |
def format_user_engagement(user_duration):
"""Return session duration for each user"""
(user, session_durations) = user_duration
return session_durations |
def Diff(t):
"""Computes the differences between the adjacent elements of a sequence.
Args:
t: sequence of anything subtractable
Returns:
list of whatever is in t
"""
diffs = []
for i in range(len(t)-1):
diff = t[i+1] - t[i]
diffs.append(diff)
return diffs |
def LCase(text):
"""Return the lower case version of a string"""
return text.lower() |
def calcUpdrsRating(amplitude, totalAmplitudeError):
"""
Converts an amplitude measurement (in cm) into an MDS-UPDRS rating.
"""
# n.b. the first value is 0.01, not 0, to account for floating-point error.
# The error is subtracted from amplitude for the first classification,
# otherwise a UPDRS... |
def validate(label, function, status, initial_value):
"""
this function validates a string
--------------------------------
label: str
the input label
function: fun
the code will start over as long as function (value) is equal to True
status: str
the status of the input
... |
def remove_id_version(s, force=False):
"""
Remove the optional '.VERSION' from an id if it's an Ensembl id or if
`force` is True.
"""
if force or s.startswith('ENS'):
return s.split('.')[0]
else:
return s |
def array_diff(arr):
"""
Given an numeric array, calculate a discrete derivative between the elements. In other words,
calculate the change between going from one element to the next subsequent element.
Examples:
array_diff([1, 2, 4, 7]) == [1, 2, 3]
array_diff([1, 1, 0, 1]) == [0, -1, 1]
... |
def doi_url_for(doi_value):
"""Return the URL for the DOI."""
return 'https://doi.org/' + str(doi_value).strip('/') |
def _carry_signals(x, y):
"""
Args:
x (int): A summand.
y (int): The other summand.
Returns:
int:
A bitmask with each bit corresponding to whether adding y into x
(or vice versa) triggered a carry at each bit position.
"""
return ((x + y) ^ x ^ y) >> ... |
def _to_grey(col):
"""
Transform RGB tuple to grey values
"""
isgrey = 0.2125 * col[0] + 0.7154 * col[1] + 0.072 * col[2]
return (isgrey, isgrey, isgrey) |
def text_formatter(team: list) -> str:
"""
transform list of lists into text
from:
[['player1', 'Sorlag'], ['player2', 'Nyx'], ['player3', 'Anarki'], ['player4', 'Ranger']]
to:
player1 - Sorlag
player2 - Nyx
player3 - Anarki
player4 - Ranger
:param team: list
:return: str
... |
def GetNextObject(obj,stop_at):
"""
Walks the hierarchy, stops at "stop_at"
"""
if obj == None:
return None
if obj.GetDown():
return obj.GetDown()
while not obj.GetNext() and obj.GetUp() and obj.GetUp() != stop_at:
obj = obj.GetUp()
return obj.GetNext() |
def encode_message(message):
"""Encode a message using base64."""
from base64 import b64encode
return b64encode(message.encode()).decode() |
def encode(num):
"""Encode a positive number into Base X and return the string.
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return BASE62[... |
def write_content(path, content):
"""Write string content to path name."""
print(f"- writing {path}")
with open(path, 'w') as file:
file.write(content)
return path |
def combine_cycles(cycle1, cycle2):
"""
INPUT: two cycles with type: list of atoms
OUTPUT: a combined cycle with type: list of atoms
"""
set1 = set(cycle1)
set2 = set(cycle2)
return list(set1.union(set2)) |
def pprint(g): # pragma: no cover
"""Pretty print a tree of goals."""
if callable(g) and hasattr(g, "__name__"):
return g.__name__
if isinstance(g, type):
return g.__name__
if isinstance(g, tuple):
return "(" + ", ".join(map(pprint, g)) + ")"
return str(g) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.