content stringlengths 42 6.51k |
|---|
def split_number_and_unit(s):
"""Parse a string that consists of a integer number and an optional unit.
@param s a non-empty string that starts with an int and is followed by some letters
@return a triple of the number (as int) and the unit
"""
if not s:
raise ValueError("empty value")
s = s.strip()
pos = len(s)
while pos and not s[pos - 1].isdigit():
pos -= 1
number = int(s[:pos])
unit = s[pos:].strip()
return number, unit |
def all_positive(entrylist):
"""True iff all values in the list are positive"""
for x in entrylist:
if x<0:
return False
return True |
def humansize(nbytes):
"""
Copied from https://stackoverflow.com/questions/14996453/python-libraries-to-calculate-human-readable-filesize-from-bytes#14996816
"""
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
i = 0
while nbytes >= 1024 and i < len(suffixes)-1:
nbytes /= 1024.
i += 1
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
return '%s %s' % (f, suffixes[i]) |
def bps_mbps(val: float) -> float:
"""
Converts bits per second (bps) into megabits per second (mbps).
Args:
val (float): The value in bits per second to convert.
Returns:
float: Returns val in megabits per second.
Examples:
>>> bps_mbps(1000000)
1.0
>>> bps_mbps(1129000)
1.13
"""
return round(float(val) / 1000000, 2) |
def busca_sequencial(valor, lista, index):
"""Busca sequencial recursiva.
Returns:
Retorna o indice do valor na lista.
Se nao encontrar retorna -1.
"""
if len(lista) == 0 or index == len(lista):
return -1
if lista[index] == valor:
return index
return busca_sequencial(valor, lista, index + 1) |
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
"""
input_line = input_line[1:]
max_num = input_line[0]
correct_nums = 1
index = 1
while index != len(input_line) - 1:
if input_line[index] > max_num:
max_num = input_line[index]
correct_nums += 1
index += 1
if correct_nums == pivot:
return True
return False |
def bcdtodec(bcd):
"""Convert binary coded decimal to decimal"""
return ((bcd >> 4) * 10) + (bcd & 0x0F) |
def words_not_the(sentence):
"""Words not 'the'
Given a sentence, produce a list of the lengths of each word in the sentence, but only if the word is not 'the'.
>>> words_not_the('the quick brown fox jumps over the lazy dog')
[5, 5, 3, 5, 4, 4, 3]
"""
words = sentence.split()
lst = [len(a) for a in words if str(a) != 'the']
return lst
pass |
def shift(register, feedback, output):
"""GPS Shift Register
:param list feedback: which positions to use as feedback (1 indexed)
:param list output: which positions are output (1 indexed)
:returns output of shift register:
"""
# calculate output
out = [register[i-1] for i in output]
if len(out) > 1:
out = sum(out) % 2
else:
out = out[0]
# modulo 2 add feedback
fb = sum([register[i-1] for i in feedback]) % 2
# shift to the right
for i in reversed(range(len(register[1:]))):
register[i+1] = register[i]
# put feedback in position 1
register[0] = fb
return out |
def _search(text, font, deleting):
"""
>>> from fontTools.agl import AGL2UV
>>> from defcon import Font
>>> font = Font()
>>> for glyphName, value in AGL2UV.items():
... _ = font.newGlyph(glyphName)
... font[glyphName].unicodes = [value]
... _ = font.newGlyph(glyphName + ".alt")
... _ = font.newGlyph(glyphName + ".xxx")
>>> _search("e", font, False)
('e', 'e')
>>> _search("eg", font, False)
('eg', 'egrave')
>>> _search("e.", font, False)
('e.', 'e.alt')
>>> _search("eight.al", font, True)
('eight.al', 'eight')
"""
# no text
if not text:
return text, None
glyphNames = font.keys()
match = None
# direct match
if text in glyphNames:
match = text
# character entry
elif len(text) == 1:
uniValue = ord(text)
match = font.unicodeData.glyphNameForUnicode(uniValue)
if match is not None:
text = ""
# fallback. find closest match
if match is None:
glyphNames = list(sorted(glyphNames))
if not deleting:
for glyphName in glyphNames:
if glyphName.startswith(text):
match = glyphName
break
else:
matches = []
for glyphName in glyphNames:
if text.startswith(glyphName):
matches.append(glyphName)
elif match is not None:
break
diff = None
for m in matches:
d = len(m) - len(text)
if diff is None or d < diff:
match = m
return text, match |
def first_rule(board: list) -> bool:
"""
Function checks whether the colored cells
of each line contain numbers from 1 to 9 without repetition.
Returns True if this rule of the game is followed.
>>> first_rule(["**** ****","***1 ****","** 3****","* 4 1****",\
" 9 5 "," 6 83 *","3 1 **"," 8 2***"," 2 ****"])
True
"""
uniqueness = True
for row in board:
square_seen = []
for square in row:
if square.isdigit() and square in square_seen:
uniqueness = False
square_seen.append(square)
return uniqueness |
def sizeof_fmt(num):
"""
Handy formatting for human readable filesize.
From http://stackoverflow.com/a/1094933/1657047
"""
for x in ["bytes", "KB", "MB", "GB"]:
if num < 1024.0 and num > -1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0
return "%3.1f %s" % (num, "TB") |
def auto_none_days(days, points):
"""Autoincrement don't works days yet with None."""
return points + [None for _ in range(len(days) - len(points))] |
def combo_cross_breeding( parent1: list, parent2: list):
"""
This function cross breeds the two parents by joinining and combining them
...
Attributes
----------
parent1:List
features in vectorized form
parent2:List
features in vectorized form
Returns
-------
:List
new set of features resulted from randomcrossbreeding
"""
final = []
# random.seed(0)
for i in range(len(parent1)):
if parent1[i] == 0 and parent2[i] == 0:
final.append(0)
else:
final.append(1)
# first_divide=parent1[:index]
# secodn_divide=parent2[index:]
return final |
def _make_tester_for_previous(var, expr, context, strong):
"""Return temporal tester for "previous"."""
# select operator
if context == 'bool':
op = '<=>'
# strong "previous" operator "--X" ?
if strong:
init = '(~ {var})'.format(var=var)
else:
init = var
else:
raise Exception(
'unknown context: "{c}"'.format(c=context))
# translate "previous" in future LTL
trans = '((X {var}) {op} {expr})'.format(
var=var, op=op, expr=expr)
return init, trans |
def format_dict(input_dict):
"""Dict string formatter
>>> from collections import OrderedDict
>>> from pyams_utils.dict import format_dict
>>> input = {}
>>> format_dict(input)
'{}'
>>> input = OrderedDict((('key1', 'Value 1'), ('key2', 'Value 2'),))
>>> print(format_dict(input))
{
key1: Value 1
key2: Value 2
}
"""
if not input_dict:
return '{}'
return "{{\n{}\n}}".format('\n'.join((' {}: {}'.format(key, value)
for key, value in input_dict.items()))) |
def perfect_unshuffle(seq):
"""Returns a list containing the perfectly unshuffled supplied sequence SEQ, if
previously perfectly shuffled.
"""
return seq[::2] + seq[1::2] |
def check_filters(filters):
"""Checks that the filters are valid
:param filters: A string of filters
:returns: Nothing, but can modify ``filters`` in place, and raises ``ValueError``s if the filters are badly formatted.
This functions conducts minimal parsing, to make sure that the relationship exists, and that the filter is generally well formed.
The ``filters`` string is modified in place if it contains space.
"""
if not isinstance(filters, str):
raise TypeError("filters must be a string")
# We replace all spaces with %20
filters.replace(' ', '%20')
# These steps will check that the filters are correct
REL = ['startswith', 'endswith', 'exact', 'contains', 'range', 'gt', 'lt', 'gte', 'lte', 'in']
filters = filters.split('&')
for fi in filters:
if not '=' in fi:
raise ValueError("Filter "+fi+" is invalid (no =)")
if not '__' in fi:
raise ValueError("Filter "+fi+" is invalid (no __)")
splitted_filter = fi.split('=')
match = splitted_filter[0]
target = splitted_filter[1]
request = match.split('__')
relationship = request[len(request)-1]
if not relationship in REL:
raise ValueError("Filter "+fi+" is invalid ("+ relationship +" is not a valid relationship)")
if len(filters) == 1 :
return filters
else :
return '&'.join(filters) |
def get_text_list(list_, last_word='or'):
"""
>> get_text_list(['a', 'b', 'c', 'd'])
'a, b, c or d'
>> get_text_list(['a', 'b', 'c'], 'and')
'a, b and c'
>> get_text_list(['a', 'b'], 'and')
'a and b'
>> get_text_list(['a'])
'a'
>> get_text_list([])
''
"""
if len(list_) == 0:
return ''
if len(list_) == 1:
return list_[0]
return '%s %s %s' % (
# Translators: This string is used as a separator between list elements
', '.join([i for i in list_][:-1]),
last_word, list_[-1]) |
def split_variable_name(name):
"""Extracts layer name and variable name from the full variable scope."""
parts = name.split('/')
return parts[-2], parts[-1] |
def get_band_height(element):
"""
Return height the the specified element.
:param element: current jrxml element being processes.
:return:
"""
return float(element['child'][0]['band']['attr']['height']) |
def match2(g1, s, guesses_number, ans):
"""
The second and subsequence letters, user inputted, matched with the answer or not.
"""
answer1 = ""
if g1 in s:
print("You are correct!")
for k in range(len(s)):
ch3 = s[k]
ch4 = ans[k]
if ch3 == g1:
answer1 += g1
else:
answer1 += ch4
if answer1.find("-") != -1:
print("The word looks like: " + answer1)
return answer1
else:
ans = ans
guesses_number -= 1
if guesses_number == 0:
pass
else:
print("There is no " + str(g1) + "'s in the word.")
print("The word looks like: " + str(ans))
return ans |
def PatternCount(Text, Pattern):
"""Count the input patern in the text."""
Text = str(Text)
Pattern = str(Pattern)
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Text.find(Pattern, i, i + len(Pattern)) != -1:
count = count + 1
return count |
def lexical_distance(a, b):
"""
Computes the lexical distance between strings A and B.
The "distance" between two strings is given by counting the minimum number
of edits needed to transform string A into string B. An edit can be an
insertion, deletion, or substitution of a single character, or a swap of two
adjacent characters.
This distance can be useful for detecting typos in input or sorting
@returns distance in number of edits
"""
d = [[i] for i in range(len(a) + 1)] or []
d_len = len(d) or 1
for i in range(d_len):
for j in range(1, len(b) + 1):
if i == 0:
d[i].append(j)
else:
d[i].append(0)
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost)
if i > 1 and j < 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
d[i][j] = min(d[i][j], d[i - 2][j - 2] + cost)
return d[len(a)][len(b)] |
def scaled(signal, factor):
""""
scale the signal
scaling factor limit 0.2 - 2 """
scaled_signal = signal * factor
return scaled_signal |
def check_sw_status_admin(supported_nodes, output):
"""Check if a node is in OPERATIONAL status"""
lines = output.splitlines()
for line in lines:
line = line.strip()
if len(line) > 0 and line[0].isdigit():
node = line[0:10].strip()
if node in supported_nodes:
sw_status = line[48:62].strip()
if "OPERATIONAL" not in sw_status:
return False
return True |
def convert_bytes(fileSize):
"""
utility function to convert bytes into
higher size units.
Arguments:
1. fileSize: Size of the file in bytes
Result:
Returns size of file in ['bytes', 'KB', 'MB', 'GB', 'TB']
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if fileSize < 1024.0:
return "%3.1f %s" % (fileSize, x)
fileSize /= 1024.0
return fileSize |
def frange(a, b, n):
"""
kind of like a floating point range function
:param a: the start point
:param b: the end point
:param n: the number of intervals you want.
:returns: a sequence of floating point nubers, evenly spaced between
a and b
result[0] == a
result[-1] == b
len(result) == n+1
n specifies the number of intervals, so you get a nice delta. i.e.
frange(1,10,100) == [1.0, 1.1, 1.2, ..., 9.8, 9.9, 10.0]
"""
delta = (float(b) - a) / n
return [a + i*delta for i in range(n+1)] |
def selectdeclevel(freq):
"""
Calculate an appropriate SHD order for the given frequency
:param freq: Frequency (in Hz)
:return: Decomposition order
Note: This is not used since we are looking at frequencies above 2607 Hz only. Hence Nmax=4 is used
"""
if freq < 652.0:
Ndec = 1
elif freq < 1303.0:
Ndec = 2
elif freq < 2607.0:
Ndec = 3
else:
Ndec = 4
return Ndec |
def _dictionary_product(dictionary):
"""Returns a named cartesian product of dictionary's values."""
# Converts {'a': [1, 2], 'b': [3, 4]} into
# [{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}]
product = [[]]
for values in dictionary.values():
# Iteratively grow the elements of the product.
product = [element + [value] for element in product for value in values]
dicts = [{k: v for k, v in zip(dictionary, element)} for element in product]
return dicts |
def io_serdes(serial_in_p, serial_in_n,
serial_out_p, serial_out_n):
""" Vendor specific IO SERDES
"""
mod_insts = []
return mod_insts |
def calc_metric(y_true, y_pred):
"""
:param y_true: [(tuple), ...]
:param y_pred: [(tuple), ...]
:return:
"""
num_proposed = len(y_pred)
num_gold = len(y_true)
y_true_set = set(y_true)
num_correct = 0
for item in y_pred:
if item in y_true_set:
num_correct += 1
print('proposed: {}\tcorrect: {}\tgold: {}'.format(num_proposed, num_correct, num_gold))
if num_proposed != 0:
precision = num_correct / num_proposed
else:
precision = 1.0
if num_gold != 0:
recall = num_correct / num_gold
else:
recall = 1.0
if precision + recall != 0:
f1 = 2 * precision * recall / (precision + recall)
else:
f1 = 0
return precision, recall, f1 |
def check_new_items(db_info, api_info):
""" Find the number of new items on the API """
new_items = []
for item in api_info['data']:
if not any(d['case_id'] == item['id'] for d in db_info):
new_items.append(item)
return new_items |
def filterResultsByRunsetFolder(runSets, form):
"""
Filters out results that don't have the specified runsetFolder name
"""
ret = []
for runset in runSets:
if runset.runsetFolder == form['runset'].value:
ret.append(runset)
return ret |
def get_bitcode(edge_array, distinct_edge):
"""
Return bitcode of distinct_edge
"""
bitcode = ["0"] * len(edge_array)
for i, row in enumerate(edge_array):
for item in row:
if distinct_edge in item[0]:
bitcode[i] = "1"
break
return "".join(bitcode) |
def onefunction(a, b):
"""
Return the addition of ``a+b``.
Second line should be aligned.
:param a: first element
:param c: second element
:return: ``a + b``
:raises TypeError: guess
"""
if type(a) != type(b):
raise TypeError("Different type {0} != {1}".format(a, b))
return a + b |
def b(u, dfs_data):
"""The b(u) function used in the paper."""
return dfs_data['b_u_lookup'][u] |
def get_abyss_rank_mi18n(rank: int, tier: int) -> str:
"""Turn the rank returned by the API into the respective rank name displayed in-game."""
if tier == 4:
mod = ("1", "2_1", "2_2", "2_3", "3_1", "3_2", "3_3", "4", "5")[rank - 1]
else:
mod = str(rank)
return f"bbs/level{mod}" |
def single_char_xor(input_bytes, char_value):
"""Returns the result of each byte being XOR'd with a single value.
"""
output_bytes = b''
for byte in input_bytes:
output_bytes += bytes([byte ^ char_value])
return output_bytes |
def file_text(txt_or_fname: str) -> str:
"""
Determine whether text_or_fname is a file name or a string and, if a file name, read it
:param text_or_fname:
:return:
"""
if len(txt_or_fname) > 4 and '\n' not in txt_or_fname:
with open(txt_or_fname) as ef:
return ef.read()
return txt_or_fname |
def _tpu_version(index):
"""Chooses a GCP TPU version based on the index."""
if index < 100:
return 'v2-alpha', 'v2-8' # version, accelerator-type
else:
return 'v2-alpha', 'v3-8' |
def _hashable(x):
"""
Ensure that an point is hashable by a python dict.
"""
return tuple(map(float, x)) |
def cubic_ease_in(p):
"""Modeled after the cubic y = x^3"""
return p * p * p |
def prepare_target(x):
""" Encode the OS into 3 categories """
if x <= 24:
return 0
elif x <= 72:
return 1
else:
return 2 |
def _apply_inputs(config, inputs_map):
"""Update configuration with inputs
This method updates the values of the configuration parameters using values
from the inputs map.
"""
config.update(inputs_map)
return config |
def detect(source):
"""Detects if source is likely to be eval() packed."""
return source.strip().lower().startswith('eval(function(') |
def get_vf_res_scale_down(width: int, height: int, res_limit='FHD', vf: str = '') -> str:
"""generate 'scale=<w>:<h>' value for ffmpeg `vf` option, to scale down the given resolution
return empty str if the given resolution is enough low thus scaling is not needed"""
d = {'FHD': (1920, 1080), 'HD': (1280, 720), 'qHD': (960, 540), 'QHD': (2560, 1440), '4K': (3840, 2160),
'360p': (640, 360)}
auto_calc = -2
if not res_limit:
return vf
tgt_long, tgt_short = d[res_limit]
long = max((width, height))
short = min((width, height))
if long <= tgt_long and short <= tgt_short:
return vf
ratio = short / long
tgt_ratio = tgt_short / tgt_long
thin = False if ratio > tgt_ratio else True
portrait = True if height > width else False
baseline = tgt_long if thin else tgt_short
res_scale = 'scale=' + (
f'{baseline}:{auto_calc}' if thin ^ portrait
else f'{auto_calc}:{baseline}'
)
return f'{res_scale},{vf}' if vf else res_scale |
def failed(response):
"""DreamHost does not use HTTP status codes to indicate success or failure,
relying instead on a 'result' key in the response."""
try:
if response['result'] == u'success':
return False
except:
pass
return True |
def process_coin(amt, moneyIn):
"""Returns the amount of each coin"""
if moneyIn == 'quarter' or moneyIn == 'quarters':
return amt * .25
elif moneyIn == 'dime' or moneyIn == 'dimes':
return amt * .10
elif moneyIn == 'nickel' or moneyIn == 'nickels':
return amt * .05
elif moneyIn == 'penny' or moneyIn == 'pennies':
return amt * .01 |
def getKfactorsFrom(output):
"""
Read NLLfast output and return the k-factors.
"""
if not output:
return False
else:
lines = output.split('\n')
il = 0
line = lines[il]
process = False
while not "K_NLO" in line and il < len(lines) - 2:
if "process" in line:
process = line[line.find("process:") + 8:].replace(" ", "")
il += 1
line = lines[il]
if not process:
return False
# Line with header
line = lines[il]
# Count number of mass entries
nmass = line.count('GeV')
# Line with values
line = lines[il + 2]
data = [eval(x) for x in line.split()]
if len(data) != nmass + 11:
return False
else:
kFacs = data[9 + nmass:]
return kFacs |
def aggregation(item1, item2):
"""
For an (airport, counters) item, perform summary aggregations.
"""
count1, total1, squares1, min1, max1 = item1
count2, total2, squares2, min2, max2 = item2
minimum = min((min1, min2))
maximum = max((max1, max2))
count = count1 + count2
total = total1 + total2
squares = squares1 + squares2
return (count, total, squares, minimum, maximum) |
def template_substitute(text, **kwargs):
"""
Replace placeholders in text by using the data mapping.
Other placeholders that is not represented by data is left untouched.
:param text: Text to search and replace placeholders.
:param data: Data mapping/dict for placeholder key and values.
:return: Potentially modified text with replaced placeholders.
"""
for name, value in kwargs.items():
placeholder_pattern = "{%s}" % name
if placeholder_pattern in text:
text = text.replace(placeholder_pattern, value)
return text |
def len_selfies(selfies: str) -> int:
"""Returns the number of symbols in a given SELFIES string.
:param selfies: a SELFIES string.
:return: the symbol length of the SELFIES string.
:Example:
>>> import selfies as sf
>>> sf.len_selfies("[C][=C][F].[C]")
5
"""
return selfies.count("[") + selfies.count(".") |
def update_deviation(player_ratings, deviation_factors=None):
"""
:param player_ratings: The previous rating period's data. The key must
be hashable and uniquely identify a player.
The dictionary and its values are not modified by this function.
:type player_ratings: dict[Any, Rating]
:param deviation_factors: Each player's inactivity factor. The key must
be hashable and uniquely identify a player.
A player that is not present in this dictionary is considered to have a
factor of 1.0 (completely inactive).
The dictionary and its values are not modified by this function.
:type deviation_factors: dict[Any, float]
:return: A new rating dictionary with updated deviations.
:rtype: dict[Any, Rating]
"""
deviation_factors = deviation_factors or dict()
player_ratings = {p: r.clone() for p, r in player_ratings.items()}
for player, rating in player_ratings.items():
factor = deviation_factors.get(player, 1.0)
rating.update_deviation(factor)
return player_ratings |
def get_atom_list(line):
"""
splits the number from the atom
a\\a o1 c2 c3 c4 o5 h6 h7 h8 h9
-> [O, C, C, C, O, H, H, H, H]
"""
line = line.split()[1:]
atoms = []
for a in line:
atom = ''
num = ''
for b in a:
if b.isdigit():
num += b
else:
atom += b
atoms.append(atom.capitalize())
return atoms |
def strip_special_characters(some_string):
"""Remove all special characters, punctuation, and spaces from a string"""
# Input: "Special $#! characters spaces 888323"
# Output: 'Specialcharactersspaces888323'
result = ''.join(e for e in some_string if e.isalnum())
return result |
def attributify(numeral: str) -> str:
"""Returns the numeral string argument as a valid attribute name."""
return numeral.replace(" ", "").replace("-", "") |
def parseBool(value):
"""
Parse a boolean, which in FIX is either a single 'Y' or 'N'.
:param value: the tag value (should be 1 character)
:return: bool
"""
if value == 'Y':
return True
elif value == 'N':
return False
else:
raise ValueError('FIX boolean values must be Y or N (got %s)' % value) |
def gcd(m, n):
"""(int, int) -> int
Uses Euclid's method to compute the greatest common factor
(greatest common divisor) of two integers, <m> and <n>
Returns greatest common factor (gcd) of the two integers
"""
if n == 0:
result = m
else:
result = gcd(n, m % n)
return result |
def p_to_r(p, d, rtype='EI'):
"""
Converts an RB decay constant (`p`) to the RB error rate (`r`).
Here `p` is (normally) obtained from fitting data to `A + Bp^m`. There are two
'types' of RB error rate corresponding to different rescalings of `1 - p`.
These are the entanglement infidelity (EI) type r and the average gate
infidelity (AGI) type `r`. The EI-type `r` is given by:
`r = (d^2 - 1)(1 - p)/d^2`,
where `d` is the dimension of the system (i.e., 2^n for n qubits).
The AGI-type `r` is given by
`r = (d - 1)(1 - p)/d`.
For RB on gates whereby every gate is followed by an n-qubit
uniform depolarizing channel (the most idealized RB scenario)
then the EI-type (AGI-type) r corresponds to the EI (AGI) of
the depolarizing channel to the identity channel.
The default (EI) is the convention used in direct RB, and is perhaps
the most well-motivated as then r corresponds to the error probablity
of the gates (in the idealized pauli-errors scenario). AGI is
the convention used throughout Clifford RB theory.
Parameters
----------
p : float
Fit parameter p from P_m = A + B*p**m.
d : int
Number of dimensions of the Hilbert space
rtype : {'EI','AGI'}, optional
The RB error rate rescaling convention.
Returns
-------
r : float
The RB error rate
"""
if rtype == 'AGI': r = (1 - p) * (d - 1) / d
elif rtype == 'EI': r = (d**2 - 1) * (1 - p) / d**2
else:
raise ValueError("rtype must be `EI` (for entanglement infidelity) or `AGI` (for average gate infidelity)")
return r |
def _InvokeMember(obj, membername, *args, **kwargs):
"""Retrieves a member of an object, then calls it with the provided arguments.
Args:
obj: The object to operate on.
membername: The name of the member to retrieve from ojb.
*args: Positional arguments to pass to the method.
**kwargs: Keyword arguments to pass to the method.
Returns:
The return value of the method invocation.
"""
return getattr(obj, membername)(*args, **kwargs) |
def dict_to_item_list(table):
"""Given a Python dictionary, convert to sorted item list.
Parameters
----------
table : dict[str, any]
a Python dictionary where the keys are strings.
Returns
-------
assoc_list : list[(str, str)]
the sorted item list representation of the given dictionary.
"""
return [[key, table[key]] for key in sorted(table.keys())] |
def get_distributive_name() -> str:
"""Try to obtain distributive name from /etc/lsb-release"""
try:
with open('/etc/lsb-release', mode='r', encoding='utf-8') as file:
for line in file:
if line.startswith('DISTRIB_ID'):
parts = line.split('=')
if len(parts) > 1:
return parts[1].strip()
except OSError:
pass
return '' |
def next_power_of_two(x):
""""Next Largest Power of 2
Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm
that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with
the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next
largest power of 2."""
x=int(x)
x = x | (x >> 1)
x = x | (x >> 2)
x = x | (x >> 4)
x = x | (x >> 8)
x = x | (x >> 16)
return x+1 |
def get_num_processes(profileDict):
"""
Returns the number of processes used in the given profile
Args:
profileDict (dict): Dictionary of the JSON format of a MAP profile
Returns:
Number of processes used in the profile passed in
"""
assert isinstance(profileDict, dict)
return profileDict["info"]["number_of_processes"] |
def reduce_nums(val_1, val_2, val_op):
"""
Apply arithmetic rules to compute a result
:param val1: input parameter
:type val1: int or string
:param val2: input parameter
:type val2: int or string
:param val_op: C operator in *+*, */*, *-*, etc
:type val_op: string
:rtype: int
"""
#print val_1, val_2, val_op
# now perform the operation, make certain a and b are numeric
try: a = 0 + val_1
except TypeError: a = int(val_1)
try: b = 0 + val_2
except TypeError: b = int(val_2)
d = val_op
if d == '%': c = a%b
elif d=='+': c = a+b
elif d=='-': c = a-b
elif d=='*': c = a*b
elif d=='/': c = a/b
elif d=='^': c = a^b
elif d=='|': c = a|b
elif d=='||': c = int(a or b)
elif d=='&': c = a&b
elif d=='&&': c = int(a and b)
elif d=='==': c = int(a == b)
elif d=='!=': c = int(a != b)
elif d=='<=': c = int(a <= b)
elif d=='<': c = int(a < b)
elif d=='>': c = int(a > b)
elif d=='>=': c = int(a >= b)
elif d=='^': c = int(a^b)
elif d=='<<': c = a<<b
elif d=='>>': c = a>>b
else: c = 0
return c |
def helper(n, best):
"""
:param n: int, the number we need to find the the biggest digit.
:param best: int, currently biggest digit.
:return: int, the biggest digit.
"""
if n < 0: # if the number is negative number, change it to positive.
n = -n
if n < 10:
if best != 0:
return best
else:
return n # if the first input number is less than 10, return it directly.
else:
if best == 0:
standard = n % 10
else:
standard = best
next_value = n // 10
second_last = next_value % 10
if second_last < standard:
best = standard
else:
best = second_last
return helper(next_value, best) |
def squared_error(label, prediction):
"""Calculates the squared error for a single prediction."""
return float((label - prediction)**2) |
def get_latitude_and_longitude_list(all_places):
"""Return list of dictionaries containing latitude and longitude of all places"""
places_list = []
for place in all_places:
temp_dict = {}
temp_dict['latitude'] = float(place.latitude)
temp_dict['longitude'] = float(place.longitude)
places_list.append(temp_dict)
return places_list |
def vol_cone(area_of_base: float, height: float) -> float:
"""
Calculate the Volume of a Cone.
Wikipedia reference: https://en.wikipedia.org/wiki/Cone
:return (1/3) * area_of_base * height
>>> vol_cone(10, 3)
10.0
>>> vol_cone(1, 1)
0.3333333333333333
"""
return area_of_base * height / 3.0 |
def xss_strip_all_tags(s):
"""
Strips out all HTML.
"""
return s
def fixup(m):
text = m.group(0)
if text[:1] == "<":
return "" # ignore tags
if text[:2] == "&#":
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
elif text[:1] == "&":
import htmlentitydefs
entity = htmlentitydefs.entitydefs.get(text[1:-1])
if entity:
if entity[:2] == "&#":
try:
return unichr(int(entity[2:-1]))
except ValueError:
pass
else:
return unicode(entity, "iso-8859-1")
return text # leave as is
return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, s) |
def calc_tnr(tn: float, fp: float) -> float:
"""
:param tn: true negative or correct rejection
:param fp: false positive or false alarm
:return: true negative rate
"""
try:
calc = tn / (tn + fp)
except ZeroDivisionError:
calc = 0
return calc |
def hex_to_rgb(h):
"""Converts a "#rrbbgg" string to a (red, green, blue) tuple.
Args:
h: a hex string
Returns:
an R, G, B tuple
"""
h = h.lstrip("#")
return tuple(int(h[i : i + 2], 16) for i in (0, 2, 4)) |
def mag_to_flux(mag, mag_zp):
"""
Returns total flux of the integrated profile, units relative to mag_zp
"""
return 10 ** (-0.4 * (mag - mag_zp)) |
def is_eof(data):
"""check for eof indication in data"""
return data[0] == 254 |
def decode_pdb_address(addr, aliases=[]):
"""Decodes Ax-By-z or x/y/z into PDB address, bank number, and output
number.
Raises a ValueError exception if it is not a PDB address, otherwise returns
a tuple of (addr, bank, number).
"""
for alias in aliases:
if alias.matches(addr):
addr = alias.decode(addr)
break
if '-' in addr: # Ax-By-z form
params = addr.rsplit('-')
if len(params) != 3:
raise ValueError('pdb address must have 3 components')
board = int(params[0][1:])
bank = int(params[1][1:])
output = int(params[2][0:])
return (board, bank, output)
elif '/' in addr: # x/y/z form
params = addr.rsplit('/')
if len(params) != 3:
raise ValueError('pdb address must have 3 components')
board = int(params[0])
bank = int(params[1])
output = int(params[2])
return (board, bank, output)
else:
raise ValueError('PDB address delimeter (- or /) not found.') |
def comma_formatter(x, pos):
"""Return tick label for Indian-style comma delimited numbers."""
x = str(int(x))
result = x[-3:]
i = len(x) - 3
while i > 0:
i -= 2
j = i + 2
if i < 0: i = 0
result = x[i:j] + ',' + result
return result |
def fibonacci(n):
"""Find nth fibonacci number using recursive algorithm.
input: n (int) n for nth fibonacci number
returns: (int) representing value of nth fib number
"""
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2) |
def num_atoms_in_shell(shell: int) -> int:
"""Calculates number of atoms in a magic number NP shell
- icosahedron shells
- cuboctahedron shells
- elongated-pentagonal-bipyramid shells
"""
if shell == 0:
return 1
return 10 * (shell + 1) * (shell - 1) + 12 |
def _req_input_to_args(req_input):
"""
Given a list of the required inputs for the build command, create an args
string
:param list[str] req_input: input names
:return str: args string
"""
return ["--" + x + " <arg_here>" for x in req_input] |
def remove_non_class_entries(entries):
"""
Removes entries that do not end with `.class`.
:param entries: dict of zip file entry name to the list of entry names inside that
nested zip file
:return: entries without files that do not end with `.class`
"""
new_entries = {}
for entry_name in entries.keys():
new_nested_entries = []
for nested_entry in entries[entry_name]:
if nested_entry[-6:] == '.class':
new_nested_entries.append(nested_entry)
new_entries[entry_name] = new_nested_entries
return new_entries |
def filter_data(lines):
"""
Filter out lines that are too short or too long.
"""
return [line for line in lines if len(line) >= 8 and len(line) <= 60] |
def find_str(find_exp, where):
"""find_exp is present in buffer where"""
for item in where:
if find_exp in str(item):
return True
return False |
def check_parens(str):
"""
check_parens takes a string and:
returns 0 if the number of parentheses is balanced and matched.
returns 1 if more left parentheses than right.
returns -1 if string has broken (unmatched) parentheses.
"""
counter = 0
for i in range(len(str)):
# if loop encounters (, counter is incremented
if str[i] == '(':
counter += 1
# else if loop encounters ), decrement counter
elif str[i] == ')':
if counter == 0:
return -1
else:
counter -= 1
# after going through str looking for parentheses, if counter still
# positive, we have too many (, but if counter 0 we have balanced parens.
if counter > 0:
return 1
elif counter == 0:
return 0 |
def check_special_characters(string):
"""
Check if string has the target special character.
Return True if unwanted character is in the string.
"""
check = ["[", "@", "_", "!", "#", "$", "%", "^", "&", "*", "(", ")", "<", ">",
"?", "/", "\\", "|", "}", "{", "~", ":", "]", "'"]
return any(ext in string for ext in check) |
def validateFilenameGmv(value):
"""
Validate filename.
"""
if 0 == len(value):
raise ValueError("Filename for LaGriT input mesh not specified.")
return value |
def remove_punctuation(string: str) -> str:
"""
Removes all non-letter, non-space characters from a string
:param string: a string
:return: a string containing only letters and spaces
"""
return ''.join([c for c in string if c.isalpha() or c.isspace()]) |
def get_primary_registry_uid(service_uid):
"""Return the primary registry uid of the service with
passed service_uid.
"""
try:
root = service_uid.split("-")[0]
return "%s-%s" % (root, root)
except:
return "a0-a0" |
def f_to_t(f: float) -> float:
"""
Convertrs frequency to time.
:param f: Frequency in uHz
:return: Time in seconds
"""
return 10 ** 6 / f |
def is_empty(value):
"""
"""
if value is None:
return True
return value in ['', [], {}] |
def replace_all(buffer, replacements):
"""Substitute multiple replacement values into a buffer.
Replacements is a list of (start, end, value) triples.
"""
result = bytearray()
prev = 0
offset = 0
for u, v, r in replacements:
result.extend(buffer[prev:u])
result.extend(r)
prev = v
offset += len(r) - (v - u)
result.extend(buffer[prev:])
assert len(result) == len(buffer) + offset
return bytes(result) |
def in_bounds(x, y, margin, maxx, maxy):
"""Returns True if (x,y) is within the rectangle (margin,margin,maxx-margin,maxy-margin)."""
return margin <= x < (maxx - margin) and margin <= y < (maxy - margin) |
def rotate_inplace(matrix):
"""Performs the same task as above, in constant space complexity.
:type matrix: List[List[int]]
:rtype: None
"""
# useful constants
NUM_ROWS, NUM_COLS = len(matrix), len(matrix[0])
# A: Reverse the rows in the Matrix
row_index_start, row_index_end = 0, NUM_ROWS - 1
while row_index_start < row_index_end:
# swap rows around the middle row, or until the indicies overlap
matrix[row_index_start], matrix[row_index_end] = (
matrix[row_index_end],
matrix[row_index_start],
)
# move the indices
row_index_start += 1
row_index_end -= 1
# B: Swap elements along the left-right, up-down diagonal
for diagonal_index in range(NUM_ROWS):
# index the elements to swap around the diagonal element
for swap_elem in range(diagonal_index + 1):
# index the elements to swap
next_to_diagonal = matrix[diagonal_index][diagonal_index - swap_elem]
above_diagonal = matrix[diagonal_index - swap_elem][diagonal_index]
# make the swap
matrix[diagonal_index][diagonal_index - swap_elem] = above_diagonal
matrix[diagonal_index - swap_elem][diagonal_index] = next_to_diagonal
print(matrix)
return None |
def OR(condition_1, condition_2):
"""Evaluates both conditions and returns True or False depending on how both conditions are evaluated.
Parameters
----------
condition_1 : condition that evaluates to True or False
condition that will return True or False
condition_2 : condition that evaluates to True or False
condition that will return True or False
Returns
-------
boolean
True if one or both conditions are True, False otherwise
"""
if(type(condition_1) == bool):
if(type(condition_2) == bool):
return(condition_1 or condition_2)
else:
print('Invalid type: second condition does not evaluate to True or False.')
else:
print('Invalid type: first condition does not evaluate to True or False.') |
def gen_include_exclude_sets(include_filename, exclude_filename):
"""
generate an include and an exclude set of indicators by
reading indicators from a flat, newline-delimited file
"""
include = set()
exclude = set()
if include_filename:
for indicator in open(include_filename).readlines():
include.add(indicator.strip())
if exclude_filename:
for indicator in open(exclude_filename).readlines():
exclude.add(indicator.strip())
return include, exclude |
def shared_length(a, *args) -> int:
"""
Returns the shared length between arguments if the length identical.
>>> shared_length([1,1,1], [2,2,2], [3,3,3])
3
>>> shared_length(np.array([1]), np.array([2]))
1
>>> shared_length((1, 1), [2, 2])
2
>>> shared_length((1, 1), (2, 2))
2
>>> shared_length((1, 2), (1, 2, 3))
Traceback (most recent call last):
Exception: lengths of (1, 2) and (1, 2, 3) differ: 2 != 3
"""
na = len(a)
for arg in args:
nb = len(arg)
if na != nb:
raise Exception(f"lengths of {a} and {arg} differ: {na} != {nb}")
return na |
def find_factors(n):
"""
Finds a list of factors of a number
"""
factList = {1, n}
for i in range(2, int(n ** 0.5) + 1):
if (n % i == 0):
factList.add(i)
factList.add(n // i)
return sorted(factList) |
def f2x(x):
"""function is only used for testing purposes"""
return( 2*x ) |
def canonical_message_builder(content, fmt):
"""Builds the canonical message to be verified.
Sorts the fields as a requirement from AWS
Args:
content (dict): Parsed body of the response
fmt (list): List of the fields that need to go into the message
Returns (str):
canonical message
"""
m = ""
for field in sorted(fmt):
try:
m += field + "\n" + content[field] + "\n"
except KeyError:
# Build with what you have
pass
return str(m) |
def any_key_from_list_in_dict(test_list, test_dict):
"""
Takes a list and a dictionary and checks if any of the keys from the list are
present in the dict. Raises a KeyError with the key if found, returns False
otherwise.
"""
for key in test_list:
if key in test_dict:
raise KeyError(key)
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.