content
stringlengths 42
6.51k
|
|---|
def reflect(point0, point1):
"""Reflects off-curve control point in relation to on-curve one. Used for
smooth curves."""
px = point1[0] + (point1[0] - point0[0])
py = point1[1] + (point1[1] - point0[1])
return (px, py)
|
def get_reorientations(in_orient, out_orient):
"""Generates a list of axes flips and swaps to convert from in_orient to out_orient
Args:
in_orient (str): 3-letter input orientation
out_orient (str): 3-letter output orientation
Raises:
Exception: Exception raised if in_orient or out_orient not valid
Returns:
tuple of lists: New axis order and whether or not each axis needs to be flipped
"""
dimension = len(in_orient)
in_orient = str(in_orient).lower()
out_orient = str(out_orient).lower()
inDirection = ""
outDirection = ""
orientToDirection = {"r": "r", "l": "r", "s": "s", "i": "s", "a": "a", "p": "a"}
for i in range(dimension):
try:
inDirection += orientToDirection[in_orient[i]]
except BaseException:
raise Exception("in_orient '{0}' is invalid.".format(in_orient))
try:
outDirection += orientToDirection[out_orient[i]]
except BaseException:
raise Exception("out_orient '{0}' is invalid.".format(out_orient))
if len(set(inDirection)) != dimension:
raise Exception("in_orient '{0}' is invalid.".format(in_orient))
if len(set(outDirection)) != dimension:
raise Exception("out_orient '{0}' is invalid.".format(out_orient))
order = []
flip = []
for i in range(dimension):
j = inDirection.find(outDirection[i])
order += [j]
flip += [-1 if in_orient[j] != out_orient[i] else 1]
return order, flip
|
def format_sys_time(seconds):
"""
Convert total seconds to fromatted HH:MM:SS string
"""
s = seconds % 60
m = (seconds // 60) % 60
h = (seconds // 3600) % 3600
return "{:02d}:{:02d}:{:02d}".format(h, m, s)
|
def iio_uri(_iio_emu_func):
"""URI fixture which provides a string of the target uri of the
found board filtered by iio_hardware marker. If no hardware matching
the required hardware is found, the test is skipped. If no iio_hardware
marker is applied, first context uri is returned. If list of hardware
markers are provided, the first matching is returned.
"""
if isinstance(_iio_emu_func, dict):
return _iio_emu_func["uri"]
else:
return False
|
def tobytes(value):
"""Convert value to bytes."""
if isinstance(value, bytes):
return value
else:
if isinstance(value, str):
return value.encode()
else:
return bytes(value)
|
def comp_binary_same(term, number):
"""
:param term:
:param number:
:return:
"""
for i in range(len(term)):
if term[i] != '-':
if term[i] != number[i]:
return False
return True
|
def compile_str_from_parsed(parsed):
"""The (quasi-)inverse of string.Formatter.parse.
Args:
parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples,
as yield by string.Formatter.parse
Returns:
A format string that would produce such a parsed input.
>>> from string import Formatter
>>> s = "ROOT/{}/{0!r}/{1!i:format}/hello{:0.02f}TAIL"
>>> assert compile_str_from_parsed(Formatter().parse(s)) == s
>>>
>>> # Or, if you want to see more details...
>>> parsed = list(Formatter().parse(s))
>>> for p in parsed:
... print(p)
('ROOT/', '', '', None)
('/', '0', '', 'r')
('/', '1', 'format', 'i')
('/hello', '', '0.02f', None)
('TAIL', None, None, None)
>>> compile_str_from_parsed(parsed)
'ROOT/{}/{0!r}/{1!i:format}/hello{:0.02f}TAIL'
"""
result = ''
for literal_text, field_name, format_spec, conversion in parsed:
# output the literal text
if literal_text:
result += literal_text
# if there's a field, output it
if field_name is not None:
result += '{'
if field_name != '':
result += field_name
if conversion:
result += '!' + conversion
if format_spec:
result += ':' + format_spec
result += '}'
return result
|
def splitQuery(text):
"""Function that process message and returns query and database"""
maintext = text.replace('\xa0', ' ').split(" ", 1)[1].split("\n", 1)
query = maintext[1].replace("```", "").replace("\n", " ").strip()
db = maintext[0].strip()
return query, db
|
def divide(x, y):
"""
Question 5.6: Given two positive integers,
compute their quotient, using only the addition,
subtraction, and shifting operators
"""
result = 0
power = 32
y_power = y << power
while x >= y:
while y_power > x:
y_power >>= 1
power -= 1
result += 1 << power
x -= y_power
return result
|
def F2C(F):
"""Convert Fahrenheit to Celcius"""
return (F - 32) / 1.8
|
def stringfromtime(t, accuracy=4):
"""
:param t : Time in seconds
:returns : Formatted string
"""
m, s = divmod(t, 60)
h, m = divmod(m, 60)
d, h = divmod(h, 24)
components = []
if d > 0:
components.append(f"{int(d)} day" + ("s" if d > 1 else ""))
if h > 0:
components.append(f"{int(h)} hour" + ("s" if h > 1 else ""))
if m > 0:
components.append(f"{int(m)} minute" + ("s" if m > 1 else ""))
if s > 0:
components.append(f"{int(s)} second" + ("s" if s > 1 else ""))
return " ".join(components[:accuracy])
|
def hexStrToInt(inputstr):
"""
Converts a string with hex bytes to a numeric value
Arguments:
inputstr - A string representing the bytes to convert. Example : 41414141
Return:
the numeric value
"""
valtoreturn = 0
try:
valtoreturn = int(inputstr,16)
except:
valtoreturn = 0
return valtoreturn
|
def _fix_mimic_icd(icd):
""" Add the decimal to the correct location for the ICD code
From the mimic documentation (https://mimic.physionet.org/mimictables/diagnoses_icd/):
> The code field for the ICD-9-CM Principal and Other Diagnosis Codes
> is six characters in length, with the decimal point implied between
> the third and fourth digit for all diagnosis codes other than the V
> codes. The decimal is implied for V codes between the second and third
> digit.
"""
icd = str(icd)
if len(icd) == 3:
# then we just have the major chapter
icd = icd
else:
icd = [
icd[:3],
".",
icd[3:]
]
icd = "".join(icd)
return icd
|
def contains_term_from_list(name, terms):
"""
Iter check for term
:param name:
:param terms:
:return:
"""
for term in terms:
if name.__contains__(term):
return True
return False
|
def cc(col, ccol):
"""Color correction for pygame visualization.
"""
if ccol:
return (col[0]/2, col[1], col[2])
else:
return (col[2], col[1], col[0])
|
def split_apt(field):
"""
Parses the ADDRESS field (<site address>, <apt number> <municipality>) from the CLEMIS CFS Report
and returns the apartment number.
"""
if ',' in field:
f = field.split(', ')
f = f[1]
f = f.split(' ')
apt = f[0]
else:
apt = None
return apt
|
def number_keys(a_dictionary):
"""Return the number of keys in a dictionary."""
return (len(a_dictionary))
|
def byteify(element):
"""Converts unicode elements of dict or list into str.
# Source:
# http://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-ones-from-json-in-python
"""
if isinstance(element, dict):
return {byteify(key): byteify(value)
for key, value in element.items()}
elif isinstance(element, list):
return [byteify(element) for element in element]
elif isinstance(element, str):
return element.encode('utf-8')
else:
return element
|
def header_dict_from_list(array):
"""Given a list of strings in http header format, return a dict.
If array is None, return None"""
if array is None:
return array
header_dict = {}
for item in array:
(key, sep, value) = item.partition(':')
if sep and value:
header_dict[key.strip()] = value.strip()
return header_dict
|
def fortran_float(string: str) -> float:
"""Construct :class:`float` from Fortran style float strings.
This function can convert strings to floats in all of the formats below:
* ``3.14e10`` (also parsable with :class:`float`)
* ``3.14E10`` (also parsable with :class:`float`)
* ``3.14d10``
* ``3.14D10``
* ``3.14e+10`` (also parsable with :class:`float`)
* ``3.14E+10`` (also parsable with :class:`float`)
* ``3.14d+10``
* ``3.14D+10``
* ``3.14e-10`` (also parsable with :class:`float`)
* ``3.14E-10`` (also parsable with :class:`float`)
* ``3.14d-10``
* ``3.14D-10``
* ``3.14+100``
* ``3.14-100``
.. note::
Because RADS was written in Fortran, exponent characters in
configuration and passindex files sometimes use 'D' or 'd' as
the exponent separator instead of 'E' or 'e'.
.. warning::
If you are Fortran developer stop using 'Ew.d' and 'Ew.dDe' formats
and use 'Ew.dEe' instead. The first two are not commonly supported
by other languages while the last version is the standard for nearly
all languages. Ok, rant over.
:param string:
String to attempt to convert to a float.
:return:
The float parsed from the given `string`.
:raises ValueError:
If `string` does not represent a valid float.
"""
try:
return float(string)
except ValueError as err:
try:
return float(string.replace("d", "e").replace("D", "E"))
except ValueError:
try:
return float(string.replace("+", "e+").replace("-", "e-"))
except ValueError:
raise err
|
def gates_to_coords(gates):
"""
This is a helper function for test_utils(). Given a set of gates, it
extracts the coordinates of the qubits that the gates were applied to
"""
# Get gates and extract the coordinates, this is a bit tricky
coords = []
[coords.append(g[1]) for g in gates if g[1] not in coords]
coords = [sorted((coords[2 * i], coords[2 * i + 1])) for i
in range(len(coords) // 2)]
coords = sorted((i, j) for (i, j) in coords)
return coords
|
def my_reduce_function(results):
"""sums up the number of words by totaling the number of appearances of each word.
@param results: dictionary that counts the appearances of each word within a url."""
final_result = 0
for count in results:
for word in count:
final_result += count[word]
return final_result
|
def transformation_normalizer(name: str) -> str:
"""Normalize the name of a transformation."""
return name.lower().replace('_', '').replace('transformation', '')
|
def _recipe_name(raw_configuration):
"""
Given a raw repository configuration, returns its recipe name.
:param raw_configuration: configuration as returned by the SCRIPT_NAME_GET
groovy script.
:type raw_configuration: dict
:return: name of the recipe ("format")
"""
name = raw_configuration['recipeName'].split('-')[0].title()
if name == 'Maven2':
name = 'Maven'
return name
|
def fancy_format(in_str, **kwargs):
"""
A format command for strings that already have lots of curly brackets (ha!)
:param in_str:
:param kwargs: the arguments to substitute
:return:
>>> fancy_format('{haha} {dan} {bob}', dan = 1, bob = 2)
'{haha} 1 2'
"""
new_str = in_str.replace('{', '{{').replace('}', '}}')
for key in kwargs.keys():
new_str = new_str.replace('{{%s}}' % key, '{%s}' % key)
return new_str.format(**kwargs)
|
def factorial(number: int) -> int:
"""
Calculating factorial of a number using
prime decomposition method
"""
prime: list = [True] * (number + 1)
result: int = 1
for i in range (2, number + 1):
if prime[i]:
j: int = 2 * i
while j <= number:
prime[j] = False
j += i
SUM: int = 0
num: int = i
while num <= number:
SUM += number // num
num *= i
result *= i ** SUM
return result
|
def sdnv_encode(value):
"""Returns the SDNV-encoded byte string representing value
Args:
value (int): Non-negative integer that should be encoded
Returns:
bytes: SDNV-encoded number
Raises:
ValueError: If value not an integer or negative
"""
if value < 0 or not isinstance(value, int):
raise ValueError("Only non-negative integers can be SDNV-encoded")
# Special case: zero whould produce an empty byte string
if value == 0:
return b"\x00"
result = bytearray()
while value != 0:
result.append((value & 0x7f) | 0x80)
value >>= 7
# Clear MSB in the first byte that was set by the XOR with 0x80
result[0] &= 0x7f
# Network byte order
return bytes(reversed(result))
|
def est_palindrome3(s : str) -> bool:
""" ... cf. ci-dessus ...
"""
i : int
for i in range(0,len(s)//2):
if s[i] != s[-i-1]:
return False
return True
|
def make_vector(inFN1, inFN2=None, jointFusion=False):
"""
This function...
:param inFN1:
:param inFN2:
:param jointFusion:
:return:
"""
# print("inFN1: {0}".format(inFN1))
# print("inFN2: {0}".format(inFN2))
if inFN2 == None:
returnVector = [inFN1]
else:
returnVector = [inFN1, inFN2]
if jointFusion:
returnVector = [returnVector]
print(("jointFusion: " + str(jointFusion)))
print(returnVector)
print("============================================")
return returnVector
|
def is_file_genpath(genpath):
"""
Determine whether the genpath is a file (e.g., '/stdout') or not (e.g., 'command')
:param genpath: a generalized path
:return: a boolean value indicating if the genpath is a file.
"""
return genpath.startswith('/')
|
def manhattan_distance(x, y):
""" Calculates the manhattan distance
:param x: x position
:param y: y position
:return: int
"""
return abs(x) + abs(y)
|
def win_text(total_tests, passing_tests=0):
"""
The text shown in the main window.
"""
return "%d/%d" % (passing_tests, total_tests)
|
def _ws_url(host, rpc_opts):
"""
Given a hostname and set of config options returned by _rpc_opts, return the
standard URL websocket endpoint for a Sideboard remote service.
"""
return '{protocol}://{host}/wsrpc'.format(host=host, protocol='wss' if rpc_opts['ca'] else 'ws')
|
def required_padding(address, alignment):
""" Return how many padding bytes are needed to align address """
rest = address % alignment
if rest:
# We need padding bytes:
return alignment - rest
return 0
|
def relEqual(x, y, tol=2 ** -26):
"""
Simple test for relative equality of floating point within tolerance
Default tolerance is sqrt double epsilon i.e. about 7.5 significant figures
"""
if y == 0:
return x == 0
return abs(float(x) / float(y) - 1.) < tol
|
def electrolyte_TDF_base_Landesfeind2019(c_e, T, coeffs):
"""
Thermodynamic factor (TDF) of LiPF6 in solvent_X as a function of ion concentration
and temperature. The data comes from [1].
References
----------
.. [1] Landesfeind, J. and Gasteiger, H.A., 2019. Temperature and Concentration
Dependence of the Ionic Transport Properties of Lithium-Ion Battery Electrolytes.
Journal of The Electrochemical Society, 166(14), pp.A3079-A3097.
Parameters
----------
c_e: :class:`pybamm.Symbol`
Dimensional electrolyte concentration
T: :class:`pybamm.Symbol`
Dimensional temperature
coeffs: :class:`pybamm.Symbol`
Fitting parameter coefficients
Returns
-------
:class:`pybamm.Symbol`
Electrolyte thermodynamic factor
"""
c = c_e / 1000 # mol.m-3 -> mol.l
p1, p2, p3, p4, p5, p6, p7, p8, p9 = coeffs
tdf = (
p1
+ p2 * c
+ p3 * T
+ p4 * c ** 2
+ p5 * c * T
+ p6 * T ** 2
+ p7 * c ** 3
+ p8 * c ** 2 * T
+ p9 * c * T ** 2
)
return tdf
|
def get_variables(models):
"""get variables of all models
Args:
models: dict containing all the models available
Returns:
variables: variables of all models
"""
variables = []
for model in models.keys():
variables += models[model].variables
return variables
|
def named_capturing(pattern, name):
""" generate a named capturing pattern
:param pattern: an `re` pattern
:type pattern: str
:param name: a name for the capture
:type name: str
:rtype: str
"""
return r'(?P<{:s}>{:s})'.format(name, pattern)
|
def primes(n):
""" Returns a list of primes < n """
sieve = [True] * n
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i]:
sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, n, 2) if sieve[i]]
|
def find_blank_position(grid, blank):
"""Returns the number of row, from bottom, that contains the blank value."""
for i, row in enumerate(grid[::-1]):
if blank in row:
return i + 1
|
def run_and_read_all(run_lambda, command):
"""Runs command using run_lambda; reads and returns entire output if rc is 0"""
rc, out, _ = run_lambda(command)
if rc is not 0:
return None
return out
|
def iscomplex(pscale):
""" Returns whether pscale is an instance of a complex number """
return isinstance(pscale, complex)
|
def _Cond(test, if_true, if_false):
"""Substitute for 'if_true if test else if_false' in Python 2.4."""
if test:
return if_true
else:
return if_false
|
def _get_1st_obj(ll):
"""given a list [of list ...] of something
get the first non-list object
"""
if type(ll) is not list:
return ll
return _get_1st_obj(ll[0])
|
def query_finder(line):
"""Split record on rows that start with query label."""
return line.startswith("# Query:")
|
def get_dataset_by_code(activity_code, data):
"""get the dataset specified by an activity id from a database"""
dataset = [i for i in data if i['code'] == activity_code][0]
return dataset
|
def round_scores(student_scores):
"""
:param student_scores: list of student exam scores as float or int.
:return: list of student scores *rounded* to nearest integer value.
"""
return [round(score) for score in student_scores]
|
def axisheader2dic(header):
"""
Convert axisheader list into dictionary
"""
dic = dict()
dic["nucleus"] = str(header[0]).strip('\x00')
dic["spectral_shift"] = header[1]
dic["npoints"] = header[2]
dic["size"] = header[3]
dic["bsize"] = header[4]
dic["spectrometer_freq"] = header[5]
dic["spectral_width"] = header[6]
dic["xmtr_freq"] = header[7]
dic["zero_order"] = header[8]
dic["first_order"] = header[9]
dic["first_pt_scale"] = header[10]
dic["extended"] = header[11]
return dic
|
def frequency(text, char):
""" Counts frequency of a character in a string. """
count = 0
for c in text:
if c == char:
count += 1
return count
|
def classes(*names, convert_underscores=True, **names_and_bools):
"""Join multiple class names with spaces between them.
Example
-------
>>> classes("foo", "bar", baz=False, boz=True, long_name=True)
"foo bar boz long-name"
Or, if you want to keep the underscores:
>>> classes("foo", "bar", long_name=True, convert_underscores=False)
"foo bar long_name"
"""
if convert_underscores:
def clean(name):
return name.replace("_", "-")
else:
def clean(name):
return name
classes = [clean(name) for name in names]
for name, include in names_and_bools.items():
if include:
classes.append(clean(name))
return " ".join(classes)
|
def extended_gcd(a, b):
"""
Return r, s, t such that gcd(a, b) = r = a * s + b * t
"""
r0, r1 = a, b
s0, s1, t0, t1 = 1, 0, 0, 1
if r0 > r1:
r0, r1, s0, s1, t0, t1 = r1, r0, t0, t1, s0, s1
while r1 > 0:
q, r = divmod(r0, r1)
r0, r1, s0, s1, t0, t1 = r1, r, s1, s0 - q * s1, t1, t0 - q * t1
return r0, s0, t0
|
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
|
def byte_list_to_u32le_list(data, pad=0x00):
"""! @brief Convert a list of bytes to a list of 32-bit integers (little endian)
If the length of the data list is not a multiple of 4, then the pad value is used
for the additional required bytes.
"""
res = []
for i in range(len(data) // 4):
res.append(data[i * 4 + 0] |
data[i * 4 + 1] << 8 |
data[i * 4 + 2] << 16 |
data[i * 4 + 3] << 24)
remainder = (len(data) % 4)
if remainder != 0:
padCount = 4 - remainder
res += byte_list_to_u32le_list(list(data[-remainder:]) + [pad] * padCount)
return res
|
def build_record_unique_id(doc):
"""Build record unique identifier."""
doc['unique_id'] = '{0}_{1}'.format(doc['pid_type'], doc['pid_value'])
return doc
|
def get_venv_command(venv_path: str, cmd: str) -> str:
"""Return the command string used to execute `cmd` in virtual env located at `venv_path`."""
return f"source {venv_path}/bin/activate && {cmd}"
|
def argmax(seq, fn):
"""Return an element with highest fn(seq[i]) score; tie goes to first one.
argmax(['one', 'to', 'three'], len)
'three'
return 0: used, 1: replace, 2: both
"""
if len(seq) == 1:
return seq[0]
best = -1
best_score = float("-inf")
for x in seq:
x_score = fn(x)
if x_score > best_score:
best, best_score = x, x_score
elif x_score == best_score:
best, best_score = 2, x_score
return best
|
def is_isogram4(string: str) -> bool:
"""
Another person's solution. So concise!
"""
return len(string) == len(set(string.lower()))
|
def get_cloudera_sample_cut(sample_lines_ratio=None):
"""Get cut int value for sample proportion."""
if sample_lines_ratio is None:
sample_lines_ratio = 1.0
# Generate the value for sample selection.
sampling_cut = int(2 ** 64 * sample_lines_ratio / 2.0) - 1
return sampling_cut
|
def first_int(*args, default=1):
"""Parse the first integer from an iterable of string arguments."""
for arg in args:
try:
return int(arg)
except ValueError:
continue
return default
|
def warmup_linear(x, warmup=0.002):
""" Specifies a triangular learning rate schedule where peak is reached at `warmup`*`t_total`-th (as provided to BertAdam) training step.
After `t_total`-th training step, learning rate is zero. """
if x < warmup:
return x / warmup
return max((x - 1.0) / (warmup - 1.0), 0)
|
def seperate_list(list, division_part):
"""
Dividing list into equal parts or partialy equal parts
Parameters
----------
list - list
division_part - number of part to divide list into
Returuns
--------
out - single list containing all the divided lists
"""
avg = len(list) / float(division_part)
out = []
last = 0.0
while last < len(list):
out.append(list[int(last):int(last + avg)])
last += avg
return out
|
def offbyK(s1,s2,k):
"""Input: two strings s1,s2, integer k
Process: if both strings are of same length, the function checks if the
number of dissimilar characters is less than or equal to k
Output: returns True when conditions are met otherwise False is returned"""
if len(s1)==len(s2):
flag=0
for i in range(len(s1)):
if s1[i]!=s2[i]:
flag=flag+1
if flag==k:
return True
else:
return False
else:
return False
|
def divceil(divident, divisor):
"""Integer division with rounding up"""
quot, r = divmod(divident, divisor)
return quot + int(bool(r))
|
def get_adopters_for_advertisement(adoption_center, list_of_adopters, n):
"""
:param adoption_center: A single AdoptionCenter instance
:param list_of_adopters: A list of Adopter (or a subclass of Adopter) instances.
:param n: The number of adopters, up to a maximum of n, who will be sent advertisements.
:return: a list of length up to n that represents the highest scoring Adopters/Adopter Subclasses
for the specific AdoptionCenter (You want to find the top n best Adopter matches).
"""
ranking = [(ad, ad.get_score(adoption_center)) for ad in list_of_adopters]
# Sort by score first, in case of duplicates - sort by adopters's name
ranking = sorted(ranking, key=lambda x: x[0].get_name()) # sort by name
ranking = sorted(ranking, key=lambda x: x[1], reverse=True) #sort by score
return [x[0] for x in ranking[0:n]]
|
def csv_name(str_name):
"""Add extension for file.
return:
String: File name with the extension .csv
"""
return f'{str_name}.csv'
|
def _is_instance(type_to_check, element, condition="any", deep=False):
"""
-----
Brief
-----
Function that verifies when "all" or "any" elements of the list "element" have the type
specified in "type_to_check" input.
-----------
Description
-----------
In some biosignalsnotebooks functions their implementation is extremely dependent on a specific
criterion, i.e., 'all' list entries should be of a specific data type.
In order to ensure this functionality _is_instance function was implemented.
For example, when plotting data through 'plot' function of 'visualise' module, 'all' entries
of time axis and data samples lists need to be 'Numeric'.
In order to this condition be checked _is_instance should be called with the following input
values:
_is_instance(Number, [1, 2, 3, True, ...], 'all')
Sometimes is also relevant to check if at least one of list entries belongs to a data type, for
cases like this, the argument "condition" should have value equal to "any".
--------
Examples
--------
>>> _is_instance(Number, [1, 2, 3, True], 'all')
False
>>> _is_instance(Number, [1, 1.2, 3, 5], 'all')
True
----------
Parameters
----------
type_to_check : type element
Data type (all or any elements of 'element' list must be of the type specified in the
current input).
element : list
List where condition specified in "condition" will be checked.
condition : str
String with values "any" or "all" verifying when "any" or "all" element entries have the
specified type.
deep : bool
Flag that identifies when element is in a matrix format and each of its elements should be
verified iteratively.
Returns
-------
out : boolean
Returns True when the "condition" is verified for the entries of "element" list.
"""
out = None
# Direct check of "condition" in "element".
if deep is False:
if condition == "any":
out = any(isinstance(el, type_to_check) for el in element)
elif condition == "all":
out = all(isinstance(el, type_to_check) for el in element)
# Since "element" is in a matrix format, then it will be necessary to check each dimension.
else:
for row in range(0, len(element)):
for column in range(0, len(element[row])):
flag = _is_instance(type_to_check, element[column][row], "all", deep=False)
if flag is False:
out = flag
else:
out = True
return out
|
def is_installed(module):
"""Tests to see if ``module`` is available on the sys.path
>>> is_installed('sys')
True
>>> is_installed('hopefullythisisnotarealmodule')
False
"""
try:
__import__(module)
return True
except ImportError:
return False
|
def parse_output(out, line=None):
"""
Function will parse given output and if some line starts with 'line', if will be removed
Parameters
----------
out : bytes
output from subprocess.check_output
line : str
prefix which will be removed
"""
lines = out.decode().strip().splitlines()
if line:
for l in lines:
if l.startswith(line):
return l[len(line):].replace('"', '')
return lines[0].replace('"', '')
|
def site_read(context, data_dict):
"""\
This function should be deprecated. It is only here because we couldn't
get hold of Friedrich to ask what it was for.
./ckan/controllers/api.py
"""
# FIXME we need to remove this for now we allow site read
return {'success': True}
|
def assemble_clause_from_tokens(token_list):
"""
Assemble each string value from a list of tuples into a string, representing an individual clause in a cypher query
:param token_list: A list of tuples in the format (Token, value) which is returned by the py2neo cypher lexer
:return: string representing part of a cypher query
"""
reassembled = ''
for tup in token_list:
reassembled += tup[1]
return reassembled
|
def parameterized_config(template):
"""
https://github.com/apache/incubator-airflow/blob/master/airflow/configuration.py
https://github.com/apache/incubator-airflow/blob/master/LICENSE
Generates a configuration from the provided template + variables defined in
current scope
:param template: a config content templated with {{variables}}
"""
all_vars = {k: v for d in [globals(), locals()] for k, v in d.items()}
return template.format(**all_vars)
|
def _func_destroy_scheduler_session(sessionId, dask_scheduler):
"""
Remove session date from _raft_comm_state, associated with sessionId
Parameters
----------
sessionId : session Id to be destroyed.
dask_scheduler : dask_scheduler object
(Note: this is supplied by DASK, not the client)
"""
if sessionId is not None and sessionId in dask_scheduler._raft_comm_state:
del dask_scheduler._raft_comm_state[sessionId]
else:
return 1
return 0
|
def set_show_scroll_bottleneck_rects(show: bool) -> dict:
"""Requests that backend shows scroll bottleneck rects
Parameters
----------
show: bool
True for showing scroll bottleneck rects
"""
return {"method": "Overlay.setShowScrollBottleneckRects", "params": {"show": show}}
|
def find_target(LowerSeq, TargetLoc):
"""
Assigns TargetLoc
Priorities for assigning target:
1. first coded (NE in LowerSeq that does not have the same code as
SourceLoc; codes are not checked with either SourceLoc or the
candidate target are compounds (NEC
2. first null-coded (NE in LowerSeq ;
3. first coded (NE in UpperSeq -- that is, searching backwards from
the verb -- that does not have the same code as SourceLoc;
4. first null-coded (NE in UpperSeq
"""
# Look in the lower phrase after the verb
k = 0
for item in LowerSeq:
if item.startswith('(NEC'):
return [k, False]
if item.startswith('(NE') and not item.endswith('>---'):
return [k, False]
k += 1
k = 0
for item in LowerSeq:
if item.startswith('(NE'):
return [k, False]
k += 1
return TargetLoc
|
def _getSubtitleNumber(entry):
"""
Helper function that returns the subtitle number
of a TTI block.
Used to sort a list of TTI blocks by subtitle number.
"""
return entry['SN']
|
def connected_three(position: int, mask: int) -> bool:
"""
Return True, when the player has connected 3 and free space after/before them
Arguments:
position: bit representation of the board with players pieces
mask: bit representation of board with all pieces
Return:
bool: True for 3 connected
"""
opp_pos = mask ^ position
# Diagonal /
m = position & (position >> 8)
if m & (m >> 8):
bits = "{0: 049b}".format(m & (m >> 8))
foo = [len(bits) - i - 1 for i in range(0, len(bits)) if bits[i] == '1']
for j in range(len(foo)):
if ((opp_pos >> int(foo[j] + 24)) & 1) != 1 and foo[j] + 24 < 49: # one piece before
return True
elif foo[j] >= 8 and ((opp_pos >> int(foo[j] - 8)) & 1) != 1: # one piece after
return True
# Diagonal \
m = position & (position >> 6)
if m & (m >> 6):
bits = "{0: 049b}".format(m & (m >> 6))
foo = [len(bits) - i - 1 + 6 for i in range(0, len(bits)) if bits[i] == '1']
for j in range(len(foo)):
if ((opp_pos >> int(foo[j] + 12)) & 1) != 1 and foo[j] + 12 < 49: # one piece before
return True
elif foo[j] >= 12 and ((opp_pos >> int(foo[j] - 12)) & 1) != 1 and foo[j] - 12 % 6 == 0: # one piece after
return True
# Horizontal
m = position & (position >> 7)
b = m & (m >> 7)
if b:
bits = "{0: 049b}".format(b)
foo = [len(bits) - i - 1 + 7 for i in range(0, len(bits)) if bits[i] == '1']
for j in range(len(foo)):
if ((opp_pos >> int(foo[j] + 14)) & 1) != 1 and foo[j] + 14 < 49: # one piece before
return True
elif foo[j] >= 14 and ((opp_pos >> int(foo[j] - 14)) & 1) != 1: # one piece after
return True
# Vertical
m = position & (position >> 1)
t = m & (m >> 1)
if t:
bits = "{0: 049b}".format(t)
foo = [len(bits) - i for i in range(0, len(bits)) if bits[i] == '1']
for j in range(len(foo)):
if foo[j] >= 2 and ((opp_pos >> int(foo[j] - 2)) & 1) != 1: # one piece after
return True
# Nothing found
return False
|
def transpose(matrix):
""" :returns the matrix transposed """
zipped_rows = zip(*matrix)
transpose_matrix = [list(row) for row in zipped_rows]
return transpose_matrix
|
def bs3_cols(num_entries):
"""Return the appropriate bootstrap framework column width.
Args:
num_entries (int): The number of entries to determine column width for.
Returns:
int: The integer value for column width.
"""
if not isinstance(num_entries, int):
return 12
mappings = {
1: 12,
2: 6,
3: 4,
4: 3,
5: 2,
6: 2,
}
try:
return mappings[num_entries]
except KeyError:
return 12
|
def privacy_check(postal_code: str) -> bool:
"""
Helper function for the callbacks.
Checks if postal code is private.
---
Args:
postal_code (str): Area postal code.
Returns:
True (bool): When postal code is in the private_list
False (bool): When postal code is not found in the private_list
"""
# List of private area postcodes
private_list = ['00230', '02290', '01770']
if postal_code in private_list:
return True
else:
return False
|
def getClusters(taus, neighborsets):
"""
input:
taus : values of overlap between two spin configurations.
Array of N spin-values.
neighborsets: list ordered by spin index, whose
elements are the spins neighboring the spin at that index.
output:
list of cluster indices split according to the adjacency
matrix to find contiguous regions of 'up' or 'down' spins
"""
result = []
spins = set(range(len(taus)))
while spins:
seed = spins.pop()
newclust = {seed}
queue = [seed]
while queue:
nxt = queue.pop(0)
neighs = neighborsets[nxt].difference(newclust)
for neigh in list(neighs):
if not taus[neigh] == taus[seed]: neighs.remove(neigh)
newclust.update(neighs)
queue.extend(neighs)
spins.difference_update(neighs)
result.append(list(newclust))
return result
|
def _get_cols_length(table, cols_num):
"""Return the max length of every columns.
"""
cols_length = [0] * cols_num
for row in table:
for (i, col) in enumerate(row):
col_len = len(col)
if col_len > cols_length[i]:
cols_length[i] = col_len
return cols_length
|
def split_arg(arg: str) -> list:
"""
Splits arg string using comma separator and returns a filtered list
:param arg:
:return:
"""
args = arg.split(",")
return [a.strip() for a in args if a]
|
def symmetric_difference_cardinality(s, q):
"""Return the cardinality of the symmetric difference of two sets.
Parameters
----------
s : iterable
Elements of the first set. Values must be hashable.
q : iterable
Elements of the second set. Values must be hashable.
Returns
-------
int
``len(set(s) ^ set(q))``.
"""
return len(set(s) ^ set(q))
|
def clip(text, max_len=80):
"""Return max_len characters clipped at space if possible"""
text = text.rstrip()
if len(text) <= max_len or ' ' not in text:
return text
end = len(text)
space_at = text.rfind(' ', 0, max_len + 1)
if space_at >= 0:
end = space_at
else:
space_at = text.find(' ', max_len)
if space_at >= 0:
end = space_at
return text[:end].rstrip()
|
def metric(x):
"""
This function will convert Metric meters to Imperial Feet (and Inches).
:return: Converted value from Metric to Imperial
"""
# Initial conversion
# Meters to Feet
meters_in_ft = float("{:.4f}".format(x * 3.280839895))
# Inches portion of conversion
meters_in_in = meters_in_ft % 1 * 12
# For the weird rounding issues where it assumes .999 is 12 inches (1ft) just convert it over to prevent
# 5 ft 12 inch issues
if meters_in_in >= 11.992:
meters_in_ft = meters_in_ft + 1
meters_in_in = meters_in_in - 11.992
# LIMIT/FORMAT OUTPUTS
# Limit Feet to 0 decimal places
meters_in_ft = int(meters_in_ft)
# Limit Inches to 2 decimal places
meters_in_in = float("{:.2f}".format(meters_in_in))
# Return the
return meters_in_ft, meters_in_in
|
def street_check_fold_json(
rus_check_json, benny_bet_json, rus_fold_json, oven_show_json
):
"""Expected JSON for street_check_fold model-fixture"""
return {
"actions": [
rus_check_json,
benny_bet_json,
rus_fold_json,
oven_show_json,
]
}
|
def dirs(obj, st='', caseSensitive=False):
"""
I very often want to do a search on the results of dir(), so
do that more cleanly here
:param obj: the object to be dir'd
:param st: the strig to search
:param caseSensitive: If False, compares .lower() for all, else doesn't
:return: The results of dir() which contain st
"""
if caseSensitive:
return [ii for ii in dir(obj) if st in ii]
return [ii for ii in dir(obj) if st.lower() in ii.lower()]
|
def sanitise_keys(d):
"""
Strip all of the colons out of the key names
:param d:
:return: dict
"""
new_d = {}
for k, v in d.items():
new_d[k.replace(':', '_')] = v
return new_d
|
def regex_unanchor(regexp):
"""
ES regexps are anchored, so adding .* is necessary at the beginning and
end to get a substring match. But we want to skip that if front/end
anchors are explicitly used.
Also avoid doubling up wildcards, in case the regexp engine is not smart
about backtracking.
"""
if regexp.startswith('^'):
regexp = regexp.lstrip('^')
elif not regexp.startswith('.*'):
regexp = '.*' + regexp
if regexp.endswith('$'):
regexp = regexp.rstrip('$')
elif not regexp.endswith('.*'):
regexp += '.*'
return regexp
|
def empirical_hpd(values, conf=0.05):
"""
Assuming a **unimodal** distribution, returns the 0.95 highest posterior
density (HPD) interval for a set of samples from a posterior distribution.
Adapted from ``emp.hpd`` in the "TeachingDemos" R package (Copyright Greg
Snow; licensed under the Artistic License).
"""
conf = min([conf, 1.0 - conf])
n = len(values)
nn = int(round(n * conf))
x = sorted(values)
xx = []
if nn == 0:
raise ValueError("Sample size too small: %s" % len(values))
for i in range(nn):
Z1 = x[n-(nn-i)]
Z2 = x[i]
#print "==>", Z1, Z2
xx.append(Z1 - Z2)
m = min(xx)
nnn = xx.index(m)
#print "n=", n
#print "nn=", nn
#print "xx=", xx
#print "m=", m
#print "nnn=", n
return (x[nnn], x[n-nn+nnn])
|
def lerp(p0, p1, t):
"""Linear interpolation."""
return (1.0 - t) * p0 + t * p1
|
def _number(s):
"""Given a numeric string, return an integer or a float, whichever
the string indicates. _number("1") will return the integer 1,
_number("1.0") will return the float 1.0.
"""
try:
n = int(s)
except ValueError:
n = float(s)
return n
|
def parseacclist(infile):
"""
parses the user specified accession list file
parameters
----------
infile
the name of the accession list input file
returns
----------
acclist = a list containing each accession number from file
"""
acclist = []
try:
with open(infile, "r") as f:
for line in f:
line = line.strip()
acclist.append(line)
except(FileNotFoundError):
# raise error
print(f"file: {infile} not found!")
return(acclist)
|
def _calc_proprtn_srvd_unsrvd(total_pop,
servd_pop,
unsrvd_pop):
"""[summary]
Args:
total_pop (int): The total population for that category
servd_pop (int): Of the population, those who are served
by public transport
unsrvd_pop (int): Of the population, those who are NOT served
by public transport
Returns:
dict: A dictionary with the following:
i) the total number of people that column (e.g. age range, sex)
ii) the number served by public transport
iii) the percentage of who are served by public transport
iv) the percentage ofwho are not served by public transport
"""
# Get proportion served
pct_servd = round((servd_pop/total_pop)*100, 2)
# Get proportion unserved
pct_unserved = round(((total_pop-servd_pop)/total_pop)*100, 2)
results_dict = {"Total": str(total_pop),
"Served": str(servd_pop),
"Unserved": str(unsrvd_pop),
"Percentage served": str(pct_servd),
"Percentage unserved": str(pct_unserved)}
return results_dict
|
def test_row(counter):
"""
Tests if counter%4 is 0
:param counter: For loop counter
:rtype: boolean
"""
if counter%4 == 0:
return True
return False
|
def _construct_GPL_url(accession):
"""Example URL:
ftp://ftp.ncbi.nlm.nih.gov/geo/platforms/GPLnnn/GPL570/annot/GPL570.annot.gz
"""
number_digits = len(accession) - 3 # 'GPL' is of length 3.
if number_digits < 4:
folder = accession[:3] + 'nnn' # e.g. GPLnnn.
elif 3 < number_digits < 5:
folder = accession[:4] + 'nnn' # e.g. GPL6nnn.
else:
folder = accession[:5] + 'nnn' # e.g. GPL19nnn.
url = '/'.join(['ftp://ftp.ncbi.nlm.nih.gov/geo/platforms',
folder,
accession,
'annot',
accession + '.annot.gz'])
return url
|
def points_to_matrix(points):
"""List of points (x, y) is transformed into system of linear equations."""
degree = len(points) - 1
matrix = [[] for i in range(degree + 1)]
vector = []
for i, point in enumerate(points):
for j in range(degree, -1, -1):
matrix[i].append(point[0] ** j)
vector.append(point[1])
return matrix, vector
|
def _round_fractions(fractions):
"""Format float fractions as rounded fraction strings.
Fractions are rounded as short as possible without losing the precision
necessary to distinguish one fraction from another. The rounding starts at
3 decimal places and continues up to 10 decimal places, if a shorter
rounded representation isn't converged upon earlier. If rounding at 10
decimal places doesn't provide enough precision, each fraction's full
float precision will be used (i.e. as returned by `repr(float)`).
For example, [0.12345, 0.12351] would be rounded to four decimal places:
['0.1234', '0.1235']. 3 decimal places would be tried first but there isn't
enough precision to keep both fractions distinguishable.
"""
for decimals in range(3, 11):
rounded = ['{fraction:1.{decimals}f}'.format(fraction=fraction,
decimals=decimals)
for fraction in fractions]
if len(rounded) == len(set(rounded)):
return rounded
return [repr(fraction) for fraction in fractions]
|
def string_is_equal_case_insensitive(subject: str, value: str) -> bool:
"""Case insensitive string is equal"""
return subject.strip().lower() == value.strip().lower()
|
def reduce_vocab(word_vecs):
"""
just takes words already used, but reserves 0
"""
uniques = set()
for wv in word_vecs:
uniques.update(wv)
new2old = [0] # always map 0 to itself
if 0 in uniques:
uniques.remove(0)
new2old.extend(sorted(uniques))
old2new = dict((w, i) for i, w in enumerate(new2old))
return new2old, old2new
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.