content stringlengths 42 6.51k |
|---|
def checkio(array):
"""
sums even-indexes elements and multiply at the last
"""
if len(array) == 0:
return 0
elif len(array) == 1:
return array[0] ** 2
return sum([x for i, x in enumerate(array) if i % 2 == 0]) * array[-1] |
def nint(a):
"""return the nearest integer to a."""
i = int(a)
if a > 0:
if a - i > 0.5:
i += 1
elif a < 0:
if a - i < -0.5:
i -= 1
return i |
def _cleanup(s):
"""Utility function to remove unwanted characters."""
unwanted_chars = '-_=+()[]{}.'
return s.translate({ord(c): None for c in unwanted_chars}) |
def turning_speed(radius):
"""Maximum speed given turning radius."""
return 10.219 * radius - 1.75404E-2 * radius**2 + 1.49406E-5 * radius**3 - 4.486542E-9 * radius**4 - 1156.05 |
def strcmp_const_time(s1, s2):
"""Constant-time string comparison.
:params s1: the first string
:params s2: the second string
:return: True if the strings are equal.
This function takes two strings and compares them. It is intended to be
used when doing a comparison for authentication purpos... |
def year_month_period(start_year, start_month, end_year, end_month):
"""
Generate all year,month tuple between given time period
:param start_year: int, start from this year
:param start_month: int, start from this month
:param end_year: int, end to this year(inclusive)
:param end_month: int, en... |
def _look_ahead(groups, c, text):
"""
Looks ahead at provided groups and counts # of instances of something that could match c (literal or ?) in text and return that count
"""
count = 0
for group in groups:
if group == "?":
count = count + 1 # There's a bug here where the lookahe... |
def parse_input(s):
"""parses input removing single quotes and semicolons"""
s = ''.join([i for i in s if i != "'" and i != ';'])
return s |
def max_product(li, n):
"""Return maxima(not maximum) product from a list from the set number.
input: list of integers
output: integer, product of given integers
ex: maxProduct ({4,3,5} , 2) returns return 20
since the size (k) equal 2 , then it's 5*4 = 20
"""
std_li = sorted(li)[-n:]
... |
def _check_weights(weights):
"""Check to make sure weights are valid"""
if weights not in (None, "uniform", "distance") and not callable(weights):
raise ValueError(
"weights not recognized: should be 'uniform', "
"'distance', or a callable function"
)
return ... |
def filter_warnings(ar, startswith="get_gid"):
"""Remove non-deterministic warnings
Some of our tests produce get_gid() warnings, which are safe to ignore
for the purposes of this testing
"""
return [a for a in ar if not a.startswith(startswith)] |
def xor_fault(a, b, out, fault):
"""Returns True if XOR(a, b) == out and fault == 0 or XOR(a, b) != out and fault == 1."""
if (a != b) == out:
return fault == 0
else:
return fault == 1 |
def job_dict(ts_epoch, request_template_dict, trigger_dict):
"""A dictionary representation of a job."""
return {
'name': 'job_name',
'trigger_type': 'date',
'trigger': trigger_dict,
'request_template': request_template_dict,
'misfire_grace_time': 3,
'coalesce': T... |
def dotProd(a, b):
"""
Return the dot product of two lists of numbers
"""
return sum([ai*bi for (ai,bi) in zip(a,b)]) |
def r(s: str) -> str:
"""
Pytest string handling is quite inappropriate for the task.
"""
print(s.__repr__())
return s.__repr__() |
def str_to_bool(val: str) -> bool:
"""Takes string and tries to turn it into bool as human would do.
If val is in case insensitive (
"y", "yes", "yep", "yup", "t",
"true", "on", "enable", "enabled", "1"
) returns True.
If val is in case insensitive (
"n", "no", "f", "false", "of... |
def get_classlist(records):
""" iterate through records and get the set
of all labels
"""
all_labels = [entry['label'] for entry in records]
classlist = list(set(all_labels))
classlist.sort()
return classlist |
def sample_var(sequence_of_values):
"""A function that computes the unbiased sample variance."""
mean = float(sum(sequence_of_values))/float(len(sequence_of_values))
SSD = sum([(float(x)-mean)**2 for x in sequence_of_values])
return SSD/(len(sequence_of_values)-1) |
def bitmask_to_boolean_list(mask):
"""Convert a bitmask to boolean list
Args:
mask (int): the mask returned by the API
Returns:
list: list of booleans.
"""
of_length = max(1, mask.bit_length())
return [
bool(mask >> i & 1)
for i in range(of_length)
] |
def fib(n):
"""
Return the first Fibonacci number above n.
Iteratively calculate Fibonacci numbers until it finds one
greater than n, which it then returns.
Parameters
----------
n : integer
The minimum threshold for the desired Fibonacci number.
Returns
-------
b : integer... |
def _new_summaries(metrics):
"""Returns new summaries for the input metrics."""
return [{'name': metric, 'covered': 0, 'total': 0} for metric in metrics] |
def dict_to_block_state(dict: dict) -> str:
"""
dict_to_block_state - Converts a dictionary into a block state
Args:
dict (dict): The dictionary to convert
Returns:
str: The block state
"""
return f"[{','.join([f'{key}={value}' for key, value in dict.items()])}]" |
def intervalsIntersect(a1, b1, a2, b2):
"""
Returns True if the specified half-closed intervals [a1, b1)
and [a2, b2) intersect.
"""
# Intervals do not interset if [a1, b1) is wholly to the left
# or right of [a2, b2).
return not (b1 <= a2 or a1 >= b2) |
def display_time(seconds: float) -> str:
"""
Converts float type seconds into a nice string representation
Args:
seconds (float): time you want a strin gfrom
Returns:
str: formatted time.
"""
ret = ""
sign = ""
if seconds < 0:
tot = abs(seconds)
sign = ... |
def map(f,data):
""" return: copy of data | f applied to each entry """
accum = ()
for item in data:
accum = accum + (f(item), )
return accum |
def list_startswith(l, prefix):
"""Like str.startswith, but for lists."""
return l[:len(prefix)] == prefix |
def build_efficiencies(efficiencies, species_names, default_efficiency=1.0):
"""Creates line with list of third-body species efficiencies.
Parameters
----------
efficiencies : dict
Dictionary of species efficiencies
species_names : dict of str
List of all species names
default_e... |
def get_ca_id_from_ref(ca_ref):
"""Parse a ca_ref and return the CA ID
:param ca_ref: HHTO reference of the CA
:return: a string containing the ID of the CA
"""
ca_id = ca_ref.rsplit('/', 1)[1]
return ca_id |
def set_blast_chunk(config):
"""Set minimum chunk size for splitting long sequences."""
return config["settings"].get("blast_chunk", 100000) |
def count_violations_lipinski(
molecular_weight: float, slogp: float, num_hbd: int, num_hba: int
) -> int:
"""Apply the filters described in reference (Lipinski's rule of 5) and count how many rules
are violated. If 0, then the compound is strictly drug-like according to Lipinski et al.
Ref: Lipinski, ... |
def parse_reference(reference):
"""
Helper function, parses a 'reference' to document name and anchor
"""
if '#' in reference:
docname, anchor = reference.split('#', 1)
else:
docname = reference
anchor = None
return docname, anchor |
def _restrict_reject_flat(reject, flat, raw):
"""Restrict a reject and flat dict based on channel presence"""
use_reject, use_flat = dict(), dict()
for in_, out in zip([reject, flat], [use_reject, use_flat]):
use_keys = [key for key in in_.keys() if key in raw]
for key in use_keys:
... |
def init_node_states(nids, base_template):
"""
Initializes and returns the node state structure to the state the test
nodes will be in after we reboot them into the base template
"""
return { nid: {
"motd_template_name": None,
"power": "off",
... |
def sec2time_ffmpeg(secs): # no .second
#return strftime("%H:%M:%S",time.gmtime(secs)) # doesnt support millisecs
"""
>>> strftime("%H:%M:%S",time.gmtime(24232.4242))
'06:43:52'
>>> sec2time(24232.4242)
'06:43:52.424200'
>>>
"""
m,s = divmod(secs,60)
#print m,s
h,m = divmod(m,60)
s = int(s)
return "%02d:%... |
def f3cubic(x,gamma,mu,p12,p23,g13,g23):
""" calculates cubic equation for solving for gp3
in the form ax^3+bx^2+cx+d = 0
normalized with constant term d = -p12*gamma/mu
note that p12 and p23 are inverses of p21 and p32 in gamma_div_mu
"""
if p12==0 or p23==0:
print("Error: z... |
def t_name(key):
"""
Rename the feature keys so that they don't clash with the raw keys when
running the Evaluator component.
Args:
key: The original feature key
Returns:
key with '_xf' appended
"""
return key + '_xf' |
def common(a, b):
"""
Calculates the number of unique common elements between two lists.
Parameters
----------
a: list
list of strings to be compared to b
b: list
list of strings to be compared to a
Raises
------
TypeError
if a or b are not lists
Return... |
def n11c_1024c_1d(n, h, w, c):
"""Return index map for n11c_1024 1d layout"""
return [n, h, w, c // 1024, c % 1024] |
def samify_phred_scores( quals ):
"""
Convert a decimal list of phred base-quality scores to a sam quality string.
Note that if a quality is outside the dynamic range of sam's ability to
represent it, we clip the value to the max allowed. SAM quality scores
range from chr(33) to chr(126).
"""
... |
def prep_example_prost_gcp(example):
""" Prepare PROST example for the T5 Colab Notebook """
template = '{ex_question} \\n (A) {A} (B) {B} (C) {C} (D) {D} \\n {context}'
instance = {
'input': template.format_map(example),
'target': example[list('ABCD')[example['label']]],
'target_idx': example['labe... |
def max_value(a, b):
""" Compute max of a pair of two ints. """
return a ^ ((a ^ b) & -(a < b)) |
def get_transport(url):
"""
Gets transport type. This is more accurate than the urlparse module which
just does a split on colon.
First parameter, url
Returns the transport type
"""
url = str(url)
result = url.split("://", 1)
if len(result) == 1:
transport = ""
else:
... |
def parseprevload(prevload):
"""
Parses prevload list into readable HTML option objects
:param prevload: Array of txt filenames
:return: HTML String of <option> objects
"""
resultstring = ''
for f in prevload:
resultstring += '<option value="' + f + '">' + f + '</option>'
retu... |
def is_superset(a, b):
"""Check if a is a superset of b.
This is typically used to check if ALL of a list of sentences is in the
ngrams returned by an lf_helper.
:param a: A collection of items
:param b: A collection of items
:rtype: boolean
"""
return set(a).issuperset(b) |
def strtr(text, table):
"""String Translate
Port of PHP strtr (string translate)
Args:
text (str): The string to translate
table (dict): The translation table
Returns:
str
"""
text = str(text)
buff = []
i = 0
n = len(text)
while i < n:
for s, r in table.items():
if text[i:len(s)+i] == s:
buf... |
def _merge_dicts(dict_1, dict_2):
"""Merge two dictionaries. (In Python3.5 or greater, {**dict_1, **dict_2}."""
assert set(dict_1.keys()).intersection(dict_2.keys()) == set([])
dict_1_copy = dict_1.copy()
dict_1_copy.update(dict_2)
return dict_1_copy |
def _FormAdj_w(a1, a2):
"""
transform eisensteinInteger a1+a2*w -> form 1+3*(x+y*w)
"""
if a1 % 3 == 0:
if a2 % 3 == -1 or a2 % 3 == 2:
return a1 - a2, a1
else:
return a2 - a1, -a1
elif a1 % 3 == 1:
if a2 % 3 == 1:
return a2, a2 -a1
... |
def check_password(pw):
"""Ensure password meets complexity requirements."""
if len(pw) < 8:
return False
else:
return True |
def bitget_string(z: str, bit: int):
"""
get the bit value at position bit:int, assume it's binary.
"""
if bit >= len(z):
return False
bit_str = z[::-1][bit]
return bool(int(bit_str)) |
def site_facility(hybrid_plant_size_MW, hybrid_construction_months, num_turbines):
"""
Uses empirical data to estimate cost of site facilities and security, including
Site facilities:
Building design and construction
Drilling and installing a water well, including piping
Electric power for ... |
def round_float(value, digits=3):
"""
Round the float to max digits.
Django's floatformat is supposed to do this but it doesn't work!
"""
if value is not None:
try:
fvalue = float(value)
if digits >= 0:
fvalue = round(fvalue, digits)
retur... |
def is_generation_specified(query_params):
"""Return True if generation or if_generation_match is specified."""
generation = query_params.get("generation") is not None
if_generation_match = query_params.get("ifGenerationMatch") is not None
return generation or if_generation_match |
def convert_string_to_float(s):
"""
Attempt to convert a string to a float.
Parameters
---------
s : str
The string to convert
Returns
-------
: float / str
If successful, the converted value, else the argument is passed back
out.
"""
try:
retur... |
def RGBTupleToString(rgb_tuple):
"""Takes a tuple containing three ints and returns an RGB string code"""
rtn_str = "#%02x%02x%02x" % rgb_tuple
return rtn_str |
def get_step_g(step_f, norm_L2, N=1, M=1):
"""Get step_g compatible with step_f (and L) for ADMM, SDMM, GLMM.
"""
# Nominally: minimum step size is step_f * norm_L2
# see Parikh 2013, sect. 4.4.2
#
# BUT: For multiple constraints, need to multiply by M.
# AND: For multiple variables, need to... |
def isprimeF(n,b):
"""isprimeF(n) - Test whether n is prime or a Fermat pseudoprime to base b."""
return (pow(b,n-1,n) == 1) |
def cria_copia_peca(peca):
"""
Devolve uma copia da peca inserida.
:param peca: peca
:return: peca
"""
return peca.upper() |
def compute_accuracy(target, response):
"""Compute accuracy given a target side and a response
Assume:
target is one of R, L, N
response is one of right, left, center, away, off
"""
if target in ('R', 'L', 'N'):
if (target == 'R' and response == 'right') or (target == 'L' and response ==... |
def is_point_tuple(t,minsize):
"""
Checks whether a value is an EVEN sequence of numbers.
The number of points tuple must be size greater than or equal to ``minsize``, or the
function returns False. As a point is a pair of numbers, this means the length of
list ``t`` must be at least **twice*... |
def and_(arg, *args):
"""Lisp style and. Evaluates expressions from left to right
and returns the value of the last truthy expression.
If an expression evaluates to False, returns the value of the Falsey expression.
usage
>>> and_(True, True, False)
False
>>> and_(True, True, 2)
2
>... |
def _GetOutputTargetExt(spec):
"""Returns the extension for this target, including the dot
If product_extension is specified, set target_extension to this to avoid
MSB8012, returns None otherwise. Ignores any target_extension settings in
the input files.
Arguments:
spec: The target dictionary containing... |
def default_panels(request, parsed_case):
"""Return a list with the gene panels of parsed case"""
panels = parsed_case['default_panels']
return panels |
def ends_overlap(left, right) -> int:
"""Returns the length of maximum overlap between end of the first and start of the second"""
max_overlap = min(len(left), len(right))
for i in range(max_overlap, 0, -1):
if left.endswith(right[:i]):
return i
return 0 |
def tableToDicts(header, entries):
"""Converts a tuple of header names, and a list of entry tuples, to a list of dictionaries
"""
dicts = []
for entry in entries:
dicts.append(dict(zip(header, entry)))
return dicts |
def coverage(tiles):
"""Sum of length of all tiles.
"""
accu = 0
for tile in tiles:
accu = accu + tile[2]
return accu |
def get_mesos_gpu_status(metrics):
"""Takes in the mesos metrics and analyzes them, returning gpus status.
:param metrics: mesos metrics dictionary
:returns: Tuple of the output array and is_ok bool
"""
total = metrics['master/gpus_total']
used = metrics['master/gpus_used']
available = tota... |
def startwith (pool, term, case_sensitive = True, unique = False):
"""Look in a set of strings for ones that start with a given string.
startwith(pool, term, case_sensitive = True, unique = False) -> match(es)
pool: the set of strings to search in.
term: the string to match against.
case_sensitive: whether to do ... |
def gcd(a, b):
"""
a, b: two positive integers
Returns the greatest common divisor of a and b
"""
#YOUR CODE HERE
def gcd(a, b):
if b == 0:
return a
return gcd(b, a%b)
print(gcd(2,8)) |
def _to_lowercase(ftype, fname, *_):
"""
Tranforms data to it's lowercase representation
"""
return ftype, fname if fname is ... else fname.lower() |
def factorial(number: int) -> int:
"""
Calculate the factorial of specified number (n!).
>>> import math
>>> all(factorial(i) == math.factorial(i) for i in range(20))
True
>>> factorial(0.1)
Traceback (most recent call last):
...
ValueError: factorial() only accepts integral val... |
def example2(S):
"""Return the sum of the elements with even index in sequence S."""
n = len(S)
total = 0
for j in range(0, n, 2): # note the increment of 2
total += S[j]
return total |
def eint(a,b,c,d):
"""
"""
if a > b: ab = a*(a+1)/2 + b
else: ab = b*(b+1)/2 + a
if c > d: cd = c*(c+1)/2 + d
else: cd = d*(d+1)/2 + c
if ab > cd: abcd = ab*(ab+1)/2 + cd
else: abcd = cd*(cd+1)/2 + ab
return int(abcd) |
def plucker_c(ld, v, mu, w):
"""[summary]
Arguments:
ld (type): [description]
v (type): [description]
mu (type): [description]
w (type): [description]
Returns:
[type]: [description]
"""
x1, y1, z1 = v
x2, y2, z2 = w
return (ld * x1 + mu * x2, ld * y1... |
def to_line_protocol(parsed_output):
"""
Converts the parsed output to InfluxDB line protocol metrics
"""
return ["kafka.consumer_offset,topic={topic},group={group},partition={partition} current_offset={current_offset},log_end_offset={log_end_offset},lag={lag}"
.format(**line) for line in pa... |
def split_layers_str(layers_str):
""" Splits a comma seperated list into its components.
Strips leading and trailing blanks from each entry.
Args:
layers_str: String in the form: "layer_1,layer_2,..."
Returns:
List of strings in the form [layer_1, layer_2, ...]
"""
if layers_str ... |
def TrimAll(val):
"""
* Trim all spaces from ends of each string in container.
Inputs
* val: iterable or string.
"""
if isinstance(val, str):
val = val.strip()
elif isinstance(val, dict):
for key in val:
val[key] = TrimAll(val[key])
elif isinstance(val, tuple)... |
def gpio_altfunc_enums(port, pin, altfunc):
"""return an enumeration set for the given port and pin"""
enums = []
for (portx, pinx, af, name) in altfunc:
if port == portx and pin == pinx:
enums.append((name, af, None))
return enums |
def next_code(code):
"""
:param code: the previous code in the sequence
:return: the next code in the sequence
"""
return (code * 252533) % 33554393 |
def pseudocolor(value, minval, maxval, palette):
""" Maps given value to a linearly interpolated palette color. """
max_index = len(palette)-1
# Convert value in range minval...maxval to the range 0..max_index.
v = (float(value-minval) / (maxval-minval)) * max_index
if v >= max_index:
v = ma... |
def conv_f2c(f):
"""
Convert fahrenheit to Celsius
:param f: Temperature in Fahrenheit
:type f: float
:return: Temperature in Celsius
:rtype: float
:Example:
>>> import hygrometry
>>> hygrometry.conv_f2c(70.0)
21.111128
"""
return (f - 32.0) * 0.555556 |
def _parse_free_spaces(string):
"""
Parses the free spaces string and returns the free spaces as integer.
Input example (without quotes): "Anzahl freie Parkplätze: 134"
"""
last_space_index = string.rindex(" ")
return int(string[last_space_index+1:]) |
def calculate_iou(box1, box2, contains=False):
# Shamelessly adapted from
# https://stackoverflow.com/questions/25349178/calculating-percentage-of-bounding-box-overlap-for-image-detector-evaluation
# determine the coordinates of the intersection rectangle
"""
Calculate the IoU of two boxes
:para... |
def pad(string, max_len):
"""
add some leading spaces to string to bring it up to max_len.
"""
string = str(string)
return " "*(max_len - len(string)) + string |
def makeDistancesList(list):
"""Returns a list of distances between adjacent numbers in some input list.
E.g. [1, 1, 2, 3, 5, 7] -> [0, 1, 1, 2, 2]
"""
d = []
for i in range(len(list[:-1])):
d.append(list[i+1] - list[i])
return d |
def format_option(option, argument_required):
"""
Return appropriate string for flags requiring arguments and flags that do not
:param option: flag to format
:param argument_required: whether argument is required
"""
return option + '=' if argument_required else option + ' ' |
def if_always_true(x):
""" if_always_true """
if True:
return x
else:
return 0 |
def _poa_ground_pv(f_x, poa_ground, f_gnd_pv_shade, f_gnd_pv_noshade):
"""
Reduce ground-reflected irradiance to account for limited view of the
ground from the row surface.
Parameters
----------
f_x : numeric
Fraction of row slant height from the bottom that is shaded. [unitless]
p... |
def get_default_value(key):
""" Gives default values according to the given key """
default_values = {
"coordinates": 2,
"obabel_path": "obabel",
"obminimize_path": "obminimize",
"criteria": 1e-6,
"method": "cg",
"hydrogens": False,
"steps": 2500,
"cutoff": False,
"rvdw": 6.0,
"rele": ... |
def setr(registers, a, b, c):
"""(set register) copies the contents of register A into register C. (Input B is ignored.)"""
registers[c] = registers[a]
return registers |
def _check_patch(i, dileft, diright, dim):
"""Check if i is too close to interval endpoints and adjust if so."""
if i <= dileft:
ans = dileft
elif dim-i <= diright:
ans = dim-diright
else:
ans = i
return ans |
def get_shard_range(data_size: int, rank: int, world_size: int):
"""
Add extra 1 examples in the remainder(e.g data_size % world_size) rank,
For example, world_size = 8, data_size = 66
The shard size is [9, 9, 8, 8, 8, 8, 8, 8]
"""
remainder = data_size % world_size
shard_len = data_size // ... |
def f(x: float) -> float:
"""f : [-1, 1] -> R."""
return 1 / (25 * (x ** 2) + 1) |
def _get_integer_intervals(xmin, xmax):
"""
For a given interval [xmin, xmax], returns the minimum interval [iXmin, iXmax] that contains the original one where iXmin and iXmax are Integer numbers.
Examples: [ 3.45, 5.35] => [ 3, 6]
[-3.45, 5.35] => [-4, 6]
[-3.45, -2.... |
def split_lines(text):
"""Split text into lines.
Removes comments, blank lines, and strips/trims whitespace.
"""
lines = []
for line in text.splitlines():
if '#' in line:
line = line[:line.index('#')]
line = line.strip()
if line:
lines.append(line)
... |
def softmax(x):
"""
Softmax function to change log likelihood evidence values to probabilities.
Use with Evidence values from FACET.
Args:
x: value to softmax
"""
return 1.0 / (1 + 10.0 ** -(x)) |
def gather(m):
"""
Helper function to gather constraint Jacobians. Adapated from fenics.
"""
if isinstance(m, list):
return list(map(gather, m))
elif hasattr(m, "_ad_to_list"):
return m._ad_to_list(m)
else:
return m |
def list_public_methods(obj):
"""Returns a list of attribute strings, found in the specified
object, which represent callable attributes"""
return [member for member in dir(obj)
if not member.startswith('_') and
hasattr(getattr(obj, member), '__call__')] |
def dot(x: dict, y: dict):
"""Returns the dot product of two vectors represented as dicts.
Parameters
----------
x
y
Examples
--------
>>> from river import utils
>>> x = {'x0': 1, 'x1': 2}
>>> y = {'x1': 21, 'x2': 3}
>>> utils.math.dot(x, y)
42
"""
if len(... |
def search4letters(phrase: str, letters: str = 'aeiou') -> set:
"""Returns set of 'letters' found in 'phrase'."""
return set(letters).intersection(set(phrase)) |
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n) because it can loop through all items in the list
Memory usage: O(1) Only declares a single counter variable
"""
# First item doesn't need to be checked
i = 1
# Loop through all i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.