content stringlengths 42 6.51k |
|---|
def prefix(x: int, name: str):
"""Prefix node name with an instance"""
return f"{x}_{name}" |
def _default_bounds(signal):
"""Create a default list of bounds for a given signal description
If no bounds were specified, they default to [0, 0]:
['name', 0, 0, 0, 0]
If no bits of the port were picked, the whole port is picked:
['name', x, y, x, y]
A signal may use a slice of a port
This example uses the 6th and the 7th bits of the 16-bit port:
['example_2_of_16', 15, 0, 7, 6]
:param signal can be one of:
'port_name'
['port_name', upper_bound, lower_bound]
['port_name', upper_bound, lower_bound, upper_picked, lower_picked]
:return:
['port_name', upper_bound, lower_bound, upper_picked, lower_picked]
"""
# there's just the name
if isinstance(signal, str):
return (signal, 0, 0, 0, 0)
else:
# there's just the name in a list
if len(signal) == 1:
return signal + [0, 0, 0, 0]
# there's the name and bounds
if len(signal) == 3:
return signal + [signal[1], signal[2]]
return signal |
def order_issues(validated_data):
"""
validated_data should contain issues key.
We use it in Backlog and Sprint serializers to order it
by dragging between sprint and Backlog and inside of SCRUM board.
"""
if 'issues' not in validated_data:
return validated_data
ordered_issues = validated_data['issues']
for index, issue in enumerate(ordered_issues):
issue.ordering = index
issue.save()
ordered_issues[index] = issue
validated_data['issues'] = ordered_issues
return validated_data |
def foldx_variants(genotypes, sub, chain='A', offset=0, region=None):
"""Convert a list of genotypes into a list of FoldX individual_variants.txt entries.
Returns an empty list if no variants are suitable (e.g. out of region or mutate to same)"""
if region is None:
region = [0, float('inf')]
foldx_strs = []
for geno in genotypes:
ref, pos, mut = geno[0], int(geno[1:-1])-offset, geno[-1]
if region[0] <= pos <= region[1] and not ref == mut:
foldx_strs.append(f'{sub[pos][1] if pos in sub else ref}{chain}{pos}{mut}')
return foldx_strs |
def extend_indices(indices, required_total_size):
""" Extend the indices to obtain the required total size
by duplicating the indices """
# add extra samples to make it evenly divisible, if needed
if len(indices) < required_total_size:
while len(indices) < required_total_size:
indices += indices[:(required_total_size - len(indices))]
else:
indices = indices[:required_total_size]
assert len(indices) == required_total_size
return indices |
def find_primary_lithology(tokens, lithologies_dict):
"""Find a primary lithology in a tokenised sentence.
Args:
v_tokens (iterable of iterable of str): the list of tokenised sentences.
lithologies_dict (dict): dictionary, where keys are exact markers as match for lithologies. Keys are the lithology classes.
Returns:
list: list of primary lithologies if dectected. empty string for none.
"""
keys = lithologies_dict.keys()
for x in tokens:
if x in keys:
return lithologies_dict[x]
return '' |
def generate_weighted_list(st, ed, ratio=(20, 2, 1)):
"""
Generate an integer list consists of [st, ed].
Ratio of each integer in the list is determined using ratio parameter.
For example, st = 1, ed = 6, ratio = (20, 2, 1),
output = [ 20 1s, 20 2s, 2 3s, 2 4s, 1 5s, 1 6s ]
"""
nums = [i for i in range(st, ed+1)]
n_boundary = len(ratio)
boundary_offset = (ed - st + n_boundary) // n_boundary
choices = []
for i, n in enumerate(nums):
r = ratio[i // boundary_offset]
choices.extend([n] * r)
return choices |
def split_into_chunks(xs, chunk_size):
"""Split the list, xs, into n evenly sized chunks (order not conserved)"""
return [xs[index::chunk_size] for index in range(chunk_size)] |
def moon_phase2 (yr, mn, dy, hr=0, mi=0, se=0, tz=0) :
""" get moon phase at given time
https://www.daniweb.com/programming/software-development/code/453788/moon-phase-at-a-given-date-python
args:
yr: year
mn: month
dy: day
hr: hour
mi: minute
se: second
tz: timezone
returns:
moonphase, 0.0 to 1.0
"""
hh = hr + mi / 60.0 + se / 3600.0 - tz
year_corr = [18, 0, 11, 22, 3, 14, 25, 6, 17, 28, 9, 20, 1, 12, 23, 4, 15, 26, 7]
month_corr = [-1, 1, 0, 1, 2, 3, 4, 5, 7, 7, 9, 9]
lunar_day = (year_corr[(yr + 1) % 19] + month_corr[mn-1] + dy + hh) % 30.0
phase = 2.0 * lunar_day / 29.0
if phase > 1.0:
phase = abs(phase - 2.0)
return phase |
def get_item_thumbnail_url(item):
"""Returns the thumbnail for an enclosure or feedparser entry or raises a
:exc:`KeyError` if none is found."""
if 'media_thumbnail' in item:
return item['media_thumbnail'][0]['url']
blip_thumbnail_src = item.get('blip_thumbnail_src', None)
if blip_thumbnail_src:
return u'http://a.images.blip.tv/{0}'.format(blip_thumbnail_src)
if 'itunes_image' in item:
return item['itunes_image']['href']
if 'image' in item:
return item['image']['href']
raise KeyError |
def parse_interpro(row):
""" This function parses all of the Interpro families out of the "interpro"
field of a record. It assumes the "interpro" field, if it is present,
contains a list of dictionaries, and each dictionary contains a key
called "desc" which gives the description of that family.
Args:
row (pd.Series, or dictionary): presumably, the result of a call
to mygene.get_genes
Returns:
dictionary: containing the keys:
'gene_id': which is retrieved from the 'query' field of row
'interpro_families': a semi-colon delimited list of the Interpro families
"""
interpro_terms = []
if 'interpro' not in row:
return None
ip = row['interpro']
if isinstance(ip, list):
for ip_term in ip:
interpro_terms.append(ip_term['desc'])
return {
'gene_id': row['query'],
'interpro_families': ';'.join(interpro_terms)
} |
def extract_total_coverage(raw: str) -> int:
"""Extract total coverage."""
tail_line = raw.splitlines()[-1]
return int(float(tail_line.split("\t")[-1][:-1])) |
def icingByteFcnSEV(c):
"""Return severity value of icing pixel.
Args:
c (unicode): Unicode icing pixel.
Returns:
int: Value of severity portion of icing pixel.
"""
return (ord(c) >> 3) & 0x07 |
def process_messages(email_list):
""" takes a list of messages and convert them to a format we can shove into CSV """
message_fields = ['From', 'To', 'Subject', 'Date']
messages = []
for msg in email_list:
message = { key: msg[key] for key in message_fields }
body = ''
if msg.is_multipart():
# Make a best guess at the body of the message
# 1. Use text/plain
# 2. Use text/html
for part in msg.walk():
if body == '' and part.get_content_type() == 'text/html':
body = part.get_payload()
if part.get_content_type() == 'text/plain':
body = part.get_payload()
else:
body = msg.get_payload()
message['body'] = body
messages += [message]
return messages |
def add(x, y):
"""Return the addition of values x & y"""
return (x + y) |
def sample_cloudwatch_cloudtrail_rule(rec):
"""IAM Key Decrypt operation"""
return rec['detail']['eventName'] == 'Decrypt' |
def InLabels(labels, substr):
"""Returns true iff one of the labels contains substr."""
return any([substr in x for x in labels]) |
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
return filename.lower().endswith(extensions) |
def _get_function(line, cur_func):
"""
>>> _get_function('foo', None)
>>> _get_function('def hello():', None)
'hello'
"""
if 'def ' in line:
start = line.find('def ') + len('def ')
end = line.find('(')
return line[start:end]
return cur_func |
def __strip_angle_brackets(prefixed_str):
"""Strips prefixed_str from sorrounding angle brackets."""
return prefixed_str[1:-1] if len(prefixed_str) > 1 and prefixed_str.startswith("<") else prefixed_str |
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for item in outcomes:
new_sequence = list(partial_sequence)
new_sequence.append(item)
temp_set.add(tuple(new_sequence))
answer_set = temp_set
return answer_set |
def get_registry(url: str) -> str:
"""
Get registry name from url
"""
return url[8:] if url.startswith('https://') else url |
def to_numpy(t):
"""
If t is a Tensor, convert it to a NumPy array; otherwise do nothing
"""
try:
return t.numpy()
except:
return t |
def square_root(value):
""" (float) -> float
Compute an approximation of the square root of <value>
"""
# Init
root = 1.0 # Provisional square root
difference = (root * root) - value # How far off is our provisional root
##--- Loop until the provisional root is close enough to the actual root ----###
while difference > 0.00000001 or difference < -0.00000001:
root = (root + (value / root)) / 2 # Compute new provisional root
difference = (root * root) - value # # How far off is our current approximation?
return root |
def _gamut(component):
"""keeps color components in the proper range"""
return min(max(int(component), 0), 254) |
def sigma(ab_sig, bb_sig):
""" Perform combining rule to get A+A sigma parameter.
Output units are whatever those are of the input parameters.
:param ab_sig: A+B sigma parameter
:type ab_sig: float
:param ab_sig: B+B sigma parameter
:type ab_sig: float
:rtype: float
"""
if ab_sig is not None and bb_sig is not None:
aa_sig = 2.0 * ab_sig - bb_sig
else:
aa_sig = None
return aa_sig |
def _before_after(n_samples):
"""Get the number of samples before and after."""
if not isinstance(n_samples, (tuple, list)):
before = n_samples // 2
after = n_samples - before
else:
assert len(n_samples) == 2
before, after = n_samples
n_samples = before + after
assert before >= 0
assert after >= 0
assert before + after == n_samples
return before, after |
def bytes2human(n, format="%(value).1f%(symbol)s"):
"""Used by various scripts. See:
http://goo.gl/zeJZl
>>> bytes2human(10000)
'9.8K'
>>> bytes2human(100001221)
'95.4M'
"""
symbols = ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols[1:]):
prefix[s] = 1 << (i + 1) * 10
for symbol in reversed(symbols[1:]):
if n >= prefix[symbol]:
value = float(n) / prefix[symbol]
return format % locals()
return format % dict(symbol=symbols[0], value=n) |
def lock_params(access_mode):
"""Returns parameters for Action Lock"""
return {'_action': 'LOCK', 'accessMode': access_mode} |
def nations_from_str(nations, home, identifier):
"""Determine the nations of identified by ``qualifier``.
Args:
nations (set): Set of all possible nations.
home (str): String denoting the home nations.
identifier (str): String qualifying a country or a
group of countries eg: ``Entrants``.
Returns:
Set of identified nations.
Raises:
ValueError if ``identifier`` does not represent
recognized nations.
"""
if identifier == 'Entrants':
return nations
if identifier == 'Foreigners':
identified_nations = nations.copy()
identified_nations.discard(home)
return identified_nations
if identifier not in nations:
raise ValueError(f'{identifier} is not a recognized country')
return {identifier} |
def factors(n):
""" Return a sequence of (a, b) tuples where a < b giving factors of n.
Based on https://stackoverflow.com/a/6909532/916373
"""
return [(i, n//i) for i in range(1, int(n**0.5) + 1) if n % i == 0] |
def find_sequence_with_x(consensus, single_sequences):
"""
Determine the correct consensus sequence with X replacing consolidated nucleotides, based on the original
sequences to be consolidated
"""
output_sequence = ''
for position, nt in enumerate(consensus):
if nt == 'X':
reference_base, flag = single_sequences[0][position], None
for seq in single_sequences:
if seq[position] != reference_base:
output_sequence += 'X'
flag = 1
break
if not flag:
output_sequence += reference_base
else:
output_sequence += nt
return output_sequence |
def forgetting_to_bwt(f):
"""
Convert forgetting to backward transfer.
BWT = -1 * forgetting
"""
if f is None:
return f
if isinstance(f, dict):
bwt = {k: -1 * v for k, v in f.items()}
elif isinstance(f, float):
bwt = -1 * f
else:
raise ValueError("Forgetting data type not recognized when converting"
"to backward transfer.")
return bwt |
def draw_turn(row, column, input_list, user):
"""
Draw the game board after user typing a choice.
Arguments:
row -- the row index.
column -- the column index.
input_list -- a two dimensional list for game board.
user -- the user who type the choice
Returns:
input_list -- a two dimensional list for game board after changed.
"""
mark_dict = {'player1':'X', 'player2':'O'}
input_list[row-1][column-1] = mark_dict[user]
return input_list |
def lelu(x):
"""LeLu activation function
Basically ReLu but the lower range leaks slightly and has a range from -inf to inf
Args:
x (float): input value
Returns:
float: output value
"""
return 0.01 * x if x < 0 else x |
def split_interface(interface):
"""Split an interface name based on first digit, slash, or space match.
Args:
interface (str): The interface you are attempting to split.
Returns:
tuple: The split between the name of the interface the value.
Example:
>>> from netutils.interface import split_interface
>>> split_interface("GigabitEthernet1/0/1")
('GigabitEthernet', '1/0/1')
>>> split_interface("Eth1")
('Eth', '1')
>>>
"""
head = interface.rstrip(r"/\0123456789. ")
tail = interface[len(head) :].lstrip() # noqa: E203
return (head, tail) |
def pursuant_parenting_arrangement(responses, derived):
"""
Return a list of parenting arrangement bullet points, prefaced by the
correct 'pursuant to' phrase.
"""
act = derived['child_support_acts']
act = 'Pursuant to %s,' % act if act != '' else act
try:
arrangements = responses.get('order_respecting_arrangement', '').split('\n')
return ['%s %s' % (act, arrangement.strip())
for arrangement in arrangements
if len(arrangement.strip()) > 0]
except ValueError:
return [] |
def _merge(*objects):
"""Merge one or more objects into a new object"""
result = {}
[result.update(obj) for obj in objects]
return result |
def etaval(lambda_reg, iteration):
""" Decrease learning rate proportionally to number of iterations """
return 1.0 / (lambda_reg * iteration) |
def from_anscii(buf):
"""
Converts a string to its alpha-numeric equivalent using a modified scheme for numeric
characters and stores the results in a list.
"""
alpha_num_list = []
for char in buf:
if ord(char) >= 128:
num = ord(char)-128 # Subtract 128 to obtain original numeric charccters (based
# on our custom encoding scheme used for numeric characters)
alpha_num_list.append(num)
else:
alpha_num_list.append(char)
return alpha_num_list |
def move(position, roll):
"""position plus double the roll amount."""
return position + (roll * 2) |
def k_invers( k,q):
""" Compute the K invers mod q-1."""
q = q-1
k = k % q
try:
for i in range(1,q):
if ((k * i) % q == 1):
return i
return 1
except Exception as e:
print("Something went wrong: ",e.__str__())
return |
def order_ids(ids):
"""
This returned the ids sorted
:param ids: array, tuple, iterator. The list of ids
:return: A sorted tuple of the ids
"""
return tuple(set(ids)) |
def number_of_yang_modules_that_passed_compilation(in_dict, compilation_condition):
"""
return the number of drafts that passed the pyang compilation
:in_dict : the "PASSED" or "FAILED" is in the 3rd position of the list,
in the dictionary key:yang-model, list of values
: compilation_condition: a string
currently 3 choices: PASSED, PASSED WITH WARNINGS, FAILED
:return: the number of "PASSED" YANG models
"""
t = 0
for k, v in in_dict.items():
if in_dict[k][3] == compilation_condition:
t += 1
return t |
def check_auth(username, password):
"""This function is called to check if a username /
password combination is valid.
"""
return username == 'admin' and password == 'noexit' |
def addprint(x: str, y: float):
"""Implementation for (str, float)."""
expr = "%s + %.1f" % (x, y)
return "str_float addprint(x=%r, y=%r): %r" % (x, y, expr) |
def _limits_helper(x1, x2, a, b, snap=False):
"""
Given x1, x2, a, b, where:
x1 - x0 x3 - x2
a = ------- , b = -------
x3 - x0 x3 - x0
determine the points x0 and x3:
x0 x1 x2 x3
|----------|-----------------|--------|
"""
if x2 < x1:
raise ValueError("x2 < x1")
if a + b >= 1:
raise ValueError("a + b >= 1")
if a < 0:
raise ValueError("a < 0")
if b < 0:
raise ValueError("b < 0")
if snap:
if x1 >= 0:
x1 = 0
a = 0
elif x2 <= 0:
x2 = 0
b = 0
if x1 == x2 == 0:
# garbage in garbage out
return 0., 1.
elif x1 == x2:
# garbage in garbage out
return x1 - 1., x1 + 1.
if a == 0 and b == 0:
return x1, x2
elif a == 0:
return x1, (x2 - b * x1) / (1 - b)
elif b == 0:
return (x1 - a * x2) / (1 - a), x2
x0 = ((b / a) * x1 + x2 - (x2 - x1) / (1 - a - b)) / (1 + b / a)
x3 = (x2 - x1) / (1 - a - b) + x0
return x0, x3 |
def increments(data):
"""
sums up all incrementing steps in list
so:
if x2 > x1 : increments += (x2-x1)
else : do nothin
"""
return float(sum([data[index + 1] - data[index] for index in range(len(data)-1) if data[index + 1] > data[index]])) |
def get_game_mode(queue_id):
"""
Get game mode by the queue_id
"""
if queue_id == 400:
queue_id = "Normal Draft"
elif queue_id == 420:
queue_id = "Ranked Solo"
elif queue_id == 430:
queue_id = "Normal Blind"
else:
queue_id = "Special"
return queue_id |
def first_n(m: dict, n: int):
"""Return first n items of dict"""
return {k: m[k] for k in list(m.keys())[:n]} |
def get_provenance(
software_name="x", software_version="y", schema_version="1", environment=None,
parameters=None):
"""
Utility function to return a provenance document for testing.
"""
document = {
"schema_version": schema_version,
"software": {
"name": software_name,
"version": software_version,
},
"environment": {} if environment is None else environment,
"parameters": {} if parameters is None else parameters,
}
return document |
def bounding_box(points):
"""
Computes a bounding box from a list of coordinates
Parameters
----------
points : list
List of coordinates in the form of [[x,y], ...]
Returns
-------
list
A 4-tuple consisting of [xmin, ymin, xmax, ymax]
"""
x_coordinates, y_coordinates = zip(*points)
return [
min(x_coordinates),
min(y_coordinates),
max(x_coordinates),
max(y_coordinates),
] |
def partition(thelist, n):
"""
Break a list into ``n`` pieces. The last list may be larger than the rest if
the list doesn't break cleanly. That is::
>>> l = range(10)
>>> partition(l, 2)
[[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]
>>> partition(l, 3)
[[0, 1, 2], [3, 4, 5], [6, 7, 8, 9]]
>>> partition(l, 4)
[[0, 1], [2, 3], [4, 5], [6, 7, 8, 9]]
>>> partition(l, 5)
[[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]]
"""
try:
n = int(n)
thelist = list(thelist)
except (ValueError, TypeError):
return [thelist]
p = len(thelist) // n
return [thelist[p * i:p * (i + 1)] for i in range(n - 1)] + [thelist[p * (n - 1):]] |
def progress(train_loss: float, val_loss: float) -> str:
"""
Create progress bar description.
Args:
train_loss: Training loss
val_loss: Validation or test loss
Returns:
String with training and test loss
"""
return 'Train/Loss: {:.8f} ' \
'Val/Loss: {:.8f}' \
.format(train_loss, val_loss) |
def convertToTitle(n):
"""
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
based = ord('A')
ret = ""
while n:
ret = chr((n - 1) % 26 + based) + ret
n = (n - 1) // 26
return ret |
def get_status(summary):
"""
:param summary: The job summary dict. Normally ctx.summary
:returns: A status string like 'pass', 'fail', or 'dead'
"""
status = summary.get('status')
if status is not None:
return status
success = summary.get('success')
if success is True:
status = 'pass'
elif success is False:
status = 'fail'
else:
status = None
return status |
def utf8len(strn):
"""Length of a string in bytes.
:param strn: string
:type strn: str
:return: length of string in bytes
:rtype: int
"""
return len(strn.encode("utf-8")) |
def __normalize_str(name):
"""Removes all non-alphanumeric characters from a string and converts
it to lowercase.
"""
return ''.join(ch for ch in name if ch.isalnum()).lower() |
def get_score(word):
"""Score a given word."""
if len(word) == 4:
return 1
else:
score = len(word)
if len(set(word)) == 7:
score += 7
return score |
def count_items_bigger_than(numbers, threshold):
"""
What comes in:
-- An sequence of numbers.
-- A number that is a 'threshold'.
What goes out:
Returns the number of items in the given sequence of numbers
that are strictly bigger than the given 'threshold' number.
Side effects: None.
Examples:
If numbers is [45, 84, 32, 70, -10, 40]
and threshold is 45,
then this function returns 2 (since 84 and 70 are bigger than 45).
If numbers is [45, 84, 32, 70, -10, 40]
and threshold is 0,
then this function returns 5
(since all of the 6 numbers except -10 are bigger than 0).
If numbers is [45, 84, 32, 70, -10, 40]
and threshold is -10,
then this function still returns 5
(since all of the 6 numbers except -10 are bigger than -10;
note that -10 is NOT bigger than itself).
If numbers is [45, 84, 32, 70, -10, 40]
and threshold is -10.00000001,
then this function returns 6.
Type hints:
:type numbers: list or tuple (of numbers)
:type threshold: float
"""
# -------------------------------------------------------------------------
# DONE: 5. Implement and test this function.
# Note that you should write its TEST function first (above).
# -------------------------------------------------------------------------
count = 0
for k in range(len(numbers)):
if numbers[k] > threshold:
count = count + 1
return count |
def Z(m):
"""
@summary: fill m zero in string
@param m: {int} size of string
@return: \x00 * m
"""
return "\x00" * m |
def get_hosts_from_node(node):
"""
Return the host set for an MPI node in the graph and its children
"""
node_hosts = set()
node_host = node["msg"].get("exec_host", "")
node_hosts.add(node_host)
children = node.get("chained", list())
for c in children:
child_hosts = get_hosts_from_node(c)
node_hosts = node_hosts.union(child_hosts)
return node_hosts |
def index_to_world(index, resolution, origin, width):
""" Convert index to world coordinates """
x = int(index % width); y = int(index // width)
x = resolution * x + origin[0] + resolution / 2
y = resolution * y + origin[1] + resolution / 2
return x, y |
def split_by_len(string, length):
"""
Split a string into an array of strings of max length ``len``.
Last line will be whatever is remaining if there aren't exactly enough
characters for all full lines.
:param str string: String to split.
:len int length: Max length of the lines.
:return list: List of substrings of input string
"""
return [string[i:i + length] for i in range(0, len(string), length)] |
def normal(x, mu, sigma):
""" Evaluate logarithm of normal distribution (not normalized!!)
Evaluates the logarithm of a normal distribution at x.
Inputs
------
x : float
Values to evaluate the normal distribution at.
mu : float
Distribution mean.
sigma : float
Distribution standard deviation.
Returns
-------
y : float
Logarithm of the normal distribution at x
"""
if (sigma < 0):
return 0.0
return -0.5 * (x - mu)**2 / sigma**2 |
def bt2IndexFiles(baseName):
"""Return a tuple of bowtie2 index files.
Input:
baseName: the base name of bowtie2 index files.
Output:
list of strings, bowtie2 index files.
"""
exts = ['1.bt2', '2.bt2', '3.bt2', '4.bt2',
'rev.1.bt2', 'rev.2.bt2']
return [".".join([baseName, ext]) for ext in exts] |
def find_first_occurrence(key, numbers):
"""
vstup: 'key' hodnota hledaneho cisla, 'numbers' serazene pole cisel
vystup: index prvniho vyskytu hodnoty 'key' v poli 'numbers',
-1, pokud se tam tato hodnota nevyskytuje
casova slozitost: O(log n), kde 'n' je pocet prvku pole 'numbers'
"""
low = 0
high = len(numbers)
while low < high:
mid = (low + high) // 2
if numbers[mid] < key:
low = mid + 1
elif numbers[mid] > key:
high = mid
elif mid > 0 and numbers[mid-1] == key:
high = mid
else:
return mid
return -1 |
def trans_dict_to_dict(pose, indice_transform):
"""
param pose : dict()
param indice_transform : [int, int, int, ...]
return : dict()
"""
ret = {}
for idx_ret, idx in enumerate(indice_transform):
if idx in pose.keys():
ret[idx_ret] = pose[idx]
return ret |
def needs_binary_relocation(m_type, m_subtype):
"""Returns True if the file with MIME type/subtype passed as arguments
needs binary relocation, False otherwise.
Args:
m_type (str): MIME type of the file
m_subtype (str): MIME subtype of the file
"""
if m_type == 'application':
if m_subtype in ('x-executable', 'x-sharedlib', 'x-mach-binary'):
return True
return False |
def euclidean_gcd(first, second):
"""
Calculates GCD of two numbers using the division-based Euclidean Algorithm
:param first: First number
:param second: Second number
"""
while(second):
first, second = second, first % second
return first |
def prettyPercent( numerator, denominator, format = "%5.2f" ):
"""output a percent value or "na" if not defined"""
try:
x = format % (100.0 * numerator / denominator )
except (ValueError, ZeroDivisionError):
x = "na"
return x |
def for_update(row_file, row_db):
"""
Checks if row in uploaded file is equal to record in database with same feature_uuid value.
Takes two arguments:
- "row_file" (dictionary that contains data from row in uploaded file)
- "row_db" (dictionary that contains data from record in database)
Returns "should be updated" boolean value which is True if row in uploaded file differs from corresponding record in
database and False if it doesn't.
"""
should_be_updated = False
for key, cell_file in row_file.items():
if key == 'changeset':
continue
try:
col_db = row_db[key]
except KeyError:
continue
if cell_file == col_db:
should_be_updated = False
else:
should_be_updated = True
break
return should_be_updated |
def convertTimeFormatToSecs(timeString):
"""Converts the time in format h:mm:ss to seconds from midnight.
The input is a string and must have the format h:mm:ss or hh:mm:ss.
Example:
#print(convertTimeFormatToSecs('14:03:04'));
"""
# gets the value of hour, minute, and second
hhStr = timeString[:timeString.find(':')];
mmStr = timeString[(timeString.find(':')+1):timeString.rfind(':')];
ssStr = timeString[timeString.rfind(':')+1:];
# converts the string values into int values
hhInt = int(hhStr);
mmInt = int(mmStr);
ssStr = int(ssStr);
# calculates the number of seconds from midnight
return (hhInt*3600 + mmInt*60 + ssStr); |
def rgba_to_int(r: int, g: int, b: int, a: int) -> int:
"""Use int.from_bytes to convert a color tuple.
>>> print(rgba_to_int(0, 0, 0, 0))
0
>>> print(rgba_to_int(0, 1, 135, 4))
100100
"""
return int.from_bytes([r, g, b, a], byteorder="big", signed=True) |
def percentage(value, arg):
"""
Divides the value; argument is the divisor.
Returns empty string on any error.
"""
try:
percent_value = float( arg )
if percent_value:
return round(value / 100 * percent_value, 2)
except Exception:
pass
return '' |
def rms(varray=[]):
""" Root mean squared velocity. Returns
square root of sum of squares of velocities """
squares = map(lambda x: x*x, varray)
return pow(sum(squares), 0.5) |
def _escapeArg(arg):
"""Escape the given command line argument for the shell."""
#XXX There is a *lot* more that we should escape here.
return arg.replace('"', r'\"') |
def find_count(substring, string):
"""finds the number of occurences of substring in string"""
counter = 0
index = string.find(substring)
while index >= 0:
counter += 1
index = string.find(substring, index + 1)
return counter |
def hotel_name(hotel):
"""Returns a human-readable name for a hotel."""
if hotel == "sheraton_fisherman_s_wharf_hotel":
return "Sheraton Fisherman's Wharf Hotel"
if hotel == "the_westin_st_francis":
return "The Westin St. Francis San Francisco on Union Square"
if hotel == "best_western_tuscan_inn_fisherman_s_wharf_a_kimpton_hotel":
return "Best Western Fishermans Wharf"
return hotel |
def int_to_bytes(n, byte_order='big'):
"""
:param n: int
:param byte_order: str
:return: str
"""
return n.to_bytes(8, byte_order) |
def percent_of(part, whole):
"""What percent of ``whole`` is ``part``?
>>> percent_of(5, 100)
5.0
>>> percent_of(13, 26)
50.0
"""
# Use float to force true division.
return float(part * 100) / whole |
def _dedent(text):
"""Like `textwrap.dedent()` but only supports space indents."""
indents = []
for line in text.splitlines():
stripped = line.lstrip(" ")
if stripped:
indents.append(len(line) - len(stripped))
if not indents:
return text
indent = min(indents)
result = []
for line in text.splitlines(True):
if line.startswith(" " * indent):
line = line[indent:]
result.append(line)
return "".join(result) |
def binSearch(myList, start, end, objetive, iter_bin=0):
"""
Searches the objetive number in the list, if cannot find the number, it will make the list smaller to search again.
"""
print(f'Searching {objetive} between {myList[start]} and {myList[end-1]}:')
iter_bin+=1
if start > end:
return (False, iter_bin)
middle = (start+end)//2 # divides the size into 2 to find the middle
if myList[middle] == objetive: # Found case
return (True, iter_bin)
elif myList[middle] < objetive: # if the objetive number is bigger than the middle
return binSearch(myList, middle+1, end, objetive, iter_bin=iter_bin)
else: # if the objetive number is smaller than the middle
return binSearch(myList, start, middle-1, objetive, iter_bin=iter_bin) |
def unpack_mm_params(p):
"""
Description:
Unpacking parameter that can contains min and max values or single value.
Checking type of input parameter for correctly process.
Parameters:
p (int or float or list or tuple) - single value or min and max values for some range
Returns:
(p1, p2) (tuple of int or tuple of float) - tuple of min and max values for some range
"""
if isinstance(p, (tuple, list)):
return p[0], p[1]
elif isinstance(p, (int, float)):
return p, p
else:
raise Exception('Unknown input parameter type.') |
def normalise_text_score(query: str, score: float) -> float:
"""Approximate a mongo text score to the range [0, 1].
Args:
query: Query which was used
score: Text score
Returns:
An approximation of the normalised text score which is guaranteed
to be in the closed interval [0, 1].
"""
words = len(query.split())
expected_max_score = (words + 1) * .5
return min(score / expected_max_score, 1) |
def format_float(f, precision=3):
""" returns float as a string with given precision """
fmt = "{:.%df}" % precision
return fmt.format(f) |
def get_audios(connection):
"""Get audios list for selected album.
:param connection: :class:`vk_api.vk_api.VkApi` connection
:type connection: :class:`vk_api.vk_api.VkApi`
:return: list of photo albums or ``None``
:rtype: list
"""
try:
return connection.method('audio.get')
except Exception as e:
print(e)
return None |
def move_right(board, row):
"""Move the given row to one position right"""
board[row] = board[row][-1:] + board[row][:-1]
return board |
def update_tuple_item_with_fn(tuple_data, index, fn, *args):
"""
Update the ``index``th item of ``tuple_data`` to the result of calling ``fn`` on the existing
value.
"""
list_data = list(tuple_data)
try:
old_value = list_data[index]
list_data[index] = fn(old_value, *args)
except IndexError:
raise Exception(
"the length of the given tuple_data is {}, the given index {} is out of index".format(
len(tuple_data), index
)
)
else:
return tuple(list_data) |
def get_DF(fname):
"""Specify the DF value for equation.
DF= -8.d0 for all most recent models (Ergs/sec/cm**2/cm). For older model
series like the NextGen and AMES-Cond grids DF= -26.9007901434d0,
because previous Phoenix outputs were giving out the luminosity,
L (= R**2 * H) in erg/s/cm**2/cm. And for NextGen spectra
of effective temperature 5000K and above, DF'= -28.9007901434d0.
Note: Jason assumes there is a typo above and it is /A instead of cm for Df=-8.
To match the flux units for column 2."""
if "AMES-Cond" in fname:
DF = -26.9007901434
else:
DF = -8.0
# print("DF = {0}".format(DF))
return DF |
def is_suspicious(transaction: dict) -> bool:
"""Determine whether a transaction is suspicious."""
return transaction['amount'] >= 900 |
def blackjack(a, b, c):
"""
Given three integers between 1 and 11, if their sum is less than or equal to 21,
return their sum.
If their sum exceeds 21 and there's an eleven, reduce the total sum by 10.
Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'
:param a: int
:param b: int
:param c: int
:return: int or str
blackjack(5,6,7) --> 18
blackjack(9,9,9) --> 'BUST'
blackjack(9,9,11) --> 19
"""
if sum((a, b, c)) <= 21:
return sum((a, b, c))
elif sum((a, b, c)) <= 31 and 11 in (a, b, c):
return sum((a, b, c)) - 10
else:
return 'BUST' |
def preprocess_reference_text(text):
"""Preprocess a PDF text.
Parameters
----------
text : str
The text (possibly from a converted PDF) to preprocess.
Returns
-------
tuple
A tuple consisting of the following elements:
- has_reference_section : A boolean which is true when the text contained the string 'reference'
(not case-sensitive), false otherwise.
- reference_section : A string containing the reference section.
- non_reference_section : A string containing the text which was not in the reference section.
"""
try:
splitpoint = text.lower().rindex('reference')
except ValueError:
splitpoint = False
while splitpoint and len(text) - splitpoint < 100 and 'reference' in text[:splitpoint].lower():
text = text[:splitpoint]
splitpoint = text.lower().rindex('reference')
if not splitpoint:
has_reference_section = False
non_reference_section, reference_section = text, ''
else:
has_reference_section = True
non_reference_section, reference_section = text[:splitpoint], text[splitpoint:]
return has_reference_section, reference_section, non_reference_section |
def isValidPasswordPartTwo(firstIndex: int, secondIndex: int, targetLetter: str, password: str) -> int:
"""
Takes a password and returns 1 if valid, 0 otherwise. Second part of the puzzle
"""
bool1: bool = password[firstIndex - 1] == targetLetter
bool2: bool = password[secondIndex - 1] == targetLetter
return 1 if bool1 ^ bool2 else 0 |
def is_palindrome(sequence):
"""
Checks if sequence is a palindrome, returns true or false
"""
sequence = str(sequence).lower()
for index, letter in enumerate(sequence):
if letter != sequence[(index + 1) * -1]:
return False
return True |
def allow_incoming_bindings_for_initial_objects(annotation,name_into_obj,zep):
"""
this function inject a -1 as a requirer for the intial objects
this allows the binder to add bindings also to the intial object
:param the intial json annotation
:param the zephyrus json specification
:return: the zephyrus json specification
"""
for i in annotation["obj"]:
if "methods" in i:
comp = zep["components"][name_into_obj[i["name"]]]
comp["requires"] = {}
for j in i["methods"]:
# set value to -1 to allow the possible income of non mandatory bindings
comp["requires"][j["add"]["param_type"]] = -1
return zep |
def minutes_readable(minutes):
"""
convert the duration in minutes to a more readable form
Args:
minutes (float | int): duration in minutes
Returns:
str: duration as a string
"""
if minutes <= 60:
return '{:0.0f}min'.format(minutes)
elif 60 < minutes < 60 * 24:
minutes /= 60
if minutes % 1:
fmt = '{:0.1f}h'
else:
fmt = '{:0.0f}h'
return fmt.format(minutes)
elif 60 * 24 <= minutes:
minutes /= 60 * 24
if minutes % 1:
fmt = '{:0.1f}d'
else:
fmt = '{:0.0f}d'
return fmt.format(minutes)
else:
return str(minutes) |
def default_if_false(value, default):
"""Return given default if value is False"""
if not value:
return default
return value |
def maxSubarray(x):
"""Returns (a, b, c) such that sum(x[a:b]) = c and c is maximized.
See https://en.wikipedia.org/wiki/Maximum_subarray_problem"""
cur, best = 0, 0
curi = starti = besti = 0
for ind, i in enumerate(x):
if cur + i > 0:
cur += i
else: # reset start position
cur, curi = 0, ind + 1
if cur > best:
starti, besti, best = curi, ind + 1, cur
return starti, besti, best |
def is_media_url(url):
"""
Returns whether the given url uses the discord's media content delivery network.
Parameters
----------
url : `str`
The url to check.
Returns
-------
is_media_url : `bool`
"""
return url.startswith('https://media.discordapp.net/') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.