content stringlengths 42 6.51k |
|---|
def mults_of_ns(mults=[1], limit=1000):
"""
returns the sum of all the values that are multiples of ns up to limit
"""
return sum(set([val for val in range(limit) for arg in mults if val%arg==0])) |
def date_extend(month, year):
"""
A function to help me not write the same thing many times.
If the month is December the month switches to January next year
@type month: integer
@param month: a month of the year
@type day: integer
@param day: a day of the given month
@rtype: tuple
@return: returns the new month and year
"""
if month == 12:
month = 1
year += 1
else:
month += 1
return (month, year) |
def half_even_round(value, scale):
"""
Round values using the "half even" logic
See more: https://docs.python.org/3/library/decimal.html#rounding-modes
>>> half_even_round(7.5, 0)
8.0
>>> half_even_round(6.5, 0)
6.0
>>> half_even_round(-7.5, 0)
-8.0
>>> half_even_round(-6.5, 0)
-6.0
"""
# Python2 and Python3's round behavior differs for rounding e.g. 0.5
# hence we handle the "half" case so that it round even up and odd down
if scale > 0:
return round(value, scale)
scaled_value = (value * (10 ** scale))
removed_part = scaled_value % 1
if removed_part == 0.5:
rounded_part = int(scaled_value)
is_even = (rounded_part + max(0, scale)) % 2 == 0
sign = -1 if value < 0 else 1
if is_even:
value -= 10 ** -(scale + 1) * sign
else:
value += 10 ** -(scale + 1) * sign
return round(value, scale) |
def checkAnswers(answers):
"""
checkAnswers(answers): Check our answers. This is an array that is returned (even if empty) in the same order as the actual answers.
"""
retval = []
for answer in answers:
sanity = answer["sanity"]
headers = answer["headers"]
#headers["class"] = 0 # Debugging
if headers["class"] < 1:
warning = "QCLASS in answer is < 1 (%s)" % headers["class"]
sanity.append(warning)
#headers["class"] = 123 # Debugging
if headers["class"] > 4:
warning = "QCLASS in answer is > 4 (%s)" % headers["class"]
sanity.append(warning)
retval.append(sanity)
return(retval) |
def print_reverse(head_node):
"""Prints the elements of the given Linked List in reverse order"""
# If reached end of the List
if head_node is None:
return None
else:
# Recurse
print_reverse(head_node.next)
print(head_node.data) |
def _get_in_response_to(params):
"""Insert InResponseTo if we have a RequestID."""
request_id = params.get('REQUEST_ID', None)
if request_id:
return {
'IN_RESPONSE_TO': request_id,
**params,
}
else:
return params |
def _py_list_append(list_, x):
"""Overload of list_append that executes a Python list append."""
# Revert to the original call.
list_.append(x)
return list_ |
def get_nested_obj_attr_value(obj, lookup_str, seperator="__"):
"""
return the value of an inner attribute of an object
e.g. `user__organization__member__organization__slug` would return the organization slug related to the user
:object obj: an object. could be model obj
:string lookup_str: str to look for (e.g., organization__slug)
:string seperator: seperator to identify the nesting in the lookup string
"""
if obj is None:
return None
operations = ("COUNT",)
if seperator not in lookup_str:
if lookup_str in operations:
return getattr(obj, lookup_str.lower())()
return getattr(obj, lookup_str)
first_lookup_str, remaining_lookup_str = lookup_str.split(seperator, maxsplit=1)
new_obj = getattr(obj, first_lookup_str)
return get_nested_obj_attr_value(new_obj, remaining_lookup_str, seperator) |
def make_url(path):
""" This is a terrible function. Don't take it as a reference in your own code.
It just happens to be good enough for our purposes here. """
return "http://localhost:5000/{path}".format(path=path) |
def get_branch(version: str) -> str:
""" Get the branch of an update """
return 'stable' if version.startswith('V') else 'weekly' |
def print_port(filter_port, packet_port):
"""
Confirm if filter_port is packet_port or any
"""
if filter_port in [packet_port, 'Any', 'any', 'ANY']:
return True
return False |
def rootsearch(f, a: float, b: float, dx: float):
"""Seacrh one root in range [a, b]."""
x1 = a
f1 = f(a)
x2 = a + dx
f2 = f(x2)
if x2 > b:
x2 = b
f2 = f(x2)
while f1*f2 > 0.0:
if x1 >= b:
return None, None
x1 = x2
f1 = f2
x2 = x1 + dx
f2 = f(x2)
if x2 > b:
x2 = b
f2 = f(x2)
return x1, x2 |
def parse_params(params):
"""
Take Tor-formatted parameters, then returns a keyword-based dictionary
of integers.
For example, we use it to parse "params" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L1820
:param str params: input params to be processed
:returns: a dictionary with (param-name, param-integer-value) items
"""
pairs = params.split(' ')
content = dict()
for key, value in [pair.split('=') for pair in pairs]:
content[key] = int(value)
return content |
def get_fields(json):
"""
Retrieve arguments from JSON request
:param json: JSON request sent in payload
:return: Parsed arguments
"""
record_name = json.get('record_name')
ip4_address = json.get('address')
parent_zone = json.get('parent_zone')
return record_name, ip4_address, parent_zone |
def pluralize(num: int, thing: str) -> str:
"""Return the string f"1 {thing}" or f"{num} {thing}s", depending on `num`."""
return f"1 {thing}" if num == 1 else f"{num} {thing}s" |
def convert_dms_from_float(value, loc):
"""
convert floats coordinates into degrees, munutes and seconds + ref tuple
return: tuple like (25, 13, 48.343 ,'N')
"""
if value < 0:
loc_value = loc[0]
elif value > 0:
loc_value = loc[1]
else:
loc_value = ""
abs_value = abs(value)
deg = int(abs_value)
t1 = (abs_value-deg) * 60
min = int(t1)
sec = round((t1 - min) * 60, 5)
return deg, min, sec, loc_value |
def merge(source, destination):
"""Update destination dict with source recursively.
see: https://stackoverflow.com/questions/20656135 (also: 7204805)
"""
for key, value in source.items():
if isinstance(value, dict):
node = destination.setdefault(key, {}) # get node or create one
merge(value, node)
else:
destination[key] = value
return destination |
def handle_problematic_characters(errors, filename, start, end, message):
"""Trivial helper routine in case something goes wrong in `decode`.
:Parameters:
- `errors`: the ``errors`` parameter known from standard ``str.encode``
methods. It is just passed by `decode`.
- `filename`: the input to be converted to Unicode by `decode`
- `start`: the starting position of the problematic area as an index in
``filename``
- `end`: the ending position of the problematic area as an index in
``filename``. Note that this obeys to the standard upper-limit
notation in Python (range() etc).
- `message`: error message describing the problem
:type errors: str
:type filename: str
:type start: int
:type end: int
:type message: str
:Return:
the single character to be inserted into the output string
:rtype: unicode
"""
if errors == 'ignore':
return u""
elif errors == 'replace':
return u"?"
else:
raise UnicodeDecodeError("safefilename", filename, start, end, message) |
def _compare(idx, text):
"""
compare function for sorted
"""
txt = text[idx]
if isinstance(txt, tuple):
txt = txt[1]
try:
decimal_string = txt
decimal_value = float(decimal_string)
txt = u""
except ValueError:
decimal_value = float('Infinity')
decimal_string = u""
return (decimal_value, decimal_string, txt) |
def pre_process(board, turn="x"):
""" Takes the board with x and o and turns in into vectors with numbers. 1 is AI, -1 is human, and 0 is empty """
result = []
opposite = "o" if turn == "x" else "x"
result = [1 if x == turn else x for x in board]
result = [-1 if x == opposite else x for x in result]
return result |
def abort_message(message):
"""Generic abort message"""
return {'message': message} |
def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return bits
return min(bits, (~number & (number-1)).bit_length()) |
def element(atomic_number):
"""
Return the element of a given atomic number.
:param atomic_number:
The atomic number for the element in question (e.g., 26).
:type atomic_number:
int-like
:returns:
The short-hand element for a given atomic number.
:rtype:
str
"""
atomic_number = int(atomic_number)
periodic_table = """H He
Li Be B C N O F Ne
Na Mg Al Si P S Cl Ar
K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr
Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe
Cs Ba Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn
Fr Ra Lr Rf Db Sg Bh Hs Mt Ds Rg Cn UUt"""
lanthanoids = "La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb"
actinoids = "Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No"
periodic_table = periodic_table.replace(" Ba ", " Ba " + lanthanoids + " ") \
.replace(" Ra ", " Ra " + actinoids + " ").split()
del actinoids, lanthanoids
return periodic_table[atomic_number - 1] |
def zipstar(L, lazy=False):
"""
A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])
May return lists or tuples.
"""
if len(L) == 0:
return L
width = len(L[0])
if width < 100:
return [[elem[idx] for elem in L] for idx in range(width)]
L = zip(*L)
return L if lazy else list(L) |
def parse_compute_version(compute_version):
"""Parse compute capability string to divide major and minor version
Parameters
----------
compute_version : str
compute capability of a GPU (e.g. "6.0")
Returns
-------
major : int
major version number
minor : int
minor version number
"""
split_ver = compute_version.split(".")
try:
major = int(split_ver[0])
minor = int(split_ver[1])
return major, minor
except (IndexError, ValueError) as err:
# pylint: disable=raise-missing-from
raise RuntimeError("Compute version parsing error: " + str(err)) |
def LinearSearch(array, value):
"""
Function to implement linear search where each
element of array is consecutively checked to
find the key element
"""
# Traversing through each element of the array
for i in range(len(array)):
# Comparing current array element with the
# element to be searched
if array[i] == value:
return True
return False |
def isint(o):
"""Determine if object is int-like (is convertible using `int()`)."""
try:
int(o)
return True
except ValueError:
return False |
def get_vector(value):
"""Convert an integer into a byte-vector string."""
if value == 0: return ''
vector = []
sign = 1
if value < 1:
sign = -1
value *= -1
while value:
vector.insert(0, value % 256)
value //= 256
if vector[0] & 0x80:
vector.insert(0, 0)
if sign == -1:
vector[0] |= 0x80
return "".join(chr(c) for c in vector) |
def cross_product(a, b):
""" Return the angles in (x, y, z) between two vectors, a & b. """
a1, a2, a3 = a
b1, b2, b3 = b
return (a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1) |
def expsum(x, coefficient, powers):
"""
:param x: Input variable
:param coefficient: List of coefficients [ a0, a1, a2, a3, a4, ... an]
:param powers: List of expoents [ c0, c1, c2, c3, c4, ... cn]
:return: a0.x^c0 + a1.x^c1 + a2.x^c2 + a3.x^c3 + ...
"""
S = 0
for c, p in zip(coefficient, powers):
S += c * x ** p
return S |
def get_min_maf(mafStr):
"""Choose minimum MAF from MAF scores concatenated by :"""
maf_min = 1.0
for maf in mafStr.split(':'):
if float(maf)<maf_min:
maf_min =float(maf)
return maf_min |
def transform(record):
"""
Transforms (maps) a record.
Parameters
----------
record : dict
The record to transform.
Returns
-------
dict
The transformed record.
"""
return {
record["stakeholder_approach"]: {
record["stakeholder_id"]: {
"name": record["stakeholder_name"],
record["deliverable_id"]: {
"name": record["deliverable_name"]
}
}
}
} |
def cigar_to_lens(cigar):
"""Extract lengths from a CIGAR string.
Parameters
----------
cigar : str
CIGAR string.
Returns
-------
int
Alignment length.
int
Offset in subject sequence.
"""
align, offset = 0, 0
n = '' # current step size
for c in cigar:
if c in 'MDIHNPSX=':
if c in 'M=X':
align += int(n)
elif c in 'DN':
offset += int(n)
n = ''
else:
n += c
return align, align + offset |
def transform_groups(response_objects):
""" Strips list of API response objects to return list of group objects only
:param response_objects:
:return: list of dictionary objects as defined in /docs/schema/gsuite.md
"""
groups = []
for response_object in response_objects:
for group in response_object['groups']:
groups.append(group)
return groups |
def get_cycle_length(n):
"""
takes an integer 0 < n < 10000
returns the number of steps it
will take to get to 1
by performing n // 2 if n is even
and n * 3 + 1 if n is odd
"""
steps = 1
while ( n != 1 ):
if n % 2 == 0:
n = n / 2
steps = steps + 1
else:
n = n * 3 + 1
steps = steps + 1
return steps |
def raoult_liquido(fraccion_vapor, presion_vapor, presion):
"""Calcula la fraccion molar de liquido mediante la ec de Raoult"""
return fraccion_vapor * presion / presion_vapor |
def is_markdown(view):
"""Determine if the given view location is Markdown."""
if view is None:
return False
else:
try:
location = view.sel()[0].begin()
except IndexError:
return False
pass
pass
matcher = 'text.html.markdown'
return view.match_selector(location, matcher)
pass |
def bad_argument(*args: tuple, **kwargs: dict) -> dict:
"""
Bad Option exception response
:return: OpenC2 response message - dict
"""
return dict(
status=501,
status_text="Option not supported"
) |
def stem(word):
""" Stem word to primitive form
This example taken from toolz: https://github.com/pytoolz/toolz
There are several different ways to split a string, stem the words,
and calculate their frequency.
"""
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"") |
def bed_complete(pack_idx, x_max):
"""Check to see if bed is complete based on model params."""
# similarly, if np.count_nonzero(bed_space) == x_max
if pack_idx >= x_max:
return 1
else: return 0 |
def _mat_mat_dot_fp(x, y):
"""Matrix (list of lists) times matrix (list of lists)."""
zip_y = list(zip(*y))
return [[sum(a * b for a, b in zip(row_x, col_y))
for col_y in zip_y] for row_x in x] |
def hello(friend_name):
"""
Return a string
- param[0] = a String. Ignore for now.
- @return = a String containing a message
"""
if not isinstance(friend_name, str):
return "Try again"
response = "Hello, " + friend_name + "!"
return response |
def partition(condition, iterable, output_class=tuple):
"""
split an iterable into two according to a function evaluating to either
true or false on each element
:param condition: boolean function
:param iterable: iterable to split
:param output_class: type of the returned iterables
:return: two iterables
"""
true = []
false = []
for i in iterable:
if condition(i):
true.append(i)
else:
false.append(i)
return output_class(true), output_class(false) |
def status_sorter(a):
"""
Helper function to sort string elements, which can be None, too.
:param a: element, which gets sorted
:return:
"""
if not a["status"]:
return ""
return a["status"] |
def removecomment(astr, cphrase):
"""
the comment is similar to that in python.
any charachter after the # is treated as a comment
until the end of the line
astr is the string to be de-commented
cphrase is the comment phrase"""
# linesep = mylib3.getlinesep(astr)
alist = astr.splitlines()
for i in range(len(alist)):
alist1 = alist[i].split(cphrase)
alist[i] = alist1[0]
# return string.join(alist, linesep)
return "\n".join(alist) |
def parse_keyids(key):
"""Return parsed keyid string(s) or tuple of."""
if isinstance(key, str):
return key
elif isinstance(key, (tuple, list)):
return tuple(parse_keyids(keyid) for keyid in key)
return getattr(key, "keyid") |
def is_sublist(list_, sublist):
"""A sublist is part of a given list"""
return any(list_[i:i+len(sublist)] == sublist
for i in range(len(list_)-len(sublist)+1)) |
def split_task_parameters(line):
""" Split a string of comma separated words."""
if line is None:
result = []
else:
result = [parameter.strip() for parameter in line.split(",")]
return result |
def _convert_to_metrics_list(metrics):
"""Convert a dict of metrics names and weights as keys and values, into a list
of dicts with the two keys "name" and "weight" as keys and the metrics name and
metric weight as their corresponding values.
Examples:
metrics {"name1": 1.0, "name2": 2.0} results in the output
[{"name": "name1", "weight": 1.0}, {"name": "name2", "weight": 2.0}]
Args:
metrics (dict[str, float]): metrics to convert
Returns:
list[dict[str, object]]: list of dicts with the two keys "name" and "weight" as
keys and the metrics name and metric weight as their corresponding values.
"""
metrics_list = []
for metric_name, metric_weight in metrics.items():
metrics_list.append({"name": metric_name, "weight": metric_weight})
return metrics_list |
def iana_interface_type(
num # type: int
):
"""Parse IANA-defined interface types"""
if num == 1:
return "Other"
elif num == 2:
return "BBN 1822"
elif num == 3:
return "HDH 1822"
elif num == 4:
return "DDN X.25"
elif num == 5:
return "RFC-877 X.25"
# For all Ethernet-like CSMA-CD interfaces per IANA
elif num == 6:
return "Ethernet"
# Deprecated, should use 6 per IANA
elif num == 7:
return "Ethernet"
elif num == 8:
return "Token Bus"
elif num == 9:
return "Token Ring"
elif num == 10:
return "ISO88026Man"
elif num == 11:
return "Star LAN"
elif num == 12:
return "Proteon 10Mbit"
elif num == 13:
return "Proteon 80Mbit"
elif num == 14:
return "Hyperchannel"
elif num == 15:
return "FDDI"
elif num == 16:
return "LAPB"
elif num == 17:
return "SDLC"
elif num == 18:
return "DS1"
elif num == 19:
return "E1"
elif num == 20:
return "Basic ISDN"
elif num == 21:
return "Primary ISDN"
elif num == 22:
return "Prop Point To Point Serial"
elif num == 23:
return "PPP"
elif num == 24:
return "Software Loopback"
elif num == 25:
return "EON"
elif num == 26:
return "Ethernet 3Mbit"
elif num == 27:
return "NSIP"
elif num == 28:
return "SLIP"
elif num == 29:
return "Ultra"
elif num == 30:
return "DS3"
elif num == 31:
return "SIP"
elif num == 32:
return "Frame Relay"
elif num == 33:
return "RS232"
elif num == 34:
return "PARA"
elif num == 35:
return "ARCNet"
elif num == 36:
return "ARCNet Plus"
elif num == 37:
return "ATM"
elif num == 38:
return "MIOX25"
elif num == 39:
return "SONET"
else:
return "Other" |
def _parse_ctab_atom_block(contents):
"""
"""
atom_block = []
for row in contents:
atom_block.append(row.rstrip('\n'))
return atom_block |
def non_english_lang(lp):
"""Returns the non-English language from the supplied language pair.
Args:
lp: a string representing a language pair, e.g. "en-te"
Returns:
A string representing the non-English language in the language-pair, e.g.
"te".
Raises:
ValueError if `lp` does not have two parts separated by a dash or if one of
the languages is not 'en'.
"""
if len(lp.split("-")) != 2:
raise ValueError("ERROR: Purported language pair '{}' does not have exactly"
"two parts separated by a dash (like 'en-ml').".format(lp))
src, tgt = lp.split("-")
if src != "en":
return src
elif tgt != "en":
return tgt
raise ValueError("ERROR: Neither code in purported language pair '{}'"
"is 'en'.".format(lp)) |
def get_int_from_string(string):
"""
Turn a string into integers.
"""
conv = []
maxpool = []
for k,v in string.items():
if k == 'conv':
for i in v:
String = i.split('(')
String = String[1][:-1]
String = String.split(',')
Str = [int(i) for i in String]
conv.append(Str)
elif k == 'maxpool':
for i in v:
String = i.split('(')
String = String[1][:-1]
String = String.split(',')
Str = [int(i) for i in String]
maxpool.append(Str)
return conv, maxpool |
def transform_chw(transform, lst):
"""Convert each array in lst from CHW to HWC"""
return transform([x.transpose((1, 2, 0)) for x in lst]) |
def array_diff(a, b):
"""."""
return [x for x in a if x not in b] |
def maybe_snowflake(value):
"""
Converts the given `value` to `snowflake` if applicable. If not returns `None`.
Parameters
----------
value : `str`, `int` or `Any`
A value what might be snowflake.
Returns
-------
value : `int` or `None`
Raises
------
AssertionError
- If `value` was passed as `str` and cannot be converted to `int`.
- If the `value` is negative or it's bit length is over 64.
"""
if isinstance(value, int):
pass
elif isinstance(value, str):
if value.isdigit():
if __debug__:
if not 6 < len(value) < 21:
raise AssertionError('An `id` was given as `str` instance, but it\'s value is out of 64uint '
f'range, got {value!r}.')
value = int(value)
else:
return None
else:
return None
if __debug__:
if value < 0 or value > ((1<<64)-1):
raise AssertionError('An `id` was given as `str` instance, but it\'s value is out of 64uint range, got '
f'{value!r}.')
return value |
def islands(array):
"""
Identify islands In a given array, identify groups ("islands") of identical elements. A group must consist of 2 or more contiguous identical elements.
Given: An array like: "proogrrrammminggg"
Output: o, r, m, g
Challenge output: o:2, r:5, m:9, g:14 (positions of first occurrences of these letters)
Bonus Do this for a 2d array.
"""
prev = None
in_island = False
output = {}
for i, a in enumerate(array):
if a == prev:
if not in_island:
output[a] = i-1
in_island = True
else:
in_island = False
prev = a
return output |
def parse_file_list(data):
"""
Parse the file list contained in the torrent dict from the Gazelle API.
:param: data The string to parse
:return: A dict. The keys are the relative paths of the files and the
values are the size of the file in bytes.
"""
files = {}
for x in data.split("|||"):
name, size = x.split("{{{")
size = int(size[:-3])
files[name] = size
return files |
def list_operations(list1, list2):
"""Sa se scrie o functie care primeste ca parametri doua liste a si b.
Returneaza un tuplu de seturi care sa contina: (a intersectat cu b, a reunit cu b, a - b, b - a).
Se foloseste de operatiile pe seturi.
"""
l1set = set(list1)
l2set = set(list2)
aminusb = l1set - l2set
bminusa = l2set - l1set
reunion = l1set | l2set
intersect = l1set & l2set
return intersect, reunion, aminusb, bminusa |
def unzip_files(zip_filename_list):
"""
Unzipping the datasets
parameters
----------
zip_filename_list : the list of file names to unzip under the data folder
"""
from zipfile import ZipFile
import os
folder_names = []
for file in zip_filename_list:
# paths
filename_path = os.path.join('data', file)
folder_name = filename_path[:-4].replace("-", "_")
# extracting
try:
zip_ref = ZipFile(filename_path)
zip_ref.extractall('data')
zip_ref.close()
except:
print(f'{file} already extracted!')
return os.listdir('data') |
def joinPath(parentPath, name):
"""
Join a *canonical* `parentPath` with a *non-empty* `name`.
>>> joinPath('/', 'foo')
'/foo'
>>> joinPath('/foo', 'bar')
'/foo/bar'
>>> joinPath('/foo', '/foo2/bar')
'/foo/foo2/bar'
>>> joinPath('/foo', '/')
'/foo'
"""
if name.startswith('./'): # Support relative paths (mainly for links)
name = name[2:]
if parentPath == '/' and name.startswith('/'):
pstr = '%s' % name
elif parentPath == '/' or name.startswith('/'):
pstr = '%s%s' % (parentPath, name)
else:
pstr = '%s/%s' % (parentPath, name)
if pstr.endswith('/'):
pstr = pstr[:-1]
return pstr |
def stringToTupleOfFloats(s):
"""
Converts s to a tuple
@param s: string
@return: tuple represented by s
"""
ans = []
for i in s.strip("()").split(","):
if i.strip() != "":
if i == "null":
ans.append(None)
else:
ans.append(float(i))
return tuple(ans) |
def post_args_from_form(form):
"""
Take a table of form data or other sort of dictionary and turn it into a
regular 1D list to be passed as args
"""
res = list()
for item in form:
res.append(item)
res.append(form[item].value)
return res |
def factorial(n: int) -> int:
"""
Calculate the factorial of an integer greater than zero.
:param n: Must be an integer greater than zero.
:return: The integer value of N!
"""
if n < 0:
print("n must be a positive number. {} is an invalid response.".format(n))
exit(code=1)
if n in (0, 1):
return 1
return factorial(n - 1) * n |
def get_desktop_data_path(language: str, word_type: str):
"""
Returns the path to the data json of the desktop app given a language and word type.
Parameters
----------
language : str
The language the path should be returned for.
word_type : str
The type of word that should be accessed in the path.
Retruns
-------
The path to the data json for the given language and word type.
"""
return f"/Scribe-Desktop/scribe/language_guis/{language}/data/{word_type}.json" |
def phylsowingdatecorrection(sowingDay=1,
latitude=0.0,
sDsa_sh=1,
rp=0.0,
sDws=1,
sDsa_nh=1,
p=120.0):
"""
PhylSowingDateCorrection Model
Author: Loic Manceau
Reference: Modeling development phase in the
Wheat Simulation Model SiriusQuality.
See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427
Institution: INRA Montpellier
Abstract: Correction of the Phyllochron Varietal parameter according to sowing date
"""
if (latitude < 0):
if (sowingDay > sDsa_sh):
fixPhyll = p * (1 - rp * min(sowingDay - sDsa_sh, sDws))
else: fixPhyll = p
else:
if (sowingDay < sDsa_nh):
fixPhyll = p * (1 - rp * min(sowingDay, sDws))
else: fixPhyll = p
return fixPhyll |
def _fortran_to_val(val):
"""
Transform a Fortran value to a Python one.
Args:
val (str): The value to translate.
Returns:
A Python representation.
"""
if val[0] == val[-1] == '"': # A string
return val[1:-1]
if val == ".true.":
return True
if val == ".false.":
return False
# Assume a number
try:
return int(val)
except ValueError:
pass
# Assume a float
val = val.replace("d", "e").replace("D", "e")
try:
return float(val)
except ValueError:
pass
raise TypeError("Unable to parse: " + val) |
def is_empty(items):
"""
Iterate over a list to check if its element contains values or not.
'' or None are regarded as non-values.
Args:
``items`` (list): A list of items.
Returns:
``bool``. Returns ``True`` if the list only contains empty
values, else returns ``False``.
"""
for item in items:
if item and item != '':
return False
return True |
def merge_intervals(data):
"""
data = [(10,20), (15,30), (100, 200)]
out = [(10,30), (100,200)]
"""
if len(data)==0:
return data
result = []
saved = list(data[0])
for st, en in sorted([sorted(t) for t in data]):
if st <= saved[1]:
saved[1] = max(saved[1], en)
else:
result.append((saved[0], saved[1]))
saved[0] = st
saved[1] = en
result.append(saved)
return result |
def utilization_threshold_abstract(f, limit, utilization):
""" The abstract utilization threshold algorithm.
:param f: A function to calculate the utilization threshold.
:type f: function
:param limit: The minimum allowed length of the utilization history.
:type limit: int
:param utilization: The utilization history to analize.
:type utilization: list(float)
:return: A decision of whether the host is overloaded.
:rtype: bool
"""
if (len(utilization) < limit):
return False
return f(utilization) <= utilization[-1] |
def name_contains(test_name, vals):
"""Determines if any string in vals is a substring of test_name.
Args:
test_name: (string) String to determine if contains substrings.
vals: (list of strings) List of substrings to test for.
Returns:
True if a substring in vals is in test_name, else False.
"""
return any(val in test_name for val in vals) |
def generate_options_for_mode(server=None, control_value=None, **kwargs):
"""
Define a list of tuples that will be returned to generate the field options
for the mode Action Input, depending on the value from monitoring_tool
passed in as the control_value argument.
each tuple follows this order: (value, label)
where value is the value of the choice, and label is the label that appears
in the field.
"""
if control_value == 'nagios':
return [('log', 'Log'), ('network', 'Network'), ('server', 'Server')]
elif control_value == 'zabbix':
return [('network', 'Network'), ('server', 'Server'),
('service', 'Service'), ('cloud', 'Cloud'),
('databases', 'Databases'), ('storage', 'Storage')
] |
def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right = len(nums) - 1
if left == right:
return pivot_index, nums[pivot_index]
while left <= right:
mid = (left + right) // 2
print(nums[mid])
if min_num > nums[mid]:
min_num = nums[mid]
pivot_index = mid
right = mid - 1
else:
left = mid + 1
return pivot_index, min_num |
def _replace_esc(s: str, chars: str) -> str:
"""replace the given escape sequences of `chars` with \\uffff"""
for c in chars:
if f'\\{c}' in s:
break
else:
return s
b = []
i = 0
length = len(s)
while i < length:
try:
sbi = s.index('\\', i)
except ValueError:
b.append(s[i:])
break
if sbi > i:
b.append(s[i:sbi])
b.append('\\')
i = sbi + 1
if i < length:
if s[i] in chars:
b.append('\uffff')
else:
b.append(s[i])
i += 1
return ''.join(b) |
def translate_name(name):
"""Translate feature name."""
return name.translate(str.maketrans('', '', " '")) |
def _count_dot_semicolumn(value):
"""Count the number of `.` and `:` in the given string."""
return sum([1 for c in value if c in [".", ":"]]) |
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n') |
def dashcase(var): # some-variable
"""
Dash case convention. Include '-' between each element.
:param var: Variable to transform
:type var: :py:class:`list`
:returns: **transformed**: (:py:class:`str`) - Transformed input in ``dash-case`` convention.
"""
return "-".join(var) |
def chunk(keywords, lines):
"""
Divide a file into chunks between
key words in the list
"""
chunks = dict()
chunk = []
# Create an empty dictionary using all the keywords
for keyword in keywords:
chunks[keyword] = []
# Populate dictionary with lists of chunks associated
# with the keywords in the list
for line in lines:
if line.strip():
token = line.split()[0]
if token in keywords:
chunk = [line]
chunks[token].append(chunk)
else:
chunk.append(line)
return chunks |
def correct_protein_residue_numbers(ligand_interaction_data, protein_first_residue_number):
"""
Correct the protein residue numbers in interaction data.
Parameters
----------
ligand_interaction_data : dict
One of sub-dicts (corresponding to a single ligand)
created by the function `calculate_interactions`.
protein_first_residue_number : int
The first residue number in the protein.
Returns
-------
dict
Corrects the residue numbers in-place
in the input dict and returns it.
"""
# loop through interaction data for each interaction type (i.e. dict values)
for certain_interactions_data in ligand_interaction_data.values():
# for each type, the interaction data is a list,
# and the actual data starts from the second element
for single_interaction_data in range(1, len(certain_interactions_data)):
# the data are stored in tuples, we have to convert them to a list first,
# in order to be able to change them.
list_from_tuple = list(
certain_interactions_data[single_interaction_data]
)
# add the protein's first residue number to them, and subtract 1,
# so that we get back the original residue numbers.
list_from_tuple[0] += protein_first_residue_number - 1
# convert back to tuple and overwrite in-place
certain_interactions_data[single_interaction_data] = tuple(
list_from_tuple
)
return ligand_interaction_data |
def print_leaf(counts):
"""A nicer way to print the predictions at a leaf."""
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = str(int(counts[lbl] / total * 100)) + "%"
return probs |
def remove_close_values_on_log_scale(values, tolerance=0.1):
"""
Params
------
values -- array-like of floats
tolerance (float) -- for a given x remove all y:
x - tolerance*x < y < x + tolerance*x
Example
-------
tolerance = 0.1
[1, 1.01, 15, 14, 1.11] -> [1, 15, 1.11]
"""
values = list(values)
for i, x in enumerate(values):
d = abs(tolerance * x)
remaining_values = values[i + 1:]
for y in remaining_values:
if abs(x - y) < d:
values.remove(y)
return values |
def _includes_base_class(iter_classes, base_class):
"""
Returns whether any class in iter_class is a subclass of the given base_class.
"""
return any(
issubclass(current_class, base_class) for current_class in iter_classes
) |
def freq_label_to_human_readable_label(freq_label: str) -> str:
"""Translate pandas frequency labels to human-readable labels."""
f2h_map = {
"5T": "5 minutes",
"15T": "15 minutes",
"1h": "1 hour",
"24h": "1 day",
"168h": "1 week",
}
return f2h_map.get(freq_label, freq_label) |
def _is_code_chunk(chunk_lang):
"""determine from ```<chunk_lang>... if the chunk is executable code
or documentation code (markdown) """
return chunk_lang.startswith('{') and chunk_lang.endswith('}') |
def siwsi(b8a, b11):
"""
Shortwave Infrared Water Stress Index \
(Fensholt and Sandholt, 2003).
.. math:: SIWSI = (b8a - b11)/(b8a + b11)
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:returns SIWSI: Index value
.. Tip::
Fensholt, R., Sandholt, I. 2003. Derivation of a shortwave \
infrared water stress index from MODIS near- and shortwave \
infrared data in a semiarid environment. Remote Sensing of \
Environment 87, 111-121. doi:10.1016/j.rse.2003.07.002.
"""
SIWSI = (b8a - b11)/(b8a + b11)
return SIWSI |
def find_next_empty(puzzle):
""" Return row, col tuple (or None, None) if there is no empty square"""
for r in range(9):
for c in range(9):
if puzzle[r][c] == 0:
return r,c
return None, None |
def add_namespace_to_cmd(cmd, namespace=None):
"""Add an optional namespace to the command."""
return ['ip', 'netns', 'exec', namespace] + cmd if namespace else cmd |
def add_backslash(url: str) -> str:
"""
:param url: url
:return: add backslash to url
:rtype: str
"""
return url if "/" in url[-1] else f"{url}/" |
def getColor(cnvtype=None):
"""Return the shade of the item according to it's variant type."""
if cnvtype == "copy_number_variation":
return "128,128,128"
elif cnvtype == "deletion":
return "255,0,0"
elif cnvtype == "delins":
return "255,0,0"
elif cnvtype == "insertion":
return "0,0,255"
else:
return "0,0,0" |
def _check_int_input(var, input_name: str) -> int:
"""
_check_int_input
Convenience function to check if an input is an int (or a float coercable into an int without
rounding). If the input is not of the expected types it will raise a helpful value error.
Parameters
----------
var
the input variable to check
input_name : str
the name of the variable to include if an error is raised
Returns
-------
int
the input variable coerced into an int
"""
if not isinstance(var, int) and (
not isinstance(var, float) or not var.is_integer()):
raise ValueError("Input {} must be an integer.".format(input_name))
return int(var) |
def arclength( lat1, lon1, lat2, lon2, radius=None ):
"""Arc-length distance in km
Assumes angles in degrees ( not radians ).
Todd Mitchell, April 2019"""
if radius is None:
radius = 6.37e3 # in km
import numpy as np
meanlat = np.mean( ( lat1, lat2 ) )
rcosine = radius * np.cos( np.deg2rad( meanlat ) )
a = rcosine * ( lon2 - lon1 ) / 360 * 2 * np.pi
b = radius * ( lat2 - lat1 ) / 360 * 2 * np.pi
return np.sqrt( a * a + b * b ) |
def phred_to_prob(q):
"""Convert a phred score (Sanger or modern Illumina) in probabilty
Given a phred score q, return the probabilty p
of the call being right
Args:
q (int): phred score
Returns:
float: probabilty of basecall being right
"""
p = 10 ** (-q / 10)
return 1 - p |
def parse_copy_startup_config_running_config(raw_result):
"""
Parse the 'copy startup-config running-config' command raw output.
:param str raw_result: copy startup-config running-config
raw result string.
:rtype: dict
:return: The parsed result of the copy startup-config running-config:
::
{
'status': 'success'
'reason': 'Copied startup-config to running-config'
}
"""
if (
"Copy in progress " in raw_result and
"Success" in raw_result
):
return {
"status": "success",
"reason": "Copied startup-config to running-config"
}
if (
"Copy in progress " in raw_result and
"ERROR: Copy failed" in raw_result
):
return {
"status": "failed",
"reason": "Copy startup-config to running-config failed"
} |
def get_kwargs(names, defaults, kwargs):
"""Return wanted parameters, check remaining.
1. Extracts parameters `names` from `kwargs`, filling them with the
`defaults`-value if it is not in `kwargs`.
2. Check remaining kwargs;
- Raise an error if it is an unknown keyword;
- Print warning if it is a keyword from another routine (verb>0).
List of possible kwargs:
- ALL functions: src, rec, res, aniso, epermH, epermV, mpermH, mpermV, verb
- ONLY gpr: cf, gain
- ONLY bipole: msrc, srcpts
- ONLY dipole_k: freq, wavenumber
- ONLY analytical: solution
- ONLY bipole, loop: mrec, recpts, strength
- ONLY bipole, dipole, loop, gpr: ht, htarg, ft, ftarg, xdirect, loop
- ONLY bipole, dipole, loop, analytical: signal
- ONLY dipole, analytical, gpr, dipole_k: ab
- ONLY bipole, dipole, loop, gpr, dipole_k: depth
- ONLY bipole, dipole, loop, analytical, gpr: freqtime
Parameters
----------
names: list
Names of wanted parameters as strings.
defaults: list
Default values of wanted parameters, in same order.
kwargs : dict
Passed-through kwargs.
Returns
------
values : list
Wanted parameters.
"""
# Known keys (excludes keys present in ALL routines).
known_keys = set([
'depth', 'ht', 'htarg', 'ft', 'ftarg', 'xdirect', 'loop', 'signal',
'ab', 'freqtime', 'freq', 'wavenumber', 'solution', 'cf', 'gain',
'msrc', 'srcpts', 'mrec', 'recpts', 'strength'
])
# Loop over wanted parameters.
out = list()
verb = 2 # get_kwargs-internal default.
for i, name in enumerate(names):
# Catch verb for warnings later on.
if name == 'verb':
verb = kwargs.get(name, defaults[i])
# Add this parameter to the list.
out.append(kwargs.pop(name, defaults[i]))
# Check remaining parameters.
if kwargs:
if not set(kwargs.keys()).issubset(known_keys):
raise TypeError(f"Unexpected **kwargs: {kwargs}.")
elif verb > 0:
print(f"* WARNING :: Unused **kwargs: {kwargs}.")
return out |
def get_data_from_dict(source_dict, keys):
""" Get dict with keys witch specify and with values from specified dict by that keys from source_dict
:param source_dict: dictionary
:param keys: keys for creation new dict, that keys should be exists in a source_dict
:return: dict with keys witch specify and with values from specified dict by that keys from source_dict
"""
return {key: source_dict[key] for key in keys} |
def get(attribute_name, json_response, default=None):
"""
Retrieve attribute from a JSON response.
:param attribute_name: Attribute name to get.
:param json_response: JSON response.
:param default: Value to return if the attribute is not found.
:return: Attribute value.
"""
return default if attribute_name not in json_response else json_response[attribute_name] |
def element_to_list(element):
"""Converts an element to a list of True blocks"""
return [True] * element |
def filter_with_prefixes(value, prefixes):
"""
Returns true if at least one of the prefixes exists in the value.
Arguments:
value -- string to validate
prefixes -- list of string prefixes to validate at the beginning of the value
"""
for prefix in prefixes:
if value.startswith(prefix):
return False
return True |
def cDekel(c2, alpha):
"""
Compute the Dekel+ concentration, c, using the conventional
concentration, c_-2, and the Dekel+ innermost slope, alpha.
Syntax:
cDekel(c2,alpha)
where
c2: concentration, c_-2 = R_vir / r_-2 (float or array)
alpha: Dekel+ innermost slope (float or array of the same size
as c2)
Return:
Dekel+ concentration (float or array of the same size as c2)
"""
return (2.0 - alpha) ** 2 / 2.25 * c2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.