content stringlengths 42 6.51k |
|---|
def make_batch_indexes(size, data_len):
"""
Creates a list of start and stop indexes where start is <size> away from end.
The start and stop indexes represent the start and stop index of each batch ranging for the entire data set.
Parameters
----------
size: int
The size of the batches.
data_len: int
The number of rows in the data.
Returns
-------
list:
A list of list that where the first item in the sublist is the start index and the second is the end index of
that batch.
"""
start_i = 0
end_i = size
index_couples = []
while end_i <= data_len:
couplet = [start_i, end_i]
index_couples.append(couplet)
start_i = end_i
end_i += size
final_couplet = [end_i - size, data_len]
index_couples.append(final_couplet)
return index_couples |
def is_odd(x):
"""returns true only if x is odd"""
return x % 2 != 0 |
def Binary(data):
"""returns binary encoding of data"""
return ''.join(["%02X" % ord(i) for i in data]) |
def time_check(message):
"""
check if the duration for the quick search preference is a valid input
"""
time = 0
try:
time = int(message)
except Exception as e:
return False
if time < 1 or time > 8:
return False
return True |
def getsearchtype(searchtype):
"""Returns search code for posting requests to http://apps.webofknowledge.com/UA_GeneralSearch.do"""
if searchtype == 'title':
search = 'TI'
elif searchtype == 'topic':
search = 'TS'
elif searchtype == 'author':
search = 'AU'
elif searchtype == 'author identifiers':
search = 'AI'
elif searchtype == 'editor':
search = 'ED'
elif searchtype == 'group author':
search = 'GP'
elif searchtype == 'publication name':
search = 'SO'
elif searchtype == 'doi':
search = 'DO'
elif searchtype == 'year published':
search = 'PY'
elif searchtype == 'address':
search = 'AD'
else:
raise Exception('Error searchType invalid')
return search |
def _format_num_lists_already_formatted(num_lists):
"""
This function assumes that the numbers are already within the given bases and do not have leading zeros, or "already formated"
An example is [1, 20]. All the values, "1" and "20", are less than the given bases [24, 60] for 24 hour time
Replace any use of _format_num_lists() with this function if you know that you're only going to be dealing with already formatted numbers
"""
max_len = 0
nums = []
for a_num in num_lists:
# format negative numbers
if a_num[0] < 0:
a_num = [-value for value in reversed(a_num)]
a_num[-1] = -a_num[-1]
nums.append(a_num)
else:
nums.append(a_num[::-1])
# find length of longest num
length = len(a_num)
if length > max_len:
max_len = length
# add trailing zeros so that all numbers are equal length
return [a_num + (max_len - len(a_num)) * [0] if len(a_num) < max_len else a_num for a_num in nums] |
def fmt(n):
"""format number with a space in front if it is single digit"""
if n < 10:
return " " + str(n)
else:
return str(n) |
def median(array):
"""
Calculates the median of an array/vector
"""
import numpy as np
array=np.array(array)
result= np.median(array)
return result |
def authorization_method(original_method):
"""The method that will be injected into the authorization target to perform authorization"""
global _authorization_method
_authorization_method = original_method
return original_method |
def scale3(v, s):
"""
scale3
"""
return (v[0] * s, v[1] * s, v[2] * s) |
def ABCDFrequencyList_to_SFrequencyList(ABCD_frequency_list,Z01=complex(50,0),Z02=complex(50,0)):
""" Converts ABCD parameters into s-parameters. ABCD-parameters should be in the form [[f,A,B,C,D],...]
Returns data in the form
[[f,S11,S12,S21,S22],...],
"""
s_frequency_list=[]
for row in ABCD_frequency_list[:]:
[frequency,A,B,C,D]=row
denominator=A*Z02+B+C*Z01*Z02+D*Z01
S11=(A*Z02+B-C*Z01.conjugate()*Z02-D*Z01.conjugate())/denominator
S12=-1*(2*(Z01.real*Z02.real)**(.5))/denominator
S21=-1*(2*(Z01.real*Z02.real)**(.5))/denominator
S22=(-1*A*Z02.conjugate()+B-C*Z01*Z02+D*Z01)/denominator
s_frequency_list.append([frequency,S11,S12,S21,S22])
return s_frequency_list |
def compute_wu_bound_strong(lipschitz_constant, gamma, n_samples, batch_size, verbose=True):
"""
compute the bound in the strongly convex case
basically copied from
https://github.com/tensorflow/privacy/blob/1ce8cd4032b06e8afa475747a105cfcb01c52ebe/tensorflow_privacy/privacy/bolt_on/optimizers.py
"""
# note that for the strongly convex setting, the learning rate at every point is the minimum of (1/beta, 1/(eta *t))
# this isn't really important here
# it's just good to remember that if this wasn't the case, this bound doesn't hold! (that we know of)
l2_sensitivity = (2 * lipschitz_constant) / (gamma * n_samples * batch_size)
if verbose:
print('[noise_utils] Bound on L2 sensitivity:', l2_sensitivity)
return l2_sensitivity |
def is_bg(file):
""" if image file is background map """
return file.endswith('_bg.png') |
def file_name_to_ref_p_and_restored_p(fileName):
"""
Returns the appropriate filename based on the extension as denoted in the pipeline
:param fileName:
:return: Tuple of reference and restored filenames
"""
refPuncFileName = fileName + "_reference_punc.txt"
restoredPuncFileName = fileName + "_restored_punc.txt"
return refPuncFileName, restoredPuncFileName |
def _has_symbol(symbol, name):
"""
Check if has provided symbol in name.
Recognizes either the _SYMBOL pattern at end of string, or _SYMBOL_ in
middle.
"""
return name.endswith('_' + symbol) or ('_' + symbol + '_') in name |
def hourAngleFormatter(ra):
"""String formatter for "hh:mm"
Args:
deg: float
Return:
String
"""
if ra < 0:
ra += 360
hours = int(ra//15)
minutes = int(float(ra - hours*15)/15 * 60)
if minutes:
return "${:d}^{{{:>02}}}$h".format(hours, minutes)
return "${:d}$h".format(hours) |
def solution(A):
# write your code in Python 3.6
"""
########PSEUDOCODE###########
sort array
for index in range(len):
if index == 0:
continue
if array[index] == array[index - 1]:
continue
if array[index] - array[index - 1] > 1:
if array[index] < 1:
return 1
else:
return array[index] - 1
"""
A.sort()
print(A)
for index in range(len(A)):
if index == 0:
continue
if A[index] == A[index - 1]:
continue
if A[index] - A[index - 1] > 1:
if A[index - 1]+1 < 1:
return 1
else:
return A[index - 1] + 1
return A[-1]+1 |
def to_int(a):
"""Length of linked list"""
i = 0
while a:
i += 1
a = a.next
return i |
def find_indices(predicate, List):
"""
Returns an array of all the indices of the
elements which pass the predicate. Returns an
empty list if the predicate never passes.
find-indices even, [1 2 3 4] #=> [1, 3]
>>> find_indices(lambda x: x > 2, [1, 2, 30, 404, 0, -1, 90])
[2, 3, 6]
"""
result = []
for i, x in enumerate(List):
if predicate(x):
result.append(i)
return result |
def perform_iteration(ring, length, pos):
"""
Solve the Day 10 puzzle.
"""
if pos + length < len(ring):
ring[pos: pos+length] = ring[pos: pos+length][::-1]
else:
seq = ring[pos:] + ring[:pos + length - len(ring)]
len_new_left = pos + length - len(ring)
len_new_right = len(ring) - pos
new_left = seq[:len_new_left][::-1]
new_right = seq[-len_new_right:][::-1]
ring[:len(new_left)] = new_left
ring[-len(new_right):] = new_right
return ring |
def count_ones(n):
"""
:type n: int
:rtype: int
"""
counter = 0
while n:
counter += n & 1
n >>= 1
return counter |
def block_sizes(max_size):
"""
Return all possible block sizes of an inter-predicted frame (min size is 4x8 or 8x4)
:param max_size: maximum exponent of the power of 2 specifying width/height (e.g. 6 = 32x32), max value is 8
:return: string list of "width x height" sizes
"""
if max_size > 8:
raise ValueError("Invalid max_size value specified!")
else:
return [f"{2**x}x{2**y}" for x in range(2, max_size) for y in range(2, max_size) if x != 2 or y != 2] |
def convert_to_snake(inputstring: str):
"""Convert inputstring from camel case to snake case."""
return ''.join('_' + char.lower() if char.isupper() else char for char in inputstring).lstrip('_') |
def _deweird(s):
"""
Sometimes numpy loadtxt returns strings like "b'stuff'"
This converts them to "stuff"
@ In, s, str, possibly weird string
@ Out, _deweird, str, possibly less weird string
"""
if type(s) == str and s.startswith("b'") and s.endswith("'"):
return s[2:-1]
else:
return s |
def f1_score (true_positive, positive, gt_positive):
"""Compute the F1-score
Args:
true_positive (Int): Number of true positives
positive (Int): Number of positively classified samples
gt_positive (Int): Number of effectively positive samples
Returns:
float: F1-score
"""
if positive <= 0 or gt_positive <= 0 or true_positive <= 0:
return 0
precision = true_positive / positive
recall = true_positive / gt_positive
return 2 / (1 / precision + 1 / recall) |
def encode_to_bytes(value, encoding="utf-8"):
"""Returns an encoded version of the string as a bytes object.
Args:
encoding (str): The encoding.
Resturns:
bytes: The encoded version of the string as a bytes object.
"""
return value if isinstance(value, bytes) else value.encode(encoding) |
def to_dict(d, default=None):
"""
Convert a ``dict`` or a ``list`` of pairs or single keys (or mixed) into a ``dict``.
If a list element is single, `default` value is used.
"""
if d is None:
return {}
if isinstance(d,dict):
return d
res={}
for e in d:
if isinstance(e,list) or isinstance(e,tuple):
res[d[0]]=d[1]
else:
res[d[0]]=default
return res |
def get_density(lon, lat, alt, datarr, datlats):
"""
Function for taking array of electron densities and returning the right one
for a particular location/altitude.
(You give us the data and we'll do the work for you!)
The density array is assumed to have the form of Rob Gillies' density profiles
which have some header information in the first line, followed by lines that
possess these fields: { num of latitudinal division, latitude start, [data]}
e.g. { 2 48 1.000000000E01 1.00003E01 .. 6.239E10 .... }
**These electron densities are in terms of m^3**
***PARAMS***
lon [float]: longitude to check density at [deg]
lat [float: latitude to check density at [deg]
alt [float]: altitude to check density at [km]
***RETURNS***
<density> [float]: electron number density from the densities array [m^-3]
"""
import numpy as np
if lat > np.max(datlats) or lat < np.min(datlats):
#print("No data for that latitude - using closest latitude...")
lat = np.max(datlats) if lat > np.max(datlats) else np.min(datlats)
if alt > 559 or alt < 60:
print("No data for that altitude")
return -1
for i,dlat in enumerate(datlats):
alt_index = int(alt - 60)
if lat < dlat:
return datarr[i-1][alt_index]
elif lat == dlat:
return datarr[i][alt_index]
return 0 |
def LabelIsMaskedByField(label, field_names):
"""If the label should be displayed as a field, return the field name.
Args:
label: string label to consider.
field_names: a list of field names in lowercase.
Returns:
If masked, return the lowercase name of the field, otherwise None. A label
is masked by a custom field if the field name "Foo" matches the key part of
a key-value label "Foo-Bar".
"""
if '-' not in label:
return None
for field_name_lower in field_names:
if label.lower().startswith(field_name_lower + '-'):
return field_name_lower
return None |
def int_prop(name, node):
"""Boolean property"""
try:
return int(node.get(name))
except KeyError:
return None |
def _validate_bokeh_marker(value):
"""Validate the markers."""
all_markers = (
"Asterisk",
"Circle",
"CircleCross",
"CircleX",
"Cross",
"Dash",
"Diamond",
"DiamondCross",
"Hex",
"InvertedTriangle",
"Square",
"SquareCross",
"SquareX",
"Triangle",
"X",
)
if value not in all_markers:
raise ValueError(f"{value} is not one of {all_markers}")
return value |
def check_tie(board):
""" Checks if the board's state is tie.
"""
for element in board:
if not element:
return False
return True |
def _PointListToSVG(points, dupFirst=0):
""" convenience function for converting a list of points to a string
suitable for passing to SVG path operations
"""
outStr = ''
for i in range(len(points)):
outStr = outStr + '%.2f,%.2f ' % (points[i][0], points[i][1])
# add back on the first point. This is not required in the spec,
# but Adobe's beta-quality viewer seems to not like it being skipped
if dupFirst == 1:
outStr = outStr + '%.2f,%.2f' % (points[0][0], points[0][1])
return outStr |
def valid_file(path: str) -> bool:
"""
Check if regressi file is valid
:param path: path to the file to test
:return: whether the file is valid or not
"""
with open(path, 'r') as file:
if file.readline() == "EVARISTE REGRESSI WINDOWS 1.0":
return False
else:
return True |
def minify_html(html):
"""Perform a template-specific, rudimentary HTML minification for displaCy.
Disclaimer: NOT a general-purpose solution, only removes indentation and
newlines.
html (unicode): Markup to minify.
RETURNS (unicode): "Minified" HTML.
"""
return html.strip().replace(" ", "").replace("\n", "") |
def prettyPrint(string, maxlen=75, split=" "):
"""Pretty prints the given string to break at an occurrence of
split where necessary to avoid lines longer than maxlen.
This will overflow the line if no convenient occurrence of split
is found"""
# Tack on the splitting character to guarantee a final match
string += split
lines = []
oldeol = 0
eol = 0
while not (eol == -1 or eol == len(string) - 1):
eol = string.rfind(split, oldeol, oldeol + maxlen + len(split))
lines.append(string[oldeol:eol])
oldeol = eol + len(split)
return lines |
def recursive_rename_keys(old_dict: dict, old_to_new_map: dict):
"""
Given a nested dictionary 'old_dict', recursively update all keys according to old_to_new_map
"""
if not isinstance(old_dict, dict):
return old_dict
new_dict = {}
for key, value in old_dict.items():
if key in old_to_new_map:
new_dict[old_to_new_map[key]] = recursive_rename_keys(value, old_to_new_map)
else:
new_dict[key] = recursive_rename_keys(value, old_to_new_map)
return new_dict |
def func_a_p(a=2, *, p="p"):
"""func.
Parameters
----------
a: int
p: str, optional
Returns
-------
a: int
p: str
"""
return None, None, a, None, p, None, None, None |
def link_cmd(path, link):
"""Returns link creation command."""
return ['ln', '-sfn', path, link] |
def frange(range_def, sep=','):
"""
Return the full, unabbreviated list of ints suggested by range_def.
This function takes a string of abbreviated ranges, possibly
delimited by a comma (or some other character) and extrapolates
its full, unabbreviated list of ints.
Parameters
----------
range_def : str
The range string to be listed in full.
sep : str, default=','
The character that should be used to delimit discrete entries in
range_def.
Returns
-------
res : list
The exploded list of ints indicated by range_def.
"""
res = []
for item in range_def.split(sep):
if '-' in item:
a, b = item.split('-')
a, b = int(a), int(b)
lo = min([a, b])
hi = max([a, b])
ints = range(lo, hi+1)
if b <= a:
ints = list(reversed(ints))
res.extend(ints)
else:
res.append(int(item))
return res |
def to_int_percent(items):
""" Converts a list of numbers to a list of integers that exactly sum to
100. """
nitems = len(items)
total = sum(items)
if total == 0:
return [0] * nitems
perc = [100 * p // total for p in items]
s = sum(perc)
i = 0
while s < 100:
if items[i] > 0:
perc[i] += 1
s += 1
i = (i + 1) % nitems
return perc |
def white_to_len(string, length):
"""
Fills white space into a string to get to an appropriate length. If the string is too long, it cuts it off.
:param string: String to format.
:param length: The desired length.
:return: The final string.
"""
if len(string) < length:
string = string + (length - len(string)) * " "
else:
string = string[0: length - 3] + "..."
return string |
def xor(message, key):
""" Xor a message with a key.
"""
return bytes(m ^ k for m, k in zip(message, key)) |
def tsv_line(value_list):
"""Create tab-delimited line from Python list
Given a Python list, returns a tab-delimited string with
each value in the last converted to a string.
Arguments:
value_list: Python list of values
Returns:
String with list values separated by tabs.
"""
return '\t'.join([str(x) for x in value_list]) |
def find_relocation(func, start, end):
"""
Finds a relocation from `start` to `end`. If `start`==`end`, then they will be expanded to the closest instruction boundary
:param func: function start and end are contained in
:param start: start address
:param end: end address
:return: corrected start and end addresses for the relocation
"""
if end != start: # relocation isn't stupid
return start, end - start
# relocation is stupid (start==end), so just expand to the whole instruction
bb = func.get_basic_block_at(start)
if not bb: # not in a basicblock, don't care.
return None, None
bb._buildStartCache()
for i, insn_start in enumerate(bb._instStarts):
insn_end = insn_start + bb._instLengths[i]
if (insn_start < end and start < insn_end) or (start == end and insn_start <= start < insn_end):
return insn_start, bb._instLengths[i] |
def unique_list(lst):
"""Make a list unique, retaining order of initial appearance."""
uniq = []
for item in lst:
if item not in uniq:
uniq.append(item)
return uniq |
def join(a, *p):
"""Join two or more pathname components, inserting '/' as needed.
If any component is an absolute path, all previous path components
will be discarded."""
path = a
for b in p:
if b.startswith('/'):
path = b
elif path == '' or path.endswith('/'):
path += b
else:
path += '/' + b
return path |
def simple_object_hash(obj):
"""
Turn an arbitrary object into a hash string. Use SHA1.
"""
import hashlib
obj_str = str(obj)
hash_object = hashlib.sha1(obj_str.encode())
hex_dig = hash_object.hexdigest()
return hex_dig |
def expand_prefix(tag, prefixes):
"""
Substitutes the namespace prefix, if any, with the actual namespace in an XML tag.
:param tag: the XML tag
:type tag: str
:param prefixes: the prefix mapping
:type prefixes: dict
:return: the tag with the explicit XML namespace
"""
# See if `name` is in the form `ns:attr`
# where `ns` is listed as an XML prefix
parts = tag.split(':')
# If `ns` is listed as a prefix, substitute the prefix to get `{<ns value>}attr`
if len(parts) > 1 and parts[0] in prefixes:
return '{' + prefixes[parts[0]] + '}' + parts[1]
return tag |
def map_vectors(vectors, fun):
"""map function over vectors of image information"""
new_vectors = []
for vector in vectors:
new_vector = []
for elem in vector:
new_vector.append(fun(elem))
return(new_vectors) |
def map_range(value, from_min=0, from_max=1, to_min=0, to_max=1):
"""
Scale value from
Thanks to this SO post: http://stackoverflow.com/a/5295202/2730823
"""
return ((to_max-to_min)*(value - from_min) / (from_max - from_min)) + to_min |
def extract_node_name(node_address):
"""Given a graph node address, returns the label. For the sake of clarity, COMMENT node addresses return empty.
:param node_address: The node address
:return: The label
"""
node_type = node_address[2]
if node_type == "COMMIT":
return node_address[3][-7:]
elif node_type == "REPO":
return node_address[3] + '/' + node_address[4]
elif node_type == "USERLIKE":
return node_address[4]
elif node_type == "ISSUE":
return node_address[5]
elif node_type == "REPO":
return node_address[5]
elif node_type == "COMMENT":
return "" |
def _excel2num(x):
"""
Convert Excel column name like 'AB' to 0-based column index.
Parameters
----------
x : str
The Excel column name to convert to a 0-based column index.
Returns
-------
num : int
The column index corresponding to the name.
Raises
------
ValueError
Part of the Excel column name was invalid.
"""
index = 0
for c in x.upper().strip():
cp = ord(c)
if cp < ord("A") or cp > ord("Z"):
raise ValueError("Invalid column name: {x}".format(x=x))
index = index * 26 + cp - ord("A") + 1
return index - 1 |
def now(timespec='auto'):
""" Datetime string
Returns:
str : datetime now
"""
import datetime
return datetime.datetime.now().isoformat(timespec=timespec) |
def format_tag(organization, standard, version, tag_name):
"""
Format a YAML tag.
"""
return 'tag:{0}:{1}/{2}-{3}'.format(
organization, standard, tag_name, version) |
def flip_array_bit(ba, bitnum):
"""flips a bit in an array, 0 = MSB. Works with numpy arrays or byte arrays"""
ba[bitnum >> 3] ^= (1 << (7 - (bitnum % 8)))
return ba |
def fullname(o):
""" Returns a full module name of an object"""
return o.__module__ + "." + o.__name__ |
def compute_map(P):
"""Solution to exercise R-13.6.
Compute a map representing the last function used in the Boyer-Moore
pattern-matching algorithm for characters in the pattern string:
"the quick brown fox jumped over a lazy cat".
"""
m = len(P)
last = {}
for k in range(m):
last[P[k]] = k
return last |
def unit_test_sorting(func, *args):
"""
Unit testing, but only for sorting functions.
"""
out = func(*args)
if out is None:
out = args[0]
exp = sorted(args[0])
if out != exp:
print("Test Failed: " + func.func_name)
print("Expected = " + str(exp))
print("Actual = " + str(out))
exit(1)
return out |
def split_tag(tag):
"""
parse an xml tag into the tag itself and the tag index
Parameters
----------
tag : str
xml tag that might or might not have a [n] item
Returns
-------
tuple: fgdc_tag, index
"""
if "[" in tag:
fgdc_tag, tag = tag.split("[")
index = int(tag.split("]")[0]) - 1
else:
fgdc_tag = tag
index = 0
return fgdc_tag, index |
def check_goal(state):
"""
Returns True if state is the goal state. Otherwise, returns False.
"""
n = len(state[0])
for i in range(0, n):
for j in range(0, n):
if state[i][j] != (j + 1) + (i * n):
if not(i == j == (n - 1) and state[i][j] == '*'):
return False
return True |
def discard_unknown_labels(labels):
"""Function for discarding medial wall (unknown) labels from a list
of labels.
Input arguments:
================
labels : list
List of labels. Each label must be an instance of the MNE-Python
Label class.
Output arguments:
=================
cleaned_labels : list
List of retained labels.
"""
cleaned_labels = []
for i, label in enumerate(labels):
if ('unknown' not in label.name.lower()):
cleaned_labels.append(label)
return cleaned_labels |
def decode_dict(obj: dict) -> dict:
"""
This function simply parses a dict from the Redis database
and decode every value.
returns: dict
"""
return {key.decode("utf-8"): val.decode("utf-8")
for key, val in obj.items()} |
def And(input1,input2):
"""
Logic for AND operation
Parameters
----------
input1 (Required) : First input value. Should be 0 or 1.
input2 (Required) : Second input value. Should be 0 or 1.
"""
return f"( {input1} & {input2} )" |
def compute_sliced_len(slc, sequence_len):
"""
Compute length of sliced object.
Parameters
----------
slc : slice
Slice object.
sequence_len : int
Length of sequence, to which slice will be applied.
Returns
-------
int
Length of object after applying slice object on it.
"""
# This will translate slice to a range, from which we can retrieve length
return len(range(*slc.indices(sequence_len))) |
def encode_run_length(string):
"""I'm aware this is a dirty solution."""
encoded = ""
count = 1
for char, next_char in zip(string, string[1:] + "\n"):
if char == next_char:
count += 1
else:
encoded += f"{count}{char}"
count = 1
return encoded |
def add_xy_grid_meta(coords):
"""Add x,y metadata to coordinates"""
# add metadata to x,y coordinates
if "x" in coords:
x_coord_attrs = dict(coords["x"].attrs)
x_coord_attrs["long_name"] = "x coordinate of projection"
x_coord_attrs["standard_name"] = "projection_x_coordinate"
coords["x"].attrs = x_coord_attrs
elif "longitude" in coords:
x_coord_attrs = dict(coords["longitude"].attrs)
x_coord_attrs["long_name"] = "longitude"
x_coord_attrs["standard_name"] = "longitude"
coords["longitude"].attrs = x_coord_attrs
if "y" in coords:
y_coord_attrs = dict(coords["y"].attrs)
y_coord_attrs["long_name"] = "y coordinate of projection"
y_coord_attrs["standard_name"] = "projection_y_coordinate"
coords["y"].attrs = y_coord_attrs
elif "latitude" in coords:
x_coord_attrs = dict(coords["latitude"].attrs)
x_coord_attrs["long_name"] = "latitude"
x_coord_attrs["standard_name"] = "latitude"
coords["latitude"].attrs = x_coord_attrs
return coords |
def remove_punc(sent):
"""
Filter out punctuations
"""
punc_lst = [".", ",", "!", "?", ";"]
for punctuation in punc_lst:
sent = sent.replace(punctuation, "")
sent = sent.replace(" ", " ")
return sent |
def gather_possible_containers(the_rules, bag_color="shiny gold"):
"""
evaluate recursively how many continers can possibly contain a bag_color colored bag
"""
containers_found = []
for rule in the_rules:
for child in rule['children']:
if child['color'] == bag_color and rule['color'] not in containers_found:
containers_found.append(rule['color'])
containers_found.extend(gather_possible_containers(the_rules, rule['color']))
return containers_found |
def get_minmax_size(bbox):
"""Get aspect ratio of bbox"""
ymin, xmin, ymax, xmax = bbox
width, height = xmax - xmin, ymax - ymin
min_size = min(width, height)
max_size = max(width, height)
return min_size, max_size |
def date_time(seconds):
"""Current date and time as formatted ASCII text, precise to 1 ms
seconds: time elapsed since 1 Jan 1970 00:00:00 UST"""
from datetime import datetime
timestamp = str(datetime.fromtimestamp(seconds))
return timestamp |
def _get_color_list(n_sets):
"""
color list for dimensionality reduction plots
Args:
n_sets: number of dataset
Returns:
list of colors for n_sets
"""
color_list = ['#1a9850', '#f46d43', '#762a83', '#41b6c4',
'#ffff33', '#a50026', '#dd3497', '#ffffff',
'#36454f', '#081d58', '#d9ef8b', '#fee08b']
return color_list[:n_sets] |
def is_palindrome_v3(s):
""" (str) -> bool
Return True if and only if s is a palindrome.
>>> is_palindrome_v3('noon')
True
>>> is_palindrome_v3('racecar')
True
>>> is_palindrome_v3('dented')
False
>>> is_palindrome_v3('')
True
>>> is_palindrome_v3(' ')
True
"""
j = len(s) - 1
for i in range(len(s) // 2):
if s[i] != s[j - i]:
return False
return True |
def transform_annotation(annotation):
"""Transform annotation dumbly, asserting it is a string."""
assert isinstance(annotation, str)
return annotation |
def unitary_gate_counts_real_deterministic(shots, hex_counts=True):
"""Unitary gate circuits reference counts."""
targets = []
if hex_counts:
# CX01, |00> state
targets.append({'0x0': shots}) # {"00": shots}
# CX10, |00> state
targets.append({'0x0': shots}) # {"00": shots}
# CX01.(X^I), |10> state
targets.append({'0x2': shots}) # {"00": shots}
# CX10.(I^X), |01> state
targets.append({'0x1': shots}) # {"00": shots}
# CX01.(I^X), |11> state
targets.append({'0x3': shots}) # {"00": shots}
# CX10.(X^I), |11> state
targets.append({'0x3': shots}) # {"00": shots}
else:
# CX01, |00> state
targets.append({'00': shots}) # {"00": shots}
# CX10, |00> state
targets.append({'00': shots}) # {"00": shots}
# CX01.(X^I), |10> state
targets.append({'10': shots}) # {"00": shots}
# CX10.(I^X), |01> state
targets.append({'01': shots}) # {"00": shots}
# CX01.(I^X), |11> state
targets.append({'11': shots}) # {"00": shots}
# CX10.(X^I), |11> state
return targets |
def _trim_doc_string(text):
""" Trims a doc string to make it format
correctly with structured text. """
lines = text.replace('\r\n', '\n').split('\n')
nlines = [lines.pop(0)]
if lines:
min_indent = min([len(line) - len(line.lstrip())
for line in lines])
for line in lines:
nlines.append(line[min_indent:])
return '\n'.join(nlines) |
def total_reward(responses):
"""Calculates the total reward from a list of responses.
Args:
responses: A list of SimpleSequentialResponse objects
Returns:
reward: A float representing the total clicks from the responses
"""
reward = 0.0
for r in responses:
reward += r.reward
return reward |
def get_field_names(elems):
""" Return unique name attributes """
res = []
seen = set()
for el in elems:
if (not getattr(el, 'name', None)) or (el.name in seen):
continue
seen.add(el.name)
res.append(el.name)
return res |
def recall_at(target, scores, k):
"""Calculation for recall at k."""
if target in scores[:k]:
return 1.0
else:
return 0.0 |
def get_short_desc(long_desc):
""" Get first sentence of first paragraph of long description """
found = False
olines = []
for line in [item.rstrip() for item in long_desc.split('\n')]:
if (found and (((not line) and (not olines))
or (line and olines))):
olines.append(line)
elif found and olines and (not line):
return (' '.join(olines).split('.')[0]).strip()
found = line == '.. [[[end]]]' if not found else found |
def IsFPExt(path, extentions):
""" Returns whether the file in the filepath is in the extension/type list given.
:param path str: file path
:param extentions list: extension/type list
:returns boolean:
"""
is_ext = False
for ext in extentions:
if path.endswith(ext):
is_ext = True
return is_ext |
def get_word(line):
"""
Get word from each line
:param line: line from FILE
:return: str, word got from line
"""
word = ''
# Run each letter in line
for ch in line:
if ch.islower():
word += ch
return word |
def sub2indSH(m,n):
"""
i = sub2indSH(m,n)
Convert Spherical Harmonic (m,n) indices to array index i
Assumes that i iterates from 0 (Python style)
"""
i = n**2 + n + m
return i |
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
# Preserve unicode (if path is unicode)
#slash, dot = (u'/', u'.') if isinstance(path, _unicode) else ('/', '.')
slash, dot = ('/', '.')
if path == '':
return dot
initial_slashes = path.startswith('/')
# POSIX allows one or two initial slashes, but treats three or more
# as single slash.
if (initial_slashes and
path.startswith('//') and not path.startswith('///')):
initial_slashes = 2
comps = path.split('/')
new_comps = []
for comp in comps:
if comp in ('', '.'):
continue
if (comp != '..' or (not initial_slashes and not new_comps) or
(new_comps and new_comps[-1] == '..')):
new_comps.append(comp)
elif new_comps:
new_comps.pop()
comps = new_comps
path = slash.join(comps)
if initial_slashes:
path = slash*initial_slashes + path
return path or dot |
def cmp(x, y):
"""
Replacement for built-in funciton cmp that was removed in Python 3
Compare the two objects x and y and return an integer according to
the outcome. The return value is negative if x < y, zero if x == y
and strictly positive if x > y.
"""
if x is None and y is None:
return 0
elif x is None:
return -1
elif y is None:
return 1
return (x > y) - (x < y) |
def get_images_regions(body_response):
"""
Gets the list of regions that have been found in the Image service with its public URL
:param body_response: Keystone response (/token)
:return: List of regions found with name and public URL
"""
service_list = body_response['access']['serviceCatalog']
regions = []
for service in service_list:
if service['type'] == 'image':
for endpoint in service['endpoints']:
regions.append({'region': endpoint['region'], 'public_url': endpoint['publicURL']})
return regions |
def solve_a(grid):
"""Solve Part A"""
overlapping = 0
for pos in grid:
# count how many ids are stored at each position
# any inches with more than one claim id are considered overlapping
if len(grid[pos]) > 1:
overlapping += 1
return overlapping |
def try_get(src, getter, expected_type=None):
"""Getter for Object with type checking.
Args:
src (object): Object for getter.
getter (lambda): Lambda expression for getting item from Object.
expected_type (type, optional): Expected type from the getter. Defaults to None.
Returns:
expected_type: Value of getter for Object.
"""
if not isinstance(getter, (list, tuple)):
getter = [getter]
for get in getter:
try:
v = get(src)
except (AttributeError, KeyError, TypeError, IndexError):
pass
else:
if expected_type is None or isinstance(v, expected_type):
return v |
def parse_unknown_args(uargs):
"""uargs: a list of strings from the command line.
parse using the rule nargs='+' """
uargdict = {}
if not uargs:
return uargdict
opt = ''
values = []
while uargs:
term = uargs.pop(0)
if term.startswith('--') or term.startswith('-'):
if (not values) and opt:
logger.error("Invalid option. At least one value needed for %s", opt)
exit(errno.EINVAL)
if not uargs:
logger.error("Invalid option. At least one value needed for %s", term)
exit(errno.EINVAL)
opt=term
values = uargdict.setdefault(opt.lstrip('-'), [])
else:
values.append(term)
return uargdict |
def clean(in_word):
"""cast to lowercase alpha-only."""
chars = []
for c in in_word:
if c.isalpha():
chars.append(c.lower())
return "".join(chars) |
def ZellerDayOfWeek(input_date):
"""Uses Zeller's congruence (Gregorian) to return the day of week.
Returns 0 for Saturday, 1 for Sunday, .... 6 for Friday"""
date = [0,0,0]
date[0] = input_date[0]
date[1] = input_date[1]
date[2] = input_date[2]
if date[1] == 1 or date[1] == 2:
date[1] += 12
date[0] -= 1
q = date[2] #day of month
m = date[1] #month
K = date[0] % 100 #year of century (year % 100)
J = date[0] // 100 #century (19 for 19xx, etc)
my_sum = q
my_sum += ((13 * (m + 1)) // 5)
my_sum += K
my_sum += (K // 4)
my_sum += (J // 4)
my_sum += 5 * J
return my_sum % 7 |
def join_paths(*args):
"""Join paths without duplicating separators.
This is roughly equivalent to Python's `os.path.join`.
Args:
*args (:obj:`list` of :obj:`str`): Path components to be joined.
Returns:
:obj:`str`: The concatenation of the input path components.
"""
result = ""
for part in args:
if part.endswith("/"):
part = part[-1]
if part == "" or part == ".":
continue
result += part + "/"
return result[:-1] |
def currency_display(value, currency='AUD', show_complete=False, include_sign=True):
"""
Create a human readable string to display a currency from some number of smallest units (e.g. cents).
:param value: value of currency in smallest units (cents)
:param currency: e.g. 'AUD'
:param show_complete: if True, show '$5.00' rather than '$5'
:param include_sign: Include the e.g. dollar sign
:return:
"""
if currency != 'AUD':
raise NotImplementedError('Only AUD currently supported')
unit_modulo = 100
large_units = int(value / unit_modulo)
small_units = value % unit_modulo
sign = '$' if include_sign else ''
if show_complete or small_units:
return '{sign}{large}.{small:02}'.format(sign=sign, large=large_units, small=small_units)
else:
return '{sign}{large}'.format(sign=sign, large=large_units) |
def ordinalize(given_number: int) -> str:
"""Ordinalize the number from the given number
Args:
given_number (int): integer number
Example:
>>> ordinalize(34)
'34th'
Returns:
str: string in ordinal form
"""
suffix = ["th", "st", "nd", "rd"]
thenum = int(given_number)
if thenum % 10 in [1, 2, 3] and thenum not in [11, 12, 13]:
return f'{thenum}{suffix[thenum % 10]}'
else:
return f'{thenum}{suffix[0]}' |
def kwargs_to_filter(kw):
"""Converts key/values in the form year=yyyy to key/values usable as queryset
filters, pretty inefficient and with no checks on data.
"""
d = {}
for k in ('year', 'month', 'day', 'hour', 'minute', 'second'):
if k in kw:
try:
d['date__'+k] = int(kw[k])
except (TypeError, ValueError):
continue
return d |
def gather_txt(input_files, output_file, skip_empty=False):
"""
Very simple concatenation of text files labeled by file name.
"""
lines = []
for input_file in input_files:
with open(input_file, "r") as txt:
lines.append("### FILE {f}:\n{t}".format(f=input_file,
t=txt.read()))
with open(output_file, "w") as out:
out.write("\n\n\n".join(lines))
return output_file |
def not_found(environ, start_response):
"""Called if no URL matches."""
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
return ['Not Found'] |
def str_count(string, target, start=0, end=None):
"""
Description
----------
Count the number of times a target string appears in a string.
Parameters
----------
string : str - string to iterate\n
target : str - string to search for\n
start : int, optional - start index (default is 0)\n
end : int, optional - end index (default is None = len(string))
Returns
----------
int - number of times target appears in string
Examples
----------
>>> s = 'abcabcabc'
>>> str_count(s, 'a')
-> 3
>>> str_count(s, 'a', 2)
-> 2
"""
if not isinstance(string, str):
raise TypeError("param 'string' must be a string")
if not isinstance(target, str):
raise TypeError("param 'target' must be a string")
if target == "" or string == "":
return 0
length = len(string)
if end is None or end > length:
end = length
if start < 0 or end < 0 or start > end:
raise ValueError(
"params 'start' and 'end' must be greater than or equal to 0",
"'end' must be greater than or equal to 'start'",
)
if start == end:
return 0
n_str = string
str_len = len(target)
count = 0
while start < end:
try:
stop = start + str_len
if stop > end:
raise IndexError("End reached")
if n_str[start:stop] == target:
count = count + 1
start = start + 1
except IndexError:
return count
return count |
def polynomial_carre(a: float, b: float, c: float, x: float) -> float:
"""Retourne la valeur de ax^4 + bx^2 + c
"""
return ((a*x*x + b) * x*x) + c |
def retrieve_item(item_id):
"""
This is a stubbed method of retrieving a resource. It doesn't actually do anything.
"""
return {
"id": item_id,
"brand_name": "Clean Breathing",
"name": "Air Purifier",
"weight": 12.3,
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.