content
stringlengths 42
6.51k
|
---|
def isOutput(parameter):
""" Checks if parameter is output parameter.
Returns True if parameter has key
'gisprompt.age' == 'new',
False otherwise.
"""
try:
if '@age' in parameter['gisprompt'].keys():
return (parameter['gisprompt']['@age'] == 'new')
else:
return False
except KeyError:
return False
|
def match(long, short):
"""
:param long: The DNA sequence to search.
:param short: DNA sequence that we want to match.
:return: Sub sequences that has the highest pairing rate.
"""
maximum = 0
homology = ''
for i in range(len(long)-len(short)+1):
# number of times that we have to pair.
dna = long[i:i + len(short)]
# sub sequences of long dna sequence.(starts form i == 0)
count = 0
for j in range(len(short)):
if short[j] == dna[j]:
count += 1
# How many nitrogenous base are matched in this sub sequences.
matched = count / len(short)
if matched > maximum:
maximum = matched
homology = dna
# sub sequences that has the highest pairing rate.
return homology
|
def get_jira_tag(html_tag):
"""
Convert from HTML tags to JIRA markdown
:param html_tag:
:return:
"""
html_to_jira_tags = {
'ol': '#',
'ul': '*',
'li': ''
}
if html_tag not in html_to_jira_tags:
return ''
else:
return html_to_jira_tags[html_tag]
|
def listify(item):
"""if item is not None and Not a list returns [item] else returns item"""
if item is not None and not isinstance(item, (list, tuple)):
item = [item]
return item
|
def type_name(obj):
"""Fetch the type name of an object.
This is a cosmetic shortcut. I find the normal method very ugly.
:param any obj: The object you want the type name of
:returns str: The type name
"""
return type(obj).__name__
|
def _sanitize_bin_name(name):
""" Sanitize a package name so we can use it in starlark function names """
return name.replace("-", "_")
|
def profit(initial_capital, multiplier):
"""
Return profit
:param initial_capital:
:param multiplier:
:return:
"""
r = initial_capital * (multiplier + 1.0) - initial_capital
return r
|
def trigrid(tripts):
"""
Return a grid of 4 points inside given 3 points as a list.
INPUT:
- ``tripts`` -- A list of 3 lists of the form [x,y] where x and y are the
Cartesian coordinates of a point.
OUTPUT:
A list of lists containing 4 points in following order:
- 1. Barycenter of 3 input points.
- 2,3,4. Barycenters of 1. with 3 different 2-subsets of input points
respectively.
EXAMPLES::
sage: from sage.matroids import matroids_plot_helpers
sage: points = matroids_plot_helpers.trigrid([[2,1],[4,5],[5,2]])
sage: points
[[3.6666666666666665, 2.6666666666666665],
[3.222222222222222, 2.888888888888889],
[4.222222222222222, 3.222222222222222],
[3.5555555555555554, 1.8888888888888886]]
.. NOTE::
This method does NOT do any checks.
"""
pairs = [[0, 1], [1, 2], [0, 2]]
cpt = list((float(tripts[0][0]+tripts[1][0]+tripts[2][0])/3,
float(tripts[0][1]+tripts[1][1]+tripts[2][1])/3))
grid = [cpt]
for p in pairs:
pt = list((float(tripts[p[0]][0]+tripts[p[1]][0]+cpt[0])/3,
float(tripts[p[0]][1]+tripts[p[1]][1]+cpt[1])/3))
grid.append(pt)
return grid
|
def rec_replace(in_str, old, new):
""" Recursively replace a string in a string """
if old == new:
return in_str
if old not in in_str:
return in_str
return rec_replace(in_str.replace(old, new), old, new)
|
def deg2dec(value):
"""
encode given `value` as sexagesimal string
:param float value: declination in decimal degrees
:return str: sring in sexagesmial form
"""
value = round(value, 5)
sign = 1
if value < 0:
sign = -1
value = abs(value)
dd, r1 = divmod(value, 1)
mm, r2 = divmod(r1*60, 1)
ss = r2*60
return "{0:+03d}:{1:02d}:{2:05.2f}".format(int(sign*dd), int(mm), ss)
|
def isAppleItem(item_pl):
"""Returns True if the item to be installed or removed appears to be from
Apple. If we are installing or removing any Apple items in a check/install
cycle, we skip checking/installing Apple updates from an Apple Software
Update server so we don't stomp on each other"""
# check receipts
for receipt in item_pl.get('receipts', []):
if receipt.get('packageid', '').startswith('com.apple.'):
return True
# check installs items
for install_item in item_pl.get('installs', []):
if install_item.get('CFBundleIdentifier', '').startswith('com.apple.'):
return True
# if we get here, no receipts or installs items have Apple
# identifiers
return False
|
def arg_return_greetings(name=""):
"""
This is greetings function with arguments and return greeting message
:param name:
:return:
"""
message = F"Hello {name}"
return message
|
def stable_unique(seq):
"""unique a seq and keep its original order"""
# See http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
|
def remove_suffix_ness(word):
"""
:param word: str of word to remove suffix from.
:return: str of word with suffix removed & spelling adjusted.
This function takes in a word and returns the base word with `ness` removed.
"""
# print(word[:-4])
word = word[:-4]
if word[-1] == "i":
return word[:-1] + "y"
else:
return word
|
def make_entity_name(name):
"""Creates a valid PlantUML entity name from the given value."""
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
name = name.replace(char, "_")
return name
|
def pulverizer(a, b):
"""return (g, x, y) such that a*x + b*y = g = gcd(a, b)"""
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
q, b, a = b // a, a, b % a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0
|
def do_sizes_match(imgs):
"""Returns if sizes match for all images in list."""
return len([*filter(lambda x: x.size != x.size[0], imgs)]) > 0
|
def get_digest_len(built_prims, prim_type):
""" Calculates the maximum digest length for a given primitive type """
retval = 0
for _, p in built_prims:
if p.prim_type == prim_type:
retval = max(retval, p.digest_len)
return retval
|
def hsv_to_rgb(h, s, v):
"""
Convert HSV to RGB (based on colorsys.py).
Args:
h (float): Hue 0 to 1.
s (float): Saturation 0 to 1.
v (float): Value 0 to 1 (Brightness).
"""
if s == 0.0:
return v, v, v
i = int(h * 6.0)
f = (h * 6.0) - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i % 6
v = int(v * 255)
t = int(t * 255)
p = int(p * 255)
q = int(q * 255)
if i == 0:
return v, t, p
if i == 1:
return q, v, p
if i == 2:
return p, v, t
if i == 3:
return p, q, v
if i == 4:
return t, p, v
if i == 5:
return v, p, q
|
def is_Float(s):
"""
returns True if the string s is a float number.
s: str, int, float
a string or a number
"""
try:
float(s)
return True
except:
return False
|
def find_kth(arr, k):
"""
Finds the kth largest element in the given array arr of integers,
:param: arr unsorted array of integers
:param: k, the order of value to return
:return: kth largest element in array
:rtype: int
"""
# sanity checks
# if this is not a valid integer or float, raise a ValueError
if not isinstance(k, (int, float)) or k < 0:
raise ValueError("Expected k to be a valid number")
# if k is 1 or is equal to 0, return the maximum in the given array
# if k is greater than the given length, it makes sense to return the maximum
if (k == 1 or k == 0) or k > len(arr):
return max(arr)
# convert given number to integer
kth = int(k)
# find the current maximum
current_max = max(arr)
# filter out the numbers that are not equal to the current maximum
new_array = list(filter(lambda x: x != current_max, arr))
# recurse and return the kth largest number in the given array
return find_kth(new_array, kth - 1)
|
def bb_intersection_over_union(boxA, boxB, if_return_areas=False):
"""
Taken from https://gist.github.com/meyerjo/dd3533edc97c81258898f60d8978eddc
both boxes should be in format [x1, y1, x2, y2]
"""
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = abs(max((xB - xA, 0)) * max((yB - yA), 0))
# if interArea == 0:
# return 0
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = abs((boxA[2] - boxA[0]) * (boxA[3] - boxA[1]))
boxBArea = abs((boxB[2] - boxB[0]) * (boxB[3] - boxB[1]))
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
if not if_return_areas:
return iou
else:
return iou, (interArea, boxAArea, boxBArea)
|
def gammacorrectbyte(lumbyte: int,
gamma: float) -> int:
"""Apply a gamma adjustment
to a byte
Args:
lumbyte: int value
gamma: float gamma adjust
Returns:
unsigned gamma adjusted byte
"""
return int(((lumbyte / 255) ** gamma) * 255)
|
def calcDictNative(points):
""" SELECT e.euler1, e.euler2, pc.`refine_keep`, pc.`postRefine_keep` """
alldict = {}
eulerdict = {}
postrefinedict = {}
for point in points:
### convert data
#print point
rad = float(point[0])
theta = float(point[1])
refinekeep = bool(point[2])
postrefinekeep = bool(point[3])
key = ( "%.3f,%.3f" % (rad, theta))
#print refinekeep,postrefinekeep,key
### sort points
if key in alldict:
alldict[key] += 1
else:
alldict[key] = 0
if refinekeep is True:
if key in eulerdict:
eulerdict[key] += 1
else:
eulerdict[key] = 0
if postrefinekeep is True:
if key in postrefinedict:
postrefinedict[key] += 1
else:
postrefinedict[key] = 0
#import pprint
#pprint.pprint( alldict)
return alldict, eulerdict, postrefinedict
|
def get_related_edges(nodes_list, graph):
"""
Returns all edges between nodes in a given list. All the nodes and edges are part of a graph
which is given as a Graph object.
:param nodes_list: A list of nodes
:param graph: A Graph object
:return: A list of edges
"""
node_id_list = map(lambda x: x.id, nodes_list)
node_id_set = set(node_id_list)
edges = []
for node in nodes_list:
if node.id in graph.incoming_edges:
for edge in graph.incoming_edges[node.id]:
if edge.start in node_id_set:
edges.append(edge)
return edges
|
def double_layer_cover_reflection_coefficient(tau_1, rho_1, rho_2) -> float:
"""
The reflection coefficient
Equation 8.15
:param float tau_1: the transmission coefficients of the first layer
:param float rho_1: the reflection coefficients of the first layer
:param float rho_2: the reflection coefficients of the second layer
:return: The reflection coefficient
"""
return rho_1 + (tau_1 * tau_1 * rho_2) / (1 - rho_1 * rho_2)
|
def dict_to_table(dictionary):
"""Return a string table from the supplied dictionary.
Note that the table should start on a new line and will insert a blank
line at the start of itself and at the end.
e.g. good:
"hello\n" + dict_to_table({"a": "b"})
e.g. bad:
"hello" + dict_to_table({"a": "b"})
>>> dict_to_table({"a": "b"})
'\\n| **a** | b |\\n\\n'
>>> dict_to_table({})
''
:dictionary: the string to be formatted as a code block
:returns: string of the new wrapped code block
"""
block = ""
if dictionary:
block = "\n"
for (key, value) in dictionary.iteritems():
block += "| **" + str(key) + "** | " + str(value) + " |\n"
block += "\n"
return block
|
def isInside(point_x, point_y, area_left, area_top, area_width, area_height):
"""
Returns `True` if the point of `point_x`, `point_y` is inside the area
described, inclusive of `area_left` and `area_top`.
>>> isInside(0, 0, 0, 0, 10, 10)
True
>>> isInside(10, 0, 0, 0, 10, 10)
False
"""
return (area_left <= point_x < area_left + area_width) and (area_top <= point_y < area_top + area_height)
|
def byte_to_hex(byteStr):
""" Convert byte sequences to a hex string. """
return ''.join(["%02X " % ord(x) for x in byteStr]).strip()
|
def get_provenance_record(caption: str, ancestors: list):
"""Create a provenance record describing the diagnostic data and plots."""
record = {
'caption':
caption,
'domains': ['reg'],
'authors': [
'kalverla_peter',
'smeets_stef',
'brunner_lukas',
'camphuijsen_jaro',
],
'references': [
'brunner2019',
'lorenz2018',
'knutti2017',
],
'ancestors':
ancestors,
}
return record
|
def str_to_pi_list(inp):
"""
Parameters
----------
inp Input string
Returns A list of pi expressions
-------
"""
lines = inp.strip().splitlines()
lis = []
for line in lines:
if line == "None":
return []
lis.append(line)
return lis
|
def fahrenheit_to_celsius(deg_F):
"""Convert degrees Fahrenheit to Celsius."""
return (5 / 9) * (deg_F - 32)
|
def delta(
t1,
tauv,
taue,
tauev,
t0c,
tzc,
txc,
dzi,
dxi,
dz2i,
dx2i,
vzero,
vref,
sgntz,
sgntx,
):
"""Solve quadratic equation."""
ta = tauev + taue - tauv
tb = tauev - taue + tauv
apoly = dz2i + dx2i
bpoly = 4.0 * (sgntx * txc * dxi + sgntz * tzc * dzi) - 2.0 * (
ta * dx2i + tb * dz2i
)
cpoly = (
(ta ** 2.0 * dx2i)
+ (tb ** 2.0 * dz2i)
- 4.0 * (sgntx * txc * dxi * ta + sgntz * tzc * dzi * tb)
+ 4.0 * (vzero ** 2.0 - vref ** 2.0)
)
dpoly = bpoly ** 2.0 - 4.0 * apoly * cpoly
return 0.5 * (dpoly ** 0.5 - bpoly) / apoly + t0c if dpoly >= 0.0 else t1
|
def check_x_lim(x_lim, max_x):
"""
Checks the specified x_limits are valid and sets default if None.
"""
if x_lim is None:
x_lim = (None, None)
if len(x_lim) != 2:
raise ValueError("The x_lim parameter must be a list of length 2, or None")
try:
if x_lim[0] is not None and x_lim[0] < 0:
raise ValueError("x_lim[0] cannot be negative")
if x_lim[1] is not None and x_lim[1] > max_x:
raise ValueError("x_lim[1] cannot be greater than the sequence length")
if x_lim[0] is not None and x_lim[1] is not None and x_lim[0] >= x_lim[1]:
raise ValueError("x_lim[0] must be less than x_lim[1]")
except TypeError:
raise TypeError("x_lim parameters must be numeric")
return x_lim
|
def _stripped_codes(codes):
"""Return a tuple of stripped codes split by ','."""
return tuple([
code.strip() for code in codes.split(',')
if code.strip()
])
|
def euklid_dist(coord1, coord2):
"""
Return euklidian distance between atoms coord1 and coord2.
"""
xd2 = (coord1[0]-coord2[0]) ** 2
yd2 = (coord1[1]-coord2[1]) ** 2
zd2 = (coord1[2]-coord2[2]) ** 2
return (xd2 + yd2 + zd2)**0.5
|
def dump_uint(n):
"""
Constant-width integer serialization
:param writer:
:param n:
:param width:
:return:
"""
buffer = []
while n:
buffer.append(n & 0xff)
n >>= 8
return buffer
|
def get_slurm_script_gpu(output_dir, command):
"""Returns contents of SLURM script for a gpu job."""
return """#!/bin/bash
#SBATCH -N 1
#SBATCH --ntasks-per-node=1
#SBATCH --ntasks-per-socket=1
#SBATCH --gres=gpu:tesla_v100:1
#SBATCH --cpus-per-task=8
#SBATCH --mem=256000
#SBATCH --output={}/slurm_%j.out
#SBATCH -t 24:00:00
#module load anaconda3 cudatoolkit/10.0 cudnn/cuda-10.0/7.3.1
#source activate yumi
{}
""".format(
output_dir, command
)
|
def is_unlimited(rate_limit):
"""
Check whether a rate limit is None or unlimited (indicated by '-1').
:param rate_limit: the rate limit to check
:return: bool
"""
return rate_limit is None or rate_limit == -1
|
def exgcd(a, b):
"""
Solve a*x + b*y = gcd(a, b)
:param a:
:param b:
:return: gcd, x, y
"""
if a == 0:
return b, 0, 1
g, y, x = exgcd(b % a, a)
return g, x-(b//a)*y, y
|
def reorder_frameID(frame_dict):
"""
reorder the frames dictionary in a ascending manner
:param frame_dict: a dict with key = frameid and value is a list of lists [object id, x, y, w, h] in the frame, dict
:return: ordered dict by frameid
"""
keys_int = sorted([int(i) for i in frame_dict.keys()])
new_dict = {}
for key in keys_int:
new_dict[str(key)] = frame_dict[str(key)]
return new_dict
|
def sumTo(n):
"""Sum from 0 to given numbers"""
sum = int((n * (n + 1)) / 2)
return sum
|
def strrep(text, old, new):
"""
Replaces all the occurrences of a substring into a new one
Parameters
----------
text : str
the string where to operate
old : str
the substring to be replaced
new : str
the new substring
Returns
-------
str
The new string
"""
return text.replace(old, new)
|
def builder_support(builder):
"""Return True when builder is supported. Supported builders output in
html format, but exclude `PickleHTMLBuilder` and `JSONHTMLBuilder`,
which run into issues when serializing blog objects."""
if hasattr(builder, 'builder'):
builder = builder.builder
not_supported = set(['json', 'pickle'])
return builder.format == 'html' and not builder.name in not_supported
|
def problem_2(number_str_1, number_str_2):
""" Given two strings, return `True` if adding both those numbers in Python
would result in an `int`. Otherwise if it would return something else, like
a `float`, return `False`.
For example if you got "4" and "3.5", you would return `False`.
Assume that the strings passed in only contain valid numbers with no whitespace,
for example won't get "foobar", " 5.56 ", or "3.3.3".
"""
one_is_int, two_is_int = "." not in number_str_1, "." not in number_str_2
return one_is_int and two_is_int
|
def _get_element(lists, indices):
"""Gets element from nested lists of arbitrary depth."""
result = lists
for i in indices:
result = result[i]
return result
|
def polygon_area(points_list, precision=100):
"""Calculate area of an arbitrary polygon using an algorithm from the web.
Return the area of the polygon as a positive float.
Arguments:
points_list -- list of point tuples [(x0, y0), (x1, y1), (x2, y2), ...]
(Unclosed polygons will be closed automatically.
precision -- Internal arithmetic precision (integer arithmetic).
>>> polygon_area([(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 0), (0, 0)])
3.0
Credits:
Area of a General Polygon by David Chandler
http://www.davidchandler.com/AreaOfAGeneralPolygon.pdf
"""
# Scale up co-ordinates and convert them to integers.
for i in range(len(points_list)):
points_list[i] = (int(points_list[i][0] * precision),
int(points_list[i][1] * precision))
# Close polygon if not closed.
if points_list[-1] != points_list[0]:
points_list.append(points_list[0])
# Calculate area.
area = 0
for i in range(len(points_list)-1):
(x_i, y_i) = points_list[i]
(x_i_plus_1, y_i_plus_1) = points_list[i+1]
area = area + (x_i_plus_1 * y_i) - (y_i_plus_1 * x_i)
area = abs(area / 2)
# Unscale area.
area = float(area)/(precision**2)
return area
|
def extract_pose_sequence(pose_results, frame_idx, causal, seq_len, step=1):
"""Extract the target frame from 2D pose results, and pad the sequence to a
fixed length.
Args:
pose_results (List[List[Dict]]): Multi-frame pose detection results
stored in a nested list. Each element of the outer list is the
pose detection results of a single frame, and each element of the
inner list is the pose information of one person, which contains:
keypoints (ndarray[K, 2 or 3]): x, y, [score]
track_id (int): unique id of each person, required when
``with_track_id==True```
bbox ((4, ) or (5, )): left, right, top, bottom, [score]
frame_idx (int): The index of the frame in the original video.
causal (bool): If True, the target frame is the last frame in
a sequence. Otherwise, the target frame is in the middle of a
sequence.
seq_len (int): The number of frames in the input sequence.
step (int): Step size to extract frames from the video.
Returns:
List[List[Dict]]: Multi-frame pose detection results stored in a
nested list with a length of seq_len.
int: The target frame index in the padded sequence.
"""
if causal:
frames_left = seq_len - 1
frames_right = 0
else:
frames_left = (seq_len - 1) // 2
frames_right = frames_left
num_frames = len(pose_results)
# get the padded sequence
pad_left = max(0, frames_left - frame_idx // step)
pad_right = max(0, frames_right - (num_frames - 1 - frame_idx) // step)
start = max(frame_idx % step, frame_idx - frames_left * step)
end = min(num_frames - (num_frames - 1 - frame_idx) % step,
frame_idx + frames_right * step + 1)
pose_results_seq = [pose_results[0]] * pad_left + \
pose_results[start:end:step] + [pose_results[-1]] * pad_right
return pose_results_seq
|
def erase_none_val_from_list(list_values):
"""
Parameters
----------
list_values : list
List with different values
Returns
-------
list_no_nones : list
List with extract of list_values. No more None values included
"""
list_no_nones = []
for val in list_values:
if val is not None:
list_no_nones.append(val)
return list_no_nones
|
def celery_config(celery_config):
"""Celery configuration (defaults to eager tasks).
Scope: module
This fixture provides the default Celery configuration (eager tasks,
in-memory result backend and exception propagation). It can easily be
overwritten in a specific test module:
.. code-block:: python
# test_something.py
import pytest
pytest.fixture(scope='module')
def celery_config(celery_config):
celery_config['CELERY_ALWAYS_EAGER'] = False
return celery_config
"""
celery_config.update(dict(
CELERY_ALWAYS_EAGER=True,
CELERY_CACHE_BACKEND='memory',
CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
CELERY_RESULT_BACKEND='cache',
))
return celery_config
|
def conv_F2C(value):
"""Converts degree Fahrenheit to degree Celsius.
Input parameter: scalar or array
"""
value_c = (value-32)*(5/9)
if(hasattr(value_c, 'units')):
value_c.attrs.update(units='degC')
return(value_c)
|
def get_nonisomorphic_matroids(MSet):
"""
Return non-isomorphic members of the matroids in set ``MSet``.
For direct access to ``get_nonisomorphic_matroids``, run::
sage: from sage.matroids.advanced import *
INPUT:
- ``MSet`` -- an iterable whose members are matroids.
OUTPUT:
A list containing one representative of each isomorphism class of
members of ``MSet``.
EXAMPLES::
sage: from sage.matroids.advanced import *
sage: L = matroids.Uniform(3, 5).extensions()
sage: len(list(L))
32
sage: len(get_nonisomorphic_matroids(L))
5
"""
OutSet = []
for M in MSet:
seen = False
for N in OutSet:
if N.is_isomorphic(M):
seen = True
break
if not seen:
OutSet.append(M)
return OutSet
|
def getPMUtiming(lines):
"""
Function to get the timing for the PMU recording.
Parameters
----------
lines : list of str
list with PMU file lines
To improve speed, don't pass the first line, which contains the raw data.
Returns
-------
MPCUTime : list of two int
MARS timestamp (in ms, since the previous midnight) for the start and finish
of the signal logging, respectively
MDHTime : list of two int
Mdh timestamp (in ms, since the previous midnight) for the start and finish
of the signal logging, respectively
"""
MPCUTime = [0,0]
MDHTime = [0,0]
for l in lines:
if 'MPCUTime' in l:
ls = l.split()
if 'LogStart' in l:
MPCUTime[0]= int(ls[1])
elif 'LogStop' in l:
MPCUTime[1]= int(ls[1])
if 'MDHTime' in l:
ls = l.split()
if 'LogStart' in l:
MDHTime[0]= int(ls[1])
elif 'LogStop' in l:
MDHTime[1]= int(ls[1])
return MPCUTime, MDHTime
|
def _get_query_names_by_table_column_tuple(table_name, dwsupport_model):
"""
Helper function,returns Dict representing query names
Dict is indexed by tuples of (table, column) names for fields which
belong to the listed queries
Keyword Parameters:
source_id -- Sting, identifying the project table to return
columns for
dwsupport_model -- Dict, representing current DWSupport schema
>>> # Check return format
>>> from pprint import pprint
>>> test_table = 'catch_fact'
>>> model = { 'tables': [ { 'name': 'catch_fact', 'type': 'fact'
... ,'project': 'trawl'}
... ,{ 'name': 'depth_dim', 'type': 'dimension'
... ,'project': 'warehouse'}
... ,{ 'name': 'operation_fact', 'type': 'fact'
... ,'project': 'acoustics'}]
... ,'associations': [ { 'table': 'catch_fact'
... ,'parent': 'depth_dim'}
... ,{ 'table': 'operation_fact'
... ,'parent': 'depth_dim'}]
... ,'variables': [ { 'table': 'catch_fact'
... ,'column': 'retained_kg'}
... ,{ 'table': 'catch_fact'
... ,'column': 'retained_ct'}
... ,{ 'table': 'depth_dim'
... ,'column': 'meters'}
... ,{ 'table': 'depth_dim'
... ,'column': 'fathoms'}
... ,{ 'table': 'operation_fact'
... ,'column': 'frequency_mhz'}]
... ,'variable_custom_identifiers': [
... { 'id': 'freq', 'table': 'operation_fact'
... ,'column': 'frequency_mhz'}]
... ,'queries': [
... {'name': 'core',
... 'table': 'catch_fact',
... 'variables': {'depth_dim': ['meters'],
... 'catch_fact': ['retained_kg']}
... }]
... }
>>> out = _get_query_names_by_table_column_tuple(test_table, model)
>>> pprint(out)
{('catch_fact', 'retained_kg'): ['core'], ('depth_dim', 'meters'): ['core']}
"""
query_names_by_table_column_tuple = dict()
for query in dwsupport_model['queries']:
if query['table'] == table_name:
query_name = query['name']
for variable_table, columns in query['variables'].items():
for variable_column in columns:
key = variable_table, variable_column
try:
query_names_by_table_column_tuple[key].append(query_name)
except KeyError:
query_names_by_table_column_tuple[key] = [query_name]
return query_names_by_table_column_tuple
|
def format_td(td):
"""
Nicely format a timedelta object
as HH:MM:SS
"""
if td is None:
return "unknown"
if isinstance(td, str):
return td
seconds = int(td.total_seconds())
h = seconds // 3600
seconds = seconds % 3600
m = seconds // 60
seconds = seconds % 60
return "{h:02}:{m:02}:{seconds:02}".format(h=h, m=m, seconds=seconds)
|
def response_with_headers(headers):
"""
Content-Type: text/html
Set-Cookie: user=gua
"""
header = 'HTTP/1.1 210 VERY OK\r\n'
header += ''.join(['{}: {}\r\n'.format(k, v)
for k, v in headers.items()])
return header
|
def sex_to_dec(s):
"""Convert sexigisimal-formatted string/integer to a decimal degree value."""
s = format(int(s), '07d')
degree, arcmin, arcsec = s[:3], s[3:5], s[5:]
return float(degree) + float(arcmin) / 60 + float(arcsec) / 3600
|
def API_package(API):
"""
Returns the package of API
"""
return API.split('->')[0]
|
def split_data(iterable, pred):
"""
Split data from ``iterable`` into two lists.
Each element is passed to function ``pred``; elements
for which ``pred`` returns True are put into ``yes`` list,
other elements are put into ``no`` list.
>>> split_data(["foo", "Bar", "Spam", "egg"], lambda t: t.istitle())
(['Bar', 'Spam'], ['foo', 'egg'])
"""
yes, no = [], []
for d in iterable:
if pred(d):
yes.append(d)
else:
no.append(d)
return yes, no
|
def rate2height(rain_flow_rate, duration):
"""
convert the rain flow rate to the height of rainfall in [mm]
if 2 array-like parameters are give, a element-wise calculation will be made.
So the length of the array must be the same.
Args:
rain_flow_rate (float | np.ndarray | pd.Series): in [l/(s*ha)]
duration (float | np.ndarray | pd.Series): in minutes
Returns:
float | np.ndarray | pd.Series: height of rainfall in [mm]
"""
return rain_flow_rate * duration / (1000 / 6)
|
def sorted_keys(grouped_events):
"""Sort events by thread names"""
keys = list(grouped_events.keys())
keys = sorted(keys, key=lambda s: s.split('|')[-1])
return list(reversed(keys))
|
def remove_spaces(s):
"""variable value is used locally """
value = s
if value is None:
return None
if type(s) is not str:
raise TypeError("you messed up")
if value == "":
return ""
if value[0] != " ":
return value[0] + remove_spaces(value[1:])
else:
return remove_spaces(value[1:])
|
def generate_freenas_volume_name(name, iqn_prefix):
"""Create FREENAS volume / iscsitarget name from Cinder name."""
backend_volume = 'volume-' + name.split('-')[1]
backend_target = 'target-' + name.split('-')[1]
backend_iqn = iqn_prefix + backend_target
return {'name': backend_volume, 'target': backend_target, 'iqn': backend_iqn}
|
def parse_tuple(tuple_string):
"""
strip any whitespace then outter characters.
"""
return tuple_string.strip().strip("\"[]")
|
def part1(depths):
"""
Count the number of times a depth measurement increases from the previous measurement
How many measurements are larger than the previous measurement?
"""
depth_increases = 0
previous_depth = depths[0]
for depth in depths:
if depth > previous_depth:
depth_increases += 1
previous_depth = depth
return depth_increases
|
def best_and_worst_hour(percentages):
"""
Args:
percentages: output of compute_percentage
Return: list of strings, the first element should be the best hour,
the second (and last) element should be the worst hour. Hour are
represented by string with format %H:%M
e.g. ["18:00", "20:00"]
"""
#position [0] returns: profit = 0, and [1] returns time
hora = 1
# Calculate the best and worst hour:
bestHour = max(zip(percentages.values(), percentages.keys()))
worstHour = min(zip(percentages.values(), percentages.keys()))
return [bestHour[hora], worstHour[hora]]
|
def str_to_hex(value: str) -> str:
"""Convert a string to a variable-length ASCII hex string."""
if not isinstance(value, str):
raise ValueError(f"Invalid value: {value}, is not a string")
return "".join(f"{ord(x):02X}" for x in value)
|
def weightSlice (S1, S2, f):
"""Calculates the interpolated result intermediate between two slices:
result = (1.-f)*S1 + f*S2"""
ns = len (S1)
rt = []
for i in range (0, ns):
if S1[i][0] < 0 or S2[i][0] < 0:
rt.append ((-32767.,-32767.,-32767.))
else:
r0 = (1. - f) * S1[i][0] + f * S2[i][0]
r1 = (1. - f) * S1[i][1] + f * S2[i][1]
r2 = (1. - f) * S1[i][2] + f * S2[i][2]
rt.append((r0,r1,r2))
return rt
|
def get_drop_type(group_name):
"""
A function to map devlink trap group names into unified Mellanox WJH drop types.
"""
return group_name.split("_")[0]
|
def getXOutside(y):
"""
Funcion para generar una parabola con el embone hacia la izquierda <
:param y: valor de y
:return: valor de x
"""
return 5*(y**2) - 5*y + 1
|
def is_maple_invoke_dync_bp_plt_disabled(buf):
"""
determine where Maple breakpoint plt disable or not
params:
buf: a string output of m_util.gdb_exec_to_str("info b")
"""
match_pattern = "<maple::InvokeInterpretMethod(maple::DynMFunction&)@plt>"
buf = buf.split('\n')
for line in buf:
if match_pattern in line:
on_off = line.split()[1]
if on_off is 'y': # it is enabled
return False
else:
return True
return True
|
def needs_escaping(text: str) -> bool:
"""Check whether the ``text`` contains a character that needs escaping."""
for character in text:
if character == "\a":
return True
elif character == "\b":
return True
elif character == "\f":
return True
elif character == "\n":
return True
elif character == "\r":
return True
elif character == "\t":
return True
elif character == "\v":
return True
elif character == '"':
return True
elif character == "\\":
return True
else:
pass
return False
|
def triangleArea(ax, ay, bx, by, cx, cy):
"""Returns the area of a triangle given its 3 vertices in
cartesian coordinates.
"""
# Formula found in:
# http://www.mathopenref.com/coordtrianglearea.html
return abs(ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) / 2
|
def get_line_column(data, line, column, position):
"""Returns the line and column of the given position in the string.
Column is 1-based, that means, that the first character in a line has column
equal to 1. A line with n character also has a n+1 column, which sits just
before the newline.
Args:
data: the original string.
line: the line at which the string starts.
column: the column at which the string starts.
position: the position within the string. It is 0-based.
Returns:
A tuple (line, column) with the offset of the position.
"""
data = data[:position]
toks = data.splitlines()
if not toks or data[-1] in '\n\r':
toks.append('')
if len(toks) > 1:
return line + len(toks) - 1, 1 + len(toks[-1])
else:
return line, column + position
|
def _is_noop_report(report):
"""
Takes report and checks for needed fields
:param report: list
:rtype: bool
"""
try:
return 'noop' in report['summary']['events']
except (KeyError, AttributeError, TypeError):
return False
|
def format_string(string: str) -> str:
"""Replace specific unicode characters with ASCII ones.
Args:
string: Unicode string.
Returns:
ASCII string.
"""
string \
.replace("\u2013", "-") \
.replace("\u00a0", " ") \
.replace("\u2018", "'") \
.replace("\u2019", "'") \
.replace("\u201c", '"') \
.replace("\u201d", '"') \
.replace("\u00ed", 'i')
return string
|
def find_matrix(document):
"""
Find **matrix** in document.
The spline syntax allows following definitions:
- **'matrix'** - ordered execution of each pipeline (short form)
- **'matrix(ordered)'** - ordered execution of each pipeline (more readable form)
- **'matrix(parallel)'** - parallel execution of each pipeline
Args:
document (dict): validated spline document loaded from a yaml file.
Returns:
list: matrix as a part of the spline document or an empty list if not given.
>>> find_matrix({})
[]
>>> find_matrix({'matrix': [1]})
[1]
>>> find_matrix({'matrix(ordered)': [2]})
[2]
>>> find_matrix({'matrix(parallel)': [3]})
[3]
"""
return document['matrix'] if 'matrix' in document \
else document['matrix(ordered)'] if 'matrix(ordered)' in document \
else document['matrix(parallel)'] if 'matrix(parallel)' in document \
else []
|
def calcPositions(M=1, a=1, e=0, p=0.5):
"""
Given total mass of system M, semimajor axis a, and percentage of total mass contained in primary star p,
calculate positions of binary components keep COM at origin
(ex: If 1Msol system and MPri = Msec = 0.5 -> M =1 -> p = 0.5)
Assume stars start a perihelion
Deprecated
Parameters
----------
M : float
Total mass of system (Msol)
a : float
Semimajor axis (au)
e : float
eccentricity
p : float
% of total mass contained in primary (m1)
Returns
-------
x1, x2: float
Semimajor axes of binary stars assuming that they start at perihelion.
"""
# Compute masses
m1 = p * M
m2 = (M - m1)
# Calculate each star's semi-major axis a1,a2
a1 = (m2 / M) * a
a2 = (m1 / M) * a
# Assume both stars star at perihelion (true anomaly = 0)
x1 = a1 * (1 - e * e) / (1 + e)
x2 = -1 * a2 * (1 - e * e) / (1 + e)
return x1, x2
|
def _format_app_object_string(app_objects):
"""Format app object string to store in test case."""
app_string = ''
print("app_objects==============", app_objects)
for key in app_objects:
print("6666666666666666666666666", key)
app_string = app_string + " ' " + key + " ' :" + app_objects[key] + ",\n"+" " * 8
print("app_string=================" + app_string)
app_string = "{}".format(app_string)
return app_string
|
def num_from_str(s):
"""Return a number from a string."""
try:
return int(s)
except ValueError:
try:
return float(s)
except ValueError:
raise ValueError(
'Can not convert the string "' + s + '" into a numeric value.'
)
|
def drop_prefix(s, start):
"""Remove prefix `start` from sting `s`. Raises a :py:exc:`ValueError`
if `s` didn't start with `start`."""
l = len(start)
if s[:l] != start:
raise ValueError('string does not start with expected value')
return s[l:]
|
def smi_spliter(smi):
"""
Tokenize a SMILES molecule or reaction
"""
import re
pattern = "(\[[^\]]+]|Br?|Cl?|N|O|S|P|F|I|b|c|n|o|s|p|\(|\)|\.|=|#|-|\+|\\\\|\/|:|~|@|\?|>|\*|\$|\%[0-9]{2}|[0-9])"
regex = re.compile(pattern)
tokens = [token for token in regex.findall(smi)]
assert smi == ''.join(tokens)
return tokens
|
def _limits(band):
""" Returns initialisation wavelength and termination wavelength """
limits = {'g':(3990.0, 5440.0), 'r':(5440.0, 6960.0), 'r':(5440.0, 6960.0),
'i':(6960.0, 8500.0), 'z':(8500.0, 9320.0), 'y':(9320.0, 10760.0)}
return limits[band]
|
def update_balance(iteration_balance, contribution, current_year_tuple):
""" Takes in a single year's data during a single simulation and updates the balance. """
STOCK_RATE = 0
BOND_RATE = 1
STOCK_PCT = 2
iteration_balance = iteration_balance + contribution
stock_balance = iteration_balance * current_year_tuple[STOCK_PCT]
bond_balance = iteration_balance * (1-current_year_tuple[STOCK_PCT])
stock_balance += (stock_balance * current_year_tuple[STOCK_RATE])
bond_balance += (bond_balance * current_year_tuple[BOND_RATE])
#print("Portfolio started at " + str(iteration_balance) + " and after a year of " + str(current_year_tuple[STOCK_RATE]) + " change it is now at: " + str(stock_balance + bond_balance))
iteration_balance = stock_balance + bond_balance
return iteration_balance
|
def selection_sort(marks):
"""Function to return a sorted list using the selection sort algorithm."""
for i in range(len(marks)):
min = i
for j in range(i+1, len(marks)):
if marks[min] > marks[j]:
min = j
marks[i], marks[min] = marks[min], marks[i]
return marks
|
def get_formatted_string(text, width, formatted=True):
"""Return text with trailing spaces."""
return " " + text + " " + (" " * (width - len(text))) if formatted else text
|
def get_root_name(fp):
"""Get the root name of a Python simulation.
Extracts both the file path and the root name of the simulation.
Parameters
----------
fp: str
The directory path to a Python .pf file
Returns
-------
root: str
The root name of the Python simulation
where: str
The directory path containing the provided Python .pf file
"""
if type(fp) is not str:
raise TypeError("expected a string as input for the file path, not whatever you put")
dot = fp.rfind(".")
slash = fp.rfind("/")
root = fp[slash + 1:dot]
fp = fp[:slash + 1]
if fp == "":
fp = "./"
return root, fp
|
def update_Q(Qsa, Qsa_next, reward, alpha = 0.01, gamma = 0.9):
""" updates the action-value function estimate using the most recent time step """
return Qsa + (alpha * (reward + (gamma * Qsa_next) - Qsa))
|
def nonify_string(string):
"""Return stripped string unless string is empty string, then return None.
"""
if string is None:
return None
string = str(string).strip()
if len(string) == 0:
return None
return string
|
def calc_var_indices(input_vars, affected_vars):
"""Calculate indices of `affected_vars` in `input_vars`"""
if affected_vars is None:
return None
return [ input_vars.index(var) for var in affected_vars ]
|
def two_strings(s1: str, s2: str) -> str:
"""
>>> two_strings("hello", "world")
'YES'
>>> two_strings("hi", "world")
'NO'
"""
intersection = {*s1} & {*s2}
return "YES" if intersection else "NO"
|
def rec_pts(rec, yds, tds):
"""
multi line strings in python are between three double quotes
it's not required, but the convention is to put what the fn does in one of these multi line strings (called "docstring") right away in function
this function takes number of recieving: yards, receptions and touchdowns and returns fantasy points scored (ppr scoring)
"""
return yds*0.1 + rec*1 + tds*6
|
def pretty_time_delta(seconds: int) -> str:
"""Format seconds timedelta to days, hours, minutes, seconds
:param seconds: Seconds representing a timedelta
:return: Formatted timedelta
:Example:
>>> pretty_time_delta(3601)
'1h0m1s'
>>> pretty_time_delta(-3601)
'-1h0m1s'
"""
sign_string = "-" if seconds < 0 else ""
seconds = abs(int(seconds))
days, seconds = divmod(seconds, 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
if days > 0:
return "%s%dd%dh%dm%ds" % (sign_string, days, hours, minutes, seconds)
elif hours > 0:
return "%s%dh%dm%ds" % (sign_string, hours, minutes, seconds)
elif minutes > 0:
return "%s%dm%ds" % (sign_string, minutes, seconds)
else:
return "%s%ds" % (sign_string, seconds)
|
def clean_query_string(string: str):
""" Cleans string of ' 's and 's """
string.replace(' ', '%20')
string.replace(',', '')
return string
|
def render_pep440_pre(pieces):
"""TAG[.post2.devRUN_NUMBER] -- No -dirty.
Exceptions:
1: no tags. 0.post2.devRUN_NUMBER
"""
if pieces["closest-tag"]:
rendered = pieces["closest-tag"]
# this needs to stay distance, run_number is always non-zero
if pieces["distance"]:
rendered += ".post2.dev%d" % pieces["run_number"]
else:
# exception #1
rendered = "0.post2.dev%d" % pieces["distance"]
return rendered
|
def _strip_empty(d):
"""Strips entries of dict with no value, but allow zero."""
return {
k: v
for k, v in d.items()
if v or (type(v) == int and v == 0) or (type(v) == str and v == "")
}
|
def id(obj): # pylint: disable=redefined-builtin,invalid-name
"""Return ``id`` key of dict."""
return obj['__id']
|
def remap(obj, mapping):
"""
Helper method to remap entries in a list or keys in a dictionary
based on an input map, used to translate symbols to properties
and vice-versa
Args:
obj ([] or {} or set) a list of properties or property-keyed
dictionary to be remapped using symbols.
mapping ({}): dictionary of values to remap
Returns:
remapped list of items or item-keyed dictionary
"""
if isinstance(obj, dict):
new = {mapping.get(in_key) or in_key: obj.get(in_key)
for in_key in obj.keys()}
else:
new = [mapping.get(in_item) or in_item for in_item in obj]
if isinstance(obj, set):
new = set(new)
return new
|
def removeFromStart(text, toRemove, ignoreCase=None):
"""returns the text with "toRemove" stripped from the start if it matches
>>> removeFromStart('abcd', 'a')
u'bcd'
>>> removeFromStart('abcd', 'not')
u'abcd'
working of ignoreCase:
>>> removeFromStart('ABCD', 'a')
u'ABCD'
>>> removeFromStart('ABCD', 'ab', ignoreCase=1)
u'CD'
>>> removeFromStart('abcd', 'ABC', ignoreCase=1)
u'd'
"""
if ignoreCase:
text2 = text.lower()
toRemove = toRemove.lower()
else:
text2 = text
if text2.startswith(toRemove):
return text[len(toRemove):]
else:
return text
|
def dict_to_vega_dataset(data_dict):
""" Convert a dictionary of values, such as that produced by COBRApy, into a Vega
dataset (array of data elements)
Args:
data_dict (:obj:`dict`): dictionary that maps the labels of predicted variables
to their predicted values
Returns:
:obj:`list`: list of data elements, each with two keys ``label`` and `values`` whose values
are the labels of each variable and an array of their predicted values
"""
data_set = []
for id, val in data_dict.items():
data_set.append({
'label': id,
'values': val if isinstance(val, list) else [val]
})
return data_set
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.