content
stringlengths 42
6.51k
|
---|
def match_locations(locations):
"""
A method to match locations that appear multiple times in the same list
and return year-ordered lists that can then be plotted sequentially
"""
ident = 'Climate Identifier'
yr = 'Year'
mon = 'Month'
matches = []
order_months = [[]]
processed_stations = []
try:
for i, station1 in enumerate(locations):
if (station1[ident], station1[yr][0]) in processed_stations:
continue
matches.append([])
matches[-1].append(station1)
order_months[-1].append(int(station1[mon][0]))
for station2 in locations[i + 1:]:
if station1[ident] == station2[ident] \
and int(station1[yr][0]) == int(station2[yr][0]) \
and int(station1[mon][0]) != int(station2[mon][0]):
matches[-1].append(station2)
order_months[-1].append(int(station2[mon][0]))
processed_stations.append((station1[ident], station1[yr][0]))
return matches
except ValueError:
raise Exception("Verify that CSV has valid dates and formatted properly")
|
def int_input(input_str):
"""
Parse passed text string input to integer
Return None if input contains characters apart from digits
"""
try:
input_val = int(input_str)
except ValueError:
input_val = None
return input_val
|
def bson2bool(bval: bytes) -> bool:
"""Decode BSON Boolean as bool."""
return bool(ord(bval))
|
def tfilter(*args, **kwargs):
"""Like filter, but returns a tuple."""
return tuple(filter(*args, **kwargs))
|
def cull_candidates(candidates, text, sep=' '):
"""Cull candidates that do not start with ``text``.
Returned candidates also have a space appended.
Arguments:
:candidates: Sequence of match candidates.
:text: Text to match.
:sep: Separator to append to match.
>>> cull_candidates(['bob', 'fred', 'barry', 'harry'], 'b')
['bob ', 'barry ']
>>> cull_candidates(cull_candidates(['bob', 'fred', 'barry', 'harry'], 'b'), 'b')
['bob ', 'barry ']
"""
return [c.rstrip(sep) + sep for c in candidates if c and c.startswith(text)]
|
def chunkFx(mylist, n):
"""Break list into fixed, n-sized chunks. The final element of the new list will be n-sized or less"""
# Modified from http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
chunks = []
for i in range(0, len(mylist), n):
chunks.append(mylist[i:i+n])
return chunks
|
def is_nan(n):
"""Return True if n is NaN"""
try:
return map(lambda x: not (x==x), n)
except TypeError: # probably just integer
return not (n == n)
|
def version_components(version):
"""Split version string into major1.major2.minor components."""
components = version.split(".")
num = len(components)
if num < 1:
raise ValueError("version should have at least one component.")
major1 = components[0]
if num >= 2:
major2 = components[1]
else:
major2 = "0"
if num >= 3:
minor = components[2]
else:
minor = "0"
return (major1, major2, minor)
|
def form_frequency_dict(data):
"""
Profile
Forms sorted dictionary with
probabilities values for every character
"""
laters = {}
for char in data:
if char in laters:
laters[char] += 1
else:
laters.update({char: 1})
for later in laters:
laters[later] = laters[later] / len(data) * 100
items = laters.items()
laters = {
k: v for k, v in sorted(items, key=lambda item: item[1], reverse=True)
}
return laters
|
def pytest_gherkin_apply_tag(tag, scenario):
"""Hook for pytest-gherkin tag handling.
All tests and trace identifier numbers are given as Gherkin tags
as well as the normal tags.
Here, in this example we convert id tags to user properties instead,
and leaving the rest to the default hook implementation"""
if tag.startswith("trace_id_"):
scenario.user_properties.append(("trace_id", tag))
return True
if tag.startswith("test_id_"):
scenario.user_properties.append(("test_id", tag))
return True
# Fall back to pytest-gherkin's default behavior
return None
|
def stripSurrogatePairs(ustring):
"""Removes surrogate pairs from a Unicode string"""
# This works for Python 3.x, but not for 2.x!
# Source: http://stackoverflow.com/q/19649463/1209004
try:
ustring.encode('utf-8')
except UnicodeEncodeError:
# Strip away surrogate pairs
tmp = ustring.encode('utf-8', 'replace')
ustring = tmp.decode('utf-8', 'ignore')
return ustring
|
def str2bool(v) -> bool:
"""Converts a string to a boolean.
Raises:
ValueError: If it cannot be converted.
"""
if isinstance(v, bool):
return v
elif isinstance(v, str):
v_low = v.lower()
if v_low in ("yes", "true", "t", "y", "1", "1.0"):
return True
elif v_low in ("no", "false", "f", "n", "0", "0.0"):
return False
raise ValueError(f"{v} is not convertible to boolean!")
|
def compliment_bools(v1, v2):
"""Returns true if v1 and v2 are both bools and not equal"""
return isinstance(v1, bool) and isinstance(v2, bool) and v1 != v2
|
def find_tail(tags, num):
"""
Get the position of the end of the aspect/opinion span in a tagging sequence.
Args:
tags (list): List of tags in a sentence.
num (int): Number to look out for that signals the end of an aspect/opinion.
Returns:
"""
last = False
for i, x in enumerate(tags):
if x != num and last:
return i - 1
if x == num + 1:
last = True
return len(tags)-1 if last else -1
|
def exp4(i):
"""returns \eps**i in GF(4), coded as 2,3,1 for i=0,1,2"""
return 1 + i%3
|
def _get_split_size(split_size):
"""Convert human-readable bytes to machine-readable bytes."""
if isinstance(split_size, str):
exp = dict(MB=20, GB=30).get(split_size[-2:], None)
if exp is None:
raise ValueError('split_size has to end with either'
'"MB" or "GB"')
split_size = int(float(split_size[:-2]) * 2 ** exp)
if split_size > 2147483648:
raise ValueError('split_size cannot be larger than 2GB')
return split_size
|
def gaussian(epsilon, obs_data, sim_data):
"""Gaussian kernel."""
return -0.5 * ((obs_data - sim_data) / epsilon) ** 2
|
def get_player_details(curr_player):
"""Function to get player identifier and marker"""
if curr_player == 'A':
return ['B','O']
else:
return ['A','X']
|
def above_range(test_value: float, metric: float, center: float, interval_range: float) -> bool:
"""
Check whether test_value is larger (>) than a certain value
that is computed as: center + metric * interval_range
:param float test_value: value to be compared
:param float metric: value of metric used to comparison (IQR or std)
:param float center: center of comparison (for example, Q1)
:param float interval_range: value to multiply metric by
:return: whether test value is above range
"""
return test_value > (center + metric * interval_range)
|
def calculate_gc(x):
"""Calculates the GC content of DNA sequence x.
x: a string composed only of A's, T's, G's, and C's."""
x = x.upper()
return float(x.count('G') + x.count('C')) / (x.count('G') + x.count('C') + x.count('A') + x.count('T'))
|
def sequalsci(val, compareto) -> bool:
"""Takes two strings, lowercases them, and returns True if they are equal, False otherwise."""
if isinstance(val, str) and isinstance(compareto, str):
return val.lower() == compareto.lower()
else:
return False
|
def edge_clustering_coefficient_4(u, v, degree, neighbors):
"""
Computes a modified form of the edge clustering coefficient using squares instead of triangles.
"""
udeg = degree[u]
vdeg = degree[v]
mdeg = (udeg-1)*(vdeg-1)
if mdeg == 0:
return float('inf')
else:
uneighbors = neighbors[u] - {v}
vneighbors = neighbors[v] - {u}
num_squares = 0
for w in uneighbors:
wneighbors = neighbors[w] - {u}
num_squares += len(wneighbors & vneighbors)
return (num_squares + 1.0) / mdeg
|
def create_filter_for_endpoint_command(hostnames, ips, ids):
"""
Creates a filter query for getting the machines according to the given args.
The query build is: "or" operator separetes the key and the value between each arg.
For example,
for fields_to_values: {'computerDnsName': ['b.com', 'a.com'], 'lastIpAddress': ['1.2.3.4'], 'id': ['1','2']}
the result is: "computerDnsName eq 'b.com' or computerDnsName eq 'a.com' or lastIpAddress eq '1.2.3.4' or
id eq '1' or id eq '2'"
Args:
hostnames (list): Comma-separated list of computerDnsName.
ips (list): Comma-separated list of lastIpAddress.
ids (list): Comma-separated list of id.
Returns: A string that represents the filter query according the inputs.
"""
fields_to_values = {'computerDnsName': hostnames, 'lastIpAddress': ips, 'id': ids}
return ' or '.join(
f"{field_key} eq '{field_value}'" for (field_key, field_value_list) in fields_to_values.items() if
field_value_list for field_value in field_value_list)
|
def strip_dev_suffix(dev):
"""Removes corporation suffix from developer names, if present.
Args:
dev (str): Name of app developer.
Returns:
str: Name of app developer with suffixes stripped.
"""
corp_suffixes = (
"incorporated",
"corporation",
"limited",
"oy/ltd",
"pty ltd",
"pty. ltd",
"pvt ltd",
"pvt. ltd",
"s.a r.l",
"sa rl",
"sarl",
"srl",
"corp",
"gmbh",
"l.l.c",
"inc",
"llc",
"ltd",
"pvt",
"oy",
"sa",
"ab",
)
if dev not in (None, ""):
for suffix in corp_suffixes:
if dev.lower().rstrip(" .").endswith(suffix):
dev = dev.rstrip(" .")[: len(dev) - len(suffix) - 1].rstrip(",. ")
break
return dev
|
def isChineseChar(uchar):
"""
:param uchar: input char in unicode
:return: whether the input char is a Chinese character.
"""
if uchar >= u'\u3400' and uchar <= u'\u4db5': # CJK Unified Ideographs Extension A, release 3.0
return True
elif uchar >= u'\u4e00' and uchar <= u'\u9fa5': # CJK Unified Ideographs, release 1.1
return True
elif uchar >= u'\u9fa6' and uchar <= u'\u9fbb': # CJK Unified Ideographs, release 4.1
return True
elif uchar >= u'\uf900' and uchar <= u'\ufa2d': # CJK Compatibility Ideographs, release 1.1
return True
elif uchar >= u'\ufa30' and uchar <= u'\ufa6a': # CJK Compatibility Ideographs, release 3.2
return True
elif uchar >= u'\ufa70' and uchar <= u'\ufad9': # CJK Compatibility Ideographs, release 4.1
return True
elif uchar >= u'\u20000' and uchar <= u'\u2a6d6': # CJK Unified Ideographs Extension B, release 3.1
return True
elif uchar >= u'\u2f800' and uchar <= u'\u2fa1d': # CJK Compatibility Supplement, release 3.1
return True
elif uchar >= u'\uff00' and uchar <= u'\uffef': # Full width ASCII, full width of English punctuation, half width Katakana, half wide half width kana, Korean alphabet
return True
elif uchar >= u'\u2e80' and uchar <= u'\u2eff': # CJK Radicals Supplement
return True
elif uchar >= u'\u3000' and uchar <= u'\u303f': # CJK punctuation mark
return True
elif uchar >= u'\u31c0' and uchar <= u'\u31ef': # CJK stroke
return True
elif uchar >= u'\u2f00' and uchar <= u'\u2fdf': # Kangxi Radicals
return True
elif uchar >= u'\u2ff0' and uchar <= u'\u2fff': # Chinese character structure
return True
elif uchar >= u'\u3100' and uchar <= u'\u312f': # Phonetic symbols
return True
elif uchar >= u'\u31a0' and uchar <= u'\u31bf': # Phonetic symbols (Taiwanese and Hakka expansion)
return True
elif uchar >= u'\ufe10' and uchar <= u'\ufe1f':
return True
elif uchar >= u'\ufe30' and uchar <= u'\ufe4f':
return True
elif uchar >= u'\u2600' and uchar <= u'\u26ff':
return True
elif uchar >= u'\u2700' and uchar <= u'\u27bf':
return True
elif uchar >= u'\u3200' and uchar <= u'\u32ff':
return True
elif uchar >= u'\u3300' and uchar <= u'\u33ff':
return True
else:
return False
|
def flatten_lists_of_lists(lists_of_lists):
"""
Flatten list of lists into a list
ex:
[[1, 2], [3]] => [1, 2, 3]
:param lists_of_lists: list(list(elems))
:return: list(elems)
"""
return [elem for sublist in lists_of_lists for elem in sublist]
|
def run_length_encode(in_array):
"""A function to run length decode an int array.
:param in_array: the inptut array of integers
:return the encoded integer array"""
if(len(in_array)==0):
return []
curr_ans = in_array[0]
out_array = [curr_ans]
counter = 1
for in_int in in_array[1:]:
if in_int == curr_ans:
counter+=1
else:
out_array.append(counter)
out_array.append(in_int)
curr_ans = in_int
counter = 1
# Add the final counter
out_array.append(counter)
return out_array
|
def get_pip_package_name(provider_package_id: str) -> str:
"""
Returns PIP package name for the package id.
:param provider_package_id: id of the package
:return: the name of pip package
"""
return "apache-airflow-providers-" + provider_package_id.replace(".", "-")
|
def pack(batch):
"""
Requries the data to be in the format
>>> (*elem, target, [*keys])
The output will be a tuple of {keys: elem}
and target
"""
inp = batch[:-2]
target = batch[-2]
keys = batch[-1]
inp = {k : v for k, v in zip(keys, inp)}
return inp, target
|
def fix_variables(
instance, dynamic_components, scenario_directory, subproblem, stage, loaded_modules
):
"""
:param instance: the compiled problem instance
:param dynamic_components: the dynamic component class
:param scenario_directory: str
:param subproblem: str
:param stage: str
:param loaded_modules: list of imported GridPath modules as Python objects
:return: the problem instance with the relevant variables fixed
Iterate over the required GridPath modules and fix variables by calling
the modules' *fix_variables*, if applicable. Return the modified
problem instance with the relevant variables fixed.
"""
for m in loaded_modules:
if hasattr(m, "fix_variables"):
m.fix_variables(
instance, dynamic_components, scenario_directory, subproblem, stage
)
else:
pass
return instance
|
def format_node(node):
"""Returns a formatted node
Parameters:
node: the the math node (string)
Returns:
: a formatted node
"""
node = str(node).lower()
node = node.replace("*", "\*")
for letter in "zxcvbnmasdfghjklqwertyuiop":
node = node.replace("?" + letter, "*")
return ((str(node)
.replace(" ", "")
.replace(",", "comma")
.replace("[", "lsqb")
.replace("]", "rsqb")
))
|
def is_diagonal_interaction(int_tuple):
"""True if the tuple represents a diagonal interaction.
A one-qubit interaction is automatically "diagonal".
Examples
--------
>>> is_diagonal_interaction((2, 2))
True
>>> is_diagonal_interaction((2, 0))
True
>>> is_diagonal_interaction((1, 1, 2))
False
"""
nonzero_indices = [idx for idx in int_tuple if idx != 0]
return len(set(nonzero_indices)) == 1
|
def limit_lines(lines, N=32):
""" When number of lines > 2*N, reduce to N.
"""
if len(lines) > 2*N:
lines = [b'... showing only last few lines ...'] + lines[-N:]
return lines
|
def add_ngram(sequences, token_indice, ngram_range=2):
"""
Augment the input list by appending n-grams values
:param sequences:
:param token_indice:
:param ngram_range:
:return:
Example: adding bi-gram
>>> sequences = [[1, 3, 4, 5], [1, 3, 7, 9, 2]]
>>> token_indice = {(1, 3): 1337, (9, 2): 42, (4, 5): 2017}
>>> add_ngram(sequences, token_indice, ngram_range=2)
[[1, 3, 4, 5, 1337, 2017], [1, 3, 7, 9, 2, 1337, 42]]
"""
new_seq = []
for input in sequences:
new_list = input[:]
for i in range(len(new_list) - ngram_range + 1):
for ngram_value in range(2, ngram_range + 1):
ngram = tuple(new_list[i:i + ngram_value])
if ngram in token_indice:
new_list.append(token_indice[ngram])
new_seq.append(new_list)
return new_seq
|
def bezout(a, b):
"""
Compute Bezout's coefficients.
"""
r2, r1 = a, b
s2, s1 = 1, 0
t2, t1 = 0, 1
while r1 != 0:
q = r2 // r1
r2, r1 = r1, r2 - q * r1
s2, s1 = s1, s2 - q * s1
t2, t1 = t1, t2 - q * t1
return s2, t2
|
def format_report(count, new_inst, del_inst, svc_info):
"""
Given a service's new, deleted inst, return a string representation for email
"""
needed = False
body = ''
if new_inst is not None and len(new_inst) > 0:
needed = True
body += '\n\n New Instances: '
for inst in new_inst:
body += '\n ' + inst['myname']
else:
body += '\n\n No new instances.'
if del_inst is not None and len(del_inst) > 0:
needed = True
body += '\n\n Deleted Instances: '
for inst in del_inst:
body += '\n ' + inst['myname']
else:
body += '\n\n No deleted instances.'
if needed:
output = 'Service: ' + svc_info['Service']
output += '\n Total Instances: ' + str(count)
output += '\n\n'
return output + body
return None
|
def format_fields(field_data, include_empty=True):
"""Format field labels and values.
Parameters
----------
field_data : |list| of |tuple|
2-tuples of field labels and values.
include_empty : |bool|, optional
Whether fields whose values are |None| or an empty |str| should
be included in the formatted fields.
Returns
-------
str
Formatted field labels and values.
Examples
--------
>>> field_data = [('Name', 'Jane'), ('Age', 30), ('DOB', None)]
>>> format_fields(field_data, include_empty=True)
Name: Jane
Age: 30
DOB: None
>>> field_data = [('Name', 'Jane'), ('Age', 30), ('DOB', None)]
>>> format_fields(field_data, include_empty=False)
Name: Jane
Age: 30
"""
max_label = 0
for (label, value) in field_data:
label_length = len(label)
if label_length > max_label:
max_label = label_length
fields = []
for (label, value) in field_data:
empty = str(value).strip() in ['', 'None']
if not empty or include_empty:
label_length = len(label.strip())
extra_spaces = ' ' * (max_label - label_length)
label_sep = ':' + extra_spaces + ' '
joined_field = label_sep.join([label, str(value)])
fields.append(joined_field)
return '\n'.join(fields)
|
def aliased(aliased_class):
"""
Decorator function that *must* be used in combination with @alias
decorator. This class will make the magic happen!
@aliased classes will have their aliased method (via @alias) actually aliased.
This method simply iterates over the member attributes of 'aliased_class'
seeking for those which have an '_aliases' attribute and then defines new
members in the class using those aliases as mere pointer functions to the
original ones.
Usage:
@aliased
class MyClass(object):
@alias('coolMethod', 'myKinkyMethod')
def boring_method():
# ...
i = MyClass()
i.coolMethod() # equivalent to i.myKinkyMethod() and i.boring_method()
"""
original_methods = aliased_class.__dict__.copy()
for method in original_methods.values():
if hasattr(method, "_aliases"):
# Add the aliases for 'method', but don't override any
# previously-defined attribute of 'aliased_class'
# noinspection PyProtectedMember
for method_alias in method._aliases - set(original_methods):
setattr(aliased_class, method_alias, method)
return aliased_class
|
def is_runway_visibility(item: str) -> bool:
"""Returns True if the item is a runway visibility range string"""
return (
len(item) > 4
and item[0] == "R"
and (item[3] == "/" or item[4] == "/")
and item[1:3].isdigit()
)
|
def channel_from_scope(scope):
"""Helper method to extract channel ID from a Backplane scope."""
idx = scope.find('channel')
return scope[idx + 8:]
|
def compile_question_data(surveys):
""" creates a double nested dict of question ids containing dict with question text,
and an empty list. """
#Note: we want to keep the question text around so it can be displayed on the page.
if not surveys:
return {}
all_questions = {}
for question in surveys[0]: # we only need to get the questions once
all_questions[ question['question id'] ] = { question['question text'] : [] }
return all_questions
|
def _entity_string_for_errors(entity):
"""Derive a string describing `entity` for use in error messages."""
try:
character = entity.character
return 'a Sprite or Drape handling character {}'.format(repr(character))
except AttributeError:
return 'the Backdrop'
|
def calc_check_digit(number):
"""Calculate the check digit. The number passed should not have the
check digit included."""
check = (11 - sum((8 - i) * int(n) for i, n in enumerate(number)) % 11)
# this results in a two-digit check digit for 11 which should be wrong
return '0' if check == 10 else str(check)
|
def perfect_score(student_info):
"""
:param student_info: list of [<student name>, <score>] lists
:return: first `[<student name>, 100]` or `[]` if no student score of 100 is found.
"""
#
first = []
student_names = []
score = []
print (student_info)
for name in student_info:
print('1', 'name', name[0])
print ('2','score',name[1])
print(type(name[1]))
score = int(name[1])
print(type(score))
if (score == 100 ):
print('3', score)
print(name)
return name
return first
|
def search(bs, arr):
"""
Binary search recursive function.
:param bs: int
What to search
:param arr: array
Array of ints where to search. Array must be sorted.
:return: string
Position of required element or "cannot found" string
"""
length = len(arr)
check_item = arr[int(length / 2)]
if check_item == bs:
return str(check_item) + ' is on position ' + str(arr[int(length / 2)])
if check_item < bs:
return search(bs, arr[int(length / 2):])
if check_item > bs:
return search(bs, arr[:int(length / 2)])
return "cannot found"
|
def transform_string_mac_address_to_mac_address(string_mac_address):
"""
It transforms a MAC address from human readable string("00:11:22:33:44:55") to a raw string
format("\x00\x11\x22\x33\x44\x55").
"""
result = str()
for i in string_mac_address.split(':'):
result += chr(int(i, 16))
return result
|
def fibonacci(n):
"""
Return the nth fibonacci number, that is n if n < 2,
or fibonacci(n-2) + fibonacci(n-1) otherwise.
@param int n: a non-negative integer
@rtype: int
>>> fibonacci(0)
0
>>> fibonacci(1)
1
>>> fibonacci(3)
2
"""
if n < 2:
return n
else:
return fibonacci(n - 2) + fibonacci(n - 1)
|
def move_to_tile(location, tile):
""" Return the action that moves in the direction of the tile. """
# actions = ['', 'u', 'd', 'l', 'r', 'p']
print(f"my tile: {tile}")
# see where the tile is relative to our current location
diff = tuple(x - y for x, y in zip(location, tile))
if diff == (0, 1):
action = 'd'
elif diff == (1, 0):
action = 'l'
elif diff == (0, -1):
action = 'u'
elif diff == (-1, 0):
action = 'r'
else:
action = ''
return action
|
def any_alt_args_in_list(args, l):
"""Report whether any arguments in the args list appear in the list l."""
for a in args.get('alt_args', {}):
if a in l:
return True
return False
|
def densityGlycerol(temperature):
"""
Calculates the density of glycerol from an interpolation by Cheng (see viscosity docstring for reference).
Args:
temperature (float): in Celsius in the range [0, 100]
Returns:
:class:`float` Density of Glycerol in kg/m^3
"""
rho = 1277 - 0.654 * temperature
glycerolDensity = rho
return glycerolDensity
|
def normalizer(value, max_value):
"""
"""
if value is None:
return 0.0
if value >= max_value:
return 1.0
else:
return float(value)/float(max_value)
|
def arabic_to_roman(number: int) -> str:
"""Return roman version of the specified arabic number."""
if number > 3999:
raise ValueError(f"Number can not be represented with roman numerals: "
f"{number}")
roman_number = ""
for index, digit in enumerate(reversed(str(number))):
if index == 0:
first = "I"
fifth = "V"
tenth = "X"
elif index == 1:
first = "X"
fifth = "L"
tenth = "C"
elif index == 2:
first = "C"
fifth = "D"
tenth = "M"
elif index == 3:
first = "M"
fifth = ""
tenth = ""
else:
raise ValueError(f"Invalid input: {number}")
if digit == "0":
continue
elif digit == "1":
roman_number = first + roman_number
elif digit == "2":
roman_number = first * 2 + roman_number
elif digit == "3":
roman_number = first * 3 + roman_number
elif digit == "4":
roman_number = first + fifth + roman_number
elif digit == "5":
roman_number = fifth + roman_number
elif digit == "6":
roman_number = fifth + first + roman_number
elif digit == "7":
roman_number = fifth + first * 2 + roman_number
elif digit == "8":
roman_number = fifth + first * 3 + roman_number
elif digit == "9":
roman_number = first + tenth + roman_number
return roman_number
|
def _reform_inputs(param_dict, out_species):
"""Copies param_dict so as not to modify user's dictionary. Then reformats out_species from pythonic list
to a string of space separated names for Fortran.
"""
if param_dict is None:
param_dict = {}
else:
# lower case (and conveniently copy so we don't edit) the user's dictionary
# this is key to UCLCHEM's "case insensitivity"
param_dict = {k.lower(): v for k, v in param_dict.items()}
if out_species is not None:
n_out = len(out_species)
param_dict["outspecies"] = n_out
out_species = " ".join(out_species)
else:
out_species = ""
n_out = 0
return n_out, param_dict, out_species
|
def _FirewallRulesToCell(firewall):
"""Returns a compact string describing the firewall rules."""
rules = []
for allowed in firewall.get('allowed', []):
protocol = allowed.get('IPProtocol')
if not protocol:
continue
port_ranges = allowed.get('ports')
if port_ranges:
for port_range in port_ranges:
rules.append('{0}:{1}'.format(protocol, port_range))
else:
rules.append(protocol)
return ','.join(rules)
|
def split_timecode(time_code):
""" Takes a timecode string and returns the hours, minutes and seconds. Does not simplify timecode.
:param time_code: String of format "HH:MM:SS.S" ex. "01:23:45.6"
:return: HH (float), MM (float), SS (float)
"""
hh, mm, ss = time_code.split(':')
hh = float(hh)
mm = float(mm)
ss = float(ss)
return hh, mm, ss
|
def col_letter(col):
"""Return column letter given number."""
return chr(ord("A") + col - 1)
|
def GroupNamedtuplesByKey(input_iter, key):
"""Split an iterable of namedtuples, based on value of a key.
Args:
input_iter: An iterable of namedtuples.
key: A string specifying the key name to split by.
Returns:
A dictionary, mapping from each unique value for |key| that
was encountered in |input_iter| to a list of entries that had
that value.
"""
split_dict = {}
for entry in input_iter:
split_dict.setdefault(getattr(entry, key, None), []).append(entry)
return split_dict
|
def single_multiple(status: int):
"""
>>> single_multiple(0b1000)
'multiple sensors have errors'
>>> single_multiple(0b0000)
'only a single sensor has error (or no error)'
"""
if status & 0b1000:
return 'multiple sensors have errors'
else:
return 'only a single sensor has error (or no error)'
|
def _xtract_bsx(rec_type):
"""Parse rec_type to bsx_type"""
bsx_type = None
if not rec_type or rec_type == 'None':
# rec_type None means running a beam with no recording
bsx_type = None
elif rec_type == 'bst' or rec_type == 'sst' or rec_type == 'xst':
bsx_type = rec_type
elif rec_type == 'bfs' or rec_type == 'tbb' or rec_type == 'dmp':
# 'dmp' is for just recording without setting up a beam.
pass
else:
raise RuntimeError('Unknown rec_type {}'.format(rec_type))
return bsx_type
|
def f_numeric(A, B):
"""Operation on numeric arrays
"""
return 3.1 * A + B + 1
|
def from_string(s):
"""Converts a time series to a list of (int, int) tuples.
The string should be a sequence of zero or more <time>:<amount> pairs.
Whitespace delimits each pair; leading and trailing whitespace is ignored.
ValueError is raised on any malformed input.
"""
pairs = s.strip().split()
ret = []
for pair in pairs:
time, amount = pair.split(":")
time = int(time)
amount = int(amount)
if time < 0:
raise ValueError("Time cannot be less than zero: %s" % time)
ret.append((time, amount))
return ret
|
def other(e):
"""Reverse the edge"""
if e == e.lower():
return e.upper()
else:
return e.lower()
|
def get_release_date(data):
"""gets device release date"""
try:
launch = data['launch']
splt = launch.split(' ')
return int(float(splt[0]))
except (KeyError, TypeError):
return None
|
def isascii(s):
"""Return True if there are no non-ASCII characters in s, False otherwise.
Note that this function differs from the str.is* methods in that
it returns True for the empty string, rather than False.
>>> from bridgedb.util import isascii
>>> isascii('\x80')
False
>>> isascii('foo\tbar\rbaz\n')
True
>>> isascii('foo bar')
True
:param str s: The string to check for non-ASCII characters.
"""
return all(map((lambda ch: ord(ch) < 128), s))
|
def _assoc_list_to_map(lst):
"""
Convert an association list to a dictionary.
"""
d = {}
for run_id, metric in lst:
d[run_id] = d[run_id] + [metric] if run_id in d else [metric]
return d
|
def _language_name_for_scraping(language):
"""Handle cases where X is under a "macrolanguage" on Wiktionary.
So far, only the Chinese languages necessitate this helper function.
We'll keep this function as simple as possible, until it becomes too
complicated and requires refactoring.
"""
return "Chinese" if language == "Cantonese" else language
|
def _update_addition_info(addition_info):
""" Update default addition_info with inputs """
add_info = {"epoch": 0, "batch": 0, "batch_size": 0}
if not addition_info:
return add_info
elif not isinstance(addition_info, dict):
raise TypeError("The type of 'addition_info' should be 'dict', "
"but got '{}'.".format(str(type(addition_info))))
else:
for item, value in addition_info.items():
if item not in ["epoch", "batch", "batch_size"]:
raise ValueError(
"The key of 'addition_info' should be one of the "
"['epoch', 'batch', 'batch_size'], but got '{}'."
.format(str(item)))
if not isinstance(value, int):
raise ValueError(
"The value of 'addition_info' should be 'int', "
"but got '{}'.".format(str(type(value))))
add_info[item] = value
return add_info
|
def flatten_dict(d, separator='.', prefix=''):
"""Flatten nested dictionary.
Transforms {'a': {'b': {'c': 5}, 'd': 6}} into {'a.b.c': 5, 'a.d': 6}
Args:
d (dist): nested dictionary to flatten.
separator (str): the separator to use between keys.
prefix (str): key prefix
Returns:
dict: a dictionary with keys compressed and separated by separator.
"""
return {prefix + separator + k if prefix else k: v
for kk, vv in d.items()
for k, v in flatten_dict(vv, separator, kk).items()
} if isinstance(d, dict) else {prefix: d}
|
def is_num(var):
"""
Test if variable var is number (int or float)
:return: True if var is number, False otherwise.
:rtype: bol
"""
return isinstance(var, int) or isinstance(var, float)
|
def odd_pair(nums):
"""Solution to exercise C-1.14.
Write a short Python function that takes a sequence of integer values and
determines if there is a distinct pair of numbers in the sequence whose
product is odd.
--------------------------------------------------------------------------
Solution:
--------------------------------------------------------------------------
The product of two odd numbers will produce an odd number. If there are at
least two (unique) odd numbers in the sequence, the function should return
True.
"""
uniques = set(nums)
odd_count = 0
for num in uniques:
if num % 2 != 0:
odd_count += 1
if odd_count > 1:
break
return odd_count > 1
|
def remove_null_values(dictionary: dict) -> dict:
"""Create a new dictionary without keys mapped to null values.
Args:
dictionary: The dictionary potentially containing keys mapped to values of None.
Returns:
A dict with no keys mapped to None.
"""
if isinstance(dictionary, dict):
return {k: v for (k, v) in dictionary.items() if v is not None}
return dictionary
|
def flatten(d, key_as_tuple=True, sep='.'):
""" get nested dict as {key:val,...},
where key is tuple/string of all nested keys
Parameters
----------
d : dict
key_as_tuple : bool
whether keys are list of nested keys or delimited string of nested keys
sep : str
if key_as_tuple=False, delimiter for keys
Examples
--------
>>> from pprint import pprint
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> pprint(flatten(d))
{(1, 'a'): 'A', (2, 'b'): 'B'}
>>> d = {1:{"a":"A"},2:{"b":"B"}}
>>> pprint(flatten(d,key_as_tuple=False))
{'1.a': 'A', '2.b': 'B'}
"""
def expand(key, value):
if isinstance(value, dict):
if key_as_tuple:
return [(key + k, v)
for k, v in flatten(value, key_as_tuple).items()]
else:
return [(str(key) + sep + k, v)
for k, v in flatten(value, key_as_tuple).items()]
else:
return [(key, value)]
if key_as_tuple:
items = [item for k, v in d.items() for item in expand((k,), v)]
else:
items = [item for k, v in d.items() for item in expand(k, v)]
return dict(items)
|
def generate_dhm_response(public_key: int) -> str:
"""Generate DHM key exchange response
:param public_key: public portion of the DHMKE
:return: string according to the specification
"""
return 'DHMKE:{}'.format(public_key)
|
def index(_, __):
"""
Index Enpoint, returns 'Hello World'
"""
return {"content": "Hello World!"}
|
def block_aligned(location, block_size):
"""Determine if a location is block-aligned"""
return (location & (block_size - 1)) == 0
|
def f_pitch(p, pitch_ref=69, freq_ref=440.0):
"""Computes the center frequency/ies of a MIDI pitch
Notebook: C3/C3S1_SpecLogFreq-Chromagram.ipynb
Args:
p (float): MIDI pitch value(s)
pitch_ref (float): Reference pitch (default: 69)
freq_ref (float): Frequency of reference pitch (default: 440.0)
Returns:
freqs (float): Frequency value(s)
"""
return 2 ** ((p - pitch_ref) / 12) * freq_ref
|
def position_case_ligne_motif(pos_ligne_motif, sens, colonne, ligne):
"""
renvoie la position de la case en fontion du sens des lignes
"""
x_debut, y_debut = pos_ligne_motif
if sens=="gauche":
x_case = x_debut-colonne*25
else:
x_case = x_debut+colonne*25
return x_case, y_debut+ligne*25
|
def isNEIC(filename):
"""
Checks whether a file is ASCII NEIC format.
"""
try:
temp = open(filename, 'rt').readline()
except:
return False
try:
if not temp.startswith('time,latitude,longitude,depth,mag,magType,nst,'):
return False
except:
return False
print ("Found NEIC data")
return True
|
def replace_matrix(base, x, y, data):
"""
base = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
x = 1
y = 0
data = [[x],
[y],
[z]]
return [[1, x, 3],
[4, y, 6],
[7, z, 9]]
"""
data_height = len(data)
data_width = len(data[0])
for _row in range(data_height):
for _col in range(data_width):
base[y + _row][x + _col] = data[_row][_col]
return base
|
def stream_has_colours(stream):
"""
True if stream supports colours. Python cookbook, #475186
"""
if not hasattr(stream, "isatty"):
return False
if not stream.isatty():
return False # auto color only on TTYs
try:
import curses
curses.setupterm()
return curses.tigetnum("colors") > 2
except:
return False
|
def surface_color_format_to_texture_format(fmt, swizzled):
"""Convert nv2a draw format to the equivalent Texture format."""
if fmt == 0x3: # ARGB1555
return 0x3 if swizzled else 0x1C
if fmt == 0x5: # RGB565
return 0x5 if swizzled else 0x11
if fmt in [0x7, 0x08]: # XRGB8888
return 0x7 if swizzled else 0x1E
if fmt == 0xC: # ARGB8888
return 0x6 if swizzled else 0x12
raise Exception(
"Unknown color fmt %d (0x%X) %s"
% (fmt, fmt, "swizzled" if swizzled else "unswizzled")
)
|
def bit_read(data, position):
"""Returns the value of a single bit in a number.
:param: data The number (bytearray) that contains the desired bit.
:param: position The position of the bit in the number.
:return: The bit value (True or False).
"""
byte_pos = int(position // 8) # byte position in number
bit_pos = int(position % 8) # bit position in byte
return bool((data[byte_pos] & (1 << bit_pos)) >> bit_pos)
|
def Beta22_1(X):
""" Coefficient for the 1PN tidal correction to h_22 mode
Defined in arXiv:1203.4352, eqn A15
Input
X -- mass fraction of object being tidally deformed
Output
double, coeff for 1PN tidal correction to h_22 mode """
return (-202.+560.*X-340.*X*X+45.*X*X*X)/42./(3.-2.*X)
|
def problem_48_self_powers(series_limit, digits):
""" Problem 48: Find the last digits of series n^n (n = 1 to series limit).
Args:
series_limit (int): The maximum base and power in the series.
digits (int): The number of last digits to take from sum.
"""
result = 0
for number in range(1, series_limit + 1, 1):
result += number ** number
return str(result)[-digits:]
|
def accuracy(labels, preds):
"""Calculate the accuracy between predictions."""
correct = 0
for idx, label in enumerate(labels):
pred = preds[idx]
if isinstance(label, int):
if label == pred:
correct += 1
else:
if pred in label:
correct += 1
return correct/len(labels)
|
def space_to_kebab(s):
"""Replace spaces with dashes.
Parameters
----------
s : str
String that may contain " " characters.
"""
return "-".join(s.split(" "))
|
def isTool(name):
"""
Check if a tool is on PATh and marked as executable.
Parameters
---
name: str
Returns
---
True or False
"""
from distutils.spawn import find_executable
if find_executable(name) is not None:
return True
else:
return False
|
def convertNumbers(s,l,toks):
"""
Convert tokens to int or float
"""
n = toks[0]
try:
return int(n)
except ValueError:
return float(n)
|
def _list_to_index_dict(lst):
"""Create dictionary mapping list items to their indices in the list."""
return {item: n for n, item in enumerate(lst)}
|
def __parseAuthHeader(string):
"""
Returns the token given an input of 'Bearer <token>'
"""
components = string.split(' ')
if len(components) != 2:
raise ValueError('Invalid authorization header.')
return components[1]
|
def dashed_line(length: int, symbol: str="=") -> str:
"""Print out a dashed line
To be used as visual boundaries for tests.
Args:
length (int): number of charters
symbol (str): symbol to be used in the dashed line
default: "="
Returns:
a string of characters of length `n`.
"""
def aux(length, accum):
if length == 0:
return accum
else:
return aux(length - 1, accum + symbol)
return aux(length, "")
|
def left_to_right_check(input_line: str, pivot: int):
"""
Check row-wise visibility from left to right.
Return True if number of building from the left-most hint is visible looking to the right,
False otherwise.
input_line - representing board row.
pivot - number on the left-most hint of the input_line.
>>> left_to_right_check("412453*", 4)
True
>>> left_to_right_check("452453*", 5)
False
"""
lst = list(input_line)
if lst[-1] == "*":
del lst[-1]
del lst[0]
int_lst = []
for i in lst:
int_lst.append(int(i))
res = []
res.append(int_lst[0])
for j in range(len(int_lst)-1):
if int_lst[j+1] >= int_lst[j]:
res.append(int_lst[j+1])
if len(set(res)) == pivot:
return True
else:
return False
|
def make_list_unique(elem_list):
"""
Removes all duplicated values from the supplied list.
:param elem_list: list to remove duplicate elements from
:return: new list with all unique elements of the original list
"""
return list(dict.fromkeys(elem_list))
|
def lenght(value, min, max, message_error=None, message_valid=None):
"""
min : integer
max: integer
value : value element DOM. Example : document['id].value
message_error : str message
message_valid: str message
function return tuple
"""
if min is not None and len(value) < min:
return(False, message_error or 'length of value must be at least %s' % min, value)
if max is not None and len(value) > max:
return(False, message_error or 'length of value must be at most %s' % min, value)
else:
return(True, message_valid or 'valid', value)
|
def is_pangram(sentence: str) -> bool:
"""Return True if given string is a panagram."""
# a pangram is a sentence using every letter of the alphabet at least once
sentence = sentence.lower()
alphabet = 'abcdefghijklmnopqrstuvwxyz'
return set(sentence).issuperset(alphabet)
|
def has_perm(permissions, context):
"""
Validates if the user in the context has the permission required.
"""
if context is None:
return False
if type(context) is dict:
user = context.get('user', None)
if user is None:
return False
else:
user = context.user
if user.is_authenticated() is False:
return False
if type(permissions) is tuple:
print("permissions", permissions)
for permission in permissions:
print("User has perm", user.has_perm(permission))
if not user.has_perm(permission):
return False
if type(permissions) is str:
if not user.has_perm(permissions):
return False
return True
|
def excel_title_to_column(column_title: str) -> int:
"""
Given a string column_title that represents
the column title in an Excel sheet, return
its corresponding column number.
>>> excel_title_to_column("A")
1
>>> excel_title_to_column("B")
2
>>> excel_title_to_column("AB")
28
>>> excel_title_to_column("Z")
26
"""
assert column_title.isupper()
answer = 0
index = len(column_title) - 1
power = 0
while index >= 0:
value = (ord(column_title[index]) - 64) * pow(26, power)
answer += value
power += 1
index -= 1
return answer
|
def gcd( a , b ):
"""
Calculate the greatest common divisor.
"""
while b:
a , b = b , a%b
return a
|
def fisbHexBlocksToHexString(hexBlocks):
"""
Given a list of 6 items, each containing a hex-string of
an error corrected block, return a string with all 6 hex strings
concatinated. Used only for FIS-B.
This only returns the bare hex-string with '+'
prepended and no time, signal strength, or error count attached.
Args:
hexBlocks (list): List of 6 strings containing a hex string for each
of the 6 FIS-B hexblocks. Only called if all blocks error corrected
successfully (i.e. there should be no ``None`` items).
Returns:
str: String with all hex data and a '+' prepended at the front.
This function is only for FIS-B packets. No comment data is appended to
the end.
"""
return '+' + hexBlocks[0] + hexBlocks[1] + hexBlocks[2] + \
hexBlocks[3] + hexBlocks[4] + hexBlocks[5]
|
def running_mean_estimate(estimate,
batch_estimate,
num_samples,
batch_size):
"""Update a running mean estimate with a mini-batch estimate."""
tot_num_samples = float(num_samples + batch_size)
estimate_fraction = float(num_samples) / tot_num_samples
batch_fraction = float(batch_size) / tot_num_samples
return estimate * estimate_fraction + batch_estimate * batch_fraction
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.