content stringlengths 42 6.51k |
|---|
def bytes_to_nibbles(data):
"""
Utility function to take a list of bytes (8 bit values) and turn it into
a list of nibbles (4 bit values)
:param data: a list of 8 bit values that will be converted
:type data: list
:return: a list of 4 bit values
:rtype: list
.. versionadded:: 1.16.0
... |
def prepend_scheme(scheme, path):
"""Prepend scheme to a remote path.
Scheme is only prepended if not already present
Parameters
----------
scheme: str
a scheme like 'file', 's3' or 'gs'
path: str
path which will possibly get a scheme prepended
Returns
-------
full... |
def valid_number(phone_number):
"""Valid a cellphone number.
:param phone_number: Cellphone number.
:type phone_number: str
:returns: true if it's a valid cellphone number.
:rtype: bool
"""
phone_number = phone_number.replace(" ", "")
if len(phone_number) != 10:
return False
... |
def eulerC1(c2,rho,R):
"""Compute the optimal Euler consumption of old generation
Args:
rho (float): discount parameter
c2 (float): consumption old generation
R (float): gross return on saving
Returns:
(float): optimal Euler consumption o... |
def remove_key(vglist,key):
"""
Accepts a list of dictionaries (vglist) and a list of keys.
Returns a list of dictionaries with each of the specified keys removed for all element of original list.
"""
new_list = []
for row in vglist:
for item in key:
row.pop(item,None)
new_list.append(row)
r... |
def fill_empty(input, replacement):
""" if a cell is empty (contains only whitespace characters or an empty string), fill it with `replacement`. """
if "".join(input.split())=="":
return replacement
return input |
def _get_parameter_metadata(driver, band):
"""
Helper function to derive parameter name and units
:param driver: rasterio/GDAL driver name
:param band: int of band number
:returns: dict of parameter metadata
"""
parameter = {
'id': None,
'description': None,
'unit_la... |
def innerContents(singleModelBody):
"""
This method returns the body of the given
model, as an array. The body is between the
two curly brace { }.
We assume no comments in the model at the moment ...
same with in the properties.
"""
if singleModelBody == False:
return False
i, j = 0, len(singleModelBody)... |
def execute(data):
""" Execute boot instructions until stop condition is met.
"""
# process the instructions until we hit a duplicate
acc = 0
i = 0
executed = set()
while i not in executed:
# add this instruction to the list
executed.add(i)
# process it
instr... |
def select_atoms(frame, atom_name):
"""Select atoms based on a name."""
index = []
for i, atom in enumerate(frame['atomname']):
if atom == atom_name:
index.append(i)
return index |
def xl_col_to_name(col, col_abs=False):
"""Convert a zero indexed column cell reference to a string.
Args:
col: The cell column. Int.
col_abs: Optional flag to make the column absolute. Bool.
Returns:
Column style string.
"""
col_num = col
if col_num < 0:
rais... |
def prettyTime(time : int) -> str:
"""takes a time, in seconds, and formats it for display"""
m, s = divmod(time, 60)
h, m = divmod(m, 60)
s = round(s, 2)
if h: return "%s hour(s), %s minute(s), %s second(s)" % (int(h),int(m),s)
else: return "%s minute(s), %s second(s)" % (int(m),s) |
def human_size(bytes, units=[' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB']): # pylint: disable=W0102
""" Returns a human readable string reprentation of bytes"""
return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) |
def hxd_s(b, begin=0):
"""
hexdump
begin is the first address
"""
def isprintable(c):
return c > 0x20 and c < 0x7e
def asciify(c):
return chr(c) if isprintable(c) else '.'
ret = ''
length = len(b)
pos = 0
def take(n):
nonlocal pos
taken = b[pos... |
def lookup(name, namespaces=None, modules=None):
"""
Look up the given name and return its binding. Return `None` if not
found.
namespaces:
Iterable of namespaces / dictionaries to search.
modules:
Iterable of modules / objects to search.
"""
if namespaces is not None:
... |
def _no_pending_volumes(volumes):
"""If there are any volumes not in a steady state, don't cache"""
for volume in volumes:
if volume['status'] not in ('available', 'error', 'in-use'):
return False
return True |
def removed_files(old_status, new_status):
""" Returns a list of files that have been removed. """
return list(set(old_status.keys()).difference(set(new_status.keys()))) |
def clog2(value):
""" Ceiling of log2 """
value -= 1
result = 0
while value > 0:
result += 1
value >>= 1
return result |
def uprava_seznamu(list1, list2):
"""
Funkce na upravu dvou seznamu. Funkce vraci tri seznamy.
Jeden ktery sjednocuje dva zadane seznamy, dalsi ketry je rozdil
prvniho od druheho a treti ktery je rozdilem druheko od prvniho
"""
seznam_sjed = list(list1)
seznam_roz_1_2 = list(list1)
sezna... |
def reverse_choices(choices):
"""
Tuple of tuples -> Dict
Returns a dictionary of reversed choices structures
"""
return dict([(v, k) for k, v in choices]) |
def calc_ss(err, err_base):
"""
Simple function to calculate skill score from a loss and reference loss.
"""
return 1. - (err / err_base) |
def _get_command(config, artifact_name, remote_path, local_path):
"""
Compile command to unzip
:param config:
:param artifact_name:
:param remote_path: artifact remote host path
:param local_path: artifact client path
:return: tuple(unzip command, new configuration)
... |
def dateIsBefore(year1, month1, day1, year2, month2, day2):
"""Returns True if year1-month1-day1 is before year2-month2-day2. Otherwise, returns False."""
if year1 < year2:
return True
if year1 == year2:
if month1 < month2:
return True
if month1 == month2:
... |
def circunferencia (x,y):
"""
float, float --> booleano
OBJ: determinar si la coordenada se encuentra sobre la circunferencia x**2 + y**2 = 1000
"""
suma_coordenada = x**2 + y**2
return suma_coordenada <= 1000 |
def ride_down(slope_map, slope_conf):
"""Iterate over the map to get the tree count of a predetermined
toboggan configuration.
Args:
slope_map (list ): map of the slope
slope_conf (tuple): right (index 0) and down (index 1) values for the slope
Returns:
int: number of trees cro... |
def id(value):
"""extract(entity)
extracts a string unique ID from a opencue entity or
list of opencue entities.
"""
def _extract(item):
try:
return item.id()
# pylint: disable=bare-except
except:
pass
return item
if isinstance(value, (tup... |
def get_hist_params(hist_params, plot_params=None):
"""Return a dictionary containing parameters for calculating and plotting histograms using OpenCV. This
function defines default parameter values, then updates them based on user input to the function, and finally
it does error checking to identify incompl... |
def grad_relux(x: float):
"""
Hand-written gradient of relux, used to test AD
"""
if x < 0.0:
return 0.1
else:
return 2 * x |
def belong_to_the_same_package(
first_module_import_path: str, second_module_import_path: str
) -> bool:
"""
Return True if two modules belong to the same domain package.
"""
first_chunks = first_module_import_path.split(".")
second_chunks = second_module_import_path.split(".")
return first_... |
def vector_add(v1=[0,0,0], v2=[0,0,0]):
""" v1 + v2 """
return [v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]] |
def format_terminal_output(result, stdout_key='stdout', stderr_key='stderr'):
"""
Output a formatted version of the terminal
output (std{out,err}), if the result contains
either.
:param stdout_key: where stdout is recorded
:param stderr_key: where stderr is recorded
:param result: result to... |
def colour_distance_squared(colour1, colour2):
"""Square of the Euclidian distance between two colours"""
dist_squared = sum((a - b) ** 2 for a, b in zip(colour1, colour2))
return dist_squared |
def adjective_to_verb(sentence: str, index: int):
"""Change the adjective within the sentence to a verb.
:param sentence: str - that uses the word in sentence.
:param index: int - index of the word to remove and transform.
:return: str - word that changes the extracted adjective to a verb.
For exa... |
def relu_backward(dout, cache):
"""
Computes the backward pass for a layer of rectified linear units (ReLUs).
Input:
- dout: Upstream derivatives, of any shape
- cache: Input x, of same shape as dout
Returns:
- dx: Gradient with respect to x
"""
x = cache
# =======================================... |
def get_uid_search_xpath(uid):
# type: (str) -> str
"""Method to get the XPath expression for a UID that might contain quote characters.
Parameters
----------
uid : str
Original UID string with XPath expression.
Returns
-------
str
Processed XPath expres... |
def transitive_deps(lib_map, node):
"""Returns a list of transitive dependencies from node.
Recursively iterate all dependent node in a depth-first fashion and
list a result using a topological sorting.
"""
result = []
seen = set()
start = node
def recursive_helper(node):
if no... |
def filesizeformat(bytes, sep=' '):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 B, 2.3 GB etc).
Grabbed from Django (http://www.djangoproject.com), slightly modified.
:param bytes: size in bytes (as integer)
:param sep: string separator between number and a... |
def ear(r=.12 ,N=1):
"""
Computes the effective annual rate for the rate r paid N times per year
"""
return (1+r/N)**N |
def qw_not_found(arg1, arg2, path=None, headers=None, payload=None):
"""This function is used when a not found resource should be returned.
According arg2 argument, if "not_found" is detected as a string then
payload is returned directly or as part of "data" dictionnary.
"""
payload = {'errors': [{
... |
def transform_columnwisedict_to_rowwisedict(dictionary, key_of_keys, key_of_vals, func_key=lambda x: x, func_val=lambda x: x):
"""
Parameters
----------
dictionary: dict[str, list[str]]
key_of_keys: str
key_of_vals: str
func_key: function: str -> Any
func_val: function: str -> Any
R... |
def impact_seq(impact_list):
"""String together all selected impacts in impact_list."""
impact_string = ''
connector = '-'
for impact in impact_list:
impact_string += connector + impact.iname.strip()
return impact_string |
def icomma(i):
""" Return an integer formatted with commas """
if i<0: return "-" + icomma(-i)
if i<1000:return "%d" % i
return icomma(i/1000) + ",%03d" % (i%1000) |
def isPrime(x):
"""
Checks whether the given
number x is prime or not
"""
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3, int(x ** 0.5) + 1, 2):
if x % i == 0:
return False
return True |
def IsStringInt(string_to_check):
"""Checks whether or not the given string can be converted to an int."""
try:
int(string_to_check)
return True
except ValueError:
return False |
def square_root_2param(t, a, b):
"""t^1/2 fit w/ 2 params: slope a and vertical shift b."""
return a*t**(0.5) + b |
def check_int(num):
"""Check if arguement is integer.
Arg:
num (int): The only arguement.
Returns:
bool: The return value. True if num is indeed an integer, False otherwise.
"""
if num is not None:
try:
int(num)
return True
except ValueError:... |
def digitToInt(s):
"""
digitToInt :: str -> int
Convert a single digit Char to the corresponding Int. This function fails
unless its argument satisfies isHexDigit, but recognises both upper and
lower-case hexadecimal digits (i.e. '0'..'9', 'a'..'f', 'A'..'F').
"""
if s not in "0123456789abc... |
def mergeConfig(source, destination):
"""
Merges `source` object into `destination`.
"""
for key, value in source.items():
if not key in destination:
destination[key] = value
elif type(value) is dict:
# get node or create one
node = destination.setdefault(key, {})
mergeConfig(val... |
def row(*cols)->str:
"""Turns a series of html snippets into a bootstrap row with equally sized
columns for each snippet.
Example:
to_html.row("<div>first snippet</div>", "<div>second snippet</div>")
"""
row = '<div class="row" style="margin-top: 20px;">'
for col in cols:
row +=... |
def hexescape(char):
"""Escape char as RFC 2396 specifies"""
hex_repr = hex(ord(char))[2:].upper()
if len(hex_repr) == 1:
hex_repr = "0%s" % hex_repr
return "%" + hex_repr |
def degrees_as_hex(angle_degrees, seconds_decimal_places=2):
"""
:param angle_degrees: any angle as degrees [float]
:param seconds_decimal_places: number of decimal places to express for seconds part of hex string [int]
:return: same angle in hex notation, unbounded [string].
from photrix August 201... |
def primes(number):
"""
:param number:
"""
primfac = []
divisor = 2
while divisor * divisor <= number:
while (number % divisor) == 0:
# supposing you want multiple factors repeated
primfac.append(divisor)
number /= divisor
divisor += 1
... |
def acidityIndex (sample_weight, NaOH_molarity, NaOH_fc, NaOH_volume_spent):
"""
Function to calculate the acidity index in mg of KOH in 1g of sample
Function usage: x, y = acidityIndex(4.98, 0.01, 1.09987, 3.9)
x (grams of acid in 100g of sample) = 0.2428990012048192
y (acidity index grams of KOH i... |
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i |
def goal_error(name):
"""Adds a string which occurs in the
output of coq if a goal is admitted.
Arguments:
- `name`: a goal name
"""
return "*** [ {0!s}".format(name) |
def _src_lines(start_line, end_line):
"""
Test lines to write to the source file
(Line 1, Line 2, ...).
"""
return "\n".join(
[f"Line {line_num}" for line_num in range(start_line, end_line + 1)]
) |
def f_coupled(state, t, sigma, beta, rho, c_e, c, c_z, tau, S, k1, k2):
"""
:param state: 9D state (list)
:param t:
:param sigma: Lorenz param
:param beta: Lorenz param
:param rho: Lorenz param
:param c_e: Coupling coefficient (extratropical to tropical)
:param c: Coupling coefficient (... |
def get_coincidence(period1:int, start1:int, period2:int, start2:int)->int:
"""Get the first coincidence of two sequences with given period and starts.
period1 is assumed to be larger if of extremely different sizes."""
val = start1
while (val - start2) % period2:
val += period1
return ... |
def empty_units(number: int, from_unit: int) -> int:
"""
Puts zeros on all digits from the from_unit
num being 152 and from_unit being 1 gives 100
"""
mask: int = int(10 ** (from_unit + 1))
return number - (number % mask) |
def supersplit(string: str, delimiter: str):
"""Like str.split, but keeps delimiter and discards empty bits."""
return [
bit
for split in string.split(delimiter)
for bit in [delimiter, split]
if len(bit) > 0
][1:] |
def start_of_chunk(prev_tag, tag, prev_type, type_):
"""
check if a chunk started between the previous and current word
arguments: previous and current chunk tags, previous and current types
"""
chunk_start = False
if tag == 'B':
chunk_start = True
if tag == 'S':
chunk_star... |
def equals(d1, d2):
"""check if two hashmaps are the same"""
if len(d1) != len(d2):
return False
for k1, v1 in d1.items():
if k1 not in d2.keys() or d1[k1] != d2[k1]:
return False
return True |
def t1w_container_from_filename(t1w_filename):
"""
Extracts <participant_id> & <sesssion_id> from BIDS <t1w_filename> and
returns CAPS path.
"""
import re
from os.path import join
m = re.search(r'(sub-[a-zA-Z0-9]+)_(ses-[a-zA-Z0-9]+)_', t1w_filename)
if m is None:
raise ValueErr... |
def RecExpo(base, exp):
"""
Recursively computes base^exp for nonnegative exponents and return the result
Examples:
>>> RecExpo(0,200)
0
>>> RecExpo(200,0)
1
>>> RecExpo(2,10)
1024
>>> RecExpo(10,4)
10000
>>> from math imp... |
def output2sentiment(output):
"""Convert NN output to {-1, 0, 1}"""
return [0 if x[1] < .5 else (x[0] < 0.5 and -1 or 1) for x in output] |
def start_timer(index: int):
"""Start timer."""
return f'B;StartTimer("{index}");'.encode() |
def steady_state_tRNA_balance(nu_max,
phi_P,
growth_rate):
"""
Computes the steady state value of the charged-tRNA abundance.
Parameters
----------
nu_max : positive float
The maximum nutritional capacity in units of inverse time.... |
def S_self_operate_values(_data_list, _step=1, _operation=1):
"""
Apply arithmetic operation on data samples themselves
step parameter is used to define how many data points to skip for calculating accelerated values
_operation parameter is used for selecting one of the operations (1: addition, 2: subtr... |
def convert_deg_to_ha(area_deg: float):
"""
converts value in degrees^2
(of latitude and longitude)
into a value in hectars ha
#Parameters:
# area_deg (float): The value in deg^2 to be converted
#Returns:
# converted value in ha
"""
scale_m_per_deg = 30 / 0.00025
ret... |
def get_point(values, pct):
"""
Pass in array values and return the point at the specified top percent
:param values: array: float
:param pct: float, top percent
:return: float
"""
assert 0 < pct < 1, "percentage should be lower than 1"
values = sorted(values)
return values[-int(len(... |
def log_file_with_status(log_file: str, status: str) -> str:
"""
Adds an extension to a log file that represents the
actual status of the tap
Args:
log_file: log file path without status extension
status: a string that will be appended to the end of log file
Returns:
string... |
def norm(distribution):
"""Normalize array 'distribution', so that its entries
add up to 1.0."""
S = sum(distribution)
if S <= 0.0:
# raise ValueError, "Cannot normalize empty distribution!"
return distribution # do nothing
return distribution / S |
def filter_columns_by_prefix(columns, prefixes):
"""Filter columns by prefix."""
filtered_columns = {column for column in columns
if True in (column.startswith(prefix)
for prefix in prefixes)}
return filtered_columns |
def _make_ss_flux(reaction_str):
"""Format reaction identifier to match steady state flux parameter.
Warnings
--------
This method is intended for internal use only.
"""
return "v_" + reaction_str |
def multiples_three_five(limit):
"""Function that given limit filters the array by the number that are multiple of 3 or 5"""
# pylint: disable=misplaced-comparison-constant
# mislaced-comparison-constant a.k.a.: 'Yoda conditions'
return [x for x in range(1, limit) if 0 == x%3 or 0 == x%5] |
def calcualte_length(data):
"""
LDAP protocol doesnt send the total length of the message in the header,
it only sends raw ASN1 encoded data structures, which has the length encoded.
This function "decodes" the length os the asn1 structure, and returns it as int.
"""
if data[1] <= 127:
return data[1] + 2
else:... |
def asymmetry(pi, pK, e, g_pK, g_e):
"""
calculates background-subtracted asymmetry given
pi = (content,error)
pK = (content,error)
e = (content,error)
g_pK = (pK contamination in pi window) / purity of pK sideband
g_e = (e contamination in pi window) / purity of e sideband
... |
def slice_and_pad_to_n(ls, n):
"""ls list to be cut/padded to length n"""
ls= ls[:n]
if len(ls)<n: ls=(['<pad>']*(n-len(ls))) + ls
return ls |
def transpose_mat(M):
"""
Takes a matrix M and transposes its columns and rows
"""
res = [[M[j][i] for j in range(len(M))] for i in range (len(M[0]))]
print('\n')
return res |
def edd_pre_sequencing(dataset, *args, **kwargs):
"""
Generates an initial job sequence based on the earliest-due-date
dispatching strategy. The job sequence will be feed to the model.
"""
sequence = []
for job in dataset.values():
if sequence == []:
sequence.append(job)
... |
def _GetPossibleActions(actions_grouped_by_kind):
"""The list of possible action kinds."""
possible_actions = []
for action_group in actions_grouped_by_kind:
if action_group.members:
possible_actions.append(action_group.name)
return possible_actions |
def strip_tuple(tuple_list, tuple_index = 0):
"""Given a list of tuples, creates a list of elements at tuple_index"""
elem_list = []
for i in range(0, len(tuple_list)):
elem_list.append(tuple_list[i][tuple_index])
return elem_list |
def update_detects_payload(current_payload: dict, passed_keywords: dict) -> dict:
"""Update the provided payload with any viable parameters provided as keywords."""
if passed_keywords.get("assigned_to_uuid", None):
current_payload["assigned_to_uuid"] = passed_keywords.get("assigned_to_uuid", None)
i... |
def transform_url_parameters(params):
"""Transform python dictionary to aiohttp valid url parameters.
support for:
key=["a", "b"] -> ?key=a&key=b
"""
if isinstance(params, list):
# nothing to do
return params
p = []
for key, value in params.items():
if isinstance(va... |
def underscore_to_camelcase(word, initial_capital=False):
"""Transform a word to camelCase."""
words = [x.capitalize() or "_" for x in word.split("_")]
if not initial_capital:
words[0] = words[0].lower()
return "".join(words) |
def get_assumed_creds(sts, arn):
"""
Gets assume role credentials
"""
if arn:
credentials = sts.assume_role(RoleArn=arn, RoleSessionName="AssumeRoleSession1")
return {
"aws_access_key_id": credentials["Credentials"]['AccessKeyId'],
"aws_secret_access_key": credent... |
def index_page(a):
"""
Return '' if page is 0, return page index number otherwise
"""
if(a>0):
return str(a)
else:
return '' |
def fizz_buzz(inp: int) -> str:
"""
Fizz buss game
if input is a
number divisible by 3 - fizz
number divisible by 5 - buzz
number divisible by 3 and 5 - 'fizz buzz'
:param inp: an `int` natural number <= 100
:return: 'fizz', 'buzz', 'fizz buzz'
"""
if inp... |
def sum_2(strg):
"""Sums last 3 digits"""
sum = 0
for i in strg[3:]:
sum += int(i)
if sum == 0:
sum = 1
return sum |
def get_max_unsecured_debt_ratio(income):
"""Return the maximum unsecured-debt-to-income ratio, based on income."""
if not isinstance(income, (int, float)):
raise TypeError("Expected a real number.")
# Below this income, you should not have any unsecured debt.
min_income = 40000
if income <... |
def _get_container_port_mappings(app):
"""
Get the ``portMappings`` field for the app container.
"""
container = app['container']
# Marathon 1.5+: container.portMappings field
port_mappings = container.get('portMappings')
# Older Marathon: container.docker.portMappings field
if port_ma... |
def execute(opts, data, func, args, kwargs):
"""
Directly calls the given function with arguments
"""
return func(*args, **kwargs) |
def unlist(d):
"""
If the list contain only one element, unlist it
"""
for key, val in d.items():
if isinstance(val, list):
if len(val) == 1:
d[key] = val[0]
elif isinstance(val, dict):
unlist(val)
return d |
def uniformSegmentAlignment(alignment, subLabelsOut):
"""Converts a one-level alignment to two-level by uniform segmentation."""
alignmentOut = []
numSubLabels = len(subLabelsOut)
for labelStartTime, labelEndTime, label, subAlignment in alignment:
assert subAlignment is None
durMult = (l... |
def create_range_as_list(rng, as_type=str):
"""
Parameters
----------
range : str
The range to create as a list.
e.g.
range="1-4" --> [1, 2, 3, 4]
range="1-3,5,7-9,1001" --> [1, 2, 3, 5, 7, 8, 9, 1001]
as_type : type
map list to as_type. default = str... |
def prod(lst):
"""Computes the product of a list of numbers."""
p = 1.0
for i in lst:
p *= i
return p |
def building_rainwater(array):
"""
array is a sequence of nonnegative numbers representing the height of the buildings, each with width 1.
After rain, how much water can be trapped by the buildings?
"""
n = len(array)
left = [0] * n # max height including itself on the left
right = [0] * n ... |
def getANum(aStr):
""":type aStr str"""
intValue = -1
aStr = aStr.replace("#","").replace("=","").strip()
if aStr.lower().startswith("0x"):
intValue = int(aStr,16)
else:
intValue = int(aStr,10)
return intValue |
def full_name_with_name(klass: type) -> str:
"""Returns the klass module name + klass name."""
return f"{klass.__module__}.{klass.__name__}" |
def fixed2Float(value):
"""The fixed2Float method translates a fixed 1/64 pixel-unit value to
float."""
return float(value) / 64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.