content stringlengths 42 6.51k |
|---|
def tree_structure(n):
"""
Return structure of binary tree using parentheses to show nodes with left/right subtrees.
"""
if n is None:
return ''
return '({},{},{})'.format(n.value, tree_structure(n.left), tree_structure(n.right)) |
def to_tuple(values):
"""Combine values."""
return (values,) if isinstance(values, (str, bytes)) else tuple(values) |
def _one_both_open(x, y, c=None, l=None):
"""convert coordinates to zero-based, both strand, open/closed coordinates.
Parameters are from, to, is_positive_strand, length of contig.
"""
return x - 1, y - 1 |
def compare_rot(ref, qry):
"""Compare circular DNA.
"""
if len(ref) != len(qry):
raise Exception('%d != %d' %(len(ref), len(qry)))
for i in range(len(ref)):
rot = ref[i:] + ref[:i]
if rot == qry:
return i
raise Exception('no match') |
def process_results(results):
"""
Convert n digit binary result from the QVM to a value on a die.
"""
raw_results = results[0]
processing_result = 0
for each_qubit_measurement in raw_results:
processing_result = 2 * processing_result + each_qubit_measurement
# Convert from 0 indexed ... |
def verb_check(tag):
"""
:param tag: a string representing a POS-TAG
:return: boolean if the given tag belongs to the verb class
"""
return tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] |
def watch(object, watchedspec):
"""Wrap object with a wrapper class (like watchedlist).
watchedspec is either None or a callable (like watchedlist), or
a 2-tuple of (callable, local_var_names), where local_var_names
can be a string or a sequence of strings."""
if not watchedspec:
return obje... |
def is_iterable(test):
"""is_iterable."""
if hasattr(test, '__iter__'):
return True
else:
return False |
def merge(source, destination):
"""Merge source into destination.
Values from source override those of destination"""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = destination.setdefault(key, {})
merge(value, node)
... |
def create_vector_clock(node_id, timeout):
"""This method builds the initial vector clock for a new key.
Parameters
----------
node_id : int
the id of one node in the cluster
timeout : int
the expire timeout of the key
Returns
-------
dict
the vector clock as di... |
def Choose(index, *args):
"""Choose from a list of options
If the index is out of range then we return None. The list is
indexed from 1.
"""
if index <= 0:
return None
try:
return args[index - 1]
except IndexError:
return None |
def direction_string_cleaner(record):
"""
Pandas Helper Function to clean a record in the "direction" column.
Args:
record (str): Strings in "direction" column.
Returns:
str: Cleaned string.
"""
if "eastbound" in str(record):
return "eastbound"
elif "northbound" in ... |
def getFilename(subject_data):
"""
Given the subject_data field from a row of one of our SpaceFluff dataframes, extract the name of the object being classified
by extracting the 'Filename'|'image'|'IMAGE' field".
To be used with df[column].apply()
@returns {string} filename of the object being cla... |
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (red << 16)| (green << 8) | bl... |
def findWithPattern(mystr, startPattern, endPattern):
"""
Find the string that starts with <startPattern> and ends with <endPattern> in the orginal string <mystr>.
Args:
+ mystr: orginal string.
+ startPattern:
+ endPattern:
Returns:
+ The found string,
+ and th... |
def format_equivariance_error(errors: dict) -> str:
"""Format the dictionary returned by ``equivariance_error`` into a readable string.
Parameters
----------
errors : dict
A dictionary of errors returned by ``equivariance_error``.
Returns
-------
A string.
"""
ret... |
def linear_search(l, item):
"""
Liner Search Implementation.
Time O(n) run.
O(1) space complexity, finds in place.
:param l: A List
:param item: Item from the List or N/a (-1).
:return:the founded index of the wanted item.
"""
for i in range(len(l)):
if item == l[i]:
... |
def strip_out_internal_stats(record, stats_text):
"""Delete lines with internal query statistics."""
delete = 0
lines = record.split('\n')
for i, line in enumerate(lines):
if stats_text in line:
delete = i
break
if delete:
lines = lines[:delete]
return '\n... |
def filter_new_cons(packet):
"""
filter packets by there tcp-state and
returns codes for specific states
"""
flags = []
TCP_FIN = 0x01
TCP_SYN = 0x02
TCP_RST = 0x04
TCP_PSH = 0x08
TCP_ACK = 0x10
TCP_URG = 0x20
TCP_ECE = 0x40
TCP_CWK = 0x80
if packet["tcp"]["flags... |
def limits(num1, num2, result, N, plus_or_minus, mid_or_last_sol='', last_lower=-1, last_upper=-1,
sol1=0, sol2=0, sol3=0, current_min=0, flag_solved=0):
"""
This function gets:
:param remove_or_add: remove / add matchsticks
:param num1: 1st operand - input
:param num2: 2nd operand ... |
def kv_tuple_list(d):
"""
Transforms a dict into a list of (key, val) tuples.
This tuple_list can recover the original dict by doing dict(tuple_list)
:param d: dict {a: aa, b: bb, etc.}
:return: list of tuples [(a, aa), (b, bb), etc.]
Example:
>>> n = 100
>>> d = {k: v for k, v in zip(r... |
def merge_dicts(first, second):
"""Merges two dictionaries and errors if keys are the same."""
for key in first:
if key in second:
raise KeyError('Matching keys in dicts trying to be merged.')
merged = first.copy()
merged.update(second)
return merged |
def moeda(num, moeda: str = 'R$'):
"""
:type num: float
:type moeda: str
"""
return f'{moeda}{num:.2f}'.replace('.', ',') |
def product(window1, window2):
"""Returns the product of two windows.
:param window1: a :class:`numpy.ndarray` of shape (``n``,) or ``None``.
:param window2: a :class:`numpy.ndarray` of shape (``n``,) or ``None``.
:returns: the product of the two windows. If one of the windows is equal to
``Non... |
def _deep_annotate(element, annotations, exclude=None):
"""Deep copy the given ClauseElement, annotating each element
with the given annotations dictionary.
Elements within the exclude collection will be cloned but not annotated.
"""
def clone(elem):
if exclude and \
ha... |
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0 # Define i
j = 1 # Define j
n = n - 1 # Define n
while n >= 0: # while n is greater than or equal to 0
i, j = j, i + j
n = n - 1
return i |
def __galois_multiply(a, b):
"""Multiplication in GF(2^8), taken from https://en.wikipedia.org/wiki/Finite_field_arithmetic#C_programming_example"""
result = 0
while a != 0 and b != 0:
if b & 0x01:
result ^= a
if a & 0x80 != 0:
a = (a << 1) ^ 0x11b
else:
... |
def fib2(n):
"""return the Fibonacci series up to n.
:param n: an input argument
:returns: the Fibonacci series up to n
"""
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result |
def modulardiv(a, b, p):
"""
--------------
Modular Multiplicative Inverse
--------------
"""
return (a * pow(b, p-2, p)) % p |
def _format_collider_string(colliders):
""" Write the string for the bath gas collider and their efficiencies
for the Lindemann and Troe functional expressions:
:param colliders:
:type colliders: list(str)
:return: collider_str: ChemKin-format string with colliders
:rtype: s... |
def sort_list(list):
"""Sort the values of a nested list"""
sorted_list = []
for row in range(len(list)):
new_row = sorted(list[row])
sorted_list.append(new_row)
return sorted_list |
def check_permutation(permutation):
"""Verify that a tuple of permutation image points ``(sigma(1), sigma(2),
..., sigma(n))`` is a valid permutation, i.e. each number from 0 and n-1
occurs exactly once. I.e. the following **set**-equality must hold:
``{sigma(1), sigma(2), ..., sigma(n)} == {0, 1, ... |
def pad_after(s, n, c):
"""Pad s by appending n bytes of c."""
return s + (c * n)[:n - len(s)] if len(s) < n else s |
def get_int_param(request, param, default=None):
""" @return Numerical value of named parameter. """
try:
return int(request.params[param])
except:
return default |
def get_timestamp(milliseconds):
"""
Generates timestamp for an amount of milliseconds
Parameters
----------
milliseconds : int
Time in milliseconds
Returns
-------
str
Timestamp (in format H:M:S.milli)
"""
hours = int(milliseconds / (60 * 60 * 1000))
millis... |
def unlabel_rgb(colors):
"""
Takes rgb color(s) 'rgb(a, b, c)' and returns tuple(s) (a, b, c)
This function takes either an 'rgb(a, b, c)' color or a list of
such colors and returns the color tuples in tuple(s) (a, b, c)
"""
str_vals = ''
for index in range(len(colors)):
try:
... |
def substring_index(l, substr):
"""
select index of substring substr in list l
"""
index = [idx for idx, s in enumerate(l) if substr in s]
return index |
def celciusToRankie(celcius:float, ndigits: int = 2)->float:
"""
Convert a given value from Celsius to Rankine and round it to 2 decimal places.
Wikipedia reference: https://en.wikipedia.org/wiki/Celsius
Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale
"""
return round((float(cel... |
def create_slack_attachment(fallback,
color=None,
pretext=None,
author_name=None,
author_link=None,
author_icon=None,
title=None,
... |
def convert_currency_to_float(dollar_amt):
"""
Converts a US dollar string to a float
:param dollar_amt string:
:return float:
"""
# check if dollar_amt is a string
if not isinstance(dollar_amt, str):
raise TypeError('dollar_amt is not a string')
# removes $ at the beginning of ... |
def summarizeHar(har):
"""Given a har file (parsed json object), returns total size of all responses, in bytes."""
return sum((entry["response"]["content"]["size"] for entry in har["log"]["entries"])) |
def format_whitelist(line):
"""
Ensure whitelist is a list if it contains commas.
"""
_, whitelist = line.split(":", maxsplit=1)
if "," in whitelist:
whitelist = [_.strip() for _ in whitelist.split(",")]
else:
whitelist = [whitelist.strip()]
return whitelist |
def get_editconf_translate_args(from_path, to_path, shift):
"""Create cmd command to translate a configuration."""
return [
'gmx', 'editconf',
'-f', from_path,
'-o', to_path,
'-translate', '0', '0', str(shift),
'-quiet',
] |
def validate_int_to_str(x):
"""
Backward compatibility - field was int and now str.
Property: AutoScalingGroup.MaxSize
Property: AutoScalingGroup.MinSize
"""
if isinstance(x, int):
return str(x)
if isinstance(x, str):
return str(int(x))
raise TypeError(f"Value {x} of ty... |
def get_delim(delim):
"""
manage special conversions for difficult bash characters
"""
if delim == "newline":
delim = "\n"
elif delim == "tab":
delim = "\t"
elif delim == "space":
delim = " "
return delim |
def rreplace(s, old, new, occurrence):
"""Convenience function from:
https://stackoverflow.com/questions/2556108/\
rreplace-how-to-replace-the-last-occurrence-of-an-expression-in-a-string
"""
li = s.rsplit(old, occurrence)
return new.join(li) |
def checksum(spreadsheet):
"""
Calculate the checksum of a spreadsheet by summing up the ranges of all
lines.
>>> checksum([
... [5, 1, 9, 5],
... [7, 5, 3],
... [2, 4, 6, 8]
... ])
18
"""
return sum(
max(line) - min(line)
for line in spreadsheet
... |
def plural(n):
"""Utility function to optionally pluralize words based on the value of n.
"""
if n == 1:
return ''
else:
return 's' |
def flatten(d, pre = '', sep = '_'):
"""Flatten a dict (i.e. dict['a']['b']['c'] => dict['a_b_c'])"""
new_d = {}
for k,v in d.items():
if type(v) == dict:
new_d.update(flatten(d[k], '%s%s%s' % (pre, k, sep)))
else:
new_d['%s%s' % (pre, k)] = v
return new_d |
def f(B, x):
"""A linear function for the ODR."""
return B*(x) |
def map_data_values_to_header(header, line):
"""
Maps data values in 'line' to the column headers.
"""
data = dict(zip(header, list(map(str.strip, line.split("\t")))))
return data |
def contains(dataset, example):
"""
Returns if dataset contains the example.
:param dataset:
:param example:
:return: True or False depending on whether dataset contains the example.
"""
for x in dataset:
if all(x == example):
return True
return False |
def metade(p=0):
"""
-> Divide o valor inicial
:param p: valor inicial
:return: valor dividido pela metade
"""
res = p / 2
return res |
def layer(project, param, url):
"""a layer description for the tilemill project file."""
return {
"geometry": "point",
"extent": [-158, -33.866669, 178.08837900000003, 70.110481],
"id": project,
"class": "",
"Datasource": {
"file": url,
"id": proje... |
def pgcd(a, b):
"""
return the best page size for a given limited query
:param a: the start offset
:param b: the end offset
:return:
>>> pgcd(30, 40)
10
>>> pgcd(7, 13)
1
"""
while a % b != 0:
a, b = b, a % b
return b |
def calc_idf(docs):
"""Calculates the idf scores based on the corpus"""
terms = set()
for doc in docs:
for term in doc:
terms.add(term)
idf = {}
for term in terms:
term_count = 0
doc_count = 0
for doc in docs:
doc_count += 1
... |
def progress_report(
curr, best, curr_score, best_score, step, totalsteps, accept, improv, elaps, remain
):
"""Report progress"""
text = """
Current Formula {curr} (hist distance {curr_score})
Best Formula {best} (hist distance {best_score})
Step {step} of {totalsteps}
Acceptance Rate : {accept... |
def hook_index(n: int, t: int) -> int:
"""For integers n and t, finds the largest number not greater than n such that the binary
representation of n has exactly t zeros."""
d = 1 << t
r = n & ~(d - 1) # zero the last t bits of n
if n & d != 0:
return r
else:
return (r - 1) & ~(d... |
def to_numeric(arg):
"""
Converts a string either to int or to float.
This is important, because e.g. {"!==": [{"+": "0"}, 0.0]}
"""
if isinstance(arg, str):
if '.' in arg:
return float(arg)
else:
return int(arg)
return arg |
def _strip(string):
"""
Removes unicode characters in string.
"""
return "".join([val for val in string if 31 < ord(val) < 127]) |
def student_ranking(student_scores, student_names):
"""
:param student_scores: list of scores in descending order.
:param student_names: list of names in descending order by exam score.
:return: list of strings in format ["<rank>. <student name>: <score>"].
"""
output = []
counter = 1
fo... |
def fry(word):
"""Drop the `g` from `-ing` words, change `you` to `y'all`"""
if word.lower() == 'you':
return word[0] + "'all"
if word.endswith('ing'):
if any(map(lambda c: c.lower() in 'aeiouy', word[:-3])):
return word[:-1] + "'"
else:
return word
ret... |
def gcd(x, y):
"""Find the Greatest Common Devisor (GCD) of the two given integers.
Args:
x (int): some integer
y (int): another integer
Return Value:
The greatest common devisor of the two integers.
"""
while(y):
x, y = y, x % y
return x |
def hex_to_rgb(value):
"""In: hex(#ffffff). Out: tuple(255, 255, 255)"""
value = value.lstrip("#")
rgb = tuple(int(value[i : i + 2], 16) for i in (0, 2, 4))
return rgb |
def make_backreference(namespace, elemid):
"""Create a backreference string.
namespace -- The OSM namespace for the element.
elemid -- Element ID in the namespace.
"""
return namespace[0].upper() + elemid |
def iterable(obj):
"""Check if object is iterable"""
try: iter(obj)
except Exception: return False
else: return True |
def mac_to_bytes(addr):
""" Covert Mac address to a bytes. """
if (isinstance(addr, bytes)):
addr = addr.decode()
val = [int(v, 16) for v in addr.encode("utf-8").decode().split(':')]
return bytearray(val) |
def reduce_centers(a, b):
"""
Reduce method to sum the result of two partial_sum methods
:param a: partial_sum {cluster_ind: (#points_a, sum(points_a))}
:param b: partial_sum {cluster_ind: (#points_b, sum(points_b))}
:return: {cluster_ind: (#points_a+#points_b, sum(points_a+points_b))}
"""
... |
def list_to_element(listobj):
""" Get the singleton list element.
<process>
<return name="element" type="Any" desc="the returned
list single element."/>
<input name="listobj" type="List_Any" desc="an input singleton list."/>
</process>
"""
# Check that we have a singleto... |
def Uunbalance_calc(ua,ub,uc):
"""Calculate voltage/current unbalance."""
uavg = (ua + ub + uc)/3
return (max(ua,ub,uc) - min(ua,ub,uc))/uavg |
def convert_inf(x):
"""The tqdm doesn't support inf values. We have to convert it to None."""
if x == float("inf"):
return None
return x |
def char_collect(s, f, c):
"""
Find char from position
:param s: haystack
:param f: starting position
:param c: needle
:return: char index or None if not found
"""
try: res = s[f:].index(c) + f
except: res = None
return res |
def double_layer_cover_transmission_coefficient(tau_1, tau_2, rho_1, rho_2) -> float:
"""
The transmission coefficient of a double layer cover
Equation 8.14
:param float tau_1: the transmission coefficients of the first layer
:param float tau_2: the transmission coefficients of the second layer
... |
def get_accuracy(actual=None, predicted=None):
"""Computes accuracy, done with strings"""
if predicted == actual:
return 1.0
else:
return 0.0 |
def url(address):
"""Sanitize url.
Converts address to valid HTTP url.
"""
if address.startswith("http://") or address.startswith("https://"):
return address
else:
return "http://{}".format(address) |
def _calculate_compliance(results):
"""
Calculate compliance numbers given the results of audits
"""
success = len(results.get('Success', []))
failure = len(results.get('Failure', []))
control = len(results.get('Controlled', []))
total_audits = success + failure + control
if total_audit... |
def linearSearch(data:list, item):
"""
Algoritmo de busca linear.
"""
for k, v in enumerate(data):
if v == item:
return(k)
return(-1) |
def map_hostname_info(hostname, nmap_store):
"""Map hostname if there is one to the database record."""
if hostname is not None:
nmap_store["hostname"] = hostname.get('name')
return nmap_store
nmap_store["hostname"] = None
return nmap_store |
def get_volume_path(voltype, volhash, volname):
"""Volume path based on hash"""
return "%s/%s/%s/%s" % (
voltype,
volhash[0:2],
volhash[2:4],
volname
) |
def flatten_array(orig):
"""returns a new, flattened, list"""
flattened_list = []
for item in orig:
if isinstance(item, list):
flattened_list += flatten_array(item)
else:
flattened_list.append(item)
return flattened_list |
def aa_or(x, y, nx, ny):
"""Dimensionless production rate for a gene regulated by two
activators with OR logic in the absence of leakage.
Parameters
----------
x : float or NumPy array
Concentration of first activator.
y : float or NumPy array
Concentration of second activator.
... |
def longest_common_substr(str1, str2):
"""
:param str1:
:type str1:
:param str2:
:type str2:
"""
if not str1 or not str2:
return ""
str1_char, str1_rest, str2_char, str2_rest = \
str1[0], str1[1:], str2[0], str2[1:]
if str1_char == str2_char:
return str1_c... |
def split_pair(pair_string, separator, nullable_idx=1):
"""Split a string into a pair, which can have one empty value.
Args:
pair_string: The string to be split.
separator: The separator to be used for splitting.
nullable_idx: The location to be set to null if the separator is not in the
... |
def diff_sum_squares(n: int) -> int:
"""difference between the sum of the squares and the square of the sum of the first n naturals"""
return sum([i for i in range(1, n+1)])**2 - sum([i**2 for i in range(1, n+1)]) |
def capitalize(str):
"""Capitalize a string, not affecting any character after the first."""
return str[:1].upper() + str[1:] |
def add_trailing_slash(la_url):
"""Add a trailing slash to a url"""
if la_url and not la_url[-1] == '/':
la_url = '%s/' % la_url
return la_url |
def _apply_wrappers(wrappers, multi_env):
"""Helper method to apply wrappers if they are present. Returns wrapped multi_env"""
if wrappers is None:
wrappers = []
for wrap in wrappers:
multi_env = wrap(multi_env)
return multi_env |
def zip_codes_to_go(target: list, zip_code: list) -> list:
"""finds the zip codes that haven't been used
Args:
target (list): the list of zip codes that you want
zip_code (list): the list of zip codes that you already have
Returns:
list: list of zip codes that you still need
""... |
def parseRelation(relationLine):
""" parse relation line """
result = relationLine.split('(')
entities_str = result[1].rstrip(')')
entities_list = entities_str.split(',')
src = entities_list[0].strip()
dst = entities_list[1].strip()
return "ADD LINK %s %s" % (src,dst) |
def build_response(session_attributes, speechlet_response):
"""builds resopnse"""
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
} |
def get_gps_check_fail_flags(estimator_status: dict) -> dict:
"""
:param estimator_status:
:return:
"""
gps_fail_flags = dict()
# 0 : insufficient fix type (no 3D solution)
# 1 : minimum required sat count fail
# 2 : maximum allowed PDOP fail
# 3 : maximum allowed horizontal positio... |
def binary2str(b):
"""
:param b: binary content to be transformed to string
:return: string
"""
return b.decode('utf-8') |
def trim(name: str):
"""Return max 255 characters"""
if isinstance(name, str):
return name[:255]
return name |
def Main(a, b):
"""
:param a: First input number of concern
:param b: Second input number of concern
:type a: int
:type b: int
:return: The smallest value of the 2 input numbers
:rtype: int
"""
result = min(a, b)
return result |
def fartokelv(fahrenheit):
""" This function converts fahrenheit to kelvin, with fahrenheit as parameter."""
kelvin = (fahrenheit + 459.67) / 1.8
return kelvin |
def prepare_test_bytes(b_field: bytes) -> bytes:
"""
Returns the bytes of the B-field which are to be CRCed.
It can be thought of as "2 on 6 off cont.".
>>> prepare_test_bytes(bytes.fromhex('0b 0b 0c 0d 0e 0f aa bb cc'))
b'\\x0b\\x0b\\xcc'
"""
# bytes be CRCed
test_bytes = bytearray()
... |
def ijkl(i, j, k, l):
"""Based on the four orbital indices i,j,k,l return the address
in the 1d vector."""
ij = max(i, j) * (max(i, j) + 1) / 2 + min(i, j)
kl = max(k, l) * (max(k, l) + 1) / 2 + min(k, l)
return max(ij, kl) * (max(ij, kl) + 1) / 2 + min(ij, kl) |
def argument_parse(arg):
"""
Small helper function to get rid of excess parenthesis at the begining and end and any whitespace.
@param: arg is a string
@return: arg with the spaces and parenthesis around arg removed
"""
a = arg.replace(' ','')
while a[0] == '(' and a[len(arg) - 1] =... |
def mg2k(m, g, M):
"""Convert from (m, g) indexing to k indexing."""
return m + M*g |
def eat_number(input_str, index):
""" Helper for explode_version """
first = index
while index < len(input_str):
if not input_str[index].isdigit():
break
index += 1
return input_str[first:index], index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.