content
stringlengths 42
6.51k
|
---|
def thresholding(x):
"""Thresholding function."""
if x > 0.:
y = 1
else:
y = 0.
return y
|
def nearest_band(wavelengths, target):
"""Get index of band nearest to a target wavelength."""
idx = 0
minimum = float('inf')
for (i, wl) in enumerate(wavelengths):
if abs(target - wl) < minimum:
minimum = abs(target - wl)
idx = i
return idx
|
def get_social_discount(t, r=0.01):
"""
Calaculate social discount rate.
"""
return 1 / (1 + r) ** t
|
def path2handle(path):
""" Translates a full path to a handle. """
return path.split('/')[-1]
|
def popular_articles_query(limit=None):
"""Return an SQL string to query for popular articles.
Args:
limit (int): The maximum number of results to query for. If
ommited, query for all matching results.
Returns:
str: An SQL string. When used in a query, the result will contain
two columns:
- str: The article's name.
- str: The number of page visits (e.g. "1337 views").
"""
return """
SELECT title, format('%s views', count(*)) AS views
FROM log
JOIN articles ON log.path = ('/article/' || articles.slug)
GROUP BY articles.title
ORDER BY count(*) DESC
LIMIT {number};
""".format(number=limit or 'ALL')
|
def choose(paragraphs, select, k):
"""Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
paragraph returns true. If there are fewer than K such paragraphs, return
the empty string.
"""
# BEGIN PROBLEM 1
"*** YOUR CODE HERE ***"
result = []
for p in paragraphs:
if select(p):
result.append(p)
if len(result) >= k + 1:
return result[k]
else:
return ''
# END PROBLEM 1
|
def col_length(headline, content, dict_key=None):
"""
calculate the max needed length for a output col by getting the headline, the content of the rows
(different data types) and in some cases a specific key
:param headline: Column headline
:param content: A list of column contents
:param dict_key: Extract only a part of the columns
:return: Maximum length of contents
"""
length = len(headline)
if type(content) == list:
for x in content:
if type(x) == str:
if len(x) > length:
length = len(x)
elif type(content) == dict:
for key in content:
if type(content[key]) == dict:
if dict_key in content[key]:
if len(str(content[key][dict_key])) > length:
length = len(str(content[key][dict_key]))
else:
x = key
for key in content[x]:
if type(content[x][key]) == dict:
if dict_key in content[x][key]:
if type(content[x][key]) == dict:
if len(content[x][key][dict_key]) > length:
length = len(content[x][key][dict_key])
elif type(content[key]) == int or type(content[key]) == float:
if len(str(content[key])) > length:
length = len(str(content[key]))
elif type(content) == int:
if len(str(content)) > length:
length = len(str(content))
return length
|
def robustlog(x):
"""Returns log(x) if x > 0, the complex log cmath.log(x) if x < 0,
or float('-inf') if x == 0.
"""
if x == 0.:
return float('-inf')
elif type(x) is complex or (type(x) is float and x < 0):
return cmath.log(x)
else:
return math.log(x)
|
def insert_relationships(datapoints):
"""Inserts an empty relationship at index 4"""
new_datapoints = set()
for dp in datapoints:
cast_dp = list(dp)
cast_dp.insert(4, "")
new_datapoints.add(tuple(cast_dp))
return new_datapoints
|
def d_phi_dy(x, y):
"""
angular derivative in respect to y when phi = arctan2(y, x)
:param x:
:param y:
:return:
"""
return x / (x**2 + y**2)
|
def convert_size(size):
"""Convert bytes to mb or kb depending on scale"""
kb = size // 1000
mb = round(kb / 1000, 1)
if kb > 1000:
return f'{mb:,.1f} MB'
else:
return f'{kb:,d} KB'
|
def average_above_zero(tab):
"""
brief: computes ten average of the list
args:
tab: a list of numeric value expects at leas one positive value
return:
the computed average
raises:
ValueError if expected a list as input
ValueError if no positive value found
"""
if not(isinstance(tab, list)):
raise ValueError('Expected a list as input')
valSum = 0.0
nPositiveValues = 0
for i in range(len(tab)):
if tab[i] > 0:
valSum += float(tab[i])
nPositiveValues += 1
if nPositiveValues <= 0:
raise ValueError('No positive value found')
avg = valSum/nPositiveValues
return avg
|
def match_users(users):
"""Returns a tuple: a list of pairs of users and a list of unmatched users."""
user_list = users.copy()
matched = []
# print(user_list)
while len(user_list) > 1:
matched.append(
(user_list.pop(), user_list.pop())
)
return matched, user_list
|
def get_true_url(url):
"""
get the true URL of an otherwise messy URL
"""
data = url.split("/")
return "{}//{}".format(data[0], data[2])
|
def onehot_encoding_unk(x, allowable_set):
"""Maps inputs not in the allowable set to the last element."""
if x not in allowable_set:
x = allowable_set[-1]
return [x == s for s in allowable_set]
|
def hb_energy_times_to_power(es, ee, ts, te):
"""Compute power from start and end energy and times.
Return: power values
"""
return (ee - es) / ((te - ts) / 1000.0)
|
def pretty_time_delta(seconds):
"""Prints a number of seconds in a terse, human-readable format.
Adapted from: https://gist.github.com/thatalextaylor/7408395
"""
seconds = int(seconds)
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
return '%dd%dh%dm%ds' % (days, hours, minutes, seconds)
if hours > 0:
return '%dh%dm%ds' % (hours, minutes, seconds)
if minutes > 0:
return '%dm%ds' % (minutes, seconds)
return '%ds' % (seconds,)
|
def split_message(data, boundary):
""" Split the message into it separate parts based on the boundary.
:param data: raw message data
:param boundary: boundary used in message
:return: message parts, that were separated by boundary
"""
# Split the data into message parts using the boundary
message_parts = data.split(b'--' + boundary)
# Remove empty messages (that contain only '--' or '--\r\n'
message_parts = [p for p in message_parts
if p != b'--' and p != b'--\r\n' and len(p) != 0 and p != b'\r\n']
return message_parts
|
def format_filename(string):
"""
Converts a string to an acceptable filename
e.g. "Go! series - F1" into "Go_series_-_F1"
Parameters:
string (str): raw filename
Returns:
formatted_filename (str): formatted filename
Raises:
"""
# NOTE: Periods (.) and dashes (-) are allowed
# Spaces are converted to dashes
formatted_filename = []
symbols = "!@#$%^&*()+=[]\{}|:\";'<>?,/'"
for c in string:
if c == " ":
formatted_filename.append("_")
elif c in symbols:
pass
else:
formatted_filename.append(c)
formatted_filename = "".join(formatted_filename)
return formatted_filename
|
def _ToLocalPath(toplevel_dir, path):
"""Converts |path| to a path relative to |toplevel_dir|."""
if path == toplevel_dir:
return ''
if path.startswith(toplevel_dir + '/'):
return path[len(toplevel_dir) + len('/'):]
return path
|
def index_requests(reqs):
"""adds an index key for each dict entry in the array
Args:
requests_set (list): Array of requests to send:
request(dict): required to have
- method(string): http method to use
- url(string): url of the requested resource
- kwargs(dict): defines more specs for the request
- data(dict): if request has json body
- headers(dict): if you want to attach any headers to the request
Returns:
Array: Array of all requests with indexed key in each request dict {'index': index}.
"""
for idx, req in enumerate(reqs):
req['index'] = idx
return reqs
|
def get_matrix41():
"""
Return the matrix with ID 41.
"""
return [
[0.000, 0.000, 0.333],
[0.033, 0.050, 0.267],
[0.067, 0.100, 0.200],
[0.100, 0.175, 0.100],
[0.200, 0.200, 0.067],
[0.267, 0.225, 0.033],
[0.333, 0.250, 0.000],
]
|
def compute_chi_eff(m1,m2,s1,s2):
""" Compute chi effective spin parameter (for a given component)
--------
m1 = primary mass component [solar masses]
m2 = secondary mass component [solar masses]
s1 = primary spin z-component [dimensionless]
s2 = secondary spin z-component [dimensionless]
"""
return (m1*s1+m2*s2)/(m1+m2)
|
def nearly_equal(a,b,sig_fig=5):
"""
Returns it two numbers are nearly equal within sig_fig decimal places
http://stackoverflow.com/questions/558216/function-to-determine-if-two-numbers-are-nearly-equal-when-rounded-to-n-signific
:param flt a: number 1
:param flt b: number 2
:param int sig_fig: number of decimal places to check agreement to
:returns bool:
"""
return ( a==b or
int(a*10**sig_fig) == int(b*10**sig_fig)
)
|
def span(data, **kwargs):
"""
Compute the difference of largest and smallest data point.
"""
return max(data) - min(data)
|
def _evalfact(lcs, c):
"""Input: a list of variable-bracketed strings, the known LCS
Output: number of variables needed and the variables themselves in a list."""
allbreaks = []
for w in c:
breaks = [0] * len(lcs)
p = 0
inside = 0
for pos in w:
if pos == "[":
inside = 1
elif pos == "]":
inside = 0
breaks[p - 1] = 1
else:
if inside:
p += 1
allbreaks.append(breaks)
finalbreaks = [0] * len(lcs)
for br in allbreaks:
for idx, val in enumerate(br):
if val == 1:
finalbreaks[idx] = 1
# Extract vars
variables = []
currvar = ""
for idx, val in enumerate(lcs):
currvar += lcs[idx]
if finalbreaks[idx] == 1:
variables.append(currvar)
currvar = ""
numvars = sum(finalbreaks)
return numvars, variables
|
def align(num, exp):
"""Round up to multiple of 2**exp."""
mask = 2**exp - 1
return (num + mask) & ~mask
|
def summ_nsqr(i1, i2):
"""Return the summation from i1 to i2 of n^2"""
return ((i2 * (i2+1) * (2*i2 + 1)) / 6) - (((i1-1) * i1 * (2*(i1-1) + 1)) / 6)
|
def tokens(_s, _separator=' '):
"""Returns all the tokens from a string, separated by a given separator, default ' '"""
return _s.strip().split(_separator)
|
def isSea(obj):
"""
Detect whether obj is a SEA object.
:param obj: Object
"""
return True if hasattr(obj, 'SeaObject') else False
|
def getElectronDensityLink(pdb_code, diff=False):
"""Returns the html path to the 2FoFc electron density file on the ebi server
:param diff: Optionaly, defaults to False, if true gets the Fo-Fc, if Flase gets the 2Fo-Fc
"""
file_name = pdb_code + '.ccp4'
if diff:
file_name = pdb_code + '_diff.ccp4'
pdb_loc = 'https://www.ebi.ac.uk/pdbe/coordinates/files/' + file_name
return file_name, pdb_loc
|
def e_palavra_potencial(arg):
"""
Reconhecedor do TAD palavra_potencial
Verifica se o arg e palavra_potencial e devolve valor booleano
Argumentos:
arg -- argumento a verificar
"""
return isinstance(arg, str) and all(l.isupper() for l in arg)
|
def not_lane(b, n):
"""
Bitwise NOT in Python for n bits by default.
"""
return (1 << n) - 1 - b
|
def replace_celltypes(celldict,row,label):
""" Replaces cell type with max celltype in anndata object, but preserves original call if no max cell type is found. """
if row['leiden'] in celldict:
return(celldict[row['leiden']])
else:
return(row[label])
|
def read_key_value(line, separator='='):
"""
Read a key and value from a line.
Only splits on first instance of separator.
:param line: string of text to read.
:param separator: key-value separator
"""
key, value = line.split(separator, 1)
return key.strip(), value.strip()
|
def isfloat(element):
"""
This function check if a string is convertable to float
"""
try:
float(element)
return True
except ValueError:
return False
|
def _public_coverage_ht_path(data_type: str, version: str) -> str:
"""
Get public coverage hail table
:param data_type: One of "exomes" or "genomes"
:param version: One of the release versions of gnomAD on GRCh38
:return: path to coverage Table
"""
return f"gs://gnomad-public-requester-pays/release/{version}/coverage/{data_type}/gnomad.{data_type}.r{version}.coverage.ht"
|
def order_to_process(a, b):
"""
Takes two sorted lists of tuples and returns a
combined list sorted by lowest first element
Paramters:
a, b - a sorted list of tuples
"""
ret_l = []
while a and b:
ret_l.append(a.pop(0) if a <= b else b.pop(0))
ret_l.extend(a)
ret_l.extend(b)
return ret_l
|
def first_item(l):
"""Returns first item in the list or None if empty."""
return l[0] if len(l) > 0 else None
|
def power_set(values):
"""Return all the set of all subsets of a set."""
# A: init the set for the return value
subsets = list()
def size_subsets(size, current, values):
"""Finds all subsets of a given size in a set."""
# Base Case: the current subset is full
if len(current) == size:
# add the current subset to the output (if not already there)
current_set = set(current)
if current_set not in subsets:
subsets.append(current_set)
# Recursive Case: need to find more values for the subset
else: # len(current) < size
# iterate over adding the others
for _ in range(len(values)):
new_item = values.pop()
print(f"Current and new item: {current, new_item}")
# add one more value to the current subset
current.append(new_item)
size_subsets(size, current, {v for v in values})
print(f"Values left: {values}")
# remove one of the elements, so we reach all possibilities
current.pop()
return None
# B: iterate over all possible sizes
for size in range(1, len(values) + 1):
# add the subsets of the given size to the output
size_subsets(size, [], {v for v in values})
# C: return all the subsets
return len(subsets)
|
def signed_to_unsigned_8bit(data):
"""
Converts 8-bit signed data initally read as unsigned data back to its
original relative position.
"""
# Python reads bytes as unsigned chars (0 to 255).
# For example: Byte "FF" in a signed file is -1, but Python will read it
# as the unsigned value 255. -1 is halfway in the signed range (-127 to 127)
# at position 127 (counting the sign bit). However, 255 corresponds to the
# very end of the unsigned range. To match the original position as a signed
# number, we subtract 128, landing us at the original position of 127.
# While positive decimals will be the same signed or unsigned (under 127),
# their relative position will change again. 127 is position 255 while
# signed, and 127 while unsigned. We add 128 and arrive at 255, the correct
# position.
converted = bytearray()
for byte in data:
if byte > 127:
signed = byte - 128
else:
signed = byte + 128
converted.append(signed)
return converted
|
def ordered_binary_search(ordered_list, item):
"""Binary search in an ordered list
Complexity: O(log n)
Args:
ordered_list (list): An ordered list.
item (int): The item to search.
Returns:
bool: Boolean with the answer of the search.
Examples:
>>> alist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
>>> sequential_search(alist, 3)
False
>>> sequential_search(alist, 13)
True
"""
first = 0
last = len(ordered_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if ordered_list[midpoint] == item:
found = True
else:
if item < ordered_list[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
|
def create_dict(items):
"""
creates a dict with each key and value set to an item of given list.
:param list items: items to create a dict from them.
:rtype: dict
"""
result = {name: name for name in items}
return result
|
def _ReportFileAndLine(filename, line_num):
"""Default error formatter for _FindNewViolationsOfRule."""
return '%s (line %s)' % (filename, line_num)
|
def has_spaces(txt:str) -> bool:
"""Determine if txt has spaces."""
return len(txt.split(" ")) > 1
|
def forge_nat(value) -> bytes:
"""
Encode a number using LEB128 encoding (Zarith)
:param int value: the value to encode
:return: encoded value
:rtype: bytes
"""
if value < 0:
raise ValueError('Value cannot be negative.')
buf = bytearray()
more = True
while more:
byte = value & 0x7f
value >>= 7
if value:
byte |= 0x80
else:
more = False
buf.append(byte)
return bytes(buf)
|
def mc_pow(data):
"""
Modulus calculation. Squared version.
Calculated real^2+imag^2
"""
return data.real ** 2 + data.imag ** 2
|
def to_px8(p):
"""Convenience method to convert pymunk coordinates to px8
"""
return int(p[0]), 128 - int(p[1])
|
def replace_python_tag(wheelname, new_tag):
# type: (str, str) -> str
"""Replace the Python tag in a wheel file name with a new value.
"""
parts = wheelname.split('-')
parts[-3] = new_tag
return '-'.join(parts)
|
def clean_question_mark(content):
"""Removes question mark strings, turning them to nulls.
Parameters
----------
content: :class:`str`
A string to clean.
Returns
-------
:class:`str`
The string, or None if it was a question mark.
"""
if not content:
return None
if "?" in content:
return None
return content.strip()
|
def tag_clean(n):
"""Get tagname without prefix"""
if n[0] in u"-~!": return n[1:]
return n
|
def _create_sanic_web_config():
"""
Sanic log configuration to avoid duplicate messages
Default log configuration Sanic uses has handlers set up that causes
messages to be logged twice, so pass in a minimal config of our own to
avoid those handlers being created / used
"""
return dict(
version=1,
disable_existing_loggers=False,
loggers={
"sanic.root": {"level": "INFO"},
"sanic.error": {"level": "INFO"},
"sanic.access": {"level": "INFO"},
}
)
|
def transpose_tabular(rows):
"""
Takes a list of lists, all of which must be the same length,
and returns their transpose.
:param rows: List of lists, all must be the same length
:returns: Transposed list of lists.
"""
return list(map(list, zip(*rows)))
|
def get_detailtrans_21cn(data_base, type):
"""
get 21 detail trans dict
:param data_base:
:param type:
:return:
"""
data21cn = data_base.get("ec21") if type == 'en' else data_base.get("ce_new")
if not data21cn:
return None
# -----source
# source21cn = data21cn.get("source").get("name")
# -----word
# word = data21cn.get("return-phrase").get("l").get("i")[0]
# -----detail trans
detailtrans_dict = {}
data21cn = data21cn.get("word")[0]
# data21.keys(): dict_keys(['phone', 'phrs', 'return-phrase', 'trs'])
# data21_phrs = data21.get("phrs")
data21cn_trs = data21cn.get("trs")
# len(data21_trs): 4: n. vt. vi. adj.
for each_data21cn_trs in data21cn_trs:
temp_dict = {}
pos = each_data21cn_trs.get("pos")
temp = each_data21cn_trs.get("tr")
for i in range(len(temp)):
if temp[i].get("l").get("i"):
interpre_list = [temp[i].get("l").get("i")[0]]
else:
interpre_list = []
# ---list---
temp_temp = temp[i].get("tr")
if temp_temp:
for j in range(len(temp_temp)):
interpre_list.append('(' + str(j + 1) + ')' + "." + temp_temp[j].get("l").get("i")[0])
# ---exam---
temp_temp_temp = temp[i].get("exam")
if temp_temp_temp:
for k in range(len(temp_temp_temp)):
interpre_list.append(temp_temp_temp[k].get("i").get("f").get("l").get("i"))
interpre_list.append(temp_temp_temp[k].get("i").get("n").get("l").get("i"))
temp_dict[str(i + 1)] = interpre_list
detailtrans_dict[pos] = temp_dict
return detailtrans_dict
|
def find_filename(path_to_file):
"""
extract filename given path
@param path_to_file - relative path to file
"""
return path_to_file.split('/')[-1]
|
def beaufort(n):
"""Converts windspeed in m/s into Beaufort Scale descriptor."""
s = ''
if n < 0.3:
s = 'calm'
elif n < 1.6:
s = 'light air'
elif n < 3.4:
s = 'light breeze'
elif n < 5.5:
s = 'gentle breeze'
elif n < 8.0:
s = 'moderate breeze'
elif n < 10.8:
s = 'fresh breeze'
elif n < 13.9:
s = 'strong breeze'
elif n < 17.2:
s = 'high wind'
elif n < 20.8:
s = 'gale'
elif n < 24.5:
s = 'strong gale'
elif n < 28.5:
s = 'storm'
elif n < 32.7:
s = 'violent storm'
else:
s = 'hurricane force'
return s
|
def test_sub_grids(board: list) -> bool:
"""
test each of the nine 3x3 sub-grids
(also known as blocks)
"""
sub_grids = [
board[0][0:3] + board[1][0:3] + board[2][0:3],
board[0][3:6] + board[1][3:6] + board[2][3:6],
board[0][6:] + board[1][6:] + board[2][6:],
board[3][0:3] + board[4][0:3] + board[5][0:3],
board[3][3:6] + board[4][3:6] + board[5][3:6],
board[3][6:] + board[4][6:] + board[5][6:],
board[6][0:3] + board[7][0:3] + board[8][0:3],
board[6][3:6] + board[7][3:6] + board[8][3:6],
board[6][6:] + board[7][6:] + board[8][6:],
]
for row in sub_grids:
if sorted(row) != [1, 2, 3, 4, 5, 6, 7, 8, 9]:
return False
return True
|
def manhatten_distance(point):
"""Manhatten distance between point and the origin."""
return int(abs(point.real) + abs(point.imag))
|
def timedur(x):
"""
Print consistent string format of seconds passed.
Example: 300 = '5 mins'
Example: 86400 = '1 day'
Example: 86705 = '1 day, 5 mins, 5 sec'
"""
divs = [('days', 86400), ('hours', 3600), ('mins', 60)]
x = float(x)
res = []
for lbl, sec in divs:
if(x >= sec):
rm, x = divmod(x, float(sec))
# If exactly 1, remove plural of label
if(rm == 1.0):
res.append((lbl[:-1], int(rm)))
else:
res.append((lbl, int(rm)))
# anything left over is seconds
x = int(x)
if(x == 1):
res.append(("second", x))
elif(x == 0):
pass
else:
res.append(("seconds", x))
return ", ".join(["%d %s" % (w[1], w[0]) for w in res])
|
def fix_star(word):
""" Replace ``*`` with ``\*`` so that is will be parsed properly by
docutils.
"""
return word.replace('*', '\*')
|
def mention_user(user):
"""
Helper function to make it easier to mention users
:Args:
`user` the ID of the user
:Returns:
A string formatted in a way that will mention the user on Slack
"""
return "<@" + user + ">"
|
def assemble_message_from_columns(columns_to_build_from):
"""Reacrete message from N columns (N = columns_to_build_from)"""
#initialize the text structure
max_column_len = max([len(c) for c in columns_to_build_from])
text = ""
for i in range(0, max_column_len):
for c in columns_to_build_from:
try:
text += c[i]
except:
text += ""
return text
|
def _rn_daily(rs, rnl):
"""Daily net radiation (Eqs. 15 & 16)
Parameters
----------
rs : scalar or array_like of shape(M, )
Incoming solar radiation [MJ m-2 d-1].
rnl : scalar or array_like of shape(M, )
Net long-wave radiation [MJ m-2 d-1].
Returns
-------
ndarray
Net radiation [MJ m-2 d-1].
"""
return 0.77 * rs - rnl
|
def _myDet(p, q, r):
"""Calc. determinant of a special matrix with three 2D points.
The sign, "-" or "+", determines the side, right or left,
respectivly, on which the point r lies, when measured against
a directed vector from p to q.
"""
# We use Sarrus' Rule to calculate the determinant.
# (could also use the Numeric package...)
sum1 = q[0]*r[1] + p[0]*q[1] + r[0]*p[1]
sum2 = q[0]*p[1] + r[0]*q[1] + p[0]*r[1]
return sum1 - sum2
|
def get_failing_item(state):
"""Return name of failing item or None if none are failing"""
for key, value in state.items():
if not value:
return key
return None
|
def echo(obj):
"""
Prints the value to the console.
"""
print(obj)
return obj
|
def merge_partial(a, b):
"""
:return: Merged value containing the partial combined calculation
"""
if hasattr(a, '__add__'):
return a + b
for key, val in b.items():
if key not in a:
a[key] = val
else:
a[key] = merge_partial(a[key], val)
return a
|
def schema_decorator(decorators_state, cls):
"""Adds cls to decorator_state"""
decorators_state['schema'] = cls()
return cls
|
def _edge_is_between_selections(edge, selection_a, selection_b):
"""
Returns ``True`` is the edge has one end in each selection.
Parameters
----------
edge: tuple[int, int]
selection_a: collections.abc.Container[collections.abc.Hashable]
selection_b: collections.abc.Container[collections.abc.Hashable]
Returns
-------
bool
"""
return (
(edge[0] in selection_a and edge[1] in selection_b)
or (edge[1] in selection_a and edge[0] in selection_b)
)
|
def is_prime(number: int):
"""
This function finds if the number is prime
Returns:
True if prime false otherwise
"""
for index in range(2, (number//2) + 1):
if number%index == 0:
return False
return True
|
def my_confusion_matrix(rater_a, rater_b, sample_weight, min_rating=None, max_rating=None):
"""
Returns the (weighted) confusion matrix between rater's ratings
"""
assert (len(rater_a) == len(rater_b))
if min_rating is None:
min_rating = min(rater_a + rater_b)
if max_rating is None:
max_rating = max(rater_a + rater_b)
num_ratings = int(max_rating - min_rating + 1)
conf_mat = [[0 for i in range(num_ratings)]
for j in range(num_ratings)]
for a, b, w in zip(rater_a, rater_b, sample_weight):
conf_mat[a - min_rating][b - min_rating] += w
return conf_mat
|
def remove_sql_comment_from_string(string):
""" takes a string of the form : part of query -- comment and returns only the former.
:string: part of sql query -- comment type strings
:returns: the part of the sql query
"""
query_part = string.strip().split('--')[0].strip()
return query_part
|
def parameters_analyser(string_instruction):
""" Return a list with the parameters of the instruction.
A post treatment may be required for some instruction """
return string_instruction.split(', ')
|
def is_input_valid(char: str) -> bool:
"""
Helper that checks if input is valid
"""
# is there a char at all?
if char is None:
return False
# check for embedded 0 byte
if char == "\0":
return False
return True
|
def scale(points, scalar):
"""Try really hard to scale 'points' by 'scalar'.
@type points: mixed
@param points: Points can either be:
- a sequence of pairs, in which case the second item will be scaled,
- a list, or
- a number
@type scalar: number
@param scalar: the amount to multiply points by
"""
if type(points) is list:
try:
return [(k, p * scalar) for k, p in points]
except TypeError:
return [p * scalar for p in points]
else:
return points * scalar
|
def compare_version_part(a_part, b_part):
"""Compare two parts of a version number and return the difference (taking into account
versions like 7.0.0-M1)."""
try:
a_bits = a_part.split('-')
b_bits = b_part.split('-')
version_difference = int(a_bits[0]) - int(b_bits[0])
if version_difference != 0 or (len(a_bits) == 1 and len(b_bits) == 1):
return version_difference
if len(a_bits) != len(b_bits):
# Fewer parts indicates a later version (e.g. '7.0.0' is later than '7.0.0-M1')
return len(b_bits) - len(a_bits)
# If letter doesn't match then we can't compare the versions.
a_letter = a_bits[1][0]
b_letter = b_bits[1][0]
if a_letter != b_letter:
return 0
# Try to get number from after M, A or RC and compare this.
a_number_start = [char.isdigit() for char in a_bits[1]].index(True)
b_number_start = [char.isdigit() for char in b_bits[1]].index(True)
return int(a_bits[1][a_number_start:]) - int(b_bits[1][b_number_start:])
except ValueError:
# If the strings aren't in the format we're expecting then we can't compare them.
return 0
|
def prime_sieve(upper, lower=2):
"""Returns a list of primes from 2 to 'upper'"""
if lower < 2:
raise ValueError("Lower bound cannot be lower than 2")
prime_list = list(range(lower, upper))
index = 0
while True:
try:
prime = prime_list[index]
for i in prime_list[index + 1:]:
if i % prime == 0:
prime_list.remove(i)
except IndexError:
break
index += 1
return prime_list
|
def websocketize(value):
"""Convert a HTTP(S) URL into a WS(S) URL."""
if not (value.startswith('http://') or value.startswith('https://')):
raise ValueError('cannot websocketize non-HTTP URL')
return 'ws' + value[len('http'):]
|
def magnitude_relative_error(estimate, actual, balanced=False):
"""
Normalizes the difference between actual and predicted values.
:param estimate:Estimated by the model.
:param actual: Real value in data.
:return: MRE
"""
if not balanced:
denominator = actual
else:
denominator = min(estimate, actual)
if denominator == 0:
# 1 is our normalizing value
# Source: http://math.stackexchange.com/questions/677852/how-to-calculate-relative-error-when-true-value-is-zero
denominator = 1
mre = abs(estimate - actual) / float(denominator)
return mre
|
def get_lattice_points(tup1, tup2, check_diagonals = True):
"""Returns a list of points which lie in a line defined by two endpoints"""
x1, y1 = tup1[0], tup1[1]
x2, y2 = tup2[0], tup2[1]
# for horizontal lines, y values are same
if y1 == y2:
if x1 <= x2:
points = [(i, y1) for i in range(x1, x2 + 1)]
return points
else:
points = [(i, y1) for i in range(x2, x1 + 1)]
return points
# for vertical points, x values are same
elif x1 == x2:
if y1 <= y2:
points = [(x1, i) for i in range(y1, y2 + 1)]
return points
else:
points = [(x1, i) for i in range(y2, y1 + 1)]
return points
elif check_diagonals:
# diagonal lines
slope = (y2-y1)/(x2-x1)
y_int = y1 - slope*x1
# getting the poitns
if x1 <= x2:
points = [(i, int(slope * i + y_int)) for i in range(x1, x2 + 1) if (slope * i + y_int).is_integer()]
return points
else:
points = [(i, int(slope * i + y_int)) for i in range(x2, x1 + 1) if (slope * i + y_int).is_integer()]
return points
|
def is_wildcard_allowed(san_regexes):
"""
:param list[str] san_regexes:
:rtype: bool
"""
if not san_regexes:
return False
for val in san_regexes:
if not val.startswith('[*a'):
return False
return True
|
def get_empty_preference_message(preference_key):
"""
Returns the validation message shown for an empty preference.
"""
return f"Preference '{preference_key}' cannot be set to an empty value."
|
def reverse_table(tab):
"""
This function reverse the table
Parameters :
tab: the list
Returns :
return the reverse table
"""
for i in range(len(tab)//2):
tmp = tab[i]
endVal = len(tab)-i-1
tab[i] = tab[endVal]
tab[endVal] = tmp
return tab
|
def _Spaced(lines):
"""Adds a line of space between the passed in lines."""
spaced_lines = []
for line in lines:
if spaced_lines:
spaced_lines.append(' ')
spaced_lines.append(line)
return spaced_lines
|
def orm_coerce_row(row, extra_columns, result_type):
"""Trim off the extra columns."""
# orm_get_page might have added some extra columns to the query in order
# to get the keys for the bookmark. Here, we split the rows back to the
# requested data and the ordering keys.
N = len(row) - len(extra_columns)
return result_type(row[:N])
|
def cube(x):
"""Cube of x."""
return x * x * x
|
def submit_url(url):
"""Returns the submission url."""
return 'https://class.coursera.org/' + url + '/assignment/submit'
|
def add_up_errors(list_keyerror):
"""
#################################################################################
Description:
Adds in one string the given keyerrors from the list of keyerrors
#################################################################################
:param list_keyerror: list of string
list of keyerrors (strings or None) listing encountered errors
:return keyerror: string
string of all encountered errors concatenated
"""
keyerror = ''
for key in list_keyerror:
if len(keyerror) > 0 and key is not None:
keyerror += " ; "
if key is not None:
keyerror += str(key)
if keyerror == '':
keyerror = None
return keyerror
|
def getChanprofIndex(chanprof, profile, chanList):
""" List of indices into the RTTOV chanprof(:) array corresponding to the chanlist.
NB This assumes you've checked the chanlist against chanprof already.
"""
ilo = sum(map(len, chanprof[:profile-1]))
ichanprof = []
for c in chanList:
ichanprof.append(ilo + chanprof[profile-1].index(c))
return ichanprof
|
def _gr_ymax_ ( graph ) :
""" Get maximal x for the points
>>> graph = ...
>>> ymax = graph.ymax ()
"""
ymx = None
np = len ( graph )
for ip in range ( np ) :
x , y = graph[ip]
if None == ymx or y >= ymx : ymx = y
return ymx
|
def curve(t, acc_t, fast_t, dec_t, slow_t, fast, slow):
"""Returns a speed value between 0 and fast for a given t
t is the time (a float in seconds), from zero at which point acceleration starts
typically t would be incrementing in real time as the door is opening/closing
acc_t is the acceleration time, after which the 'fast' speed is reached
fast_t is the time spent at the fast speed
dec_t is the time spent decelarating from fast to slow
slow_t is the time then spent running at 'slow' speed.
after acc_t + fast_t + dec_t + slow_t, 0.0 is returned
fast is the fast speed, provide a float
slow is the slow speed, provide a float, this is the slow door speed which typically
would take the door to a limit stop switch."""
assert fast > slow > 0.0
duration = acc_t + fast_t + dec_t
full_duration = duration + slow_t
if t >= full_duration:
return 0.0
if t >= duration:
return slow
if t >= acc_t and t <= acc_t + fast_t:
# during fast time, fast should be returned
return fast
# this list must have nine elements describing an acceleration curve from 0.0 to 1.0
c = [0.0, 0.05, 0.15, 0.3, 0.5, 0.7, 0.85, 0.95, 1.0]
# increase from 0.0 to fast during acceleration
if t <= acc_t:
# first calculate an increase from 0.0 to 1.0
# scale acc_t to match the list on the acceleration curve
tacc = t * 8.0 / acc_t # when acc_t = 8, tacc = t
lowindex = int(tacc)
highindex = lowindex + 1
diff = c[highindex] - c[lowindex]
y = diff*tacc + c[lowindex] - diff* lowindex
if y < 0.0:
y = 0.0
# scale 1.0 to be fast
speed = y * fast
return round(speed, 3)
# for the deceleration, treat time in the negative direction
# so rather than a decrease from 1.0 to 0.0, it again looks like
# an increase from 0.0 to 1.0
s = duration - t
if s >= dec_t:
return fast
# scale dec_t to match the list on the acceleration curve
sdec = s * 8.0 / dec_t
lowindex = int(sdec)
highindex = lowindex + 1
diff = c[highindex] - c[lowindex]
y = diff*sdec + c[lowindex] - diff* lowindex
if y < 0.0:
y = 0.0
# 1.0 should become 'fast' and 0.0 should become 'slow'
speed = (fast - slow)*y + slow
return round(speed, 3)
|
def _find_imports(*args):
"""
Helper sorting the named modules into existing and not existing.
"""
import importlib
exists = {
True: [],
False: [],
}
for name in args:
try:
importlib.import_module(name)
exists[True].append(name)
except ImportError:
exists[False].append(name)
return exists
|
def extract_port_num(arg):
"""Extract port number from command line argument."""
port = 0
try:
port = int(arg)
except ValueError:
print("Invalid port number\n")
return port
|
def _get_reputation(followers, following):
"""Get reputation of user."""
try:
return followers / (followers + following)
except ZeroDivisionError:
return 0.0
|
def cli_err_msg(cmd, err):
""" get cli exception message"""
if not err:
return "Error: Fail to get cli exception message."
msg = list()
err_list = str(err).split("\r\n")
for err in err_list:
err = err.strip('.,\r\n\t ')
if not err:
continue
if cmd and cmd == err:
continue
if " at '^' position" in err:
err = err.replace(" at '^' position", "").strip()
err = err.strip('.,\r\n\t ')
if err == "^":
continue
if len(err) > 2 and err[0] in ["<", "["] and err[-1] in [">", "]"]:
continue
err.strip('.,\r\n\t ')
if err:
msg.append(err)
if cmd:
msg.insert(0, "Command: %s" % cmd)
return ", ".join(msg).capitalize() + "."
|
def tupleRemoveByIndex(initTuple, indexList):
"""
Remove the elements of given indices from a tuple.
Parameters
----------
initTuple : tuple of any
The given tuple from which we will remove elements.
indexList : list of ints
The indices of elements that we want to remove.
Returns
-------
tuple of any
The tuple after removing elements from initTuple
"""
initList = list(initTuple)
indexSet = set(indexList)
resList = []
for i in range(len(initList)):
if not (i in indexSet):
resList.append(initList[i])
return tuple(resList)
|
def make_full_size_url(image_name):
"""Return the URL to the full size of the file."""
base_url = "http://commons.wikimedia.org/w/index.php?title=Special:FilePath&file=%s"
return base_url % (image_name)
|
def words_are_alphabetic(word_list, debug):
"""Return whether words in list are sorted alphabetically."""
return sorted(word_list) == word_list
|
def break_words(stuff):
"""This fuction will break up words for us."""
words = stuff.split(' ')
return words
|
def fib(number):
"""Get the Nth Fibonacci number, cache intermediate results in Redis."""
if number < 0:
raise ValueError
if number in (0, 1):
return number
return fib(number - 1) + fib(number - 2)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.