content stringlengths 42 6.51k |
|---|
def shell_sort(lst: list):
"""Shell sort implementation."""
counter = 0
lst_copy = lst
length = len(lst_copy)
interval = length // 2
while interval > 0:
for i in range(interval, length):
temp = lst_copy[i]
j = i
counter += 1
while j >= interval and lst_copy[j-interval] > temp:
if lst_copy[j-interval] > temp:
counter += 1
lst_copy[j], lst_copy[j -
interval] = lst_copy[j-interval], lst_copy[j]
j -= interval
else:
break
lst_copy[j] = temp
interval = interval // 2
return counter |
def palindrome(string):
"""
:type string: str
"""
from re import sub
s = sub('[\W_]', '', string.lower())
return s == s[::-1] |
def dict_nested_get(dictionary_or_value, keys, default=None):
"""
Performs a dictionary.get(key, default) using the supplied list of keys assuming that each successive key is nested.
For example, for a dictionary dictionary = { "key1": { "key2": 1 } }, use nested_get(dictionary, ["key1", "key2"]) to get the value of "key2".
Args:
dictionary_or_value: The dictionary to get the value from or the value itself from this recursive method.
keys: The list of nested keys.
default: The default value to return if no value exists. Default is None.
Returns:
The value of the nested key or the default if not found.
"""
if isinstance(dictionary_or_value, dict) and isinstance(keys, list) and (len(keys) > 1):
key = keys.pop(0)
return dict_nested_get(dictionary_or_value.get(key, default), keys, default)
elif isinstance(dictionary_or_value, dict) and isinstance(keys, list) and (len(keys) == 1):
return dictionary_or_value.get(keys[0], default)
elif (dictionary_or_value is not None) and (not isinstance(dictionary_or_value, dict)):
return dictionary_or_value
else:
return default |
def check_valid_password_1(minimum, maximum, letter, password):
"""PART ONE
Checks if a password is valid based on the criteria.
The letter must exist in the password between the min and
max number of times to be valid.
"""
if password.count(letter) >= minimum and password.count(letter) <= maximum:
# print(minimum, maximum, letter, password)
return True |
def merge_file_dicts(dict_1, dict_2):
"""Combine a pair of file dictionaries
Parameters
----------
dict_1 : `dict`
A dictionary of data_ids or filenames keyed by raft, slot, filetype
dict_2 : `dict`
A dictionary of data_ids or filenames keyed by raft, slot, filetype
Returns
-------
out_dict : `dict`
A dictionary of data_ids or filenames keyed by raft, slot, filetype
"""
out_dict = dict_1.copy()
for key, val in dict_2.items():
if isinstance(val, dict):
out_dict[key] = merge_file_dicts(out_dict[key], val)
else:
out_dict[key] = val
return out_dict |
def merge_overlap_segment(segments):
"""
Merged the overlapped segemtns {(0, 1.5), (1, 3.5), } -> {(0, 3.5), }
"""
segments = [list(i) for i in segments]
segments.sort(key=lambda x: x[0])
merged = []
for segment in segments:
if not merged or merged[-1][1] < segment[0]:
merged.append(segment)
else:
merged[-1][1] = max(merged[-1][1], segment[1])
merged_set = set([tuple(t) for t in merged])
return merged_set |
def check_pair_sum_divisible(arr, k):
"""
Check if an array can be divided into pairs whose sum is divisible by k.
"""
rem_freq_map = {}
for elem in arr:
rem = elem % k
rem_freq_map[rem] = rem_freq_map.get(rem, 0) + 1
for rem, freq in rem_freq_map.items():
if rem == 0 or rem * 2 == k:
if freq & 1:
return False
elif not freq == rem_freq_map.get(k - rem, 0):
return False
return True |
def simplify_to_one_line(lines):
"""Doc."""
new_lines = []
in_one_lines = []
is_line_end = False
for line in lines:
line = line.strip()
is_line_end = False
is_start_break = False
if line.startswith('void'):
is_start_break = True
elif line.startswith('#'):
is_line_end = True
if is_start_break:
new_lines.append(' '.join(in_one_lines))
in_one_lines = [line]
elif line.endswith(';') or line.endswith('}'):
is_line_end = True
if is_line_end:
in_one_lines.append(line)
new_lines.append(' '.join(in_one_lines))
in_one_lines = []
if not (is_start_break or is_line_end):
in_one_lines.append(line)
if not is_line_end:
new_lines.append(' '.join(in_one_lines))
return new_lines |
def percent_to_float(s):
"""Converts a percentage string to a float."""
return float(s[:-1]) / 100 |
def factorize(n):
"""return the factors of the Arg and count of each factor
Args:
n (long): number to be resolved into factors
Returns:
list of tuples: factorize(220) returns [(2, 2), (5, 1), (11, 1)]
"""
fct = [] # prime factor
b, e = 2, 0 # base, exponent
while b * b <= n:
while n % b == 0:
n = n // b
e = e + 1
if e > 0:
fct.append((b, e))
b, e = b + 1, 0
if n > 1:
fct.append((n, 1))
return fct |
def compute_distance(coordinates1, coordinates2):
"""
computes how long the ships needs to fly from coordinates1 to coordinates2
"""
absolute_distance = max(
abs(coordinates1[0]-coordinates2[0]),
abs(coordinates1[1]-coordinates2[1]),
abs(coordinates1[0]+coordinates1[1]-coordinates2[0]-coordinates2[1])
)
return absolute_distance + 2 |
def element_names_from_element_unqiue_names(element_unique_names):
""" Get tuple of simple element names from the full element unique names
:param element_unique_names: tuple of element unique names ([dim1].[hier1].[elem1], ... )
:return: tuple of element names: (elem1, elem2, ... )
"""
return tuple([unique_name[unique_name.rfind('].[') + 3:-1]
for unique_name
in element_unique_names]) |
def type_to_display(type_name):
"""
Convert an Avro fully qualified type name (with dots) to a display name.
"""
# Get the thing after the last dot, if any.
return type_name.split(".")[-1] |
def ratio(num, den):
"""
Returns the ratio of integers `num` and `den`.
"""
try:
return float(num) / float(den)
except ZeroDivisionError:
return 0.0 |
def scapozza(rho):
"""
Compute Young's modulus (MPa) from density (kg/m^3).
Arguments
---------
rho : float or ndarray
Density (kg/m^3).
Returns
-------
E : float or ndarray
Young's modulus (MPa).
"""
rho = rho*1e-12 # Convert to t/mm^3
rho0 = 917e-12 # Desity of ice in t/mm^3
E = 5.07e3*(rho/rho0)**5.13 # Young's modulus in MPa
return E |
def severe_cases_by_time(infections):
"""
This is the estimated number of severe positive
cases that will require hospitalization to recover.
"""
return (infections * (15/100.0)) |
def normalize_spaces(s):
"""replace any sequence of whitespace
characters with a single space"""
return ' '.join(s.split()) |
def standardise_force_name(name):
"""use lower case with hyphens as per the filenames in the bulk crime data"""
mapping = {
"Avon & Somerset": "avon-and-somerset",
"Avon and Somerset": "avon-and-somerset",
"Bedfordshire": "bedfordshire",
"Cambridgeshire": "cambridgeshire",
"Cheshire": "cheshire",
"Cleveland": "cleveland",
"Cumbria": "cumbria",
"Derbyshire": "derbyshire",
"Devon & Cornwall": "devon-and-cornwall",
"Devon and Cornwall": "devon-and-cornwall",
"Dorset": "dorset",
"Durham": "durham",
"Dyfed-Powys": "dyfed-powys",
"Essex": "essex",
"Gloucestershire": "gloucestershire",
"Greater Manchester": "greater-manchester",
"Gwent": "gwent",
"Hampshire": "hampshire",
"Hertfordshire": "hertfordshire",
"Humberside": "humberside",
"Kent": "kent",
"Lancashire": "lancashire",
"Leicestershire": "leicestershire",
"Lincolnshire": "lincolnshire",
"London, City of": "city-of-london",
"City of London": "city-of-london",
"Merseyside": "merseyside",
"Metropolitan Police": "metropolitan",
"Norfolk": "norfolk",
"North Wales": "north-wales",
"North Yorkshire": "north-yorkshire",
"Northamptonshire": "northamptonshire",
"Northumbria": "northumbria",
"Nottinghamshire": "nottinghamshire",
"South Wales": "south-wales",
"South Yorkshire": "south-yorkshire",
"Staffordshire": "staffordshire",
"Suffolk": "suffolk",
"Surrey": "surrey",
"Sussex": "sussex",
"Thames Valley": "thames-valley",
"Warwickshire": "warwickshire",
"West Mercia": "west-mercia",
"West Midlands": "west-midlands",
"West Yorkshire": "west-yorkshire",
"Wiltshire": "wiltshire",
}
# just return the input if is a value in the map (i.e. already standardised)
if name in mapping.values(): return name
return mapping[name]
#return mapping.get(name) |
def fitness(combo, attempt):
"""Compare items in two lists and count number of matches."""
grade = 0
for i, j in zip(combo, attempt):
if i == j:
grade += 1
return grade |
def split(text):
"""Takes a list containing lines of text and splits each line to
make a list of lists.
"""
split_text = []
for line in text:
split_text.append(line.split())
return split_text |
def lon2zone(lon):
""" Convert longitude to numeric UTM zone, 1-60.
"""
zone = int(round(lon / 6. + 30.5))
return ((zone - 1) % 60) + 1 |
def _get_all_languages_or_default_template(templates):
"""
Returns the first template that isn't language specific
"""
for template in templates:
if template.language == '':
return template
return templates[0] if templates else None |
def rivers_with_station(stations):
"""Returns a list of the names of rivers with a monitoring station"""
# Creates a set of rivers with monitoring stations
rivers = set()
for station in stations:
if station.river is not None:
rivers.add(station.river)
# Converts set into alphabetically ordered list
sorted_rivers = sorted(rivers)
return sorted_rivers |
def digitize(n):
"""Return the reverse list of an integer."""
a = [int(i) for i in str(n)]
return a[::-1] |
def pad_sequence(seq, size, padding=None):
"""Force a sequence to size. Pad with padding if too short, and ignore
extra pieces if too long."""
return (list(seq) + [padding for _ in range(size)])[:size] |
def _generate_poly_lr(lr_init, lr_end, lr_max, total_steps, warmup_steps):
"""
Applies polynomial decay to generate learning rate array.
Args:
lr_init(float): init learning rate.
lr_end(float): end learning rate
lr_max(float): max learning rate.
total_steps(int): all steps in training.
warmup_steps(int): all steps in warmup epochs.
Returns:
np.array, learning rate array.
"""
lr_each_step = []
if warmup_steps != 0:
inc_each_step = (float(lr_max) - float(lr_init)) / float(warmup_steps)
else:
inc_each_step = 0
for i in range(total_steps):
if i < warmup_steps:
lr = float(lr_init) + inc_each_step * float(i)
else:
base = (1.0 - (float(i) - float(warmup_steps)) / (float(total_steps) - float(warmup_steps)))
lr = float(lr_max) * base * base
if lr < 0.0:
lr = 0.0
lr_each_step.append(lr)
return lr_each_step |
def dimcolor(rgb, prop):
"""
Dims a given rgb color to prop, which should be in the interval 0.0 - 1.0.
"""
return tuple(map(lambda x: int(round(x * prop)), rgb)) |
def _add_metadata(data):
"""Builds question metadata based on specified fields.
"""
keys = ['type', 'label', 'range', 'units', 'unique values', 'missing',
'source file']
results = {}
for key, val in data.items():
if key in keys:
results[key] = val
return results |
def unique_elements_non_linear(first_arr, second_arr):
"""
Returns a list with common elements in order of appearance in first list -- Complexity -- O(N*N)
"""
# List of common elements in both lists
common_elements_list = list(set(first_arr).intersection(set(second_arr)))
# Init the result array
result_arr = []
# Itirate over first array
for each_element in first_arr:
# If the element is present in common_elements_list, append to result_arr
if each_element in common_elements_list:
result_arr.append(each_element)
return result_arr |
def address_fixup(a):
""" Some San Diego addresses aren't fixed up by the canonicalizer. """
a = a.strip()
# A newline in the middle of a city name, that should be turned into a space.
# canonicalize() will turn it into a comma instead
d = {
"2260 Jimmy Durante Blvd, Del\nMar, CA 92014": "2260 Jimmy Durante Blvd, Del Mar, CA 92014",
"1388 Buckman Springs Road, Campo CA 91906": "1388 Buckman Springs Road, Campo, CA 91906",
}
a = d.get(a, a)
return a |
def get_selection(action, suboptions):
"""
param: action (string) - the action that the user
would like to perform; printed as part of
the function prompt
param: suboptions (dictionary) - contains suboptions
that are listed underneath the function prompt.
The keys are assumed to be in upper-case.
The function displays a submenu for the user to choose from.
Asks for user to select an option using the input() function.
Re-prints the submenu if an invalid option is given.
Prints the confirmation of the selection by retrieving the
description of the option from the suboptions dictionary.
returns: the option selection as an upper-case string
(should be a valid key in the suboptions)
"""
print(f"What would you like to do?")
opt = str(action.upper())
print(suboptions)
for (index, value) in enumerate(suboptions):
if opt in suboptions:
print(f"You selected {suboptions[opt]}")
break
else:
print(f"Please select an option from the existing menu")
continue # continue to the next iteration of the loop
return opt |
def convert_string_to_list(string_val):
"""Helper function to convert string to list.
Used to convert shape attribute string to list format.
"""
result_list = []
list_string = string_val.split(',')
for val in list_string:
val = str(val.strip())
val = val.replace("(", "")
val = val.replace(")", "")
val = val.replace("L", "")
val = val.replace("[", "")
val = val.replace("]", "")
if val == "None":
result_list.append(None)
elif val != "":
result_list.append(int(val))
return result_list |
def check_program(name):
""" Searches PATH environment variable for executable given by parameter """
import os
for dir in os.environ['PATH'].split(os.pathsep):
prog = os.path.join(dir, name)
if os.path.exists(prog): return prog |
def get_specified_programs(workflow_config, program_type):
"""
Return all programs specified by a given top-level attribute of the workflow configuration.
:param workflow_config: dict Workflow configuration
:param program_type: str A supported program type
:return: list All programs listed in the workflow config under program type
"""
return [program for program in workflow_config.get(program_type, list())] |
def are_words_sorted(words, alpha_order):
"""
Inputs:
words: List[str]
alpha_order: str
Output:
bool
"""
# Your code here
# init a dict to keep track of letters as keys and their altered indices as values
altered_order_dict = {letter: index for index, letter in enumerate(alpha_order)}
# this way we can look up each letter in our dictionary to figure out it's altered index
# once we have the altered indices we can check if they are in the right order
for i in range(1, len(words)):
w1 = words[i - 1]
w2 = words[i]
# iterate over each of the chars of the 2 words, checking that the current letters adhere to the altered order
for j in range(min(len(w1), len(w2))):
ch1 = w1[j]
ch2 = w2[j]
# check each of the letters
if ch1 != ch2:
if altered_order_dict[ch1] > altered_order_dict[ch2]:
return False
else:
break
# if we end up falling out of the inner loop check if the length of w1 is greater than the length of w2
if len(w1) > len(w2):
# return False
return False
# once we fall out of the outer loop if we did not already return then we must return true
return True |
def real_growth_rate(growth_rate, inflation_rate):
"""
Calculate the real investment growth rate after adjusting for inflation.
:param growth_rate: Growth rate of investment
:param inflation_rate: Rate of inflation
:return: Adjusted growth rate after inflation
"""
real_rate = ((1 + growth_rate) / (1 + inflation_rate)) - 1
real_rate = round(real_rate, 5)
return real_rate |
def convert_to_bits(n):
"""converts an integer `n` to bit array"""
result = []
if n == 0:
return [0]
while n > 0:
result = [(n % 2)] + result
n = n // 2
return result |
def generate_URLS(url: str = "https://csgostash.com/img/skins/large_1920/s", times: int = 1000, suffix: str = ".png"):
"""
Generate a list of icon URLs.
:param url: The prefix to apply to the URL.
:param times: How many URLs to generate.
:param suffix: The file suffix to apply to the URL.
:return: A list of URL strings that probably have images.
"""
urls = []
for i in range(times):
urls.append(url + str(i) + suffix)
return urls |
def pressure_to_pa(press_in):
"""Convert pressure in [cm H2O] to [pa]
Returns a rounded integer"""
conversion_factor = 98.0665
return int(round(press_in * conversion_factor)) |
def check_all_types_equal(iterable) -> bool:
"""
Check if all elements of an iterable are if the same type.
:param iterable: iterable to check
:return: bool saying if all elements are of equal type
"""
iterator = iter(iterable)
try:
first = next(iterator)
except StopIteration:
return True
return all(type(first) == type(rest) for rest in iterator) |
def is_public(data, action):
"""Check if the record is fully public.
In practice this means that the record doesn't have the ``access`` key or
the action is not inside access or is empty.
"""
return '_access' not in data or not data.get('_access', {}).get(action) |
def get_maintenance_type(code):
"""Get maintenance type from code."""
maintenance_type = {0: "With DC", 1: "Without DC"}
if code in maintenance_type:
return maintenance_type[code] + " (" + str(code) + ")"
return "Unknown ({})".format(str(code)) |
def _extrap_spec(interpval, lower_val, upper_val, lower_thru, upper_thru):
"""Extrapolate using two spectra to parameter at given value.
Called by :func:`interpolate_spectral_element`.
Also see :func:`_interp_spec`.
"""
m = (upper_thru - lower_thru) / (upper_val - lower_val)
b = lower_thru - m * lower_val
return m * interpval + b |
def journal(record):
"""
Turn the journal field into a dict composed of the original journal name
and a journal id (without coma or blank).
:param record: the record.
:type record: dict
:returns: dict -- the modified record.
"""
if "journal" in record:
# switch journal to object
if record["journal"]:
record["journal"] = {"name": record["journal"], "ID": record["journal"].replace(',', '').replace(' ', '').replace('.', '')}
return record |
def get_max_table_size(final_tables):
"""
Compute the maximum number of elements that appear in one of the table generated inside the main process.
Parameters
----------
final_tables : list
list of the tables generated inside the loop for each bucket.
Returns:
--------
max_table_size : int
the number of elements inside the largest table (i.e., number of row multiplied by the number of columns).
"""
# Variable initialization
max_table_size = 0
for table in final_tables:
max_table_size = max(max_table_size,len(table[0])*len(table))
return max_table_size |
def is_same_class(obj, a_class):
"""
returns True if the object is exactly an instance of the specified class;
otherwise False
"""
return(obj.__class__ == a_class) |
def _get_session_performance(md, ses_data):
"""Get performance about the session from bpod data"""
if not ses_data:
return None, None
n_trials = ses_data[-1]['trial_num']
# checks that the number of actual trials and labeled number of trials check out
assert (len(ses_data) == n_trials)
# task specific logic
if 'habituationChoiceWorld' in md['PYBPOD_PROTOCOL']:
n_correct_trials = 0
else:
n_correct_trials = ses_data[-1]['ntrials_correct']
return n_trials, n_correct_trials |
def bin_bucket_sort(arr):
"""
Binary bucket sort / 2-Radix sort
Time: O(NLog2N)
Space: O(N)
input: 1D-list array
output: 1D-list sorted array
"""
bucket = [[], []]
aux = list(arr)
flgkey = 1
while True:
for ele in aux:
bucket[int(bool(ele & flgkey))].append(ele)
if bucket[0] == [] or bucket[1] == []:
return aux
aux = list(bucket[0]) + list(bucket[1])
flgkey <<= 1
bucket = [[], []] |
def split_by_comma(line):
"""
Converts the given line of text into comma-delimited tokens
:param line: the line of text to process
:return: an array of tokens contained in the line of text
"""
return line.split(",") |
def my_round(x, base=15):
"""Summary
Args:
x (TYPE): Description
base (int, optional): Description
Returns:
TYPE: Description
"""
# https://stackoverflow.com/questions/2272149/round-to-5-or-other-number-in-python
return int(base * round(float(x) / base)) |
def _index_of_end(str, part):
"""If part is in str, return the index of the first character after part.
Return -1 if part is not in str."""
index = str.find(part)
if index >= 0:
return index + len(part)
return -1 |
def get_channels(posts):
"""
<summary> Returns post channel (twitter/facebook)</summary>
<param name="posts" type="list"> List of posts </param>
<returns> String "twitter" or "facebook" </returns>
"""
channel = []
for i in range(0, len(posts['post_id'])):
if len(posts['post_text'][i]) <= 140:
channel.append("twitter")
else:
channel.append("facebook")
return channel |
def solveit(test):
""" test, a function that takes an int parameter and returns a Boolean
Assumes there exists an int, x, such that test(x) is True
Returns an int, x, with the smallest absolute value such that test(x) is True
In case of ties, return any one of them.
"""
x = 0
if (test(0)):
return 0
while(not test(x)):
x += 1
if test(x):
return x
if test(-x):
return -x |
def check_road_length(length):
"""
Determine the key for where to store the road length.
"""
key = ''
if length <= 20:
key = '0-20'
elif 20 < length <= 40:
key = '20-40'
elif 40 < length <= 60:
key = '40-60'
elif 60 < length <= 80:
key = '60-80'
elif 80 < length <= 100:
key = '80-100'
else:
key = '100-'
return key |
def legendre(a, p):
"""Legendre symbol"""
tmp = pow(a, (p-1)//2, p)
return -1 if tmp == p-1 else tmp |
def _parse_to_last_comment(comments):
"""Unpack to get the last comment (hence the -1) or give '' when there is none"""
return [(c[-1]['comment'] if hasattr(c, '__len__') else '') for c in comments] |
def create_model_dict(input_channels, num_classes=[4, 1], name='2d'):
"""
Creates `model_dict` dictionary from parameters.
Parameters
----------
input_channels: int
1 indicates gray-channle image, 3 indicates RGB image.
num_classes: list
[4, 1] -> 4 indicates offset in x, offset in y, margin in x, margin in y; 1 indicates seediness score
name: string
"""
model_dict = {
'name': 'branched_erfnet' if name=='2d' else 'branched_erfnet_3d',
'kwargs': {
'num_classes': num_classes,
'input_channels': input_channels,
}
}
print(
"`model_dict` dictionary successfully created with: \n -- num of classes equal to {}, \n -- input channels equal to {}, \n -- name equal to {}".format(
input_channels, num_classes, name))
return model_dict |
def replace(items, replace_dict):
"""
Replace a token/lemma with a replacer codename.
Ex. usage:
replaced = replace(['1', 'hello'], {str.isnumeric: 'NUM'})
:param items: tokens/lemmas to replace
:param replace_dict: a dict with String types to replace and corresponding replacers.
Ex.: {'isnumeric': 'NUM', 'isalpha': 'WORD'}
:return: replaced items
"""
replaced = []
for item in items:
for item_type, replacer in replace_dict.items():
if item_type(item):
replaced.append(replacer)
break
else:
replaced.append(item)
return replaced |
def f(t):
"""
This curve represents the y=x+10 function
"""
return t - 10, t |
def mask(text1, text2):
"""
a simple vectorization function
"""
base = 0
vectors = {}
vector1, vector2 = [], []
for phrase in text1:
if phrase not in vectors:
vectors[phrase] = base
base += 1
vector1.append(vectors[phrase])
for phrase in text2:
if phrase not in vectors:
vectors[phrase] = base
base += 1
vector2.append(vectors[phrase])
return vector1, vector2 |
def get_next_version(version, major=False, minor=True, bug=False):
"""
this will take a current version and increment it according to the
major, minor, and bug params
"""
version_list = version.split(".")
if major:
version_list[0] = str(int(version_list[0]) + 1)
elif minor:
version_list[1] = str(int(version_list[1]) + 1)
elif bug:
version_list[2] = str(int(version_list[2]) + 1)
return ".".join(version_list) |
def remove_empty_keys(row):
"""
Remove all unneccessary things from the dictionary
:param row:
:return:
"""
if None in row:
del row[None]
if '' in row:
del row['']
return row |
def listify(x):
"""Convenience function to allow strings or lists to be used as arguments.
If a string is given, it will be tokenized into a list using whitespace as
separator. If a list or tuple is given, its elements will be processed.
If anything else is given, convert it to a string, and then try to make
the result into a list.
"""
if not x:
return []
if isinstance(x, str):
xlist = x.split()
elif isinstance(x, (list, tuple)):
xlist = []
for l in x:
xlist += listify(l)
else:
xlist = listify(str(x))
return xlist |
def merge_links(a, b):
"""deterministically merge two links, favoring longer field values over shorter,
and "cleaner" values over worse ones.
"""
longer = lambda key: (a[key] if len(a[key]) > len(b[key]) else b[key]) if (a[key] and b[key]) else (a[key] or b[key])
earlier = lambda key: a[key] if a[key] < b[key] else b[key]
url = longer('url')
longest_title = longer('title')
cleanest_title = a['title'] if '://' not in (a['title'] or '') else b['title']
return {
'url': url,
'timestamp': earlier('timestamp'),
'title': longest_title if '://' not in (longest_title or '') else cleanest_title,
'tags': longer('tags'),
'sources': list(set(a.get('sources', []) + b.get('sources', []))),
} |
def xml_string_param_to_list(string_param):
"""Given a list string param in XML, convert it to a list of float.
Used to parse position and orientation of objects.
"""
return [float(x) for x in string_param.split(' ')] |
def _node_name(tensor_name):
"""Remove the trailing ':0' from the variable name."""
if ':' not in tensor_name:
return tensor_name
return tensor_name.split(':')[0] |
def ClearAllIntegers(data):
"""Used to prevent known bug; sets all integers in data recursively to 0."""
if type(data) == int:
return 0
if type(data) == list:
for i in range(0, len(data)):
data[i] = ClearAllIntegers(data[i])
if type(data) == dict:
for k, v in data:
data[k] = ClearAllIntegers(v)
return data |
def extract_taxonomy(input):
"""extract the taxonomy"""
return input['_id'], {'taxonomy': input['taxonomy']} |
def similarityScore(arrayOne, arraytwo):
"""returns similarity score of two word arrays, similarity being matching english words"""
return set(arrayOne) & set(arraytwo) |
def distance_to_array_center(v, arr):
"""
Gives the distance from one element of the array to its center
ex: (4, [3, 4, 5]) => 0 because 4 is in the middle of the array
ex: (3, [3, 4, 5]) => 1 because 3 is 1 element away of the middle
"""
array_center = len(arr) // 2
i = arr.index(v)
return abs(array_center - i) |
def pair_contact(individual_contact, pair_type="fnln"):
"""
Valid pair types
fnln: pair as first name last name ad email
notifier: pair as first name last name | email
sendgrid: {"name": name, "email": email}
as is: no pairing
individual_contact must be a tuple in the format
(fn, ln, email)
"""
_fnln = ' '.join(individual_contact[:2])
_email = individual_contact[-1]
if pair_type == "notifier":
return '|'.join([_fnln, _email])
if pair_type == "fnln":
return (_fnln, _email)
if pair_type == "sendgrid":
return {"name": _fnln, "email": _email}
return individual_contact |
def gateway_environment(gateway_environment):
"""Enables path routing on gateway"""
gateway_environment.update({"APICAST_PATH_ROUTING": 1})
return gateway_environment |
def get_driver_readiness(config: dict) -> str:
"""Get the code_readiness config setting."""
return config.get("code_readiness", "Release") |
def getFileInfo(filename: str):
"""Get file information from filename.
Parameters
----------
filename : str
Filename of CSV file
Returns
-------
date : str
Date of the file
time : str
Time of the file
folder : str
Measurement folder of the file
filenumber : str
Number of the measurement
Example
-------
path = ir_export_20170815_P0000004_005_10-50-08
date = 20170815
time = 10-50-08
folder = P0000004
filenumber = 005
"""
date = filename[10:18]
time = filename[-12:-4]
folder = filename[19:27]
filenumber = filename[28:31]
return date, time, folder, filenumber |
def _parse_constraint(expr_string):
""" Parses the constraint expression string and returns the lhs string,
the rhs string, and comparator
"""
for comparator in ['==', '>=', '<=', '>', '<', '=']:
parts = expr_string.split(comparator)
if len(parts) == 2:
# check for == because otherwise they get a cryptic error msg
if comparator == '==':
break
return (parts[0].strip(), comparator, parts[1].strip())
# elif len(parts) == 3:
# return (parts[1].strip(), comparator,
# (parts[0].strip(), parts[2].strip()))
msg = "Constraints require an explicit comparator (=, <, >, <=, or >=)"
raise ValueError(msg) |
def is_leap_year(year):
"""
*** write a proper docstring here ***
*** add five more testcases here ***
"""
# *** YOUR CODE HERE ***
return False |
def ints(int_list):
"""coerce a list of strings that represent integers into a list of integers"""
return [int(number) for number in int_list] |
def standardise_tenure(tenure):
"""Standardise tenure types; one of the four categories:
rental (social), rental (private), owner-occupied, unknown
Parameters
----------
tenure : str
Raw tenure type.
Return
----------
standardised tenure : str
Standardised tenure type."""
# Catch NaN
if isinstance(tenure, float):
return "unknown"
tenure = tenure.lower()
tenure_mapping = {
"owner-occupied": "owner-occupied",
"rental (social)": "rental (social)",
"rented (social)": "rental (social)",
"rental (private)": "rental (private)",
"rented (private)": "rental (private)",
"unknown": "unknown",
"no data!": "unknown",
"not defined - use in the case of a new dwelling for which the intended tenure in not known. it is no": "unknown",
}
return tenure_mapping[tenure] |
def dict_max_merge(dict1, dict2):
"""For two dictionaries, merge them keeping the max value
when keys overlap"""
dict3 = {}
for key, value in dict1.items():
if (key in dict1) and (key in dict2):
dict3[key]=max(value, dict2[key])
else:
dict3[key]=value
for key, value in dict2.items():
if key not in dict3:
dict3[key]=value
return dict3 |
def ambiguous_if_matches_on_ambiguous_bibsource(marc_record, bib_source_of_input, predicate_vectors, output_handler):
"""
:param marc_record:
:param bib_source_of_input: BibSource
:type predicate_vectors: Dict[Record, PredicateVector]
:type output_handler: OutputRecordHandler
:rtype: bool
"""
n = len(predicate_vectors)
for matching_record in list(predicate_vectors.keys()):
if matching_record.source in ['81', '59', '56', '43', '22', '21', '9', '6']:
output_handler.ambiguous(marc_record, "Record matched " + str(n) + " record(s), including at least one "
"ambiguous bibsource. record: " +
matching_record.id + " source: " + matching_record.source)
return True
return False |
def add_srt_to_meta(meta_list, srt_dict):
"""
Combindes the metadata and srt dictionarys.
:param meta_list A list of metadata dictionarys from get_episode_metas
:param srt_dict A dictionary of ID, SRT
"""
new_list = [] # Make a new array to avoid pass my refrence override
for element in meta_list:
imdb_id = element['imdb_id']
new_dict = element.copy() # Copy the dict to avoid PBR override
if imdb_id in srt_dict:
new_dict['srt'] = srt_dict[imdb_id]
new_list.append(new_dict)
return new_list |
def _find_last_larger_than(target, val_array):
"""
Takes an array and finds the last value larger than the target value.
Returns the index of that value, returns -1 if none exists in array.
"""
ind = -1
for j in range(len(val_array), 0, -1):
if val_array[j - 1] > target:
ind = j - 1
break
return ind |
def _element_contains_text(element, text):
"""Scans various element attributes for the given text."""
attributes = ['name', 'class', 'id', 'placeholder', 'value', 'for', 'title', 'innerHTML']
text_list = text if type(text) is list else [text]
for s in text_list:
for attr in attributes:
e = element.get_attribute(attr)
if e is not None and s in e.lower():
return True
return False |
def finalize_mpi(request, on_mpi, mpi_comm, mpi_rank, mpi_size):
"""Slow down the exit on MPI processes to prevent collision in access
to .coverage file."""
if not on_mpi:
return
manager = request.config.pluginmanager
plugin_class = manager.get_plugin('pytest_cov').CovPlugin
plugin = None
for x in manager.get_plugins():
if isinstance(x, plugin_class):
plugin = x
break
if not plugin: # pragma: no cover
return
old_finish = getattr(plugin.cov_controller, 'finish')
def new_finish():
mpi_comm.Barrier()
for _ in range(mpi_rank):
mpi_comm.Barrier()
old_finish()
# These lines come after coverage collection
for _ in range(mpi_rank, mpi_size): # pragma: testing
mpi_comm.Barrier() # pragma: testing
mpi_comm.Barrier() # pragma: testing
plugin.cov_controller.finish = new_finish
if mpi_rank != 0:
def new_is_worker(session): # pragma: testing
return True
plugin._is_worker = new_is_worker |
def verify_url(identifier):
"""Takes an archive.org identifier and returns the verification URL."""
return "http://www.archive.org/details/%s" % (identifier) |
def is_gwf_trace(select_conf_list, text):
"""Determine if text is gwf trace that should be included."""
for index in range(len(select_conf_list)):
if text.find(select_conf_list[index].ident_text) != -1:
return True
return False |
def mel2hz(mel):
"""Convert a value in Mels to Hertz
:param mel: a value in Mels. This can also be a np array, conversion proceeds element-wise.
:returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
"""
return 700 * (10 ** (mel / 2595.0) - 1) |
def remainder(numbers):
"""Function for finding the remainder of 2 numbers divided.
Parameters
----------
numbers : list
List of numbers that the user inputs.
Returns
-------
result : int
Integer that is the remainder of the numbers divided.
"""
return numbers[0] % numbers[1] |
def round_up(val):
"""[Local] Rounds a value on second decimal """
import math
val = math.ceil(val * 100) / 100
return val |
def maybe_date(value):
"""Fix date values when Notion returns them as datetimes."""
if value is None:
return None
# Switch to str.removesuffix when dropping Python 3.8.
if value.endswith("T00:00:00.000+00:00"):
return value[:-19]
return value |
def list_duplicates(seq):
"""List all of the duplicate file names in the download path d"""
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in seq if x in seen or seen_add(x) )
# # turn the set into a list (as requested)
return list(seen_twice) |
def isLatin1(s):
"""
isLatin1 :: str -> bool
Selects the first 256 characters of the Unicode character set,
corresponding to the ISO 8859-1 (Latin-1) character set.
"""
return ord(s) < 256 |
def fit_into(value, min_, max_):
""" Return value bounded by min_ and max_.
"""
return max(min_, min(max_, value)) |
def get_blade_repr(blade_name: str) -> str:
"""Returns the representation to use
for a given blade.
Examples:
- `"12"` -> `"e_12"`
- `""` -> `"1"`
Args:
blade_name: name of the blade in the algebra (eg. `"12"`)
Returns:
Representation to use for a given blade
"""
if blade_name == "":
return "1"
return "e_%s" % blade_name |
def convert_language_code(django_lang):
"""
Converts Django language codes "ll-cc" into ISO codes "ll_CC" or "ll"
:param django_lang: Django language code as ll-cc
:type django_lang: str
:return: ISO language code as ll_CC
:rtype: str
"""
lang_and_country = django_lang.split('-')
try:
return '_'.join((lang_and_country[0], lang_and_country[1].upper()))
except IndexError:
return lang_and_country[0] |
def luminance(rgb):
"""Calculates the brightness of an rgb 255 color. See https://en.wikipedia.org/wiki/Relative_luminance
Args:
rgb(:obj:`tuple`): 255 (red, green, blue) tuple
Returns:
luminance(:obj:`scalar`): relative luminance
Example:
.. code-block:: python
>>> rgb = (255,127,0)
>>> luminance(rgb)
0.5687976470588235
>>> luminance((0,50,255))
0.21243529411764706
"""
luminance = (0.2126*rgb[0] + 0.7152*rgb[1] + 0.0722*rgb[2])/255
return luminance |
def getProbability(value, distribution, values):
"""
Gives the probability of a value under a discrete distribution
defined by (distributions, values).
"""
total = 0.0
for prob, val in zip(distribution, values):
if val == value:
total += prob
return total |
def ext2str(ext, compact=False, default_extver=1):
"""
Return a string representation of an extension specification.
Parameters
----------
ext: tuple, int, str
Extension specification can be a tuple of the form (str,int), e.g.,
('sci',1), an integer (extension number), or a string (extension
name).
compact: bool, optional
If ``compact`` is `True` the returned string will have extension
name quoted and separated by a comma from the extension number,
e.g., ``"'sci',1"``.
If ``compact`` is `False` the returned string will have extension
version immediately follow the extension name, e.g., ``'sci1'``.
default_extver: int, optional
Specifies the extension version to be used when the ``ext`` parameter
is a string (extension name).
Returns
-------
strext: str
String representation of extension specification ``ext``.
Raises
------
TypeError
Unexpected extension type.
Examples
--------
>>> ext2str('sci',compact=False,default_extver=6)
"'sci',6"
>>> ext2str(('sci',2))
"'sci',2"
>>> ext2str(4)
'4'
>>> ext2str('dq')
"'dq',1"
>>> ext2str('dq',default_extver=2)
"'dq',2"
>>> ext2str('sci',compact=True,default_extver=2)
'sci2'
"""
if isinstance(ext, tuple) and len(ext) == 2 and \
isinstance(ext[0], str) and isinstance(ext[1], int):
if compact:
return "{:s}{:d}".format(ext[0], ext[1])
else:
return "\'{:s}\',{:d}".format(ext[0], ext[1])
elif isinstance(ext, int):
return "{:d}".format(ext)
elif isinstance(ext, str):
if default_extver is None:
extver = ''
else:
extver = '{:d}'.format(default_extver)
if compact:
return "{:s}{:s}".format(ext, extver)
else:
return "\'{:s}\',{:s}".format(ext, extver)
else:
raise TypeError("Unexpected extension type.") |
def hammingDistance(string_1, string_2):
"""
:param string_1: (str)
:param string_2: (str)
:return: (int) Hamming distance between string_1 & string_2
"""
assert len(string_1) == len(string_2)
return sum(ch1 != ch2 for ch1, ch2 in zip(string_1, string_2)) |
def hex_2(integer):
"""Transforms integer between 0 and 255 into two-dimensional hex string.
Args:
integer: Integer between 0 and 255.
Returns:
Hex string of the integer.
"""
_hex_2 = hex(integer)[2:]
if integer < 0 or integer > 16**2-1:
raise ValueError("Specify integer between 0 and 255.")
if len(_hex_2) == 1:
_hex_2 = '0' + str(_hex_2)
return str(_hex_2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.