content stringlengths 42 6.51k |
|---|
def power_level(x,y,serial_number):
""" Calculate the power level for the specified cell. """
rack_id = x + 10
power = rack_id * y
power += serial_number
power *= rack_id
if power < 100:
power = 0
else:
power = int((power - (int(power / 1000) * 1000)) / 100)
power -= 5
return power |
def find_diameter(root):
""" returns (max branch length, max diameter) """
if not root:
return 0, 0
# traverse left and right subtrees
left, right = find_diameter(root.left), find_diameter(root.right)
# return the max branch from the left and right subtrees plus the current node
# and find the max diameter till now (using the current node and the max left and right subtree branches)
return max(left[0], right[0]) + 1, max(left[1], right[1], left[0] + right[0] + 1) |
def remove_quotes(string: str) -> str:
"""
>>> remove_quotes('"only a quote at the start')
'"quoted only at the start'
>>> remove_quotes('"quoted all the way"')
'quoted all the way'
"""
return string[1:-1] if (string[-1:], string[:1]) == ('"', '"') else string |
def tag(tag, content, html_class="", html_id=""):
"""
Surrounds a piece of content in an html tag, with optional added
class.
"""
html_class = " class='{}'".format(html_class) if html_class else ""
html_id = " id='{}'".format(html_id) if html_id else ""
return "<{}{}{}>{}</{}>".format(tag, html_id, html_class, content, tag) |
def bytestring(s, encoding='utf-8', fallback='iso-8859-1'):
"""Convert a given string into a bytestring."""
if isinstance(s, bytes):
return s
try:
return s.encode(encoding)
except UnicodeError:
return s.encode(fallback) |
def indextobeta(b, k):
"""
indextobeta funtion
Parameters
----------
b : integer
k : integer
Returns
-------
out : Array
return 2 * bin(b,K) - 1 where bin(b,K) is a vector of K elements
containing the binary representation of b.
"""
result = []
for i in range(0, k):
result.append(2 * (b % 2) - 1)
b = b >> 1
return result |
def run_cmd(cmd_line):
""" Run command in system shell """
import subprocess
return subprocess.call(cmd_line, shell=True) |
def _get_watch_url(video_id: str) -> str:
""" Creates watchable / downloadable URL from video's ID """
return f'https://www.youtube.com/watch?v={video_id}' |
def safeOpen(filename):
"""Open a utf-8 file with or without BOM in read mode"""
for enc in ['utf-8-sig', 'utf-8']:
try:
f = open(filename, 'r', encoding=enc)
except Exception as e:
print(e)
f = None
if f != None:
return f |
def merge_headers(header_map_list):
"""
Helper function for combining multiple header maps into one.
"""
headers = {}
for header_map in header_map_list:
for header_key in header_map.keys():
headers[header_key] = header_map[header_key]
return headers |
def get_params_for_net(params):
"""get params for net"""
new_params = {}
for key, value in params.items():
if key.startswith('optimizer.'):
new_params[key[10:]] = value
elif key.startswith('network.network.'):
new_params[key[16:]] = value
return new_params |
def get_filtered_recordings(recordings, recording_filter):
"""returns recordings filtered by recording_filter """
return recordings if recording_filter is None else [x for x in recordings
if "%s%s" % (x.type, x.direction) in recording_filter] |
def linear_diff(base_yr, curr_yr, value_start, value_end, yr_until_changed):
"""Calculate a linear diffusion for a current year. If
the current year is identical to the base year, the
start value is returned
Arguments
----------
base_yr : int
The year of the current simulation
curr_yr : int
The year of the current simulation
value_start : float
Fraction of population served with fuel_enduse_switch in base year
value_end : float
Fraction of population served with fuel_enduse_switch in end year
yr_until_changed : str
Year until changed is fully implemented
Returns
-------
fract_cy : float
The fraction in the simulation year
"""
# Total number of simulated years
sim_years = yr_until_changed - base_yr + 1
if curr_yr == base_yr or sim_years == 0 or value_end == value_start:
fract_cy = value_start
else:
#-1 because in base year no change
fract_cy = ((value_end - value_start) / (sim_years - 1)) * (curr_yr - base_yr) + value_start
return fract_cy |
def bits2frac(bits, length):
"""For a given enumeratable bits, compute the binary fraction."""
return sum(bits[i] * 2**(-i-1) for i in range(length)) |
def alloc_list(size):
"""Alloc zeros with range"""
return [0 for _ in range(size)] |
def str_to_integer(string, default):
"""
Returns string formatted to integer
@param: string - String to format
@param: default - Default integer wanted if string isn't possible to format.
"""
try:
return int(string)
except ValueError:
return default |
def unused(attr):
"""
This function check if an attribute is not set (has no value in it).
"""
if attr is None:
return True
else:
return False |
def join3Map(key_func, value_func, lst1, lst2, lst3):
"""
join3Map(key_func: function, value_func: function, iter1: iterable, iter2: iterable, iter3: iterable)
return a dict with {key_func(ele): (value_func(ele), value_func(ele), value_func(ele))}
None if one key is not in a lst
args:
join3Map(L x: -x, L x: x*2, [1,2,3], [2,3,4], [3,4,5])
returns:
{-1: (2, None, None), -2: (4, 4, None), -3: (6, 6, 6), -4: (None, 8, 8), -5: (None, None, 10)}
"""
ans = {}
for ele in lst1:
key = key_func(ele)
ans[key] = (value_func(ele), None, None)
for ele in lst2:
key = key_func(ele)
l1key = ans[key][0] if key in ans else None
ans[key] = (l1key, value_func(ele), None)
for ele in lst3:
key = key_func(ele)
l1key = ans[key] if key in ans else (None, None)
ans[key] = (l1key[0], l1key[1], value_func(ele))
return ans |
def determine_format(format_string: str):
"""
Determines file format from a string. Could be header/ext.
Args:
format_string: Header or file extension.
Returns:
str: Type of the image.
"""
formats = ["PNG",
"TIF", "TIFF",
"JPG", "JPEG"]
for format in formats:
if format in format_string.upper():
if "JPEG" in format_string.upper():
return "JPG"
if "TIF" in format_string.upper():
return "TIFF"
return format
return "JPG" |
def scale_range(mode='per_sample',axes='xyzc', min_percentile=0, max_percentile=1):
"""
Normalize the tensor with percentile normalization
"""
dict_scale_range = {'name': 'scale_range',
'kwargs': {
'mode': mode,
'axes': axes,
'min_percentile': min_percentile,
'max_percentile': max_percentile
}
}
return dict_scale_range |
def getGDXoutputOptions(project_vars: dict) -> tuple:
"""Extract from project_variables.csv the formats on which the resulting GDX file will be converted. Options are CSV, PICKLE, and VAEX.
Args:
project_vars (dict): project variables collected from project_variables.csv.
Raises:
Exception: features values must be "yes" or "no"
Returns:
tuple: 4-element tuple containing
- **csv_bool** (*bool*): boolean
- **pickle_bool** (*bool*): boolean
- **vaex_bool** (*bool*): boolean
- **convert_cores** (*int*): number of cores used to convert the symbols from GDX file to output formats.
"""
features = [
"gdx_convert_parallel_threads",
"gdx_convert_to_csv",
"gdx_convert_to_pickle",
"gdx_convert_to_vaex",
]
selection = {}
for feat in features:
if feat == "gdx_convert_parallel_threads":
selection[feat] = int(project_vars[feat])
else:
if project_vars[feat] == "yes":
selection[feat] = True
elif project_vars[feat] == "no":
selection[feat] = False
else:
raise Exception(f'{feat} must be "yes" or "no"')
convert_cores = selection["gdx_convert_parallel_threads"]
csv_bool = selection["gdx_convert_to_csv"]
pickle_bool = selection["gdx_convert_to_pickle"]
vaex_bool = selection["gdx_convert_to_vaex"]
return csv_bool, pickle_bool, vaex_bool, convert_cores |
def man_dist(a,b):
"""Manhattan Distance"""
return abs(a[0]+b[0]) + abs(a[1]+b[1]) |
def mean(nums):
"""mean: finds the mean of a list of numbers
Args:
nums (array): At least two numbers to find the mean of.
Returns:
Float: the exact mean of the numbers in the array.
"""
output = 0
for x in range(len(nums)):
output += nums[x]
return output / len(nums) |
def _get_first_link_in_contents(navigation, lang):
"""
Given a content's menu, and a language choice, get the first available link.
"""
# If there are sections in the root of the menu.
first_chapter = None
if navigation and 'sections' in navigation and len(navigation['sections']) > 0:
# Gotta find the first chapter in current language.
for section in navigation['sections']:
if 'title' in section and lang in section['title']:
first_chapter = section
break
# If there is a known root "section" with links.
if first_chapter and 'link' in first_chapter:
return first_chapter['link'][lang]
# Or if there is a known root section with subsections with links.
elif first_chapter and ('sections' in first_chapter) and len(first_chapter['sections']) > 0:
first_section = first_chapter['sections'][0]
return first_section['link'][lang]
# Last option is to attempt to see if there is only one link on the title level.
elif 'link' in navigation:
return navigation['link'][lang] |
def cmd_key(cmd):
""" Sort key on builder file, then command, then args """
verb, ringname, args = cmd
return ringname + '.' + verb + '.' + '.'.join(args) |
def xor(*args):
"""True if exactly one of the arguments of the iterable is True.
>>> xor(0,1,0,)
True
>>> xor(1,2,3,)
False
>>> xor(False, False, False)
False
>>> xor("kalimera", "kalinuxta")
False
>>> xor("", "a", "")
True
>>> xor("", "", "")
False
"""
return sum([bool(i) for i in args]) == 1 |
def _convert_email_uri(email):
"""
Evaluate email address and replace any plus signs that may appear in the
portion of the address prior to the '@' with the literal '%2B'.
Standard web servers will convert any plus ('+') symbol to a space (' ')
anywhere where they may appear in the URL. This will allow functions upstream
to create a URI that contains an email address that, when submitted to a
server, will not be replaced with a space character.
"""
if email is not None:
if "+" in email:
return email.replace("+", "%2B")
return email |
def mode_digit(n):
"""
This function takes an integer number n and
returns the digit that appears most frequently in that number.
"""
if abs(n) < 10:
return n
if n < 0:
n = n * -1
counts = [0] * 10
while n != 0:
digit = n % 10
counts[digit] += 1
n = n // 10
max_val = max(counts)
return max([i for i, j in enumerate(counts) if j == max_val]) |
def is_negligible(in_text):
"""" Checks if text or tail of XML element is either empty string or None"""
if in_text is None:
return True
elif type(in_text) is str:
if in_text.strip(chr(160) + ' \t\n\r') == '':
return True
else:
return False
else:
raise TypeError |
def factorial(n):
"""Returns n!"""
return 1 if n < 2 else n * factorial(n - 1) |
def to_ascii(input_unicode):
"""
Takes a unicode string and encodes it into a
printable US-ASCII character set.
Args:
input_unicode(str): input unicode string
Returns:
str: with all characters converted to US-ASCII,
characters that cannot be converted - will be skipped.
"""
return input_unicode.encode("ascii", "ignore") |
def eliminate_lists(row):
"""The purpose of this function is to extract the first element of a list in a row if it is a list, and the element
in the row otherwise. This solves a rare ocurrence where a measuring station had a list of values for lat and long,
which caused errors when loading the data."""
try:
return row[0]
except:
return row |
def dot(L, K):
"""returns the dot product of lists L and K"""
def dotHelp(L, K, accum):
if (L == [] or K == []):
return accum
return dotHelp(L[1:], K[1:], accum+L[0]*K[0])
return dotHelp(L, K, 0) |
def getattr_in_cls_list(cls_list, attr, default):
""" Search for an attribute (attr) in class list (cls_list). Returns
attribute value if exists or None if not. """
for cls in cls_list:
if hasattr(cls, attr):
return getattr(cls, attr)
return default |
def pyth(first, second):
"""
Calculate the area of a right angled trangle based on Pythagoras' Theorem.
:type first: number
:param first: The length of the first axis (x or y)
:type second: number
:param second: The length of the second axis (x or y)
>>> pyth(3, 5)
7.5
"""
return (first * second) / 2 |
def format_parties(parties):
"""
Return the list of parties from the case title.
:param parties: string containing the parties name
:type parties: str
:return: list of names
:rtype: [str]
"""
if parties.startswith('CASE OF '):
parties = parties[len('CASE OF '):]
if parties[-1] == ')':
parties = parties.split('(')[0]
parties = parties.split(' v. ')
parties = [p.strip() for p in parties]
return parties |
def remove_duplicates(list_with_duplicates):
"""
Removes the duplicates and keeps the ordering of the original list.
For duplicates, the first occurrence is kept and the later occurrences are ignored.
Args:
list_with_duplicates: list that possibly contains duplicates
Returns:
A list with no duplicates.
"""
unique_set = set()
unique_list = []
for element in list_with_duplicates:
if element not in unique_set:
unique_set.add(element)
unique_list.append(element)
return unique_list |
def table_to_dictionary(table):
"""Takes a table with a top row for column names, and converts table entries to dictionaries."""
columns = table[0]
del table[0]
results = []
for row in table:
results.append(dict(zip(columns,row)))
return results |
def move_by_month(month, offset):
"""Get the month with given offset raletive to current month."""
return (((month - 1) + offset) % 12) + 1 |
def red(string):
"""
Color %string red.
"""
return "\033[31m%s\033[0m" % string |
def convert_shape_dict_to_array_shape(shape_dict, type="numpy"):
"""
Converts a dict with "x", "y" (and optionally "z") attributes into
a tuple that can be used to e.g. initialise a numpy array
:param shape_dict: Dict with "x", "y" (and optionally "z") attributes
:param type: One of "numpy" or "fiji", to determine whether the "x" or the
"y" attribute is the first dimension.
:return: Tuple array shape
"""
shape = []
if type == "numpy":
shape.append(int(shape_dict["y"]))
shape.append(int(shape_dict["x"]))
elif type == "fiji":
shape.append(int(shape_dict["x"]))
shape.append(int(shape_dict["y"]))
else:
raise NotImplementedError(
"Type: {} not recognise, please specify "
"'numpy' or 'fiji'".format(type)
)
if "z" in shape_dict:
shape.append(int(shape_dict["z"]))
return tuple(shape) |
def map(x, in_min, in_max, out_min, out_max):
"""Maps a number from one range to another.
Arguments:
x {number} -- The number to map.
in_min {number} -- The min of the first range.
in_max {number} -- The max of the first range.
out_min {number} -- The min of the new range.
out_max {number} -- The max of the new range.
Returns:
number -- The mapped number.
"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def adjust_poses(poses,refposes):
"""poses, poses_ref should be in direct"""
# atoms, take last step as reference
for i in range(len(poses)):
for x in range(3):
move = round(poses[i][x] - refposes[i][x], 0)
poses[i][x] -= move
refposes = poses.copy()
return poses, refposes |
def is_word(c):
"""
:param c character to check
:returns True if c is alphanumeric
"""
return c.isalnum() |
def xgcd(a, b):
"""
Extented Euclid GCD algorithm.
Return (x, y, g) : a * x + b * y = gcd(a, b) = g.
"""
if a == 0: return 0, 1, b
if b == 0: return 1, 0, a
px, ppx = 0, 1
py, ppy = 1, 0
while b:
q = a // b
a, b = b, a % b
x = ppx - q * px
y = ppy - q * py
ppx, px = px, x
ppy, py = py, y
return ppx, ppy, a |
def update_boot_config_sector(
sector, entry_index, new_firmware_address, new_firmware_size
):
"""Updates the boot config sector in flash"""
updated_sector = bytearray(sector)
app_entry = updated_sector[entry_index * 32 : entry_index * 32 + 32]
app_entry[0:4] = (0x5AA5D0C0 | 0b1101).to_bytes(4, "big")
app_entry[4 : 4 + 4] = new_firmware_address.to_bytes(4, "big")
app_entry[8 : 8 + 4] = new_firmware_size.to_bytes(4, "big")
updated_sector[entry_index * 32 : entry_index * 32 + 32] = app_entry
return bytes(updated_sector) |
def _get_most_recent_prior_year(from_year, to_year, start_year, end_year):
"""Return the most recent prior year of the rule[from_year, to_year].
Return -1 if the rule[from_year, to_year] has no prior year to the
match[start_year, end_year].
"""
if from_year < start_year:
if to_year < start_year:
return to_year
else:
return start_year - 1
else:
return -1 |
def msisdn_formatter(msisdn):
"""
Formats the number to the International format with the Nigerian prefix
"""
# remove +
msisdn = str(msisdn).replace('+', '')
if msisdn[:3] == '234':
return msisdn
if msisdn[0] == '0':
msisdn = msisdn[1:]
return f"234{msisdn}" |
def clean_text(text):
"""
Return a text suitable for SPDX license identifier detection cleaned
from certain leading and trailing punctuations and normalized for spaces.
"""
text = ' '.join(text.split())
punctuation_spaces = "!\"#$%&'*,-./:;<=>?@[\\]^_`{|}~\t\r\n "
# remove significant expression punctuations in wrong spot: leading parens
# at head and closing parens or + at tail.
leading_punctuation_spaces = punctuation_spaces + ")+"
trailng_punctuation_spaces = punctuation_spaces + "("
return text.lstrip(leading_punctuation_spaces).rstrip(trailng_punctuation_spaces) |
def item_at_index_or_none(indexable, index):
"""
Returns the item at a certain index, or None if that index doesn't exist
Args:
indexable (list or tuple):
index (int): The index in the list or tuple
Returns:
The item at the given index, or None
"""
try:
return indexable[index]
except IndexError:
return None |
def get_version_tuple(version):
"""
Return a tuple of version numbers (e.g. (1, 2, 3)) from the version
string (e.g. '1.2.3').
"""
if version[0] == "v":
version = version[1:]
parts = version.split(".")
return tuple(int(p) for p in parts) |
def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
seen.add(i)
except TypeError:
# probably unhashable. Just keep it.
result.append(i)
if keep_last:
result.reverse()
return result |
def eat(string, s):
"""
Eat sequence s from `string`.
@param string: string you are reading.
@param s: sequence to eat.
"""
#SHOULD RAISE HERE.
return string[len(s):] |
def parse_attribute_from_url(resource_url):
""" Returns the original attribute from the resource url contained in API responses.
This is simply the last element in a resource url as returned by the API.
API responses look like {'success': {'resource_url': resource_value}},
with, for example, a url such as '/lights/<id>/state/bri' for the brightness attribute.
"""
return resource_url.rsplit('/', 1)[-1] |
def splitmod(n, k):
"""
Split n into k lists containing the elements of n in positions i (mod k).
Return the heads of the lists and the tails.
"""
heads = [None]*k
tails = [None]*k
i = 0
while n is not None:
if heads[i] is None:
heads[i] = n
if tails[i] is not None:
tails[i].next = n
tails[i] = n
n.next, n = None, n.next
i = (i+1)%k
return heads, tails |
def check_goodness(url):
"""
Function to check if the url is a dead end (pds, doc, docx, etc)
:param url: Link to be checked.
:return True/False: Flag if dead end or not.
"""
# Documents are not necessary.
unnecessary_extensions = [
'.pdf',
'.doc',
'.docx',
'.xls',
'.avi',
'.mp4',
'.xlsx',
'.jpg',
'.png',
'.gif',
'.pdf',
'.gz',
'.rar',
'.tar',
'.rv',
'.tgz',
'.zip',
'.exe',
'.js',
'.css',
'.ppt'
]
for extension in unnecessary_extensions:
if extension in url:
return False
# Sometimes, the urls contain '@' to indicate a phone number or email address.
# Remove such urls.
if '@' in url:
return False
# If everything is alright, return True.
return True |
def is_number(s):
"""Based on https://stackoverflow.com/a/40097699/519951
:param s: string
:return: True if string is a number
"""
try:
num = float(s)
# check for "nan" floats
return num == num # or use `math.isnan(num)`
except ValueError:
return False |
def intersection(set1, set2):
"""
Calculates the intersection size between two sets, used to compute overlap
between a word context and a definition's signature.
@param set1 - First set
@param set2 - Second set
@return Intersection size
"""
return len(set(set1) & set(set2)) |
def inrange(number, range):
"""convenience function. is number inside range? range is tuple (low, hi),
checks range inclusive of the endpoints"""
return (number >= range[0] and number <= range[1]) |
def pluralize(singular, plural, n, fmt='{n} {s}'):
"""Similar to `gettext.ngettext`, but returns a string including the number.
`fmt` is an optional format string with fields `{n}` and `{s}` being replaced by
the number and singular or plural string, respectively.
Examples:
pluralize('dog', 'dogs', 1) -> '1 dog'
pluralize('dog', 'dogs', 3) -> '3 dogs'
pluralize('dog', 'dogs', 3, '{n} ... {s}') -> 'dogs ... 3'
"""
if n == 1:
return fmt.format(n=n, s=singular)
else:
return fmt.format(n=n, s=plural) |
def build_sql_command(table_name, info):
"""Return a string of the sql command needed to insert data in the database."""
key_list = list(info.keys())
val_list = list(info.values())
sql_command = 'INSERT INTO ' + table_name + ' ('
#Add column names to command
for i in range(len(key_list)):
if i != len(key_list) - 1:
sql_command += key_list[i] + ', '
else:
sql_command += key_list[i] + ') VALUES ('
#Add values to command
for i in range(len(val_list)):
#Text values in SQLite need surrounding quotes
if type(val_list[i]) == str:
data = "'" + val_list[i] + "'"
else:
data = str(val_list[i])
if i != len(val_list) - 1:
sql_command += data + ', '
else:
sql_command += data + ');'
return sql_command |
def mult_saturate(a, b, upper_bound, lower_bound):
"""
Returns the saturated result of a multiplication of two values a and b
Parameters
----------
a : Integer
Multiplier
b : Integer
Multiplicand
upper_bound : Integer
Upper bound for the multiplication
lower_bound : Integer
Lower bound for the multiplication
"""
c = float(a) * float(b)
if c > upper_bound:
c = upper_bound
elif c < lower_bound:
c = lower_bound
return c |
def id_in_subset(_id, pct):
"""
Returns True if _id fits in our definition of a "subset" of documents.
Used for testing only.
"""
return (hash(_id) % 100) < pct |
def float_(value):
"""
Returns float of a value, or None
"""
if value:
return float(value)
else:
return None |
def ensure_all_tokens_exist(input_tokens, output_tokens, include_joiner_token,
joiner):
"""Adds all tokens in input_tokens to output_tokens if not already present.
Args:
input_tokens: set of strings (tokens) we want to include
output_tokens: string to int dictionary mapping token to count
include_joiner_token: bool whether to include joiner token
joiner: string used to indicate suffixes
Returns:
string to int dictionary with all tokens in input_tokens included
"""
for token in input_tokens:
if token not in output_tokens:
output_tokens[token] = 1
if include_joiner_token:
joined_token = joiner + token
if joined_token not in output_tokens:
output_tokens[joined_token] = 1
return output_tokens |
def _GetVersionContents(chrome_version_info):
"""Returns the current Chromium version, from the contents of a VERSION file.
Args:
chrome_version_info: The contents of a chromium VERSION file.
"""
chrome_version_array = []
for line in chrome_version_info.splitlines():
chrome_version_array.append(line.rpartition('=')[2])
return '.'.join(chrome_version_array) |
def split_div_mul(v):
"""Returns the base, div, and mul factor from a symbolic shape constant."""
if "*" in v:
arr = v.split("*")
if len(arr) != 2:
raise ValueError(f"Too many mults in features {v}.")
v, mul = arr[0], int(arr[1])
else:
mul = 1
if "%" in v:
arr = v.split("%")
if len(arr) != 2:
raise ValueError(f"Too many divs in features {v}.")
v, div = arr[0], int(arr[1])
else:
div = 1
return v, div, mul |
def getHighestVote(myList):
"""
Return most common occurrence item in a list
"""
voteDict = {}
for vote in myList:
if voteDict.get(vote) == None:
voteDict[vote] = 1
else:
voteDict[vote] += 1
maxVote = 0
for key, value in voteDict.items():
if value > maxVote:
maxVote = key
return maxVote |
def is_chinese(uchar):
""" return True if a unicode char is chinese. """
if uchar >= u'\u4e00' and uchar <= u'\u9fa5':
return True
else:
return False |
def remove_ssml_tags(parm_text:str) -> str:
"""Remove the SSML tags from parm text. The tags are surrounded by <chevrons>."""
output_text = ''
inside_chevrons = False
for c in parm_text:
if c == '<':
inside_chevrons = True
elif c == '>':
inside_chevrons = False
elif not inside_chevrons:
output_text += c
return output_text |
def encode(data: bytearray) -> bytearray:
"""Encode data into RLE compressed format
Parameters
----------
data: bytearray
A bytearray containing the data to be encoded
Returns
-------
bytearray
A bytearray containing the RLE encoded data
"""
output = bytearray()
run = bytearray()
running = False
i = 0
while i < len(data):
value = data[i]
last = i
count = 0
while i < len(data) and data[i] == value:
count = count + 1
i = i + 1
if count > 2:
if running:
output.append(0x80 + len(run))
output = output + run
while count > 0x7F:
output.append(0x7F)
output.append(value)
count = count - 0x7F
output.append(count)
output.append(value)
running = False
else:
if running is False:
run = bytearray(data[last:i])
running = True
else:
if len(run) > 0xFC - 0x80:
output.append(0x80 + len(run))
output = output + run
running = False
else:
run = run + bytearray(data[last:i])
if running:
output.append(0x80 + len(run))
output = output + run
# Add terminator character
output.append(0xFF)
return output |
def no_wrap_slices(slices):
"""
Prevent wrapping around index for array indexing (only fixes the start of the slice because negative indices wrap)
"""
def normalize_slice(val):
if not isinstance(val, slice):
return 0 if val < 0 else val
else:
return slice(
None if val.start is None else 0 if val.start < 0 else val.start,
None if val.stop is None else 0 if val.stop < 0 else val.stop
)
return tuple(normalize_slice(s) for s in slices) |
def _check_metric_name(metric_name):
"""
There are many metrics related to confusion matrix, and some of the metrics have more than one names. In addition,
some of the names are very long. Therefore, this function is used to check and simplify the name.
Returns:
Simplified metric name.
Raises:
NotImplementedError: when the metric is not implemented.
"""
metric_name = metric_name.replace(" ", "_")
metric_name = metric_name.lower()
metric_name_dict = {"sensitivity": "tpr",
"recall": "tpr",
"hit_rate": "tpr",
"true_positive_rate": "tpr",
"tpr": "tpr",
"specificity": "tnr",
"selectivity": "tnr",
"true_negative_rate": "tnr",
"tnr": "tnr",
"precision": "ppv",
"positive_predictive_value": "ppv",
"ppv": "ppv",
"negative_predictive_value": "npv",
"npv": "npv",
"miss_rate": "fnr",
"false_negative_rate": "fnr",
"fnr": "fnr",
"fall_out": "fpr",
"false_positive_rate": "fpr",
"fpr": "fpr",
"false_discovery_rate": "fdr",
"fdr": "fdr",
"false_omission_rate": "for",
"for": "for",
"prevalence_threshold": "pt",
"pt": "pt",
"threat_score": "ts",
"critical_success_index": "ts",
"ts": "ts",
"csi": "ts",
"accuracy": "acc",
"acc": "acc",
"balanced_accuracy": "ba",
"ba": "ba",
"f1_score": "f1",
"f1": "f1",
"matthews_correlation_coefficient": "mcc",
"mcc": "mcc",
"fowlkes_mallows_index": "fm",
"fm": "fm",
"informedness": "bm",
"bookmaker_informedness": "bm",
"bm": "bm",
"markedness": "mk",
"deltap": "mk",
"mk": "mk"}
metric_name_info = metric_name_dict.get(metric_name)
if metric_name_info is None:
raise NotImplementedError("The metric is not implemented.")
return metric_name_info |
def generate_variant_catalog(locus_id, repeat_unit, chrom, start_1based, end_1based, offtarget_regions=None):
"""Generate the ExpansionHunter variant catalog contents for a particular locus."""
return {
"LocusId": locus_id,
"LocusStructure": f"({repeat_unit})*",
"ReferenceRegion": f"{chrom}:{start_1based - 1}-{end_1based}",
"VariantType": "RareRepeat" if offtarget_regions else "Repeat",
"OfftargetRegions": offtarget_regions or [],
} |
def admit_util_getplain(formula):
""" Method to make a chemical formula more readable for embedding in filenames
Examples:
CH3COOHv=0 -> CH3COOH
g-CH3CH2OH -> CH3CH2OH
(CH3)2COv=0 -> (CH3)2CO
cis-CH2OHCHOv= -> CH2OHCHO
g'Ga-(CH2OH)2 -> (CH2OH)2
Parameters
----------
formula : str
The chemical formula to process
Returns
-------
String of the more readable formula
"""
pos = formula.find("-")
if pos != -1:
if not(-1 < formula.find("C") < pos or -1 < formula.find("N") < pos \
or -1 < formula.find("O") < pos or -1 < formula.find("H") < pos):
formula = formula[pos + 1:]
pos = formula.find("v")
if pos != -1:
formula = formula[:pos]
pos = formula.find("&Sigma")
if pos != -1:
return formula[:pos]
formula = formula.replace(";","")
return formula.replace("&","-") |
def fix_perspective_string(data):
"""Fix inconsistent perspective names"""
mapping = {
"I": "individualist",
"H": "hierarchist",
"E": "egalitarian",
}
for ds in data.values():
ds["perspective"] = (mapping.get(ds["perspective"], ds["perspective"])).title()
return data |
def insideFunction(code):
""" Return code contents from inside a function"""
return code[code.find("{")+1:code.find("}")] |
def command_error_fmt(cmd_name, exception):
"""Format error message given command and exception."""
return "pyleus {0}: error: {1}".format(cmd_name, str(exception)) |
def convert_bytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ["bytes", "KB", "MB", "GB", "TB"]:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def get_telephoto_pair(f, t, s=None):
"""returns the pair of positive and negative focal length lens pairs
that make up the telephoto lens.
Parameters
----------
f : real
focal length of the telephoto lens (i.e. focal length of the combined lens)
t : real
total track length of the telephoto lens (i.e. distance from the first lens
to the image plane at infinite focus)
s : real, optional
separation between the pair of lenses. If `None`, `s` is set equal to
`s/2` for which the |f2| is maximum
Returns
-------
f1 : real
focal length of the positive lens (towards the object)
f2 : real
focal length of the negetive lens (towards the image plane)
Notes
-----
1. The telephoto ratio is equal to t/f
2. bfl = t - s
3. |f2| is maximum at s=t/2
|------------------->
f
^ ^
| | |<--image plane
| | |
|----|-------|------|
H' | s | bfl |
| | |
v v
f1 (+) f2 (-)
|-------------->
t
References
----------
1. Telephoto lenses, Chapter 7, Lens design, Milton Laikin
Examples
--------
>>>go.get_telephoto_pair(f=200, t=100, s=60)
(75.0, -24.0)
"""
if s is None:
s = t/2.0
f1 = s*f/(f - t + s)
f2 = s*(s - t)/(f - t)
return f1, f2 |
def extend(list1, list2):
"""Return a list with the given list added to the end."""
if list1 == ():
return list2
else:
head, tail = list1
return (head, extend(tail, list2)) |
def f(n):
"""
n: integer, n >= 0.
"""
if n == 0:
return 1
else:
return n * f(n-1) |
def browser_labels(labels):
"""Return a list of browser labels only without the `browser-`."""
return [label[8:].encode('utf-8')
for label in labels
if label.startswith('browser-') and label[8:] is not ''] |
def chained_get(container, path, default=None):
"""Helper function to perform a series of .get() methods on a dictionary
and return a default object type in the end.
Parameters
----------
container : dict
The dictionary on which the .get() methods should be performed.
path : list or tuple
The list of keys that should be searched for.
default : any (optional, default=None)
The object type that should be returned if the search yields
no result.
"""
for key in path:
try:
container = container[key]
except (AttributeError, KeyError, TypeError):
return default
return container |
def parse_variables(var_dict):
"""Parse variables in current context"""
valid_vars = {}
for key, value in var_dict.items():
if type(value) is int:
valid_vars[key] = value
if type(value) is float:
valid_vars[key] = value
if type(value) is list:
valid_vars[key] = value
if type(value) is bool:
valid_vars[key] = value
return valid_vars |
def normal_intersect(p1_x, p1_y, p2_x, p2_y, px, py):
"""
Find the point at which a line through seg_p1,
seg_p2 intersects a normal dropped from p.
"""
# Special cases: slope or normal slope is undefined
# for vertical or horizontal lines, but the intersections
# are trivial for those cases
if p2_x == p1_x:
return p1_x, py
elif p2_y == p1_y:
return px, p1_y
# The slope of the segment, and of a normal ray
seg_slope = (p2_y - p1_y) / (p2_x - p1_x)
normal_slope = 0 - (1.0 / seg_slope)
# For y=mx+b form, we need to solve for b (y intercept)
seg_b = p1_y - seg_slope * p1_x
normal_b = py - normal_slope * px
# Combining and subtracting the two line equations to solve for intersect
x_intersect = (seg_b - normal_b) / (normal_slope - seg_slope)
y_intersect = seg_slope * x_intersect + seg_b
# Colinear points are ok!
return (x_intersect, y_intersect) |
def color(string, color=None):
"""
Change text color for the Linux terminal.
"""
attr = []
# bold
attr.append('1')
if color:
if color.lower() == "red":
attr.append('31')
elif color.lower() == "yellow":
attr.append('33')
elif color.lower() == "green":
attr.append('32')
elif color.lower() == "blue":
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
if string.startswith("[!]"):
attr.append('31')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.startswith("[+]"):
attr.append('32')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
elif string.startswith("[*]"):
attr.append('34')
return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)
else:
return string |
def get_global_address(address, bank):
"""
Return the rom address of a local address and bank.
This accounts for a quirk in mbc3 where 0:4000-7fff resolves to 1:4000-7fff.
"""
if address < 0x8000:
if address >= 0x4000 and bank > 0:
return address + (bank - 1) * 0x4000
return address |
def _cnt_stat(a_gold_segs, a_pred_segs):
"""Estimate the number of true pos, false pos, and false neg.
Args:
a_gold_segs (iterable): gold segments
a_pred_segs (iterable): predicted segments
Returns:
tuple: true positives, false positives, and false negatives
"""
tp = fp = fn = 0
for gs, ps in zip(a_gold_segs, a_pred_segs):
gs = gs.lower()
ps = ps.lower()
if gs == "none":
if ps != "none":
fp += 1
elif gs == ps:
tp += 1
else:
fn += 1
return tp, fp, fn |
def WalkJSONPath(json_path, data):
"""Retrieves part of a Python dictionary by walking a JSONPath-like pattern.
Uses a simplified version of jq's JSON querying language to select
to select information out of the dictionary. The supported operators
are "." and "[]".
Example:
{'hello': {'world': [100, 200]}}
".hello.world[0]" ==> 100
".hello.world[-1]" ==> 200
".hello.world" ==> [100, 200]
"." ==> {'hello': {'world': [100, 200]}}
"""
def ChompNextPart(json_path):
"""Splits the JSON path into the next operator, and everything else."""
dict_operator_pos = json_path.find('.', 1)
list_operator_pos = json_path.find('[', 1)
if dict_operator_pos == -1:
dict_operator_pos = len(json_path)
if list_operator_pos == -1:
list_operator_pos = len(json_path)
cut = min(dict_operator_pos, list_operator_pos)
return json_path[:cut], json_path[cut:]
if not json_path:
return data
current, left = ChompNextPart(json_path)
try:
if current == '.':
return WalkJSONPath(left, data)
if current.startswith('.'):
return WalkJSONPath(left, data[current[1:]])
if current.startswith('['):
return WalkJSONPath(left, data[int(current[1:-1])])
except (KeyError, TypeError):
raise ValueError('Could not access %s' % json_path)
else:
raise ValueError('Invalid syntax found at %s' % json_path) |
def _role_selector(role_arn, roles):
"""Select a role based on pre-configured role_arn and IdP roles list.
Given a roles list in the form of [{"RoleArn": "...", ...}, ...],
return the item which matches the role_arn, or None otherwise.
"""
chosen = [r for r in roles if r['RoleArn'] == role_arn]
return chosen[0] if chosen else None |
def is_valid_vc_index(vc_index):
"""
Validates vc_index. vc_index must be within 0-65535 range.
:type vc_index: int
:param vc_index: The vc index to be validated.
:rtype: bool
:return: True or False depending on whether vc index passes validation.
"""
if vc_index is None:
return False
vc_index = int(vc_index)
if vc_index < 0 or vc_index > 65535:
return False
return True |
def trapezoid_right(x1, x2, x3, y1, y3) -> float:
"""
Calculate the area of the trapezoid with corner coordinates (x1, 0), (x1, y1), (x2, 0), (x2, y2),
where y2 is obtained by linear interpolation of (x1, y1) and (x3, y3) evaluated at x2.
Args:
x1 (float): x coordinate
x2 (float): x coordinate
x3 (float): x coordinate
y1 (float): y coordinate
y3 (float): y coordinate
Returns:
float: the area of the trapezoid
"""
# Degenerate cases
if x2 == x1 or x2 > x3:
return (x2 - x1) * y1
# Find y2 using linear interpolation and calculate the trapezoid area
w = (x3 - x2) / (x3 - x1)
y2 = y1 * w + y3 * (1 - w)
return (x2 - x1) * (y1 + y2) / 2 |
def chunks(sentences, number_of_sentences):
"""
Split a list into N sized chunks.
"""
number_of_sentences = max(1, number_of_sentences)
return [sentences[i:i+number_of_sentences]
for i in range(0, len(sentences), number_of_sentences)] |
def hamming_weight(x: int):
"""
Count the number of on bits in an integer.
Args:
x: the number to count on bits
Returns:
Integer representing the number of bits
that are on (1).
"""
count = 0
while x:
# bitwise AND number with itself minus 1
x &= x - 1
count += 1
return count |
def match(pattern, p1, p2):
"""Returns index of string till where matching occurs
Arguments
---------
pattern: string
p1: First Position to start matching from [0-based]
p2: First Position to start matching pattern[p1] [0-based]
Returns
p1: Last matching index
"""
while max(p2,p1)<len(pattern) and pattern[p1] == pattern[p2]:
p1+=1
p2+=1
return p1 |
def pluginsdata(_, data):
"""
mocked getattr call for external data.
"""
if data == "PLUGINEXECS":
return {"testexec": "testmodule"}
elif data == "MODNAMEOVERRIDES":
return {"testmodule": "fictionmodule"} |
def _normalize_url(url: str) -> str:
"""Normalize a url (trim trailing slash), to simplify equality checking."""
return url.rstrip("/") or "/" |
def _generate_test_name(source):
"""
Clean up human-friendly test name into a method name.
"""
out = source.replace(' ', '_').replace(':', '').replace(',', '').lower()
return "test_%s" % out |
def _compute_subprefix(attr):
"""
Get the part before the first '_' or the end of attr including
the potential '_'
"""
return "".join((attr.split("_")[0], "_" if len(attr.split("_")) > 1 else "")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.