content stringlengths 42 6.51k |
|---|
def frequency(data):
"""Returns the frequency of items in a data tuple."""
items = sorted(set(data))
count = (data.count(i) for i in items)
return dict(zip(items, count)) |
def _H3(x):
"""Third Hermite polynomial."""
return (2 * x**3 - 3 * x) * 3**-0.5 |
def clamp(val, min_val, max_val):
"""Limits a value within a given minimum and maximum range.
"""
return min(max(val, min_val), max_val) |
def check_and_print_params(config_dict, default_param_dict, desc_dict):
"""
Function that tests that all required parameters are in file, if
not, then add default value. It also prints a short description
of each parameter along with the value being used.
Inputs:
-------
config_dict: dict
... |
def mpls_interface_group_id(ne_id):
"""
MPLS Interface Group Id
"""
return 0x90000000 + (ne_id & 0x00ffffff) |
def get_type_name(cls):
"""Gets the name of a type.
This function is used to produce a key for each wrapper to store its states in a dictionary of wrappers' states.
Args:
cls: The input class.
Returns:
str: Name of the class.
"""
name = "{}:{}".format(cls.__class__.__module__, ... |
def get_axe_names(image, ext_info):
"""
Derive the name of all aXe products for a given image
"""
# make an empty dictionary
axe_names = {}
# get the root of the image name
pos = image.rfind('.fits')
root = image[:pos]
# FILL the dictionary with names of aXe products
#
# th... |
def compute_full_sequence(ground_truth, predictions):
"""
compute full sequence accuracy
:param ground_truth:
:param predictions:
:return:
"""
try:
correct_count = 0
mistake_count = [0] * 7
for index, label in enumerate(ground_truth):
prediction = predicti... |
def sizeof_fmt(num, suffix='B'):
"""
From https://stackoverflow.com/a/1094933
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%d %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Yi', suffix) |
def _render_order(order):
"""Render the order by part of a query.
Parameters
----------
order : dict
A dictionary with two keys, fields and direction.
Such that the dictionary should be formatted as
{'fields': ['TimeStamp'], 'direction':'desc'}.
Returns
-------
str
... |
def Pi_VH(phi, cond_GT):
""" Osmotic pressure using Van-Hoff linear approximation
"""
rho = phi/cond_GT['Va']
kBT = cond_GT['kT']
return rho * kBT * 1.0 |
def parse_map_line(line):
"""
:param line:
:return:
"""
tchrom, tstart, tend, tstrand, blockid, qchrom, qstart, qend, qstrand = line.strip().split()
return tchrom, int(tstart), int(tend), tstrand, blockid.split('.')[0], qchrom, int(qstart), int(qend), qstrand |
def _deep_deannotate(element):
"""Deep copy the given element, removing all annotations."""
def clone(elem):
elem = elem._deannotate()
elem._copy_internals(clone=clone)
return elem
if element is not None:
element = clone(element)
return element |
def deep_type(obj):
"""
An enhanced version of :func:`type` that reconstructs structured :mod:`typing`` types
for a limited set of immutable data structures, notably ``tuple`` and ``frozenset``.
Mostly intended for internal use in Funsor interpretation pattern-matching.
Example::
assert de... |
def _splitstrip(string, delim=u','):
"""Split string (at commas by default) and strip whitespace from the
pieces.
"""
return [s.strip() for s in string.split(delim)] |
def fput(thing, l):
"""
FPUT thing list
outputs a list equal to its second input with one extra member,
the first input, at the beginning.
"""
return [thing] + l |
def minutes_to_second(minutes: str) -> int:
"""Function to convert minutes to seconds."""
return int(minutes) * 60 |
def binary_search(data, target, low, high):
"""Return True if target is found in indicated portion of a Python list.
The search only considers the portion from data[low] to data[high] inclusive.
"""
if low > high:
return False # interval is empty; no match
else:
... |
def signature(params, separator='/'):
"""Create a params str signature."""
def _signature(params, sig):
for key in params.keys():
sig.append(key)
if isinstance(params[key], dict):
_signature(params[key], sig)
my_list = list()
_signature(params, my_list)
... |
def is_adjacent(groups):
"""
After group cars into different group,
check whether all same character are adjacent.
1. If same characters occur in different group, them are not adjacent.
2. If same characters only occur in one group, but them are not adjacent, them are not adjacent.
:param grou... |
def TestSolver(a, b, c):
"""
Parameters
----------
a :
b :
c :
Returns
-------
d :
e :
"""
d = a + 5*b - c
e = a + b
return d, e |
def character_ngrams(text, n):
""" Returns a list of character n-grams (strings)."""
return [text[i:i+n] for i in range(len(text)-n+1)] |
def isDivisible(a,b):
"""
Check if a divides b
Parameters
----------
a : int
denotes a in a|b
b : int
denotes b in a|b
return : bool
return true if a divides b
return false if a doesn't divide b
"""
if(a==0 or b%a != 0):
return False
else... |
def _get_tif_tolerances(file_name: str):
"""
return the absolute and relative tolerances for the tif comparisons.
Comparison will use `numpy.isclose` on the back end:
https://numpy.org/doc/stable/reference/generated/numpy.isclose.html
Comparison function:
absolute(a - b) <= rtol * absol... |
def separateLeafNameFromLeafAnnotation( leafName , sepSp = "_" , sepAnnot = (".","@") ):
"""
Takes:
- leafName (str) : name of a leaf, potentially containing reconciliation information (exemple: "g_g3.T@4|3@1|g" )
- sepSp (str) [default = "_" ] : separator between species name and gene name
... |
def update_id_to_be_equal_name(playbook):
"""
update the id of the playbook to be the same as playbook name
the reason for that, demisto generates id - uuid for playbooks/scripts/integrations
the conventions in the content, that the id and the name should be the same and human readable
:param playb... |
def keep_in_dict(obj, allowed_keys=list()):
""" Prune a class or dictionary of all but allowed keys.
"""
if type(obj) == dict:
items = obj.items()
else:
items = obj.__dict__.items()
return {k: v for k, v in items if k in allowed_keys} |
def numerus(count, wordSingular, wordPlural=None):
"""
Return the singular `wordSingular` or the plural form `wordPlural` of a
noun, depending of the value of `count`.
If `wordPlural` is `None`, it equals to `wordSingular` with an appended
's'.
>>> numerus(1, 'car')
'car'
>>> numerus(... |
def _add_value(interface, value, chosen_values, total_chosen_values, interface_to_value, value_to_implementation):
"""
Add a given value and a corresponding container (if it can be found) to a chosen value set.
:param interface: Interface identifier.
:param value: Provided implementation of an interfac... |
def factorialFinderLoops(n):
"""Returns the factorial of the positive integer n using
loops."""
if not isinstance(n, int):
raise TypeError('n should be a positive integer.')
return None
if n < 0:
raise ValueError('n should be a positive integer.')
return None
resul... |
def does_not_strictly_dominate(dominator_map, x, y):
""" predicate testing if @p x does not strictly dominate @p y using
@p dominator_map """
if x == y:
return True
elif x in dominator_map[y]:
# y is dominated by x, and x != y so x strictly dominates y
return False
return... |
def split_extent(csv_ext):
"""Splits '1,2,3,4,5,6' string to six separate values:
x1, y1, z1, x2, y2, z2 = SplitExtent('1,2,3,4,5,6')
"""
return [float(x) for x in csv_ext.split(',')] |
def _discrete_log_trial_mul(n, a, b, order=None):
"""
Trial multiplication algorithm for computing the discrete logarithm of
``a`` to the base ``b`` modulo ``n``.
The algorithm finds the discrete logarithm using exhaustive search. This
naive method is used as fallback algorithm of ``discrete_log`` ... |
def clean_string(s):
"""
Process a string with "#" representing backspaces.
:param s: a string value.
:return: the string after processing the backspaces.
"""
stack = []
for x in s:
if x == "#":
if stack:
stack.pop()
else:
stack.append(... |
def is_null_class(name):
""" returns true if the name represents the null class, like _background_noise_ """
return name.startswith("_") |
def checksum(key, data, errors, context):
"""
Validates the `'checksum'` values of the CKAN package. A checksum is
considered valid under the following conditions:
- when either `hash` or `hash_algorithm` is present, the other must too be
present
- all given `'hash'` properties which are pr... |
def format_data_title(name):
"""Formats key values by removing hyphes and title() the string"""
return name.replace('-', ' ').title() |
def _Pluralize(value, unused_context, args):
"""Formatter to pluralize words."""
if len(args) == 0:
s, p = '', 's'
elif len(args) == 1:
s, p = '', args[0]
elif len(args) == 2:
s, p = args
else:
# Should have been checked at compile time
raise AssertionError
if value > 1:
return p
... |
def unit_step(t):
""" Takes time as argument and returns a unit-step function """
return 1*(t>=0) |
def calc_small_pair(n, vs):
"""n: result0 * result1\n
vs: num of vars\n
{result0} > {result1}\n
usage: +{result0}[>+{result1}<-]"""
n = n % 256
x = 1
y = 256
s = 256
for i in range(1, 256):
if n % i == 0:
j = n // i
s2 = int(i + j * vs)
i... |
def mkpy3_util_str2bool(v):
"""Utility function for argparse."""
import argparse
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return False
else:
raise argparse.ArgumentTypeError("Boolean value expected.")
... |
def get_items_of_type(type_, mapping):
"""Gets items of mapping being instances of a given type."""
return {key: val for key, val in mapping.items() if isinstance(val, type_)} |
def GetLibraryResources(r_txt_paths):
"""Returns the resources packaged in a list of libraries.
Args:
r_txt_paths: paths to each library's generated R.txt file which lists the
resources it contains.
Returns:
The resources in the libraries as a list of tuples (type, name). Example:
[('drawabl... |
def age_dia_model(m, x):
"""given (intercept,slope), calculates predicted hgt assuming hgt=m[1]*x+m[0]"""
return (x * 0.0) + m |
def insertion_sort_desc(list,n):
"""
sort list in desending order
INPUT:
list=list of values to be sorted
n=size of list that contains values to be sorted
OUTPUT:
list of sorted values in desending order
"""
for i in range(0,n):
key = list[i]
j = i - 1
... |
def convertTypes(value):
"""Helper to convert the type into float or int.
Args:
value(str): The value that will be converted to float or int.
Returns:
The converted value.
"""
value = value.strip()
try:
return float(value) if '.' in value else int(value)
except... |
def binarySearchRec(sort: list, target: int, start: int, stop: int, value: bool):
"""binary search with recursion"""
if start > stop:
if value:
return None # not found value
else:
return -1 # not found index
else:
mid = (start + stop) // 2
if targe... |
def dump_datetime(value):
"""Deserialize datetime object into string form for JSON processing."""
if value is None:
return None
return value.isoformat() |
def merge(values_1, values_2, labels, join='inner'):
"""Merge two dictionaries. The resulting dictionary will map key values to
dictionaries. Each nested dictionary has two elements, representing the
values from the respective merged dictionary. The labels for these elements
are defined by the labels ar... |
def is_image_file(filename, extensions=('.jpg', '.png')):
"""
Return true if filename has appropriate extension.
"""
return any(filename.endswith(e) for e in extensions) |
def clean_args(args: dict, *exemption) -> dict:
"""Prepares the args of every function in order to add them as parameters to the get request, if needed.
It removes None and "" values.
Args:
*exemption: Keywords to clean from the args dict.
args (dict): Arguments of the function. Can be gene... |
def _lz_complexity(binary_string):
"""Internal Numba implementation of the Lempel-Ziv (LZ) complexity.
https://github.com/Naereen/Lempel-Ziv_Complexity/blob/master/src/lziv_complexity.py
"""
u, v, w = 0, 1, 1
v_max = 1
length = len(binary_string)
complexity = 1
while True:
if bi... |
def tic_tac_toe_checker(player, cond, moves):
""" Game Status Checker
Args:
player (str): The current player
cond (list): This holds all of the winning conditions
moves (list): All available moves
Return:
The status of the game
"""
for case in cond:
... |
def _gen_find(subseq, generator):
"""Returns the first position of subseq in the generator or -1 if there is no such position."""
subseq = list(subseq)
pos = 0
saved = []
for c in generator:
saved.append(c)
if len(saved) > len(subseq):
saved.pop(0)
pos += 1
... |
def rel_font(value, max_font):
"""Returns relative font size based on max_font"""
font_size = 8 + int(int(value)/int(max_font) * 60)
return str(font_size) |
def insertionsort(list_):
"""
Idea: If you have a list with one element, it is sorted. If you add an
element in a sorted list, you have to search the place where you want
to insert it.
"""
n = len(list_)
for i in range(1, n):
value = list_[i]
j = i
while j... |
def getHotkeyKwargs(keyString):
"""
Return kwargs to be given to the maya `hotkey` command given a hotkey string
Args:
keyString: A string representing a hotkey, including modifiers, e.g. 'Alt+Shift+Q'
"""
split = keyString.lower().split('+')
kwargs = {}
for s in split:
if s... |
def padding(frame, size):
"""
Return the frame with the padding size specified.
"""
return str(int(frame)).zfill(int(size)) |
def periods(raw):
"""
Transform '1911-1951, 1953' -> [[1911, 1951], [1953]]
:param raw: string like '1911-1951, 1953'
:return: list like [[1911, 1951], [1953]]
"""
def raw_period(period):
if '-' in period:
return tuple(map(lambda year: int(year), period.split('-')))
... |
def _parse_date(lines, label_delimiter=None, return_label=False):
"""Parse embl date records"""
# take the first line, and derive a label
label = lines[0].split(label_delimiter, 1)[0]
# read all the others dates and append to data array
data = [line.split(label_delimiter, 1)[-1] for line in lines]... |
def shorten_query(query, max_len=50):
"""
:type query str
:type max_len int
:rtype: str
"""
query = query.rstrip('; ')
return '{}...'.format(query[:max_len]) if len(query) > max_len else query |
def add_ngram(sequences, token_indice, ngram_range=2):
"""
Augment the input list of list (sequences) by appending n-grams values.
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}
>>> add_ngram(sequences, token_i... |
def choose(n,r):
"""
number of combinations of n things taken r at a time (order unimportant)
"""
if (n < r):
return 0
if (n == r):
return 1
s = min(r, (n - r))
t = n
a = n-1
b = 2
while b <= s:
t = (t*a)//b
a -= 1
b += 1
return t |
def calc_ramp_time(integration_time, num_reset_frames, frame_time):
"""Calculates the ramp time -- or the integration time plus overhead
for resets.
Parameters
----------
integration_time : float
Integration time (in seconds)
num_reset_frames : int
Rest frames per integration
... |
def str_to_bool(s):
"""If unsure if the value is a string or whatever always use this utillity method.
Args:
s (unkown): Pass anything, it'll convert to bool.
Raises:
ValueError: If for whatever reason none of the checks work, it'll return error.
Returns:
[bool]: Returns the b... |
def __remove_comments(lines, comments_positions):
""" This method removes list elements containing lines numbers"""
new_lines = []
for line in lines:
if int(line) not in comments_positions:
new_lines.append(line)
return new_lines |
def all_nums(table):
"""Returns True if table contains only numbers
Precondition: table is a (non-ragged) 2d List"""
cnt = 0
number_cnt = 0
for row in table:
for item in row:
cnt += 1
if type(item) in [int, float]:
number_cnt += 1
if cnt != number_... |
def _scipy_distribution_positional_args_from_dict(distribution, params):
"""Helper function that returns positional arguments for a scipy distribution using a dict of parameters.
See the `cdf()` function here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.beta.html#Methods\
to see a... |
def gcd(a: int, b: int) -> int:
"""
Returns the Greatest Common Divisor of a and b using
Euclid's Algorithm.
"""
if b == 0:
return a
return gcd(b, a % b) |
def dict_contains(superset, subset):
"""
Returns True if dict a is a superset of dict b.
"""
return all(item in superset.items() for item in subset.items()) |
def int_to_unsigned_bytes(num: int) -> bytes:
"""Create a 64 bit unsigned byte representation of a positive integer (for nonce hashing purposes)
Args:
num: A positive (<64 bit) integer
Returns:
byte object representation of number
"""
return num.to_bytes(8, byteorder="big", signed=Fa... |
def get_last_value_from_timeseries(timeseries):
"""Gets the most recent non-zero value for a .last metric or zero
for empty data."""
if not timeseries:
return 0
for metric, points in timeseries.items():
return next((p['y'] for p in reversed(points) if p['y'] > 0), 0) |
def _get_attr_as_list(attr, attribute):
"""Helper method to always get an attribute as a list."""
value = getattr(attr, attribute)
if not value:
return []
if type(value) == type([]):
return value
return [value] |
def floatRelativeEqual(a, b, eps = 1e-7):
"""
Decide whether two float numbers are equal up to a small distance, relatively.
Parameters
----------
a, b : float
The two numbers to be compared.
eps : float, default 1e-7
The maximum relative error below which we can consider two nu... |
def jac(set_a, set_b):
"""
Compute the Jaccard Index.
"""
if len(set_a) == 0 or len(set_b) == 0:
index = 0
else:
index = len(set(set_a).intersection(set(set_b))) / len(
set(set_a).union(set(set_b))
)
return index |
def climbing_stairs_three_dp(steps: int) -> int:
"""Staircase by bottom-up dynamic programming.
Time complexity: O(n).
Space complexity: O(n).
"""
T = [0] * (steps + 1)
T[0] = 1
T[1] = 1
T[2] = 2
for s in range(3, steps + 1):
T[s] = T[s - 1] + T[s - 2] + T[s - 3]
re... |
def R_roche(rho_pl, rho_sat):
"""
Compute roche radius of a planet as a function of the planet's radius
Parameters:
----------
rho_pl: Array-like;
density of the planet
rho_sat: Array-like;
density of the satellite
Returns
-------
R_roche... |
def transpose(h):
"""Transpose a hash of hashes so that the inner keys are now outer"""
res = {}
for i in list(h.keys()):
v = h[i]
for j in list(v.keys()):
if not res.get(j, None):
res[j] = {}
res[j][i] = v[j]
return res |
def format_key_as_mldock_env_var(key, prefix=None):
"""
Formats key as mldock env variable.
Replace ' ' and '-', append mldock prefix
and lastly transforms to uppercase
"""
if prefix is not None:
if not key.lower().startswith(prefix.lower()):
key = "{PREFIX}_{KEY}".format(PRE... |
def dict_to_list(ls):
"""return a dict containing values from the list,and keys is the index in the list"""
return dict(zip(range(len(ls)+1), ls)) |
def outage_exists(outages, expected):
"""Searches a list of outages for an expected outage defined by
an object with start and end properties.
"""
for outage in outages:
if (
outage['start'] == expected['start']
and outage['end'] == expected['end']
):
... |
def get_free_from_sequence(seq, start_value=1):
"""Get next missing value form sequence starting with start_value"""
if start_value not in seq:
return start_value
i = start_value
while i in seq:
i += 1
return i |
def _create_json(name, connection, description, locked):
"""
Create a JSON to be used for the REST API call
"""
json = {
"connection": connection,
"type": "isamruntime",
"name": name,
"description": description,
"locked": locked
}
return json |
def _remove_whitespace(line_content, old_col):
"""
This function removes white spaces from the line content parameter and
calculates the new line location.
Returns the line content without white spaces and the new column number.
E.g.:
line_content = " int foo = 17; sizeof(43); "
... |
def normalize(block):
"""Normalize a block of text to perform comparison.
Strip newlines from the very beginning and very end Then split into separate lines and strip trailing whitespace
from each line.
"""
assert isinstance(block, str)
block = block.strip('\n')
return [line.rstrip() for l... |
def is_namedtuple(obj):
"""
This is a dangerous function!
We are often applying functions over iterables, but need to handle
the namedtuple case specially.
This function *is a quick and dirty* check for a namedtuple.
Args:
obj (an object)
Returns:
bool: a bool that should... |
def bytes_32_to_int(b: bytes) -> int:
"""Deserialize an integer from the corresponding big endian bytes."""
assert len(b) == 32
return int.from_bytes(b, byteorder='big') |
def is_string(gxtype):
"""
Return length of a gxtype string, 0 (False) if not a string.
Note that this is the number of available bytes in UTF-8 encoding and not
equivalent to number of Unicode characters
"""
if gxtype < 0:
return -gxtype
else:
return False |
def _scale(x, length):
"""Scale points in 'x', such that distance between max(x) and min(x) equals
to 'length'.
min(x) will be moved to 0.
"""
max_x, min_x = max(x), min(x)
s = (float(length - 1) /
(max_x - min_x) if x and max_x - min_x != 0 else length)
return [int((i - min_x) * s... |
def diagonals_danger(attacking_row, attacking_column, row, column):
"""Check safety of pieces on the same diagonals, both left and right ones.
Arguments:
attacking_row -- second piece's row number
attacking_column -- second piece-s column number
row -- first piece's row number
column -- first p... |
def find_missing_items(intList):
"""
Returns missing integers numbers from a list of integers
:param intList: list(int), list of integers
:return: list(int), sorted list of missing integers numbers of the original list
"""
original_set = set(intList)
smallest_item = min(original_set)
l... |
def get_domain(url):
"""
:param url: url
:return: domain after parsing https://www.<domain>.com
"""
domain = 'nairaland'
return domain |
def heuristic(current,target):
"""calculating the estimated distance between the current node and the targeted node
-> Manhattan Distance"""
result = (abs(target[0]-current[0]) + abs(target[1]-current[1]))
return result |
def binary_search(array, target):
"""
array is assumed to be sorted in increasing values
Find the location i in the array such that array[i-1] <= target < array[i-1]
"""
lower = 0
upper = len(array)
while lower < upper: # use < instead of <=
x = lower + (upper - lower) // 2
... |
def area_triangle(length, breadth):
"""
Calculate the area of a triangle
>>> area_triangle(10,10)
50.0
"""
return 1 / 2 * length * breadth |
def as_list(V_dict: dict):
"""Transform dictionary in list
V = [(x1, y1), (x2, y2)...(xn, yn)]"""
V = []
for key in V_dict.keys():
if isinstance(key, int):
v_x = V_dict[key][0]
v_y = V_dict[key][1]
V.append((v_x, v_y))
return V |
def two_sum(arr, target):
"""Function takes in two args, the input array
and the target.
T: O(n) - We loop through the array once
S: O(n) - We use an extra data structure to store the target-curr
:param arr: Input array
:param target: Target
:return: list of two numbers, else empty a... |
def emissions_interpolation(start_year, end_year, this_year, next_year, alpha):
"""
returns the proportion of the half-life contained within the subrange
"""
return ((1 - (0.5 ** ((next_year - start_year)/alpha))) - (1 - (0.5 ** ((this_year - start_year)/alpha))))/(1 - (0.5 ** ((end_year - start_year)/a... |
def extract_values(line):
""""Normalize lines taken from /proc/cpuinfo"""
key, value = line.split(':')
key, value = key.strip(), value.strip()
key = key.replace(' ', '_')
# values as lists
if key.lower() in ('flags', 'bugs'):
value = value.split()
return key.lower(), value |
def greatest_common_divisor(a, b):
"""finds the GCD of a and b
Args:
a, b: non-negative integers
Returns:
int: the GCD of a and b
"""
while b != 0:
a, b = b, a % b
return a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.