content stringlengths 42 6.51k |
|---|
def bx_encode(n, alphabet):
"""
Encodes an integer :attr:`n` in base ``len(alphabet)`` with
digits in :attr:`alphabet`.
::
# 'ba'
bx_encode(3, 'abc')
:param n: a positive integer.
:param alphabet: a 0-based iterable.
"""
if not isinstance(n, int):
... |
def largest_product(arr):
"""
Returns the largest_product inside an array incased inside a matrix.
input <--- Array of array with 2 value inside each
output <--- Largest Product of pair inside Matrix
"""
largest_product = 0
for container in arr:
x, y = container
if x * y > la... |
def get_health_multiple(obj):
"""
get individual scores for 4 repo components.
"""
branch_count = 0
branch_age = 0
issues = 0
pull_requests = 0
denom = len(obj["repo"])
assert all(isinstance(obj[x], list) for x in obj)
assert all(len(obj[x]) == denom for x in obj)
for brc in ... |
def as_string(raw_data):
"""Converts the given raw bytes to a string (removes NULL)"""
return bytearray(raw_data[:-1]) |
def unsignedIntegerToBytes(integer, numbytes):
"""Converts an unsigned integer into a sequence of bytes, LSB first.
integer -- the number to be converted
numbytes -- the number of bytes to be used in representing the integer
"""
bytes = list(range(numbytes))
for i in bytes:
bytes[i]... |
def scale(vertex, scale_factor):
"""Move a coordinate closer / further from origin.
If done for all vertices in a 2d shape, it has the effect of changing the size of the whole shape."""
[vertex_x, vertex_y] = vertex
return [vertex_x * scale_factor, vertex_y * scale_factor] |
def nb_arcs_from_density(n: int, d: int) -> int:
"""
Determines how many arcs in a directed graph of n and density d.
Using a function I derived that had the follow characteristics
m(d=0) = n, m(d=0.5) = (n)n-1/2 + 1, m(d=1) = n(n-1)
"""
assert n > 1
assert 0 <= d <= 1
return round((2 * ... |
def get_path_to_h1_dir(name: str, data_directory: str) -> str:
"""Get the path to the directory where the star formation data should be stored
Args:
name (str): Name of the galaxy
data_directory (str): dr2 data directory
Returns:
str: Path to h1 dir
"""
return f"{data_direc... |
def sizeof_fmt(num, suffix='B'):
"""
Print in human friendly format
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
def dictify(nl_tups):
""" Return dict if all keys unique, otherwise
dont modify """
as_dict = dict(nl_tups)
if len(as_dict) == len(nl_tups):
return as_dict
return nl_tups |
def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs):
""" Finds the span of a single knot over the knot vector using linear search.
Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
:param degree: degree
:type degree: int
:param knot_vector:... |
def calculatePixel(posMN, overlap, targetSize, shape):
"""Get the corresponding pixel start end x/y values to the tile defined by row/column in posMN.
Args:
posMN ([type]): tile as in row/column
overlap ([type]): overlap between tiles as defined by getTilePositions
targetSize ([type]): ... |
def reverse_captcha(string: str) -> int:
"""
Solves the AOC first puzzle, part two.
"""
summation = 0
half = len(string) / 2
for i, char in enumerate(string):
if char == string[int((i + half) % len(string))]:
summation += int(char)
return summation |
def get_bitstream_type(field, db_object):
"""Retrieves the bitstream type from the device image object"""
device_image = getattr(db_object, 'image', None)
if device_image:
return device_image.bitstream_type
return None |
def retrieve_team_abbreviation(team_name: str) -> str:
"""Retrieves the team abbreviation from the team name.
Args:
team_name (str): The full team name or team's home city.
Raises:
ValueError: If team name is not found in the team_abbreviation_mapping dict.
Returns:
str: The t... |
def zpad(x, l):
"""
Left zero pad value `x` at least to length `l`.
"""
return b"\x00" * max(0, l - len(x)) + x |
def value(x):
"""Returns 0 if x is 'sufficiently close' to zero, +/- 1E-9"""
epsilon = pow(1, -9)
if x >= 0 and x <= epsilon:
return 0
if x < 0 and -x <= epsilon:
return 0
return x |
def return_failure(message, error_code=500):
"""
Generates JSON for a failed API request
"""
return {"success": False, "error": message, "error_code": error_code} |
def is_aws_domain(domain):
"""
Is the provided domain within the amazonaws.com zone?
"""
return domain.endswith(".amazonaws.com") |
def get_output_video_length(timestamps: list):
"""
Calculates the output video length from the timestamps, each portion
length would be end - start
Parameters
----------
timestamps : list
timestamps for the video to edit
Returns
-------
int
final video length
R... |
def unwrapText(text):
"""Unwrap text to display in message boxes. This just removes all
newlines. If you want to insert newlines, use \\r."""
# Removes newlines
text = text.replace("\n", "")
# Remove double/triple/etc spaces
text = text.lstrip()
for i in range(10):
text = text.repl... |
def titlefirst(value):
"""Put the first letter into uppercase.
"""
if len(value) < 1:
return value.upper()
else:
return value[0].upper() + value[1:] |
def allowed_file(filename, checklist):
"""
checks if a file extension is one of the allowed extensions
"""
return '.' and filename.rsplit(".", 1)[1].lower() in checklist |
def unpack_vlq(data):
"""Return the first VLQ number and byte offset from a list of bytes."""
offset = 0
value = 0
while True:
tmp = data[offset]
value = (value << 7) | (tmp & 0x7f)
offset += 1
if tmp & 0x80 == 0:
break
return value, offset |
def ScalarAverageRamanActivityTensor(ramanTensor):
""" Average a Raman-activity tensor to obtain a scalar intensity. """
# This formula came from D. Porezag and M. R. Pederson, Phys. Rev. B: Condens. Matter Mater. Phys., 1996, 54, 7830.
alpha = (ramanTensor[0][0] + ramanTensor[1][1] + ramanTensor[2][2]) /... |
def _check_filesys_for_sadpt(savefs_dct, es_keyword_dct):
""" See if a sadpt exists
"""
# Find the TS
cnf_save_fs, cnf_save_locs = savefs_dct['runlvl_cnf_fs']
overwrite = es_keyword_dct['overwrite']
if not cnf_save_locs:
print('No transition state found in filesys',
'at {}... |
def assert_positive_int(name: str, value: str) -> int:
"""
Makes sure the value is a positive integer, otherwise raises AssertionError
:param name: Argument name
:param value: Value
:return: Value as integer
"""
try:
int_value = int(value)
except ValueError:
raise Assert... |
def get_digest_msid(digest_object):
"""given a digest object try to get the msid from the doi"""
try:
doi = getattr(digest_object, "doi")
return doi.split(".")[-1]
except AttributeError:
return None
return None |
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_worth... |
def _is_large_prime(num):
"""Inefficient primality test, but we can get away with this simple
implementation because we don't expect users to be running
print_fizzbuzz(n) for Fib(n) > 514229"""
if not num % 2 or not num % 5:
return False
test = 5
while test*test <= num:
if not nu... |
def distance(x1, y1, x2, y2):
"""
Distance between two points (x1, y1), (x2, y2).
"""
return pow((pow(x1 - x2, 2) + pow(y1 - y2, 2)), 0.5) |
def everyone(seq,method=bool):
"""Returns last that is true or first that is false"""
if not seq: return False
for s in seq:
if not method(s): return s if not s else None
return seq[-1] |
def is_unique(digit: str) -> bool:
"""Returns if a digit can be deduced solely by the length of its representation"""
return len(digit) in {2, 3, 4, 7} |
def is_leximin_better(x: list, y: list):
"""
>>> is_leximin_better([6,2,4],[7,3,1])
True
>>> is_leximin_better([6,2,4],[3,3,3])
False
"""
return sorted(x) > sorted(y) |
def rgb8_to_hsl(rgb):
"""Takes a rgb8 tuple, returns a hsl tuple."""
HUE_MAX = 6
r = rgb[0] / 255.0
g = rgb[1] / 255.0
b = rgb[2] / 255.0
cmin = min(r, g, b)
cmax = max(r, g, b)
delta = cmax - cmin
h = 0
s = 0
l = (cmax + cmin)
if delta != 0:
if l < 0.5:
s = delta / l
else:
... |
def google_form_likert(x):
"""
clean google_form_likert as numeric float value.
"""
try:
output = float(x[0])
return output
except:
return x |
def get_duplicate_indices1(words):
"""Given a list of words, loop through the words and check for each
word if it occurs more than once.
If so return the index of its first ocurrence.
For example in the following list 'is' and 'it'
occurr more than once, and they are at indices 0 and 1 s... |
def cscan_branch1(coo_names):
""" scan branch 1 directory name
"""
return '_'.join(sorted(coo_names)) |
def type_name(t) -> str:
"""
Gets a string naming the type
:param t: value to get type if
:return: the type name
"""
if not isinstance(t, type):
t = type(t)
# if isinstance(t, type):
# raise TypeError('T is "type"')
return getattr(t, '__name__', repr(t)) |
def rcumode2antset_eu(rcumode):
"""
Map rcumode to antenna set for EU stations.
Antenna set is only meaningful in Dutch stations.
But it is required in beamctl arguments.
Parameters
----------
rcumode: int
The RCU mode.
Returns
-------
antset: str
Antenna set n... |
def select_span(cropped_length, original_length, center_point):
"""
Given a span of original_length pixels, choose a starting point for a new span
of cropped_length with center_point as close to the center as possible.
In this example we have an original span of 50 and want to crop that to 40:
... |
def dic_remove_entries(in_dic, filter_dic):
"""
Remove entries from in_dic dictionary, given key values from filter_dic.
>>> in_dic = {'id1': 10, 'id2': 15, 'id3':20}
>>> filter_dic = {'id2' : 1}
>>> dic_remove_entries(in_dic, filter_dic)
{'id1': 10, 'id3': 20}
"""
# Checks.
assert ... |
def qname_encode(name):
"""Encode QNAME without using labels."""
def _enc_word(word):
return bytes([len(word) & 0xFF]) + word.encode("ascii")
return b"".join([_enc_word(x) for x in name.split(".")]) + b"\x00" |
def bar(value, minimum, maximum, size=20):
"""Print a bar from minimum to value"""
sections = int(size * (value - minimum) / (maximum - minimum))
return '|' * sections |
def rotacionar_1(lista: list, k: int) -> list:
"""
>>> lista = [1, 2, 3, 4, 5, 6, 7]
>>> rotacionar_1(lista, 3)
[5, 6, 7, 1, 2, 3, 4]
>>> rotacionar_1(lista, 5)
[3, 4, 5, 6, 7, 1, 2]
"""
tamanho = len(lista)
parte_1 = lista[tamanho-k:]
parte_2 = lista[:tamanho-k]
return parte... |
def sort(x):
"""Sorts list, if input is a list
Parameters
----------
x : List
Outputs
-------
Sorted list
"""
if isinstance(x,list):
return sorted(x)
else:
return x |
def find_or_create_node(branch, key):
"""
Given a list, look for dictionary with a key matching key and return it's
value. If it doesn't exist, create it with the value of an empty list and
return that.
"""
for node in branch:
if not isinstance(node, dict):
continue
... |
def dedupe(iterable):
"""Returns a list of elements in ``iterable`` with all dupes removed.
The order of the elements is preserved.
"""
result = []
seen = {}
for item in iterable:
if item in seen:
continue
seen[item] = 1
result.append(item)
return result |
def comp_dice_score(tp, fp, tn, fn):
"""
Binary dice score.
"""
if tp + fp + fn == 0:
return 1
else:
return (2*tp) / (2*tp + fp + fn) |
def is_str(txt):
"""test if a value's type is string
Parameters
----------
txt:
value to test
Returns
-------
bool:
True if txt is str, False otherwise
"""
return type(txt) == str |
def computeLastHitValues(blocks):
"""
given the query length and 'blacks' sting from a last hit
return the:
match length
the blocks string looks something like this:
"73,0:1,15,0:1,13,0:1,9"
where integer elements indicate lenghts of matches and
colon separated elements ... |
def get_ks001_extension(filename: str, pipe: str = "|") -> str:
"""
get extension of filename
filename extension is the string going from the end till the last dictionary separator.
For example |a=5_b=2|.csv will return "csv"
For example |a=5_b=2|.original.csv will return "original.csv"
For ex... |
def compare(x, y):
"""Write a compare function that returns 1 if x > y, 0 if x == y, and -1 if x < y"""
if x > y:
return 1
elif x < y:
return -1
else:
return 0 |
def get_recursively(search_dict: dict, field: str) -> list:
"""Take a dict with nested lists and dicts,
and searche all dicts for a key of the field
provided.
https://stackoverflow.com/a/20254842
Args:
search_dict (dict): Dictionary to search
field (str): Field to search for
R... |
def get_unique_name(new_name, name_list, addendum='_new'):
"""Utility function for returning a name not contained in a list"""
while new_name in name_list:
new_name += addendum
return new_name |
def _chargrams(s,n):
"""Generate character n-grams.
"""
return [s[i:i+n] for i in range(len(s)-n+1)] |
def relation_from_expr(expr):
"""
get relation from a tvm expression
"""
relation_lst = []
return relation_lst |
def is_single_bool(val):
"""
Checks whether a variable is a boolean.
Parameters
----------
val
The variable to check.
Returns
-------
bool
True if the variable is a boolean. Otherwise False.
"""
return type(val) == type(True) |
def _gen_neighbor_keys(result_prefix="") -> tuple:
"""Generate neighbor keys for other functions to store/access info in adata.
Parameters
----------
result_prefix : str, optional
generate keys based on this prefix, by default ""
Returns
-------
tuple:
A tup... |
def all_same(items):
"""Determine if all items of a list are the same item.
Args:
items: List to verify
Returns:
result: Result
"""
# Do test and return
result = all(item == items[0] for item in items)
return result |
def interval(seconds):
"""
gives back interval as tuple
@return: (weeks, days, hours, minutes, seconds)
formats string for fermtime_remaining
returns the formatted string for text-field
"""
WEEK = 60 * 60 * 24 * 7
DAY = 60 * 60 * 24
HOUR = 60 * 60
MINUTE = 60
weeks = seconds... |
def get_deleted_row(curr_records, prev_records):
"""
Returns
-------
row_num : int
Index of the deleted row.
Notes
-----
Assumes a row was in fact deleted.
"""
records = zip(curr_records, prev_records)
for i, (curr_record, prev_record) in enumerate(records):
if c... |
def read_bool(value):
"""converts a value to boolean"""
if hasattr(value, 'lower'):
if value.lower() in ['false', 'no', '0', 'off']:
return False
return bool(value) |
def byte_to_int16(lsb, msb):
"""
Converts two bytes (lsb, msb) to an int16
:param lsb: Least significant bit
:param msb: Most significant bit
:return: the 16 bit integer from the two bytes
"""
return (msb << 8) | lsb |
def is_url(str_):
""" heuristic check if str is url formatted """
return any([
str_.startswith('http://'),
str_.startswith('https://'),
str_.startswith('www.'),
'.org/' in str_,
'.com/' in str_,
]) |
def sort_dict_by_value(dic, reverse=False):
""" sort a dict by value
Args:
dic: the dict to be sorted
reverse: reverse order or not
Returns:
sorted dict
"""
return dict(sorted(dic.items(), key=lambda x: x[1], reverse=reverse)) |
def is_error_start(line):
"""Returns true if line marks a new error."""
return line.startswith("==") and "ERROR" in line |
def pointInRect(x, y, left, top, width, height):
"""Returns ``True`` if the ``(x, y)`` point is within the box described
by ``(left, top, width, height)``."""
return left < x < left + width and top < y < top + height |
def __GetAuthorizationTokenUsingResourceTokens(resource_tokens,
path,
resource_id_or_fullname):
"""Get the authorization token using `resource_tokens`.
:Parameters:
- `resource_tokens`: dict
- `path`: st... |
def genus_species_subprefix_subspecies(tokens):
"""
Input: Brassica oleracea var. capitata
Output: <taxon genus="Brassica" species="oleracea" sub-prefix="var"
sub-species="capitata"><sp>Brassica</sp> <sp>oleracea</sp> var
<sp>capitata</sp></taxon>
"""
(genus, species, su... |
def print_project_policies_rejection(policy_dict):
""" Prints the the policy and corresponding rejected resources from projects"""
output = ''
for policy in policy_dict:
# policy
output += "Rejected by Policy " + '"' + policy + '":\n'
for node in policy_dict[policy]:
# n... |
def c(ixs):
"""The sum of a range of integers
Parameters
----------
ixs : list
data list
Returns
----------
sum : int
values
"""
return sum(range(1, sum((i > 0 for i in ixs)) + 1)) |
def _merge(left, right):
"""Merge two lists and return the merged result
"""
result = []
while len(left) or len(right):
if len(left) and len(right):
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
... |
def read_file(filename):
"""Reads a file.
"""
try:
with open(filename, 'r') as f:
data = f.read()
except IOError as e:
return (False, u'I/O error "{}" while opening or reading {}'.format(e.strerror, filename))
except:
return (False, u'Unknown error opening or re... |
def f1d5p(f, h):
"""
A highly accurate five-point finite difference stencil
for computing derivatives of a function. It works on both
scalar and vector functions (i.e. functions that return arrays).
Since the function does four computations, it's costly but
recommended if we really need an accu... |
def uncapitalize_name(name):
"""
>>> uncapitalize_name("Href")
'href'
>>> uncapitalize_name("HttpEquiv")
'http-equiv'
"""
buf = []
for c in name:
if 'A' <= c <= 'Z' and len(buf):
buf.append('-')
buf.append(c)
return ''.join(buf).lower() |
def _validate_str_with_equals(input_string):
"""
make sure an input string is of the format {0}={1} {2}={3} {4}={5} ...
Some software programs put spaces after the equals sign and that's not
cool. So we make the string into a readable format
:param input_string: input string from an edi file
:... |
def get_tags(sync_config):
""" return a list of tags with, there name, and displayName """
tags = []
for tag in sync_config['tags']:
tags.append({'name': tag['name'], 'displayName': tag['displayName']})
return tags |
def to_locale(language):
"""
Simplified copy of `django.utils.translation.to_locale`, but we
need it while the `settings` module is being loaded, i.e. we
cannot yet import django.utils.translation.
Also we don't need the to_lower argument.
"""
p = language.find('-')
if p >= 0:
... |
def validate_str_length(value, min_length=None, max_length=None):
"""Validation value is a string and its length is between [min_size:max_size] as long
those are defined.
:param value: A string value
:type value: string | NoneType
:param min_length: The minimum amount of characters the value can ha... |
def invert_momenta(p):
""" fortran/C-python do not order table in the same order"""
new_p = []
for i in range(len(p[0])): new_p.append([0]*len(p))
for i, onep in enumerate(p):
for j, x in enumerate(onep):
new_p[j][i] = x
return new_p |
def __validate_currency_name_and_amount(currency_name, amount):
"""
Returns true if currency_name and amount contain values.
These values are already empty at the point this function
is called if they are invalid, so return false if they do
not contain values
:param currency_name:
:param amo... |
def make_repr(type_str, *args, **kwargs):
"""
Creates a string suitable for use with ``__repr__`` for a given
type with the provided arguments.
Skips keyword arguments that are set to ``None``.
For example, ``make_repr("Example", None, "string", w=None, x=2)``
would return a string: ``"Example(... |
def split_host_port(host_port, default_port):
"""
Split host:port into host and port, using the default port in case
it's not given.
"""
host_port = host_port.split(':')
if len(host_port) == 2:
host, port = host_port
return host, port
else:
return host_port[0], defau... |
def maximum_digital_sum(a: int, b: int) -> int:
"""
Considering natural numbers of the form, a**b, where a, b < 100,
what is the maximum digital sum?
:param a:
:param b:
:return:
>>> maximum_digital_sum(10,10)
45
>>> maximum_digital_sum(100,100)
... |
def mmval(mx, val, mn=0):
"""Return the value if within maxi or mini, otherwise return the boundary
(mini if less than mini, maxi if greater than maxi).
mx {number} Upper bound.
val {number} Value to boundary check.
[mn=0] {number} Lower bound, assumes zero.
return {number} val or asso... |
def get_contents(nmeaStr):
"""Return the AIS msg string. AIS goo"""
return nmeaStr.split(',')[5] |
def divisors_concise(integer: int):
"""
Same as above, except I used a list comprehension
"""
output = [i for i in range(2, integer) if integer % i == 0]
return output if len(output) else f"{str(integer)} is prime" |
def shift_pos(pos, label_shift):
"""shift a pos by (sx, xy) pixels"""
shiftx = label_shift[0]
shifty = label_shift[1]
pos2 = pos.copy()
for key, position in pos2.items():
pos2[key] = ( position[0] + shiftx, position[1] + shifty)
return pos2 |
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', \
'*35214*', '*41532*', '*2*1***'])
True
>>> check... |
def property_uses_get_resource(resource, property_name):
"""
returns true if a port's network property
uses the get_resource function
"""
if not isinstance(resource, dict):
return False
if "properties" not in resource:
return False
for k1, v1 in resource["properties"].items()... |
def minimumTotal(triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
if not triangle:
return 0
n = len(triangle)
current_cache = triangle[-1]
for i in range(n-2, -1, -1):
for j in range(i+1):
current_cache[j] = triangle[i][j] ... |
def ask_custom_question(question, choice_one, choice_two, not_done):
"""Method to ask the user a customized True or False question"""
while not_done:
answer = input(
"\n[?] {} ['{}' or '{}']: ".format(question, choice_one, choice_two)
)
if answer[0].lower() == choice_one[0]... |
def _addPrj(grpnum,pos,currentFltCat,nextFltCat,prevFltCat):
"""Almost always insures that that two or more of the same flight category exists"""
#
# Beginning hour of TAF is always added, regardless of any impending flight category
# change
#
if grpnum == 0 and pos == 0:
return True
... |
def custom_attention_masks(input_ids):
"""Creates attention mask for the given inputs"""
attention_masks = []
# For each sentence...
for sent in input_ids:
# Create the attention mask.
# - If a token ID is 0, then it's padding, set the mask to 0.
# - If a token ID is > 0, t... |
def bit_length(num):
"""Number of bits required to represent an integer in binary."""
s = bin(num)
s = s.lstrip('-0b')
return len(s) |
def get_depth(root):
"""
return 0 if unbalanced else depth + 1
"""
if not root:
return 0
left = get_depth(root.left)
right = get_depth(root.right)
if abs(left-right) > 1 or left == -1 or right == -1:
return -1
return 1 + max(left, right) |
def get_vid_name(file):
"""Creates the new video name.
Args:
file: String name of the original image name.
Returns:
A string name defined by the Subject and Session
numbers.
"""
return file.split("_")[0] + "_" + file.split("_")[1] |
def ensure_is_listlike(thing):
"""
Check if THING is list or tuple and, if neither, convert to list.
"""
if not isinstance(thing, (list, tuple)):
thing = [thing,]
return thing |
def dew_point(air_temperature):
"""Rough calculation for dew point in specific humidity (kg moisture per kg air).
Based on doubling of dew point per 10 degrees celsius, and a dew point of 0.051kg at 40 degrees celsius."""
return 0.051 * 2 ** ((air_temperature - 40.0) / 10.0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.