content stringlengths 42 6.51k |
|---|
def add_leading_zero(number: int, digit_num: int = 2) -> str:
"""add_leading_zero function
Args:
number (int): number that you want to add leading zero
digit_num (int): number of digits that you want fill up to. Defaults to 2.
Returns:
str: number that has the leading zero
Examples:
>>> add_leading_zero(5, 3)
"005"
"""
return str(number).zfill(digit_num) |
def _format_abc(num):
"""Lowercase. Wraps around at 26."""
n = (num -1) % 26
return chr(n+97) |
def TransformDecode(r, encoding, undefined=''):
"""Returns the decoded value of the resource that was encoded by encoding.
Args:
r: A JSON-serializable object.
encoding: The encoding name. *base64* and *utf-8* are supported.
undefined: Returns this value if the decoding fails.
Returns:
The decoded resource.
"""
# Some codecs support 'replace', all support 'strict' (the default).
for errors in ('replace', 'strict'):
try:
return r.decode(encoding, errors)
except: # pylint: disable=bare-except, undefined for any exception
pass
return undefined |
def _get_t(elm):
""" helper function, get text if element exists """
return elm.text.strip() if elm is not None else elm |
def popup(message, title):
"""
Function that returns UR script for popup
Args:
message: float. tooltip offset in mm
title: float. tooltip offset in mm
Returns:
script: UR script
"""
return 'popup("{}","{}") \n'.format(message, title) |
def subv3(a, b):
"""subtract 3-vector b from a"""
return (a[0]-b[0], a[1]-b[1], a[2]-b[2]) |
def atoi(text):
"""
Turn an int string into a number, but leave a non-int string alone.
"""
return int(text) if text.isdigit() else text |
def calculate_mz(
prec_mass: float,
charge: int
) -> float:
"""Calculate the precursor mono mz from mass and charge.
Args:
prec_mass (float): precursor mass.
charge (int): charge.
Returns:
float: mono m/z.
"""
M_PROTON = 1.00727646687
mono_mz = prec_mass / abs(charge) + M_PROTON
return mono_mz |
def check_existence(dictionary: dict, keys: list):
"""
Check the existence of all key elements in dictionary with the keys list
:param dictionary: dict to check all keys
:param keys: keys to check
"""
return all(key in dictionary for key in keys) and len(dictionary) == len(keys) |
def is_yaml(path):
"""
Checks whether the file at path is a yaml-file.
Parameters
----------
path : str
The relative path to the file that should be checked.
Returns
-------
bool
Whether or not the specified file is a yaml-file.
"""
return path.endswith('.yaml') or path.endswith('.yml') |
def capture_row_indices(materials, shape_only=False):
"""Captures the start and stop indices of an array based on the
contents of the array.
shape_only provides a method to control binary gap vs no-gap as
opposed to actual details of materials. This should provide a close
to optimal pairing of indices.
>>> materials = [2, 1, 1, 2]
>>> capture_row_indices(materials, shape_only=True)
[(0, 3)]
>>> materials = [2, 1, 1, 2]
>>> capture_row_indices(materials)
[(0, 0), (1, 2), (3, 3)]
>>> materials = [2, 0, 0, 1]
>>> capture_row_indices(materials, shape_only=True)
[(0, 0), (3, 3)]
>>> materials = [2, 1, 1, 2]
>>> indices = capture_row_indices(materials)
>>> print indices
[(0, 0), (1, 2), (3, 3)]
"""
last = None
last_idx = None
start = None
start_idx = None
row_data = []
for idx, m_id in enumerate(materials):
if m_id:
if not last:
start = m_id
start_idx = idx
elif not shape_only:
if start != m_id:
row_data.append((start_idx, last_idx))
start = m_id
start_idx = idx
else:
if start:
row_data.append((start_idx, last_idx))
start = None
last = m_id
last_idx = idx
if start and last:
row_data.append((start_idx, last_idx))
return sorted(row_data) |
def parse_loot_percentage(text):
"""Use to parse loot percentage string, ie: Roubo: 50% becomes 0.5"""
percentage = float(text.split(':')[1].strip("%")) / 100
return percentage |
def px2pt(p):
"""Convert pixels to points.
"""
return p * 72. / 96. |
def create_dict_from_filter(d, white_list):
"""Filter by key"""
return {k: v for k, v in filter(lambda t: t[0] in white_list, d.items())} |
def get_named_graph(ont):
"""
Ontobee uses NGs such as http://purl.obolibrary.org/obo/merged/CL
"""
if ont.startswith('http://'):
return ont
namedGraph = 'http://purl.obolibrary.org/obo/merged/' + ont.upper()
return namedGraph |
def combine_results(first, second):
"""Sum objects in given tuples using the __add__ method of
each object. e.g.
foo[0] = foo[0] + bar[0]
foo[1] = foo[1] + bar[1]
return foo
Used here to sum Method and Analyze objects together for trajectories
read in chunks.
Usage: combine_results( (Method1, Analysis1), (Method2, Analysis2) )
Returns: (summed_methods, summed_analyses)"""
comb = [ a + b for a, b in zip(first, second) ]
return tuple(comb) |
def slice_to_box(slice):
"""
Convert slice object to tuple of bounding box.
Parameters
----------
slice : tuple
A tuple containing slice(start, stop, step) objects.
Return
------
box : tuple
A tuple containing 4 integers representing a bounding box.
"""
box = (slice[0].start, slice[0].stop,
slice[1].start, slice[1].stop)
return box |
def _mock_kernel(x1, x2, history):
"""A kernel that memorizes its calls and encodes a fixed values for equal/unequal
datapoint pairs."""
history.append((x1, x2))
if x1 == x2:
return 1
else:
return 0.2 |
def parse_title(title):
"""Parse the title of the measurement
@return Tuple (what, batch, src, dest), (None, None, None, None) in case of failure.
"""
tmp = title.split('-')
if len(tmp)!=4:
return (None, None, None, None)
return (tmp[0], int(tmp[1]), int(tmp[2]), int(tmp[3])) |
def kwarg(string, separator='='):
"""Return a dict from a delimited string."""
if separator not in string:
raise ValueError("Separator '%s' not in value '%s'"
% (separator, string))
if string.strip().startswith(separator):
raise ValueError("Value '%s' starts with separator '%s'"
% (string, separator))
if string.strip().endswith(separator):
raise ValueError("Value '%s' ends with separator '%s'"
% (string, separator))
if string.count(separator) != 1:
raise ValueError("Value '%s' should only have one '%s' separator"
% (string, separator))
key, value = string.split(separator)
return {key: value} |
def message_decoder(text):
""" Decodes message content by splitting, splicing and stripping text
Args:
text (string): Input text
Returns:
dict : A hashmap containing all key value pairs of decoded text
"""
try:
first_split = text.split("-")
result = {}
for element in first_split:
element = element.strip()
el = element.split(":")
result[el[0].strip()] = el[1].strip()
return result
except Exception:
return None |
def make_blast_subject_list(local_files, addNr = True):
""" given a list of fasta filenames, make a blast list """
# helper for name breakpoints
# list of BLAST subjects
# first column is filename (for local) or database name (for NCBI)
# second column is true for local and false for NCBI
# all of these files need to be placed in the working directory
# Example below:
# blastSubjectList = [['Cth_known_regions.fa', True],
# ['Cth_transposons.fa', True],
# ['Cth_homology.fa', True],
# ['Cth_1313_CDS_annotations.fa', True],
# ['Cth_DSM_1313_genome.fa', True],
# ['nr', False]]
blastSubjectList = []
"""
## This is an old version, for using files located in the cth-mutation github directory DO 2-12-2019
for file in local_files:
parentDir = os.path.dirname(__file__) # parent directory of process_clc_files.py file
filePath = os.path.join(parentDir, file)
# print(filePath) #for debugging
blastSubjectList.append([filePath, True])
"""
for file in local_files:
blastSubjectList.append([file, True])
if addNr == True:
blastSubjectList.append(['nr', False]) # add the nr database as the final item in the list
return blastSubjectList |
def _to_tag_case(x):
"""
Returns the string in "tag case" where the first letter
is capitalized
Args:
x (str): input string
Returns:
x (str): transformed string
"""
return x[0].upper() + x[1:] |
def mat_to_svec_dim(n):
"""Compute the number of unique entries in a symmetric matrix."""
d = (n * (n + 1)) // 2
return d |
def bvi_unique(yaml, bviname):
"""Returns True if the BVI identified by bviname is unique among all BridgeDomains."""
if not "bridgedomains" in yaml:
return True
ncount = 0
for _ifname, iface in yaml["bridgedomains"].items():
if "bvi" in iface and iface["bvi"] == bviname:
ncount += 1
return ncount < 2 |
def collapse(lst):
"""
Removes all sublists from a list while keeping their values
:param lst: List to be collapsed.
:return: List
"""
temp = []
for i in lst:
if type(i) is list:
temp +=collapse(i)
else:
temp +=[i]
return temp |
def valueList(name,position):
""" Concatenate the two parameter list in on list of tuple"""
values = []
for i in range(len(name)):
values += [[name[i],position[i]]]
return values |
def edit_distance(str1, str2):
""" calculates the edit distance between 2 strings
uses a DP approach with a table that calculates the edit distance between
2 substrings
dp[i][j] = edit distance between str1[i] and str2[j]
:type str1: string
:type str2: string
:rtype int: """
dp = [[0 for _ in range(len(str2) + 1)] for _ in range(len(str1) + 1)]
# base case is just to add letters, which we know
for i in range(len(str1)):
dp[i][0] = i
for i in range(len(str2)):
dp[0][i] = i
# now iterate through strings, working on the table each row at a time
# for each iteration, we have 3 cases:
# - an element is removed from x
# - an element is added to x
# - an element is changed from x
# - nothing changes bc current element is the same
for i in range(1, len(str1) + 1):
for j in range(1, len(str2) + 1):
# if the characters are different, we know we will have to at least
# change one thing
if str1[i - 1] == str2[j - 1]:
c = 0
else:
c = 1
# take the minimum case
dp[i][j] = min(
dp[i - 1][j] + 1, # remove one char from str1
dp[i][j - 1] + 1, # remove one char from str2
# change one letter or don't change a letter (lengths stay the
# same)
dp[i - 1][j - 1] + c,
)
# print min edit distance between str1[:len(str1)-1], str2[:len(str2)-1]
return dp[len(str1) - 1][len(str2) - 1] |
def multiqubit_measure_counts_deterministic(shots, hex_counts=True):
"""Multi-qubit measure test circuits reference counts."""
targets = []
if hex_counts:
# 2-qubit measure |10>
targets.append({'0x2': shots})
# 3-qubit measure |101>
targets.append({'0x5': shots})
# 4-qubit measure |1010>
targets.append({'0xa': shots})
else:
# 2-qubit measure |10>
targets.append({'10': shots})
# 3-qubit measure |101>
targets.append({'101': shots})
# 4-qubit measure |1010>
targets.append({'1010': shots})
return targets |
def binary_sum(x : int ,y : int) -> str :
"""
Given two binary number
return their sum .
For example,
x = 11
y = 111
Return result as "1000".
Parameters:
x(int) : binary number
y(int) : binary number
Returns:
s(str) : sum of a and b in string
"""
a : str = str(x)
b : str = str(y)
s : str = ""
c : int = 0
i : int = len(a)-1
j : int = len(b)-1
zero : int = ord('0')
while (i >= 0 or j >= 0 or c == 1):
if (i >= 0):
c += ord(a[i]) - zero
i -= 1
if (j >= 0):
c += ord(b[j]) - zero
j -= 1
s = chr(c % 2 + zero) + s
c //= 2
return s |
def fetch_log_pos(server, args_array, opt_arg_list):
"""Method: fetch_log_pos
Description: Stub holder for mysql_log_admin.fetch_log_pos function.
Arguments:
"""
status = True
if server and args_array and opt_arg_list:
status = True
return status |
def getComments(header, index):
"""Get any comments before this table.
Expects the header string and the index of the table."""
cend = header.rindex('\n', 0, index) #the start of line.
cstart = cend
tmp = cend
while True: #find start of a comment.
tmp = header.rindex('\n', 0, cstart - 1)
if '//' in header[tmp:cstart]:
cstart = tmp #this is a line with a comment.
else:
return header[cstart:cend] |
def build_mjolnir_utility(config):
"""Buiild arguments for calling mjolnir-utility.py
Parameters
----------
config : dict
Configuration of the individual command to run
"""
args = [config['mjolnir_utility_path'], config['mjolnir_utility']]
try:
# while sorting is not strictly necessary, dicts have non-deterministic
# sorts which make testing difficult
for k, v in sorted(config['cmd_args'].items(), key=lambda x: x[0]):
for item in (v if isinstance(v, (list, set)) else [v]):
args.append('--' + k)
args.append(str(item))
except KeyError:
pass
return args |
def compute_precision_recall(results, partial=False):
""" Compute the micro scores for Precision, Recall, F1.
:param dict results: evaluation results.
:param bool partial: option to half the reward of partial matches.
:return: Description of returned object.
:rtype: updated results
"""
actual = results["actual"]
possible = results["possible"]
partial = results["partial"]
correct = results["correct"]
if partial:
precision = (correct + 0.5 * partial) / actual if actual > 0 else 0
recall = (correct + 0.5 * partial) / possible if possible > 0 else 0
else:
precision = correct / actual if actual > 0 else 0
recall = correct / possible if possible > 0 else 0
results["P_micro"] = precision
results["R_micro"] = recall
results["F1_micro"] = (
2 * (precision * recall) / (precision + recall) if (precision + recall) > 0 else 0
)
return results |
def corrupt_string(input, to_insert):
"""
Takes in a base string input and another string to_insert.
Corrupts the base string by making it so each character is
followed by the string in to_insert and returns.
Parameters:
input: Base string that will be corrupted/modified.
to_insert: String that is used to corrupt the base string.
Returns:
String input that has been corrupted by to_insert.
>>> corrupt_string('tickets', '#')
't#i#c#k#e#t#s#'
>>> corrupt_string('', '@')
''
>>> corrupt_string('buy now', '-')
'b-u-y- -n-o-w-'
# Add AT LEAST 3 doctests below, DO NOT delete this line
>>> corrupt_string('foo', 'bar')
'fbarobarobar'
>>> corrupt_string('pokemon', '')
'pokemon'
>>> corrupt_string(' frog!', '-')
' -f-r-o-g-!-'
"""
if len(input) == 0:
return input
if len(input) == 1:
return input + to_insert
return corrupt_string(input[0], to_insert) + \
corrupt_string(input[1:], to_insert) |
def UpperCamelCase(lowerCamelCaseStr):
"""
Return the UpperCamelCase variant of a lower camel case string.
"""
return lowerCamelCaseStr[0].upper() + lowerCamelCaseStr[1:] |
def merge_json_objects(a, b):
"""Merge two JSON objects recursively.
- If a dict, keys are merged, preferring ``b``'s values
- If a list, values from ``b`` are appended to ``a``
Copying is minimized. No input collection will be mutated, but a deep copy
is not performed.
Parameters
----------
a, b : dict
JSON objects to be merged.
Returns
-------
merged : dict
"""
# see https://github.com/dask/dask-gateway/blob/7d1659db8b2122d1a861ea820a459fd045fc3f02/
# dask-gateway-server/dask_gateway_server/backends/kubernetes/utils.py#L220
if b:
# Use a shallow copy here to avoid needlessly copying
a = a.copy()
for key, b_val in b.items():
if key in a:
a_val = a[key]
if isinstance(a_val, dict) and isinstance(b_val, dict):
a[key] = merge_json_objects(a_val, b_val)
elif isinstance(a_val, list) and isinstance(b_val, list):
a[key] = a_val + b_val
else:
a[key] = b_val
else:
a[key] = b_val
return a |
def render_filter(pattern: list):
"""
take the --filter argument list and return a k,v dict
:param pattern: type list
:return: pattern dict
"""
result = dict()
for item in pattern:
k, v = item.split(":")
result.update({k: v})
return result |
def convert_str_version_number(version_str):
"""
Convert the version number as a integer for easy comparisons
:param version_str: str of the version number, e.g. '0.33'
:returns: tuple of ints representing the version str
"""
version_numbers = version_str.split('.')
if len(version_numbers) != 2:
raise ValueError(f"Version number is malformed: '{version_str}'")
return tuple(int(part) for part in version_numbers) |
def _compute_olympic_average(scores, dropped_scores, max_dropped_scores):
"""Olympic average by dropping the top and bottom max_dropped_scores:
If max_dropped_scores == 1, then we compute a normal olympic score.
If max_dropped_scores > 1, then we drop more than one scores from the
top and bottom and average the rest.
When dropped_scores > 0, then some scores have already been dropped
so we should not double count them
Precondition: Dropped scores have higher score value than the rest
"""
# Sort scores first
scores.sort()
# Remove top and bottom scores
countable_scores = scores[max_dropped_scores:(
len(scores) - (max_dropped_scores - dropped_scores))]
sum_of_scores = sum(countable_scores)
return sum_of_scores * 1.0 / len(countable_scores) |
def line_segment_intersection(p1, p2, p3, p4):
"""
- Compute the intersect of two line segments if exists
- Input:
- p1, p2 (two end points of line segment 1; L1)
- p3, p4 (two end points of line segment 2; L2)
- Output:
- (px, py) the intersect of two segments L1 and L2 if exists
- None otherwise.
"""
d = (p2[0] - p1[0]) * (p4[1] - p3[1]) - (p2[1] - p1[1]) * (p4[0] - p3[0])
if d == 0.0:
return None
intersect = [0.0, 0.0]
u = ((p3[0] - p1[0]) * (p4[1] - p3[1]) - (p3[1] - p1[1]) * (p4[0] - p3[0])) / d
v = ((p3[0] - p1[0]) * (p2[1] - p1[1]) - (p3[1] - p1[1]) * (p2[0] - p1[0])) / d
if u < 0.0 or u > 1.0 or v < 0.0 or v > 1.0:
return None
px = p1[0] + u * (p2[0] - p1[0])
py = p1[1] + u * (p2[1] - p1[1])
if px == p1[0] and py == p1[1] or \
px == p2[0] and py == p2[1] or \
px == p3[0] and py == p3[1] or \
px == p4[0] and py == p4[1]:
return None
return (px, py) |
def convert_tx_id(tx_id):
"""
Converts the guid tx_id to string of 16 characters with a dash between every 4 characters
:param tx_id: tx_id to be converted
:return: String in the form of xxxx-xxxx-xxxx-xxxx
"""
return (tx_id[:4] + '-' + tx_id[4:])[:19] |
def transform(timescale, dt):
"""
Transform timescale to omega
Parameters
----------
timescale : float or array
dt : float
Returns
-------
float
"""
return 0.5 * (dt / timescale) ** 2 |
def _fmt_col_rpt(col):
"""
Format rpt row for missing required column.
Parameters
----------
col : str
pd.DataFrame column name
Returns
-------
dict
Rpt row for missing required column
"""
return {
'inval_line': 'All',
'inval_col': col,
'inval_val': 'All',
'error': 'Column %s is missing' % (col)
} |
def todict(conn_string, kwargs):
"""Converts the input connection string into a dictionary.
Assumption: Connection string is of the format
'driver=couchdb;server=localhost;uid=database_uid;pwd=database_pwd'
"""
ret = {}
conn_dict = {}
for c_str in conn_string:
arr = c_str.split(';')
for elem in arr:
temp = elem.split('=')
ret[temp[0]] = temp[1]
conn_dict = ret.copy()
conn_dict.update(kwargs)
return conn_dict |
def basic(context, name="world"):
"""Say hello.
This can be tested easily using cURL from the command line:
curl http://localhost:8080/ # Default value via GET.
curl http://localhost:8080/Alice # Positionally specified via GET.
curl -d name=Eve http://localhost:8080/ # Form-encoded value via POST.
"""
return "Hello {name}.".format(name=name) |
def nodigits(s):
""" Remove #s from the string """
return ''.join([i for i in s if not i.isdigit()]) |
def _str_jobid(msg) :
"""Returns (str) job Id from input string.
E.g. returns '849160' from msg='Job <849160> is submitted to queue <psnehq>.'
"""
fields = msg.split()
if len(fields)<2 : return None
if fields[0] !='Job' : return None
return fields[1].lstrip('<').rstrip('>') |
def add_pkg_to_pkgs(pkg, pkgs):
"""Add package to dictionary of packages.
"""
name = pkg["Source"]
version = pkg["Version"]
pkgs[name][version] = pkg
return pkgs |
def pick_from_list(items, suffix):
""" Pick an element from list ending with suffix.
If no match is found, return None.
:param items list of items to be searched.
:suffix String suffix defining the match.
"""
match = None
for item in items:
if item.endswith(suffix):
match = item
return match |
def progress_bar(percent_progress, saturation=0):
""" This function creates progress bar with optional simple saturation mark"""
step = int(percent_progress / 2) # Scale by to (scale: 1 - 50)
str_progress = '#' * step + '.' * int(50 - step)
c = '!' if str_progress[38] == '.' else '|'
if (saturation > 0):
saturation = saturation / 2
str_progress = str_progress[:saturation] + c + str_progress[saturation:]
return str_progress |
def error_format(search):
"""
:param search: inputted word
:return: bool.
Checking every element in the inputted word is in alphabet.
"""
for letter in search:
if letter.isalpha() is False:
return True |
def remove(numlist):
"""Removes negative numbers and numbers above 100 from a list"""
numremove = []
for item in numlist:
if item < 0 or item > 100:
numremove.append(item)
for item in numremove:
numlist.remove(item)
return (numlist) |
def _is_dumbcaps(line):
"""Is this line mostly in dumbcaps?
Dumbcaps is like so: ``D U M B H E A D E R''.
"""
good = bad = 0
seen_space = True
for c in line:
if c == ' ':
if not seen_space:
good += 1
seen_space = True
else:
if not seen_space:
bad += 1
else: good += 1
seen_space = False
if good > 1.5 * bad:
return True
return False |
def find_channel_title(item):
"""Channel Title of the channel that published the video"""
channel_name = item['snippet']['channelTitle']
return channel_name |
def _get_conv_shape_1axis(
image_shape, kernel_shape, border_mode, subsample, dilation=1
):
"""This function compute the output shape of convolution operation.
Copied and simplified from theano (2020/11/08):
https://github.com/Theano/Theano/blob/master/theano/tensor/nnet/abstract_conv.py
Parameters
----------
image_shape: int
Corresponds to the input image shape on a given axis.
kernel_shape: int
Corresponds to the kernel shape on a given axis.
border_mode: string or int. If it is a string, it must be
'valid' or 'full'.
subsample: int. It must correspond to the subsampling on the
considered axis.
dilation: int. It must correspond to the dilation on the
considered axis.
Returns
-------
out_shp: int corresponding to the output image shape on the
considered axis.
"""
# Implicit dilated kernel shape
dil_kernel_shape = (kernel_shape - 1) * dilation + 1
if border_mode == "full":
pad_l = pad_r = dil_kernel_shape - 1
elif border_mode == "valid":
pad_l = pad_r = 0
else:
assert border_mode >= 0
pad_l = pad_r = border_mode
# In case of symbolic shape, we want to build the smallest graph
# (image_shape + 2 * pad - dil_kernel_shape) // subsample + 1
out_shp = image_shape - dil_kernel_shape
if pad_l != 0:
out_shp += pad_l
if pad_r != 0:
out_shp += pad_r
if subsample != 1:
out_shp = out_shp // subsample
out_shp = out_shp + 1
return out_shp |
def is_standalone_name(list_name, stand_alone_words):
"""Return True if standalone name."""
if any(stand_alone in list_name for stand_alone in stand_alone_words):
return True
return False |
def getArg(seq, index, default=None, func=lambda x: x):
"""Returns func(seq[index]), or 'default' if it's an invalid index"""
try:
return func(seq[index])
except IndexError:
return default |
def kw_pop(*args, **kwargs):
"""
Treatment of kwargs. Eliminate from kwargs the tuple in args.
"""
arg = kwargs.copy()
key, default = args
if key in arg:
return arg, arg.pop(key)
else:
return arg, default |
def represents_int(s):
"""
Is it an integer
:param s: String to be tested
:return: True if interger, False otherwise
"""
try:
int(s)
return True
except ValueError:
return False |
def makeiter(var):
"""Converts a variable into a list of it's not already an iterable (not including strings.
If it's already an iterable, don't do anything to it.
Parameters
------------
var
the variable to check.
Returns
------------
var
an iterable version of the parameter (if it's not already one)
"""
if not hasattr(var, '__iter__') or isinstance(var, str):
return [var]
return var |
def bool_from_user_str(bool_string):
"""Parse a string description of a hlwm boolean to
a python boolean"""
if bool_string.lower() in ['true', 'on']:
return True
if bool_string.lower() in ['false', 'off']:
return False
raise Exception(f'"{bool_string}" is not a boolean') |
def VirtualTempFromMixR(tempk, mixr):
"""Virtual Temperature
INPUTS:
tempk: Temperature (K)
mixr: Mixing Ratio (kg/kg)
OUTPUTS:
tempv: Virtual temperature (K)
SOURCE: hmmmm (Wikipedia). This is an approximation
based on a m
"""
return tempk * (1.0+0.6*mixr) |
def fromiter(iterable):
"""
Construct a binary number from a finite iterable, where the ith bit
from the right is the truth value of the iterable's ith item.
:param iterable: any iterable, usually one with boolean values.
:type iterable: Iterable
:return: the binary number.
:rtype: int
"""
return sum(1 << i for i, obj in enumerate(iterable) if obj) |
def calc_max_quant_value(bits):
"""Calculate the maximum symmetric quantized value according to number of bits"""
return 2**(bits) - 1 |
def count_if(predicate, iterable):
"""Count the number of items of an iterable that satisfy predicate."""
return sum(1 for item in iterable if predicate(item)) |
def bytes_to_int(bytes: bytes) -> int:
"""
Helper function, convert set of bytes to an integer
"""
result = 0
for b in bytes:
result = result * 256 + int(b)
return result |
def peters_f(e):
"""f(e) from Peters and Mathews (1963) Eq.17
This function gives the integrated enhancement factor of gravitational
radiation from an eccentric source compared to an equivalent circular
source.
Parameters
----------
e : `float/array`
Eccentricity
Returns
-------
f : `float/array`
Enhancement factor
Notes
-----
Note that this function represents an infinite sum of g(n, e)
.. math::
f(e) = \sum_{n=1}^\infty g(n, e)
"""
numerator = 1 + (73/24)*e**2 + (37/96)*e**4
denominator = (1 - e**2)**(7/2)
f = numerator / denominator
return f |
def get_ref_path(openapi_major_version):
"""Return the path for references based on the openapi version
:param int openapi_major_version: The major version of the OpenAPI standard
to use. Supported values are 2 and 3.
"""
ref_paths = {2: 'definitions',
3: 'components/schemas'}
return ref_paths[openapi_major_version] |
def KK_RC6_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
return (
Rs
+ (R1 / (1 + w * 1j * t_values[0]))
+ (R2 / (1 + w * 1j * t_values[1]))
+ (R3 / (1 + w * 1j * t_values[2]))
+ (R4 / (1 + w * 1j * t_values[3]))
+ (R5 / (1 + w * 1j * t_values[4]))
+ (R6 / (1 + w * 1j * t_values[5]))
) |
def check_quote_in_text(quote_string, citation_text):
"""Returns True if the input quote is anywhere in the input text, and False if not"""
return bool(citation_text.find(quote_string) != -1) |
def human_readable_to_bytes(value: int, unit: str) -> int:
"""
Converts the given value and unit to bytes.
As an example, it should convert (8, GB) to 8388608.
Even though technically MB means 1000 * 1000, many producers actually mean
MiB, which is 1024 * 1024. Even Windows displays as unit MB, even though
it's actually MiB.
"""
unit = unit.casefold()
if unit == "b":
return value
elif unit == "kb" or unit == "kib":
return value * 1024
elif unit == "mb" or unit == "mib":
return value * (1024 ** 2)
elif unit == "gb" or unit == "gib":
return value * (1024 ** 3)
elif unit == "tb" or unit == "tib":
return value * (1024 ** 4)
else:
# there's more, but that's extremely unlikely
return value |
def did_run_test_module(output, test_module):
"""Check that a test did run by looking in the Odoo log.
test_module is the full name of the test (addon_name.tests.test_module).
"""
return "odoo.addons." + test_module in output |
def remove_unencodable(str_: str) -> str:
"""
:type str_: str
:param str_: string to remove unencodable character
:return: string removed unencodable character
"""
s = str_.replace("\xb2", "")
s = s.replace("\u2013", "")
s = s.replace("\u2019", "")
return s |
def _to_gj_polyline(data):
"""
Dump a GeoJSON-like MultiLineString object to WKT.
Input parameters and return value are the MULTILINESTRING equivalent to
:func:`_dump_point`.
"""
return {
'type': 'MultiLineString',
'coordinates': [
[((pt[0], pt[1]) if pt else None) for pt in part]
for part in data["paths"]
],
} |
def multiply_a_list_by(a_list, number):
"""Return a list with every item multiplied by number."""
return [item * number for item in a_list] |
def offsets_to_cell_num(y_offset, x_offset):
"""
:param y_offset: The y_offset inside a block. Precondition: 0 <= y_offset < 3
:param x_offset: The x_offset inside a block. Precondition: 0 <= x_offset < 3
:return: The cell number inside a block
"""
return 3 * y_offset + x_offset |
def is_flow_cell_owner(user, flow_cell):
"""Whether or not user is owner of the given flow cell"""
if not flow_cell:
return False
else:
return flow_cell.owner == user |
def crop_string_middle(s, length=32, cropper='...'):
"""Crops string by adding ... in the middle.
Args:
s: String.
length: Length to crop to.
Returns:
Cropped string
"""
if len(s) <= length:
return s
half = (length - len(cropper)) // 2
return s[:half] + cropper + s[-half - 1:] |
def simpleProcessor(line, prefix):
""" Processes a simple history (e.g .bash_history)
a simple history is defined as a type of history file that contains nothing but one command in each line
"""
return line.replace(prefix, '').split(' ') |
def parseFileNameString(s):
"""Returns a list of files contained in the string."""
l = []; i = 0; N = len(s)
while i < N:
while s[i] == " ": i += 1
if s[i] == "{":
k = i+1
while k < N and s[k] != "}": k += 1
l.append(s[i+1:k])
i = k+1
else:
k = i+1
while k < N and s[k] != " ": k += 1
l.append(s[i:k])
i = k+1
return l |
def find_widest_key(categories):
"""Returns width of widest key for formatting.
"""
widest_key = 0
for key in categories:
if len(key) > widest_key:
widest_key = len(key)
return widest_key |
def getHash(rawData):
"""
"""
hash = dict([ (rawData[i],rawData[i+1]) for i in range(0,len(rawData)-1,2) ])
return hash |
def xnor(*bools):
"""Takes first 2 elements and calc xnor, then use result to calc xnor with 3rd element etc"""
result = bools[0] == bools[1]
for b in bools[2:]:
result = result == b
return result |
def binstr2dec(bstr):
"""Convert binary string representation of an integer to a decimal integer.
"""
return int(bstr, base=2) |
def beautify_task(cat, subcat, name):
"""HTML format NRDiag task elements for pretty graphing"""
label_template = '<<FONT FACE="arial bold">{cat}</FONT><br/>{subcat}<br/>{name}>'
return label_template.format(cat=cat, subcat=subcat, name=name) |
def timer_list(duration, interval):
"""
reset timer list
main loop will check timer list and pop the head item to consume
:return: list consists of second (0, 30, 60, ... 1800)
"""
count = int(duration / interval)
l = []
for c in range(count + 1):
l.append(c * interval)
return l |
def split_proj_name(proj_name):
"""Split projection name.
Projections named as follows: ${transcript_ID}.{$chain_id}.
This function splits projection back into transcript and chain ids.
We cannot just use split("."), because there might be dots
in the original transcript ID.
"""
proj_name_split = proj_name.split(".")
q_num_str = proj_name_split[-1]
trans_name = ".".join(proj_name_split[:-1])
return trans_name, q_num_str |
def _last_char(word):
"""Get last alphanumeric character of word.
:param word: word to get the last letter of.
"""
for i in range(len(word)):
if word[len(word)-1-i].isalpha() or word[len(word)-1-i].isdigit():
return len(word) - 1 - i
return -1 |
def format_args(arg_type, text):
"""Format args based on type"""
if arg_type == 'list':
args_text = text.strip().split()
else:
args_text = text.strip()
return args_text |
def removeNullTerminator(bytestring):
"""Remove null terminator from bytestring"""
bytesOut = bytestring.rstrip(b'\x00')
return bytesOut |
def _convert_terms_to_spin_blocks(terms, n_orbitals: int, n_spin_components: int):
"""
See explanation in from_openfermion in conversion between conventions of netket
and openfermion.
Args:
terms: the operator terms in tuple tree format
n_orbitals: number of orbitals
n_spin_components: number of spin components (2*spin+1)
Returns:
new terms tree
"""
if n_spin_components == 1:
return terms
def _convert_loc(of_loc):
orb_idx = of_loc // n_spin_components
spin_idx = of_loc % n_spin_components
return orb_idx + n_orbitals * spin_idx
def _convert_term(term):
return tuple([(_convert_loc(t[0]), t[1]) for t in term])
return tuple(list(map(_convert_term, terms))) |
def convert_raw_cookie2dict(raw_cookie: str) -> dict:
"""
Convert cookie string which copied from browser
:param raw_cookie: string
:return: dict
"""
return {i.split("=")[0]: i.split("=")[-1] for i in raw_cookie.split("; ")} |
def is_port(port):
"""
returns true if the port is within the valid IPv4 range
"""
if port >= 0 and port <= 65535:
return True
return False |
def delta16(v1, v2):
"""Return the delta (difference) between two increasing 16-bit counters,
accounting for the wraparound from 65535 back to 0"""
diff = v2 - v1
if diff < 0:
diff += (1<<16)
return diff |
def f(coord, a0, a1, a2, a3, a4, a5, a6, a7, a8):
"""Evaluate 2-d function by: a0*x**2*y**2 + a1*x**2*y + ... + a8
Parameters:
coord: (x,y): (float, float)
a0,...,a8: float
"""
x, y = coord
#return a*x**2 + b*x*y + c*y**2 + d
return a0*x**2*y**2 + a1*x**2*y + a2*x**2 \
+ a3*x*y**2 + a4*x*y + a5*x \
+ a6*y**2 + a7*y + a8 |
def get_stream_names(streams):
""" For an instrument, process streams (list of dictionaries), create list of stream names.
"""
stream_names = []
if streams:
for stream in streams:
if stream['stream'] not in stream_names:
stream_names.append(stream['stream'])
return stream_names |
def compress_amount(n):
"""\
Compress 64-bit integer values, preferring a smaller size for whole
numbers (base-10), so as to achieve run-length encoding gains on real-
world data. The basic algorithm:
* If the amount is 0, return 0
* Divide the amount (in base units) evenly by the largest power of 10
possible; call the exponent e (e is max 9)
* If e<9, the last digit of the resulting number cannot be 0; store it
as d, and drop it (divide by 10); regardless, call the result n
* Output 1 + 10*(9*n + d - 1) + e
* If e==9, we only know the resulting number is not zero, so output
1 + 10*(n - 1) + 9.
(This is decodable, as d is in [1-9] and e is in [0-9].)"""
if not n: return 0
e = 0
while (n % 10) == 0 and e < 9:
n = n // 10
e = e + 1
if e < 9:
n, d = divmod(n, 10);
return 1 + (n*9 + d - 1)*10 + e
else:
return 1 + (n - 1)*10 + 9 |
def write_sq_normal(fname,qs,sq):
"""
Write S(Q) data in normal, gnuplot-readable format.
"""
nd = len(qs)
with open(fname,'w') as f:
f.write('# S(Q) computed in rdf.py\n')
f.write('# Q, S(Q)\n')
for i in range(nd):
f.write(' {0:10.4f} {1:10.5f}\n'.format(qs[i],sq[i]))
return None |
def calc_iou(box1, box2):
"""
:param box1: list of coordinates: row1, row2, col1, col2 [list]
:param box2: list of coordinates: row1, row2, col1, col2 [list]
:return: iou value
"""
xA = max(box1[0], box2[0])
yA = max(box1[1], box2[1])
xB = min(box1[2], box2[2])
yB = min(box1[3], box2[3])
# respective area of the two boxes
boxAArea = (box1[2] - box1[0]) * (box1[3] - box1[1])
boxBArea = (box2[2] - box2[0]) * (box2[3] - box2[1])
# overlap area
interArea = max(xB - xA, 0) * max(yB - yA, 0)
# IOU
iou = interArea / (boxAArea + boxBArea - interArea)
return iou |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.