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
... |
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 ... |
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, h... |
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... |
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_... |
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
... |
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 form... |
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... |
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... |
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:
# ... |
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
"""
retur... |
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 a... |
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 ... |
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:
r... |
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... |
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."""
... |
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
... |
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 '... |
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 lis... |
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 "fij... |
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} --... |
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, re... |
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 - ... |
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... |
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_y... |
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 expres... |
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 i... |
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)
... |
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... |
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... |
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',
'... |
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'... |
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(... |
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 f... |
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 mappi... |
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.... |
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... |
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
... |
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()
... |
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(
... |
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.
Rai... |
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"{ch... |
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
... |
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 ... |
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 tu... |
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:
val... |
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... |
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() == ... |
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
... |
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, 20... |
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]
... |
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:
retu... |
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... |
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 -... |
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,p... |
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.