content stringlengths 42 6.51k |
|---|
def is_hex_string(string):
"""Check if a string represents a hex value"""
if not string.startswith("0x"):
return False
try:
int(string, 16)
return True
except ValueError as _:
return False |
def naive_next_pos(measurement, OTHER = None):
"""This strategy records the first reported position of the target and
assumes that eventually the target bot will eventually return to that
position, so it always guesses that the first position will be the next."""
if not OTHER: # this is the first measurement
OTHER = measurement
xy_estimate = OTHER
return xy_estimate, OTHER |
def _byte_to_str_length(codec: str) -> int:
"""Return how many byte are usually(!) a character point."""
if codec.startswith("utf-32"):
return 4
if codec.startswith("utf-16"):
return 2
return 1 |
def gerrit_check(patch_url):
""" Check if patch belongs to upstream/rdo/downstream gerrit,
:param patch_url: Gerrit URL in a string format
:returns gerrit: return string i.e 'upstream'/'rdo'/'downstream'
"""
if 'redhat' in patch_url:
return 'downstream'
if 'review.rdoproject.org' in patch_url:
return 'rdo'
if 'review.opendev.org' in patch_url:
print("We don't have ability to hold a node in upstream")
return 'upstream'
raise Exception(f'Unknown gerrit patch link provided: {patch_url}') |
def DiskName(vm_name, disk_type, disk_number):
"""Returns the name of this disk.
Args:
vm_name: The name of the vm this disk will be attached to.
disk_type: The type of the disk.
disk_number: The number of this disk. Must be unique on the VM.
Returns:
The name of the disk.
"""
return "{}-disk-{}-{}".format(vm_name, disk_type, disk_number) |
def FracVisText(doc):
"""Fraction of visible text on the page"""
soup, _ = doc
try:
pagesize = len(soup.decode_contents())
except Exception:
pagesize = 0
return float(len(soup.get_text())) / pagesize if pagesize > 0 else 0 |
def all_not_none(*args):
"""Shorthand function for ``all(x is not None for x in args)``. Returns
True if all `*args` are not None, otherwise False."""
return all(x is not None for x in args) |
def shark(pontoonDistance,
sharkDistance,
youSpeed,
sharkSpeed,
dolphin) -> str:
"""
You are given 5 variables: sharkDistance = distance the shark
needs to cover to eat you in metres, sharkSpeed = how fast it
can move in metres/second, pontoonDistance = how far you need
to swim to safety in metres, youSpeed = how fast you can swim
in metres/second, dolphin = a boolean, if true, you can half
the swimming speed of the shark as the dolphin will attack it.
If you make it, return "Alive!", if not, return "Shark Bait!".
:param pontoonDistance:
:param sharkDistance:
:param youSpeed:
:param sharkSpeed:
:param dolphin:
:return:
"""
if dolphin:
sharkSpeed = sharkSpeed / 2
if pontoonDistance / youSpeed < sharkDistance / sharkSpeed:
return "Alive!"
return "Shark Bait!" |
def validate_config(config):
"""Validates config"""
errors = []
required_config_keys = [
's3_bucket',
'athena_database'
]
# Check if mandatory keys exist
for k in required_config_keys:
if not config.get(k, None):
errors.append("Required key is missing from config: [{}]".format(k))
return errors |
def remove_trailing_slash(id):
""" Remove trailing slash if not root"""
if id != '/':
id = id.rstrip('/')
return id |
def binary(code: 'int') -> 'str':
"""Convert code to binary form."""
return f'0b{bin(code)[2:].upper().zfill(8)}' |
def render_path(path_to_item):
"""Returns a string representation of a path"""
result = ""
for pth in path_to_item:
if isinstance(pth, int):
result += "[{0}]".format(pth)
else:
result += "['{0}']".format(pth)
return result |
def is_year(s):
"""
Checks to see if the string is likely to be a year or not. In
order to be considered to be a year, it must pass the following
criteria:
1. four digits
2. first two digits are either 19 or 20.
:param s: the string to check for "year-hood"
:returns: ``True`` if it is a year and ``False`` otherwise.
"""
if not s:
return False
if len(s) == 4 and s.isdigit() and \
(s.startswith("19") or s.startswith("20")):
return True
return False |
def flatten(t):
"""Standard utility function for flattening a nested list taken from
https://stackoverflow.com/questions/952914/how-to-make-a-flat-list-out-of-a-list-of-lists."""
return [item for sublist in t for item in sublist] |
def is_number(string: str) -> bool:
"""Checks if a given string is a real number."""
try:
float(string)
return True
except ValueError:
return False |
def parse_argv(argv):
"""Implement a manual option parser."""
argv = list(argv)
args, kwargs = [], {}
while len(argv):
arg = argv.pop(0)
if arg[0] == '-' and len(arg) >= 2:
ind = 2 if arg[1] == '-' else 1
kv = arg[ind:].split('=', 1)
if len(kv) == 1:
kv.append(argv.pop(0))
kwargs[kv[0]] = kv[1]
else:
args.append(arg)
return args, kwargs |
def is_even(x):
""" Determines if x is even """
return x % 2 == 0 |
def aladd(x, y):
"""
Function to add 2 operands
"""
return(x + y) |
def all(ls):
"""
expects list of Bool
"""
result = True
for l in ls:
if l is not True:
result = False
return result |
def _calc_target_bounding_box(bbox, source_shape, target_shape):
"""Calculates the bounding of the cropped target image.
``bbox`` is relative to the shape of the source image. For the target
image, the number of pixels on the left is equal to the absolute value of
the negative start (if any), and the number of pixels on the right is equal
to the number of pixels target size exceeding the source size.
Args:
bbox (tuple[slice]): The len==3 bounding box for the cropping. The start
of the slice can be negative, meaning to pad zeros on the left; the
stop of the slice can be greater than the size of the image along
this direction, meaning to pad zeros on the right.
source_shape (tuple[int]): The spatial shape of the image to crop.
target_shape (tuple[int]): The spatial shape of the cropped image.
Returns:
tuple[slice]: The bounding box of the cropped image used to put the
extracted data from the source image into the traget image.
"""
target_bbox = list()
for bounding, ssize, tsize in zip(bbox, source_shape, target_shape):
target_start = 0 - min(bounding.start, 0)
target_stop = tsize - max(bounding.stop - ssize, 0)
target_bbox.append(slice(target_start, target_stop, None))
return tuple(target_bbox) |
def prefixed_by(apath, some_paths):
"""Check if a path is a a subpath of one of the provided paths"""
return len([p for p in some_paths if apath.find(p) == 0]) > 0 |
def _note(item):
"""Handle secure note entries
Returns: title, username, password, url, notes
"""
return f"{item['name']} - Secure Note", "", "", "", item.get('notes', '') or "" |
def filter_line(line, flag=None):
"""Returns the line starting with the flag"""
if flag is None:
return line
line_flag = line.strip().split(":")[0].strip()
if line_flag == flag:
new_line = line.strip()[len(flag) + 1:].strip().lstrip(":").strip()
return new_line
return None |
def find(predicate, iterable, default=None):
"""Return the first item matching `predicate` in `iterable`, or `default` if no match.
If you need all matching items, just use the builtin `filter` or a comprehension;
this is a convenience utility to get the first match only.
"""
return next(filter(predicate, iterable), default) |
def has_sublist(l, sublist):
"""Returns whether the elements of sublist appear in order anywhere within list l.
>>> has_sublist([], [])
True
>>> has_sublist([3, 3, 2, 1], [])
True
>>> has_sublist([], [3, 3, 2, 1])
False
>>> has_sublist([3, 3, 2, 1], [3, 2, 1])
True
>>> has_sublist([3, 2, 1], [3, 2, 1])
True
"""
sublist_length = len(sublist)
l_length = len(l)
"*** YOUR CODE HERE ***"
if l_length <= sublist_length:
return l == sublist
elif l[:len(sublist)] == sublist:
return True
else:
return has_sublist(l[1:], sublist) |
def is_(value, type_):
"""
Check if a value is instance of a class
:param value:
:param type_:
:return:
"""
return isinstance(value, type_) |
def quotewrap(item):
"""wrap item in double quotes and return it.
item is a stringlike object"""
return '"' + item + '"' |
def int_to_int_array(num):
"""
Deprecated, use int_to_digit_array(num)
"""
return [int(str(num)[a]) for a in range(len(str(num)))] |
def _true_hamming_distance(a: str, b: str) -> int:
"""
Calculate classic hamming distance
"""
distance = 0
for i in range(len(a)):
if a[i] != b[i]:
distance += 1
return distance |
def calc_met_equation_hdd(case, t_min, t_max, t_base):
"""Calculate hdd according to Meteorological
Office equations as outlined in Day (2006): Degree-days: theory and application
"""
if case == 1:
hdd = t_base - 0.5 * (t_max + t_min)
elif case == 2:
hdd = 0.5 * (t_base - t_min) - 0.25 * (t_max - t_base)
elif case == 3:
hdd = 0.25 * (t_base - t_min)
else:
hdd = 0
return hdd |
def get_range_data(num_row, rank, num_workers):
"""
compute the data range based on the input data size and worker id
:param num_row: total number of dataset
:param rank: the worker id
:param num_workers: total number of workers
:return: begin and end range of input matrix
"""
num_per_partition = int(num_row/num_workers)
x_start = rank * num_per_partition
x_end = (rank + 1) * num_per_partition
if x_end > num_row:
x_end = num_row
return x_start, x_end |
def notifyRecipient(data):
"""Notify PR author about reviews."""
# Work in progress
return data |
def all(sequence, test_func = None):
"""
Returns 1 if for all members of a sequence, test_func returns a non-zero
result. If test_func is not supplied, returns 1 if all members of the
sequence are nonzero (i.e., not one of (), [], None, 0).
"""
for item in sequence:
if test_func:
if not test_func(item):
return 0
elif not item:
return 0
return 1 |
def average_for_active_days(timeline):
"""Compute the average activity per active day in a sparse timeline.
:param timeline: A dictionary of non-sequential dates (in YYYY-MM-DD) as
keys and values (representing ways collected on that day).
:type timeline: dict
:returns: Number of entities captured per day rounded to the nearest int.
:rtype: int
"""
count = 0
total = 0
for value in list(timeline.values()):
if value > 0:
count += 1
total += value
# Python 3 seems to automagically turn integer maths into float if needed
average = int(total / count)
return average |
def summarize_bitmap(bitmap: list) -> str:
"""Give a compact text summary for sparse bitmaps"""
nonzero_bits = []
for i, b in enumerate(bitmap):
if b != 0:
nonzero_bits.append(f'{i:x}:{b:02x}')
sorted_nonzero_bits = ', '.join(sorted(nonzero_bits))
summary = f'{len(nonzero_bits)}/{len(bitmap)}: {sorted_nonzero_bits}'
return summary |
def create_argument_list_wrapped_explicit(arguments, additional_vars_following = False):
"""Create a wrapped argument list with explicit arguments x=y. If no additional
variables are added (additional_vars_following == False), remove trailing ',' """
argument_list = ''
length = 0
for argument in arguments:
argument_list += argument + '=' + argument + ','
length += 2*len(argument)+2
# Split args so that lines don't exceed 260 characters (for PGI)
if length > 70 and not argument == arguments[-1]:
argument_list += ' &\n '
length = 0
if argument_list and not additional_vars_following:
argument_list = argument_list.rstrip(',')
return argument_list |
def validate_options(value, _):
"""
Validate options input port.
"""
if value:
if "max_wallclock_seconds" not in value.get_dict():
return "the `max_wallclock_seconds` key is required in the options dict." |
def ramp_geometric(phi, A):
""" Weighted geometric mean according to phi. """
return A[0]**(0.5*(1.+phi))*A[1]**(0.5*(1.-phi)) |
def spin(c):
"""print out an ASCII 'spinner' based on the value of counter 'c'"""
spin = ".:|'"
return (spin[c % len(spin)]) |
def longest_common_prefix(strs):
""" Write a function to find the longest common prefix string amongst
an array of strings. If there is no common prefix, return an empty
string ''. """
# Corner cases/basic cases.
if len(strs) == 0:
return ''
if len(strs) == 1:
return strs[0]
# Add core logic.
prefix = strs[0]
prefix_len = len(prefix)
# Loop over words, but not 1st one.
for s in strs[1:]:
while prefix != s[0:prefix_len]:
prefix = prefix[0:(prefix_len - 1)]
prefix_len -= 1
if prefix_len == 0:
return ''
return prefix |
def is_ascii(s):
"""http://stackoverflow.com/questions/196345/how-to-check-if-a-string-in-python-is-in-ascii"""
return all(ord(c) < 128 for c in s) |
def blockquote(txt):
""" Block quote some pandoc text. Returns a list of strings
"""
return [''] + [ "> " + t for t in txt.split('\n') ] + [''] |
def cga(geoact, geoacs, subff2):
"""
GEOACT: GA CENTER POINT
GEOACS: GA AREA C/SUB
0=None
1=Quest
2=<I2
3=<O2
4=<1/2 DA
5=<1DA
6=<2DA
7=>2DA
8=CG
Returns:
0, 1, 88
"""
if geoact == 2 or (geoact == 1 and 2 <= geoacs <= 4):
cga = 1
elif geoact == 8 or geoacs == 8:
cga = 88
else:
cga = 0
if cga == 1 and subff2 == 2:
cga = 0
return cga |
def list_to_lines(data):
"""cast list to lines or empty string"""
return '\n'.join(data) if data else '' |
def summation(limit):
"""
Returns the summation of all natural numbers from 0 to limit
Uses short form summation formula natural summation
:param limit: {int}
:return: {int}
"""
return (limit * (limit + 1)) // 2 if limit >= 0 else 0 |
def web_template_to_frontend_top_message(template: dict) -> dict:
"""Transforms a frontend top level message to the web template."""
top_level_message = {}
top_level_message['header_content'] = str(template['header']).strip()
menu_items = list(template['menuItems'])
top_level_message['top_level_options'] = []
for idx, menu_item in enumerate(menu_items):
title = str(menu_item['title']).strip()
content = str(menu_item['content'])
top_level_option = {
'position': idx,
'title': title,
'content': content,
}
secondary_options = []
for idx, secondary_option in enumerate(menu_item['footerItems']):
content = str(secondary_option)
secondary_options.append({
'position': idx,
'content': content,
})
top_level_option['secondary_options'] = secondary_options
top_level_message['top_level_options'].append(top_level_option)
return top_level_message |
def letter_grades(highest):
"""Create a list of grade thresholds based on the provided highest grade.
:param highest: int - value of highest exam score.
:return: list - of lower threshold scores for each D-A letter grade interval.
For example, where the highest score is 100, and failing is <= 40,
The result would be [41, 56, 71, 86]:
41 <= "D" <= 55
56 <= "C" <= 70
71 <= "B" <= 85
86 <= "A" <= 100
"""
increment = round((highest - 40) / 4)
scores = []
for score in range(41, highest, increment):
scores.append(score)
return scores |
def fast_exponentiation(a, b, q):
"""Compute (a pow b) % q, alternative shorter implementation
:param int a b: non negative
:param int q: positive
:complexity: O(log b)
"""
assert a >= 0 and b >= 0 and q >= 1
result = 1
while b:
if b % 2 == 1:
result = (result * a) % q
a = (a * a) % q
b >>= 1
return result |
def boolean(v=None):
"""a boolean value"""
if isinstance(v, str):
raise ValueError('please use True or False without quotes, or 1/0)')
return bool(v) |
def judge_index_type(index_type, target_type):
"""Judges whether the index type is valid."""
if index_type == target_type or (isinstance(target_type, (list, tuple)) and index_type in target_type):
return True
return False |
def git_unicode_unescape(s, encoding="utf-8"):
"""Undoes git/gitpython unicode encoding."""
if s.startswith('"'):
return s.strip('"').encode("latin1").decode("unicode-escape").encode("latin1").decode(encoding)
return s |
def values_from_syscalls(line):
"""
Utility method to obtain the system call count values from the relative line in the final analysis output text
file.
:param line: string from log file
:return: int corresponding to system call frequency
"""
return int(line.strip().split('\t')[1]) |
def __write_ldif_one(entry):
"""Write out entry as LDIF"""
out = []
for l in entry:
if l[2] == 0:
out.append("%s: %s" % (l[0], l[1]))
else:
# This is a base64-encoded value
out.append("%s:: %s" % (l[0], l[1]))
return "\n".join(out) |
def bubble_sort(list_object):
"""as the name implies list_object: is a list object"""
swap = False
while not swap:
swap = True
for index in range(1, len(list_object)):
if list_object[index-1] > list_object[index]:
swap = False
list_object[index], list_object[index-1] = list_object[index-1], list_object[index]
return list_object |
def ensure_service_chains(service_groups, soa_dir, synapse_service_dir):
"""Ensure service chains exist and have the right rules.
service_groups is a dict {ServiceGroup: set([mac_address..])}
Returns dictionary {[service chain] => [list of mac addresses]}.
"""
chains = {}
for service, macs in service_groups.items():
service.update_rules(soa_dir, synapse_service_dir)
chains[service.chain_name] = macs
return chains |
def prepare_bid_identifier(bid):
""" Make list with keys
key = {identifier_id}_{identifier_scheme}_{lot_id}
"""
all_keys = set()
for tenderer in bid['tenderers']:
key = u"{id}_{scheme}".format(id=tenderer['identifier']['id'],
scheme=tenderer['identifier']['scheme'])
if bid.get('lotValues'):
keys = set([u"{key}_{lot_id}".format(key=key,
lot_id=lot['relatedLot'])
for lot in bid.get('lotValues')])
else:
keys = set([key])
all_keys |= keys
return all_keys |
def recall(overlap_count: int, gold_count: int) -> float:
"""Compute the recall in a zero safe way.
:param overlap_count: `int` The number of true positives.
:param gold_count: `int` The number of gold positives (tp + fn)
:returns: `float` The recall.
"""
return 0.0 if gold_count == 0 else overlap_count / float(gold_count) |
def get_lvl(ob):
"""
Returns the number of parents of a given object, or, in other words,
it's level of deepness in the scene tree.
Parameters
----------
ob : bpy.types.object
Blender object
Returns
-------
lvl : int
The number of parents of the object. For 'None' -1 is returned.
"""
lvl = -1
while ob:
ob = ob.parent
lvl += 1
return lvl |
def keymap(func, d, factory=dict):
""" Apply function to keys of dictionary
>>> bills = {"Alice": [20, 15, 30], "Bob": [10, 35]}
>>> keymap(str.lower, bills) # doctest: +SKIP
{'alice': [20, 15, 30], 'bob': [10, 35]}
See Also:
valmap
itemmap
"""
rv = factory()
rv.update(zip(map(func, d.keys()), d.values()))
return rv |
def mag(*args):
""" Magnitude of any number of axes """
n = len(args)
return (sum([abs(arg)**2 for arg in args]))**(1/2) |
def _make_url(raw, sig, quick=True):
""" Return usable url. Set quick=False to disable ratebypass override. """
if quick and not "ratebypass=" in raw:
raw += "&ratebypass=yes"
if not "signature=" in raw:
raw += "&signature=" + sig
return raw |
def edges_to_nodes(id_edge, edges_dict):
"""
:param nodes: list
list with id of nodes
:return: list
id of edges
"""
nodes_list = list(edges_dict.keys())
edges_id = list(edges_dict.values())
id_edge = edges_id.index(id_edge)
return nodes_list[id_edge] |
def last_month(date):
"""get the name of last month"""
date = str(date)
year = date[:4]
month = date[4:]
if month == '10':
month = '09'
elif month == '01':
year = str(int(year) - 1)
month = '12'
else:
month = int(month) - 1
if month < 10:
month = '0' + str(month)
else:
month = str(month)
ret = year + month
return ret |
def _make_panel(search_record):
"""
Extract fields we currently support from a single JSON metadata file and
prepare them in dict form to render search.html.
Returns: (dict) that will be an element of the list of panel_data to be
displayed as search results
"""
panel = {"keywords": search_record['Keywords'],
"description": search_record['Description'],
"researcher_name": search_record['Researcher Name'],
"model_run_name": search_record['Model Run Name'],
"model_run_uuid": search_record['Model Run UUID']}
return panel |
def get_timestamp_format_by_ttl_seconds(ttl_value: int) -> str:
"""
Calculates the precision of the timestamp format required based on the TTL
For example:
if TTL is 3600 seconds (1hr) then return "%Y-%m-%d-%H0000"
if TTL is 600 seconds (10 mins) then return "%Y-%m-%d-%H%M00"
if TTL is 35 seconds (35 secs) then return "%Y-%m-%d-%H%M%S"
"""
if ttl_value >= 86400:
# Greater than one day, return a day timestamp
return "%Y-%m-%d-000000"
elif ttl_value >= 3600:
# Greater than one hour, return an hour-based timestamp
return "%Y-%m-%d-%H0000"
elif ttl_value >= 60:
# Greater than a minute, return a minute-based timestamp
return "%Y-%m-%d-%H%M00"
else:
# Return a second-based timestmap
return "%Y-%m-%d-%H%M%S" |
def is_len(value):
""" is value of zero length (or has no len at all)"""
return getattr(value ,'__len__', lambda : 0)() > 0 |
def generate_simulation_intervals(Nd, maxlength, overlap):
"""
Generate a list of tuples containing the begining
and the end of any simulation intervals.
Parameters
----------
Nd : int
Number of samples from the data set.
maxlength : int
Maximum length of simulation intervals.
The data will be break into intervals of
this length os smaller.
overlap : int
Overlap between two consecutives intervals.
Returns
-------
multiple_shoots : list of tuples
List of tuples containing the begining
and the end of simulation intervals.
"""
Nshoots = Nd // maxlength
if Nd % maxlength != 0:
Nshoots += 1
# Compute actual simulation lenght
simulation_length \
= maxlength - \
(maxlength - Nd % maxlength) // Nshoots
# Compute a second simulation length and the number of times
# this diferent length will be applied
diferent_length = simulation_length-1
if Nd % simulation_length == 0:
Nshoots_diferent_length = 0
else:
Nshoots_diferent_length \
= simulation_length - Nd % simulation_length
else:
Nshoots_diferent_length = 0
diferent_length = maxlength
simulation_length = maxlength
# Check if diferent_length is large enough
if diferent_length < overlap:
raise ValueError("length too small.")
# Generate list
multiple_shoots = []
firstvalue = 0
for i in range(Nshoots - Nshoots_diferent_length):
lastvalue = firstvalue+simulation_length + \
overlap
multiple_shoots += [(firstvalue, min(lastvalue, Nd))]
firstvalue += simulation_length
for i in range(Nshoots_diferent_length):
lastvalue = firstvalue + diferent_length + \
overlap
multiple_shoots += [(firstvalue, min(lastvalue, Nd))]
firstvalue += diferent_length
return multiple_shoots |
def _to_str_list(values):
"""Convert a list to a list of strs."""
return [str(value) for value in values] |
def extract_status_code(error):
"""
Extract an error code from a message.
"""
try:
return int(error.code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.status_code)
except (AttributeError, TypeError, ValueError):
try:
return int(error.errno)
except (AttributeError, TypeError, ValueError):
return 500 |
def find_harm_sum(i):
"""i: an integer > 0
takes an integer and returns the harmonic sum"""
if i == 1:
# print("base case: return 1")
return 1
harm_sum = 1/i + find_harm_sum(i-1)
# print("non-base case: return ", harm_sum)
return harm_sum |
def list_converter(columnheaders, labels):
"""
Convert input strings into input lists
"""
if not isinstance(columnheaders, list):
if columnheaders is None:
columnheaders = ''
labels = ''
columnheaders = columnheaders.split()
labels = labels.split()
return columnheaders, labels |
def getValsItems(vals):
"""
:param vals:
:return:
"""
ret = {}
for i_key, i_val in list(vals.items()):
try:
i_val = eval(i_val)
except Exception:
i_val = i_val
if isinstance(i_val, dict):
for j_key, j_val in list(i_val.items()):
ret[j_key] = j_val
return ret |
def get_index_in_permuted(x, L):
"""Mapping to undo the effects of permute4
Useful to find the location of an index in original list
in Merkle tree.
"""
ld4 = L // 4
return x // ld4 + 4 * (x % ld4) |
def right_shift(array, count):
"""Rotate the array over count times"""
res = array[:]
for i in range(count):
tmp = res[:-1]
tmp.insert(0, res[-1])
res[:] = tmp[:]
return res |
def argmax(values):
"""Returns the index of the largest value in a list."""
return max(enumerate(values), key=lambda x: x[1])[0] |
def flatten(l):
"""Flattens nested lists into a single list.
:param list l: a list that potentially contains other lists.
:rtype: list"""
ret=[]
for i in l:
if isinstance(i, list): ret+=flatten(i)
else: ret.append(i)
return ret |
def linear_search(v, b):
"""Returns: first occurrence of v in b (-1 if not found)
Precond: b a list of number, v a number
"""
# ############# method 1
# i = 0
# while i < len(b) and b[i] != v:
# i += 1
# if i == len(b):
# return -1
# return i
# ############## method 2
# for i in range(len(b)):
# if b[i] == v:
# return i
# return -1
# ############## method 3
i = len(b) - 1
while i >= 0 and b[i] != v:
i = i - 1
return i |
def extract_identifiers(response):
"""
Extract identifiers from raw response and return as a list.
"""
results = response["result_set"]
print(results)
ids = [res["identifier"] for res in results]
return ids |
def split_header(task, lines):
"""Returns if the task file has a header or not."""
if task in ["CoLA"]:
return [], lines
elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]:
return lines[0:1], lines[1:]
else:
raise ValueError("Unknown GLUE task.") |
def _digits(n):
"""
Outputs a list of the digits of the input integer.
Int -> [Int]
Note:
Returns list in reverse order from what one might expect. It doesn't matter
for our purposes since we're summing the squares of the digits anyway, but
this can be fixed by returning res[::-1] if it bothers you.
"""
res = []
while n != 0:
res.append(n % 10)
n //= 10
return res |
def replace_key_with_value(s, replace_dict):
"""In string s keys in the dict get replaced with their value"""
for key in replace_dict:
s = s.replace(key, replace_dict[key])
return s |
def GetHour(acq_time):
"""
gets simply the hour from the given military time
"""
aqtime = str(acq_time)
size = len(aqtime)
hr = aqtime[:size - 2] #get the hours
#add the 0 if we need it to match the fire db
if len(hr) == 1:
hr = '0' + hr
elif len(hr) == 0:
hr = '00' #its a 00 hour
return hr |
def ackermann(m: int, n: int) -> int:
"""Recursive implementation of Ackermann algorithm.
:param m: positive integer
:param n: positive integer
"""
if m == 0:
return n + 1
elif n == 0:
return ackermann(m - 1, 1)
else:
return ackermann(m - 1, ackermann(m, n - 1)) |
def comma_counter(field: str):
"""
:param field:
:return:
"""
total = 0
for f in field:
if f == ',':
total += 1
return total |
def myRound(n):
"""
This function rounds a number up if it has decimal >= 0.5
:param float n: input number
:return int r: rounded number
"""
if n % 1 >= 0.5:
r = int(n) + 1
else:
r = int(n)
return r |
def getRemainingBalance(balance, annualInterestRate, monthlyPaymentRate):
"""
Input balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
Return the remaining balance at the end of the year, rounded to 2 decimals
"""
monthlyInterestRate = annualInterestRate / 12.0
remainingBalance = balance
for month in range(12):
minimumMonthlyPayment = monthlyPaymentRate * remainingBalance
monthlyUnpaidBalance = remainingBalance - minimumMonthlyPayment
updatedBalanceEachMonth = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
remainingBalance = updatedBalanceEachMonth
# print('Month ', month, ' Remaining balance: ', round(remainingBalance, 2))
return round(remainingBalance, 2) |
def phred_score(letter, offset, ascii):
""" Returns the Phred score of a fastq quality character.
"""
# Offset the string
offset_string = ascii[offset - 33:]
# Find the characters score
score = 0
while score < len(offset_string):
if letter == offset_string[score]:
return score
score += 1
# If no score is found then there must be an error
raise ValueError |
def escape_nmap_filename(filename):
"""Escape '%' characters so they are not interpreted as strftime format
specifiers, which are not supported by Zenmap."""
return filename.replace("%", "%%") |
def enclose_in_parenthesis(query_txt):
"""
Encloses each word in query_txt in double quotes.
Args:
query_txt: Search query
Returns:
'(query_word1) AND (query_word2) ...'
"""
query_words = query_txt.split(',')
return '(' + ') AND ('.join([word for word in query_words if word]) + ')' |
def powers_to_list(x):
"""
Takes a value that's a sum of powers of 2 and breaks it down to a list
of powers of 2.
(Shamelessly stolen from https://stackoverflow.com/a/30227161.)
"""
powers = []
i = 1
while i <= x:
if i & x:
powers.append(i)
i <<= 1
return powers |
def is_text(value):
"""Return True if the value represents text.
Parameters
----------
value : str or bytes
Value to be checked.
Returns
-------
bool
True if the value is a string or bytes array.
"""
if isinstance(value, bytes) or isinstance(value, str):
return True
else:
return False |
def trim_batch_job_details(sfn_state):
"""
Remove large redundant batch job description items from Step Function state to avoid overrunning the Step Functions
state size limit.
"""
for job_details in sfn_state["BatchJobDetails"].values():
job_details["Attempts"] = []
job_details["Container"] = {}
return sfn_state |
def get_type(kind, props):
"""Converts API resource 'kind' to a DM type.
Only supports compute right now.
Args:
kind: the API resource kind associated with this resource, e.g.,
'compute#instance'
Returns:
The DM type for this resource, e.g., compute.v1.instance
Raises:
Exception: if the kind is invalid or not supported.
"""
parts = kind.split('#')
if len(parts) != 2:
raise Exception('Invalid resource kind: ' + kind)
service = {
'compute': 'compute.v1'
}.get(parts[0], None)
if service is None:
raise Exception('Unsupported resource kind: ' + kind)
if parts[1] == 'instanceGroupManager' and 'region' in props:
return service + '.' + 'regionInstanceGroupManager'
return service + '.' + parts[1] |
def fahrenheit(T_in_celsius):
""" returns the temperature in degrees Fahrenheit """
return (T_in_celsius * 9 / 5) + 32 |
def fizzBuzz(num: int) -> str:
"""It returns Fizz, Buzz, FizzBuzz or the number that you passed
if is divisible by 3, 5, 3 or 5, or the number if it is none of the later
Args:
num (int): The number that you want to use for the FizzBuzz algorith
Returns:
str: Fizz, Buzz, FizzBuzz or the number that you passed as a string
if is divisible by 3, 5, 3 or 5, respectively
"""
return "Fizz"*(num % 3 == 0) + "Buzz"*(num % 5 == 0) or str(num) |
def first_player_wins(a, b):
"""
If tie : Returns 0
If first player wins : Returns 1
If second player wins : Returns -1
"""
if a == b:
return 0
elif [a, b] == ["R", "S"] or [a, b] == ["S", "P"] or [a, b] == ["P", "R"]:
return 1
return -1 |
def javaToClass(file) :
""" simple helper function, converts a string from svn stat (or command line) to its corresponding
.class file
"""
rval = file.replace('src','target').replace('main','classes').replace('test','test-classes').replace('.java', '.class').replace('java','').replace('\\\\','\\')
return rval; |
def blocksFundingTxs(maxTxPerBlock, lstFundingTxs):
"""
separate the funding transactions into blocks with constants.maxTxPerBlock amount
:param maxTxPerBlock: maxTxPerBlock
:param lstFundingTxs: list of funding txs
:return: list of funding blocks
"""
lstFundingBlocks = []
i = 0
if i + maxTxPerBlock >= len(lstFundingTxs):
m = len(lstFundingTxs)
else:
m = i + maxTxPerBlock
while i < len(lstFundingTxs):
lstFundingBlocks += [lstFundingTxs[i:m]]
i = m
if i + maxTxPerBlock >= len(lstFundingTxs):
m = len(lstFundingTxs)
else:
m = m + maxTxPerBlock
return lstFundingBlocks |
def ind2sub(idx, shape):
"""Linear index to tensor subscripts"""
# assert len(shape) == 2 # 2D test
# sub = [idx // shape[1], idx % shape[1]]
# return sub
sub = [None] * len(shape)
for (s, n) in reversed(list(enumerate(shape))): # write subscripts in reverse order
sub[s] = idx % n
idx = idx // n
return sub |
def unpack(n, x):
"""Unpacks the integer x into an array of n bits, LSB-first, truncating on overflow."""
bits = []
for _ in range(n):
bits.append((x & 1) != 0)
x >>= 1
return bits |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.