content
stringlengths 42
6.51k
|
---|
def create_video_string(videoId):
"""
Function which accepts a videoId arg and returns sql string
param:
videoId = '342z248z'
returns:
" AND video_id in (342, 248)"
"""
video_list = videoId.split('z')
video_string = " AND video_id in ("
for video_id in video_list:
video_string = video_string + str(video_id) + ', '
return video_string[:-4] + ')'
|
def is_int_like(value):
"""Returns whether the value can be used as a standard integer.
>>> is_int_like(4)
True
>>> is_int_like(4.0)
False
>>> is_int_like("4")
False
>>> is_int_like("abc")
False
"""
try:
if isinstance(value, int): return True
return int(value) == value and str(value).isdigit()
except:
return False
|
def prepare_string(string):
"""
Prepare string of command output as a list for parsing results
"""
args = None
try:
string = string.decode("utf-8")
args = string.split(",")
except Exception:
raise
return args
|
def multikeysort(dictlist, columns):
"""Sorts on arbitrary multiple columns of a dictionary.
`columns` is a list of column names. Any names prefixed with '-' are
sorted in descending order
Inspired by: https://stackoverflow.com/questions/1143671/python-sorting-list-of-dictionaries-by-multiple-keys
"""
import operator
# produce a list of tuples where the first is the cleaned-up column name
# and the second is a bool for whether to reverse the sort order
comparers = []
for column in columns:
if column.startswith("-"):
comparers.append(
(operator.itemgetter(column[1:].strip()),
True)
)
else:
comparers.append(
(operator.itemgetter(column.strip()),
False)
)
"""Because Python uses a stable algorithm, we can sort by multiple keys
by sorting the comparers list in reverse order
Note that because the specific algorithm is Timsort, multiple sorts are
efficient because we take advantage of anything already in order in the
dataset
https://docs.python.org/3/howto/sorting.html
"""
for fn, reverse in comparers[::-1]:
dictlist.sort(key=fn, reverse=reverse)
return dictlist
|
def printIt(p):
"""
Input is decimal list.
Returns character list corresponding to that decimal list
"""
s=""
for byte in p:
s=s+chr(byte)
return s
|
def add(a, b):
""" Returns the sum of two numbers."""
a, b = int(a), int(b)
c = str(a + b)
print("a = {} and b = {} and a + b = {}".format(a, b, c))
return c
|
def union(set1, set2):
"""
set1 and set2 are collections of objects, each of which might be empty.
Each set has no duplicates within itself, but there may be objects that
are in both sets. Objects are assumed to be of the same type.
This function returns one set containing all elements from
both input sets, but with no duplicates.
"""
if len(set1) == 0:
return set2
elif set1[0] in set2:
return union(set1[1:], set2)
else:
return set1[0] + union(set1[1:], set2)
|
def mils(value):
"""Returns number in millions of dollars"""
try:
value = float(value) / 1000000
except (ValueError, TypeError, UnicodeEncodeError):
return ''
return '${0:,}M'.format(value)
|
def email(
message_type,
plaintext_body,
reply_to,
sender_address,
sender_name,
subject,
html_body=None,
variable_defaults=None,
):
"""
Required platform override when email in ua.device_types.
Specifies content of the email being sent. All other notification
fields are not used in the email if included.
See https://docs.urbanairship.com/api/ua/#schemas%2femailoverrideobject
for additional caveats.
:param message_type: Required. One of transactional or commercial.
:param plaintext_body: Required. The plain text body of the email. May include
variable substitution fields for use with create and send inline templates.
:param reply_to: Required. The reply-to address.
:param sender_address: Required. The email address of the sender.
The domain of the email must be enabled in the email
provider at the delivery tier.
:param sender_name: Required. The common name of the email sender.
:param subject: Required. The subject line of the email. May include variable
substitution fields for use with create and send inline templates.
:param html_body: Optional. The HTML content of the email.
:param variable_details: Required for CreateAndSendPush with inline templates.
a list of dicts of default values for inline template variables.
"""
if message_type not in ("transactional", "commercial"):
raise ValueError("message_type must be either transactional or commercial")
payload = {}
payload["message_type"] = message_type
payload["reply_to"] = reply_to
payload["sender_address"] = sender_address
payload["sender_name"] = sender_name
alert_payload = {"subject": subject, "plaintext_body": plaintext_body}
if html_body is not None:
alert_payload["html_body"] = html_body
if variable_defaults is not None:
payload["template"] = {
"variable_defaults": variable_defaults,
"fields": alert_payload,
}
else:
payload.update(alert_payload)
return payload
|
def cgiFieldStorageToDict( fieldStorage ):
"""Get a plain dictionary, rather than the '.value' system used by the cgi module."""
params = {}
for key in fieldStorage.keys():
params[ key ] = fieldStorage[ key ].value
return params
|
def _bin(n):
"""
>>> _bin(0), _bin(1), _bin(63), _bin(4096)
('0', '1', '111111', '1000000000000')
"""
return str(n) if n <= 1 else _bin(n >> 1) + str(n & 1)
|
def required_preamble(title: str, author: str, date: str):
"""
Every output must contain this in the preamble
"""
return [r"\documentclass{article}",
r"\usepackage[utf8]{inputenc}",
r"\usepackage{amsthm}",
r"\usepackage{breqn}",
r"\usepackage{enumitem}",
r"\usepackage{tcolorbox}",
r"\usepackage{hyperref}",
r"\title{"+title+"}",
r"\author{"+author+"}",
r"\date{"+date+"}"]
|
def find_by_key(data: dict, target):
"""Find a key value in a nested dict"""
for k, v in data.items():
if k == target:
return v
elif isinstance(v, dict):
return find_by_key(v, target)
elif isinstance(v, list):
for i in v:
if isinstance(i, dict):
return find_by_key(i, target)
|
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
http://docs.python.org/3.4/library/itertools.html#itertools-recipes
"""
return next(filter(pred, iterable), default)
|
def convert_price(price, use_float):
"""
Converts price to an integer representing a mil.
1 mil = 0.0001
Smallest representable size is 0.0001
"""
if use_float:
# Use floats to approximate prices instead of exact representation
return int(float(price) * float(10000))
else:
# Exact representation
idx = price.index('.')
concat = "%s%s" % (price[0:idx], price[idx+1:].ljust(4,'0')[0:4])
return int(concat)
#from decimal import Decimal
#return int(Decimal(price) * Decimal(10000))
|
def is_valid_combination(values, names):
"""
Should return True if combination is valid and False otherwise.
Dictionary that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data to validate it.
"""
dictionary = dict(zip(names, values))
rules = [
lambda d: "RedHat" == d["os"] and "ceph" == d["storage volume"],
lambda d: "RedHat" == d["os"] and "ceph" == d["storage images"],
lambda d: "RedHat" == d["os"] and "yes" == d["sahara"],
lambda d: "RedHat" == d["os"] and "yes" == d["murano"],
lambda d: "RedHat" == d["os"] and "neutron GRE" == d["network"],
lambda d: "RedHat" == d["os"] and "neutron VLAN" == d["network"],
lambda d: d["cinder"] > 0 and d["storage volume"] == "default",
lambda d: d["ceph"] > 0 and d["storage volume"] == "default"
and d["storage images"] == "default"
]
for rule in rules:
try:
if rule(dictionary):
return False
except KeyError:
pass
return True
|
def _message_no_is_in_list(message_no, main_messages):
"""Returns True if the main message in Norwegian is in the list of main messages.
:param message_no:
:param main_messages:
:return:
"""
is_in_list = False
for m in main_messages:
if message_no == m.main_message_no:
is_in_list = True
return is_in_list
|
def show_pagination_panel(page_obj, search=''):
"""Shows pagination panel."""
return {'page_obj': page_obj, 'search': search}
|
def policy_list(context, request, policies_url=None, policy_url=None, remove_url=None, update_url=None, add_url=None):
""" User list panel.
Usage example (in Chameleon template): ${panel('policy_list')}
"""
return dict(policies_url=policies_url, policy_url=policy_url,
remove_url=remove_url, update_url=update_url, add_url=add_url)
|
def interleaved_sum(n, odd_term, even_term):
"""Compute the sum odd_term(1) + even_term(2) + odd_term(3) + ..., up
to n.
>>> # 1 + 2^2 + 3 + 4^2 + 5
... interleaved_sum(5, lambda x: x, lambda x: x*x)
29
>>> from construct_check import check
>>> check(SOURCE_FILE, 'interleaved_sum', ['While', 'For', 'Mod']) # ban loops and %
True
"""
"*** YOUR CODE HERE ***"
def helper(i, odd):
if i > n:
return 0
elif odd:
return odd_term(i) + helper(i + 1, not odd)
else:
return even_term(i) + helper(i + 1, not odd)
return helper(1, True)
|
def check_rule(rule, email, group_ids):
"""
Check if a rule matches and email and group
See create_rule() for an example of what a rule looks like.
"""
for match in rule["remote"]:
if match.get("type") == "Email" and email in match.get("any_one_of"):
break
else:
return False
for match in rule["local"]:
if match.get("group", dict()).get("id") in group_ids:
return True
return False
|
def readn(f, n):
"""Read n lines from a file iterator f."""
return "".join(f.readline() for _ in range(n))
|
def is_testable(reqs):
"""Filters dict requirements to only those which are testable"""
for key, values in reqs.items():
if ("MUST" in values.get("keyword", "").upper()) and (
"none" not in values.get("validation_mode", "").lower()
):
reqs[key]["testable"] = True
else:
reqs[key]["testable"] = False
return reqs
|
def _checkFore(r, c, linko):
"""Checks if (r,c) lies on a forelink for a node."""
initialNode = (r-c)//4
if initialNode < 0:
return False
forelinks = linko[initialNode][2]
if len(forelinks) == 0:
return False
maxForelink = max(forelinks)
return 2*maxForelink > 2*initialNode + c
|
def _alpha_sorted_keys(length, range_from, range_to):
"""Test util which returns sorted alphabetically numbers range
as strings
"""
return list(sorted(str(x) for x in range(length)))[range_from:range_to]
|
def create_previous_shift_vars(num_days, model, shifts, staff, shift_days):
"""Shift variables for previous roster period."""
prev_shift_vars = {
(staff_member, role, day - num_days, shift): model.NewBoolVar(
f"staff:{staff_member}"
f"_role:{role}"
f"_day:{day - num_days}"
f"_shift:{shift}"
)
for staff_member in staff
for role in staff[staff_member]
for shift in shifts
for day in shift_days[shift]
}
return prev_shift_vars
|
def intfmt(maxval, fill=" "):
"""
returns the appropriate format string for integers that can go up to
maximum value maxvalue, inclusive.
"""
vallen = len(str(maxval))
return "{:" + fill + str(vallen) + "d}"
|
def formatSentence(variableList, finalSeparator="and"):
"""Turn a list of variables into a string, like 'Bill, John, and Jeff.'"""
# Thanks to StackOverflow user Shashank: https://stackoverflow.com/a/30084397
n = len(variableList) # Creates a variable for the number of objects being formatted
if n > 1:
return ('{}, '*(n-2) + '{} Q*Q*Q {}').format(*variableList).replace("Q*Q*Q", finalSeparator) # shut up
elif n > 0:
return variableList[0] # If only one string was input, it gets returned.
else:
return ''
|
def back_to_clean_sent(token_ls):
"""
In order to perform sentiment analysis,
here we put the words back into sentences.
"""
clean_sent_ls = []
for word_ls in token_ls:
clean_sent = ""
for word in word_ls:
clean_sent += (word + " ")
clean_sent_ls.append(clean_sent)
return clean_sent_ls
|
def oneHotEncode_EventType_exact(x, r_vals=None):
"""
This function one hot encodes the input for the event
types cascade, tracks, doubel-bang
"""
# define universe of possible input values
onehot_encoded = []
# universe has to defined depending on the problem,
# in this implementation integers are neccesary
universe = [0, 1, 2, 3, 4, 5, 6]
for i in range(len(universe)):
if x == universe[i]:
value = 1.
else:
value = 0.
onehot_encoded.append(value)
return onehot_encoded
|
def half_adder(a, b):
"""
ha_carry_out, ha_sum = a + b
"""
ha_sum = a ^ b
ha_carry_out = a & b
return ha_sum, ha_carry_out
|
def conv_curr(curr):
"""conv_curr(Access currency-typed field) -> float
Return a float from MS Access currency datatype, which is a fixed-point integer
scaled by 10,000"""
return float(curr[1])/10000
|
def turn(fen):
"""
Return side to move of the given fen.
"""
side = fen.split()[1].strip()
if side == 'w':
return True
return False
|
def selection_sort(arr):
"""Refresher implementation of selection sort - in-place & stable.
:param arr: List of integers to sort
:return: Sorted list
"""
for i in range(len(arr)):
min = i
# selecting index of smallest number
for j in range(i, len(arr)):
if arr[j] < arr[min]:
min = j
# swaping current index with smallest number
arr[i], arr[min] = arr[min], arr[i]
return arr
|
def deep_update(dct: dict, merge_dct: dict, copy=True) -> dict:
"""Merge possibly nested dicts"""
from copy import deepcopy
_dct = deepcopy(dct) if copy else dct
for k, v in merge_dct.items():
if k in _dct and isinstance(dct[k], dict) and isinstance(v, dict):
deep_update(_dct[k], v, copy=False)
elif isinstance(v, list):
if k not in _dct:
_dct[k] = []
_dct[k].extend(v)
else:
_dct[k] = v
return _dct
|
def get_field_name(field_name):
"""handle type at end, plus embedded objets."""
field = field_name.replace('*', '')
field = field.split(':')[0]
return field.split(".")[0]
|
def compute_antenna_gain(phi):
"""Computes the antenna gain given the horizontal angle between user and basestation (3GPP spec)!
Args:
phi: (float) horizontal angle between user and basestation in degrees!
Returns:
(float) horizontal angle gain!
"""
Am = 30 # Front-back ratio in dB!
horizontal_beamwidth = 65 # Horizontal 3 dB beamwidth in degrees!
gain = -min(12.*pow((phi / horizontal_beamwidth), 2), Am)
return gain
|
def input_new_values(formed_text, sample_list):
"""
formed_text: formatted text with {}
sample_list: list of new user values
formats text with user values
:@return(String) Re-formatted version of
"""
return formed_text.format(*sample_list)
|
def is_property(attribute):
"""
Check if a class attribute is of type property.
:ref: https://stackoverflow.com/questions/17735520/determine-if-given-class-attribute-is-a-property-or-not-python-object
:param attribute: The class's attribute that will be checked.
:rtype: bool
"""
return isinstance(attribute, property)
|
def min_insurance(replacement_cost):
"""
>>> min_insurance(100000)
80000.0
>>> min_insurance(123456789)
98765431.2
>>> min_insurance(0)
0.0
>>> min_insurance(-54317890)
-43454312.0
"""
return (replacement_cost * .8)
|
def as_snake_case(text: str) -> str:
"""
Converts CamelCase to snake_case.
As a special case, this function converts `ID` to `_id` instead of `_i_d`.
"""
output = ""
for i, char in enumerate(text):
if char.isupper() and i != 0:
# preserve _id
if not (char == 'D' and text[i-1] == 'I'):
output += "_"
output += char.lower()
return output
|
def _any(oper, left, right):
"""Short circuit any for ndarray."""
return any(oper(ai, bi) for ai, bi in zip(left, right))
|
def num_frames(length, fsize, fshift):
"""Compute number of time frames of spectrogram
"""
pad = (fsize - fshift)
if length % fshift == 0:
M = (length + pad * 2 - fsize) // fshift + 1
else:
M = (length + pad * 2 - fsize) // fshift + 2
return M
|
def shiny_gold_in(bag: str, rules: dict) -> bool:
"""Recursively check for shiny gold bags."""
if "shiny gold" in rules[bag].keys():
return True
elif not rules[bag]: # bag holds no others
return False
else:
for inner in rules[bag]:
if shiny_gold_in(inner, rules):
return True
return False
|
def shift_vocab(all_letters, key):
"""
performs rot-key encipherment of plaintext given the key.
essentially performs a char shift.
key == 1 turns a=b, b=c, .. z=a;
key == 3 turns a=c, b=e, .. z=c.
returns a dict with orig chars as keys and new chars as values
key = 1 returns d{'a':'b', 'b':'c', .. , 'z':'a'}
"""
d = {}
for i in range(len(all_letters)):
d[all_letters[i]] = all_letters[(i + key) % len(all_letters)]
return d
|
def longest_row_number(array):
"""Find the length of the longest row in the array
:param list in_array: a list of arrays
"""
if len(array) > 0:
# map runs len() against each member of the array
return max(map(len, array))
else:
return 0
|
def my_squares(iters):
"""squaring loop function"""
out=[]
for i in range(iters):
out.append(i**2)
return out
|
def PassN(s,substring,iFrom,iN):
"""Find index after passing substring N times.
"""
while iN>0:
iIndex= s.find(substring,iFrom)
if iIndex==-1: return -1
else: iFrom=iIndex+1
iN-=1
return iFrom
|
def Chorda(func, a: float, b: float, epsilon: float, digitRound: int, showIteration: bool):
"""
Calculates solution of equation f(x) = 0 by using chorda iterative approximations.
Parameters
----------
func : Callable
Some function (method) returning by calling with input parameter x (float) some float number.
a : float
Lower border of an interval for root searching [a, b].
b : float
Higher border of an iterval for root searching.
epsilon : float
Relative precision of roots calculations for float numbers.
digitRound : int
Rounding of returning values to some relevant number after digit point.
showIteration : bool
For explicit showing number of iterations and root iteration.
Returns
-------
float
Single root of an equation like f(x) = 0.
"""
# Epsilon - Presicion of equality the interesting function f(x) ~= 0
# DigitRound - number of digits for rounding calculations (in some dependence to Epsilon)
i = 0 # For calculation of a number of iteration steps
if (func(a)*func(b) < 0):
# The point there chorda is equal to zero (approximation to a real root)
xChorda = (a*func(b)-b*func(a))/(func(b)-func(a))
while (abs(func(xChorda)) > epsilon) and (i <= 5000):
if (func(xChorda)*func(a) < 0):
b = xChorda # [a,b] => [a,xChorda] - approximation, visual interpretation - graphically
elif (func(xChorda)*func(b) < 0):
a = xChorda
else:
print("Apparantly, there is more than real 1 root or no roots...")
return None
# The row below is for showing iteration process
if showIteration:
print("Iteration step #", i, "Root approximation is: ", round(xChorda, digitRound+1))
i += 1
if (i > 5000):
print("For some reason, there is too many ( > 5000) iteration steps made")
xChorda = (a*func(b)-b*func(a))/(func(b)-func(a)) # For allowing iteration ad test next approximation to the root
return float(round(xChorda, digitRound)) # In the end of while cycle
else:
print("There is no real roots between input a and b or more than 1 real root")
return None
|
def list_to_str(lst):
"""Convert a list of items into an underscore separated string.
For Example: [1,2,3] -> _1_2_3
Args:
lst: The list to convert into a string.
Returns:
The stringified list.
"""
s = ''
for item in lst:
s += '_%s' % (str(item))
return s
|
def make_foldername(name):
"""Returns a valid folder name by replacing problematic characters."""
result = ""
for c in name:
if c.isdigit() or c.isalpha() or c == "," or c == " ":
result += c
elif c == ':':
result += "."
elif c == '-':
result += '-'
else:
result += '_'
return result
|
def to_camel_case(snake_str):
"""
Converts snake case and title case to camelCase.
:param snake_str:
:return:
"""
components = snake_str.split('_')
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
# We also just explicitly change the first character to lowercase, in case it is not, especially
# in title case.
return components[0][0].lower() + components[0][1:] + "".join(x.title() for x in components[1:])
|
def get_key_for_grouping(item):
"""
Returns the key for grouping params during update of SqE.
Parameters
----------
item : tuple
(key, value) as given by dict.items()
"""
try:
return item[0].split("_")[1] # This should be the name of the line
except IndexError:
return "model_params"
|
def count_possibilities(board_repr):
"""Count total number of possibilities remaining on sudoku board"""
total = 0
for row in board_repr:
for col in row:
if isinstance(col, set) and len(col) > 1:
total += len(col)
return total
|
def is_valid_index (wordsearch, line_num, col_num):
"""Checks if the provided line number and column number are valid"""
if ((line_num >= 0) and (line_num < len(wordsearch))):
if ((col_num >= 0) and (col_num < len(wordsearch[line_num]))):
return True
return False
|
def get_max_value_from_pop(neuron_data_array):
"""
Get maximum value from variable of population
:param neuron_data_array:
:return:
"""
max_val = -1000000
for neuron_data in neuron_data_array:
neuron_data = map(float, neuron_data)
if max(neuron_data) > max_val:
max_val = max(neuron_data)
return max_val
|
def usb_lib_tx_data(device, data_8bit, timeout):
"""
Send data (64 bits per 8 bits) over USB interface
:param device: device description, witch programmer get when use function
usb_open_device
:param data_8bit: Data to TX (8 bytes -> 64 bits)
:type data_8bit: List of 8 bit data values
:param timeout:
"""
try:
device.ep_out.write(data_8bit, timeout)
except:
print("\n--------------------\nTX Timeout!\n---------------------\n")
return -1
return 0
|
def obj_spec_to_uri(obj_spec, job_to_uri, service_to_uri):
"""Convert a string of the form job_name[.run_number[.action]] to its
corresponding URL
"""
obj_name_elements = obj_spec.split('.')
obj_name = obj_name_elements[0]
obj_rel_path = "/".join(obj_name_elements[1:])
obj_uri = None
if obj_name in job_to_uri:
obj_uri = job_to_uri[obj_name]
elif obj_name in service_to_uri:
obj_uri = service_to_uri[obj_name]
if not obj_uri:
raise Exception("Unknown identifier")
return '/'.join((obj_uri, obj_rel_path))
|
def homo_degree_dist_filename(filestem):
"""Return the name of the homology degree distribution file."""
return f"{filestem}-degreedist.tsv"
|
def remove_postfix(text: str, postfix: str) -> str:
"""Removes a postfix from a string, if present at its end.
Args:
text: string potentially containing a postfix.
postfix: string to remove at the end of text.
"""
if text.endswith(postfix):
return text[:-len(postfix)]
return text
|
def split_ngrams(seq, n):
"""
'AGAMQSASM' => [['AGA', 'MQS', 'ASM'], ['GAM','QSA'], ['AMQ', 'SAS']]
"""
all_ngrams=[]
for x in range(n):
all_ngrams.append(zip(*[iter(seq[x:])]*n))
str_ngrams = []
for ngrams in all_ngrams:
x = []
for ngram in ngrams:
x.append("".join(ngram))
str_ngrams.append(x)
return str_ngrams
|
def get_status_summary(dictionary, certname, state):
"""
:param dictionary: dictionary holding the statuses
:param state: state you want to retrieve
:param certname: name of the node you want to find
:return: int
"""
try:
return dictionary[certname][state]
except:
return 0
|
def fmt_addr(socket):
"""(host, int(port)) --> "host:port" """
return "{}:{}".format(*socket)
|
def union(a, b):
"""
union of two lists
"""
return list(set(a) & set(b))
|
def toggleYears2(click):
"""
When syncing years, there should only be one time slider
"""
if not click:
click = 0
if click % 2 == 0:
style = {"display": "none", "margin-top": "0", "margin-bottom": "80"}
else:
style = {"margin-top": "0", "margin-bottom": "80"}
return style
|
def _value_of_point(point):
"""Extracts the actual numeric value of a point.
Only supports int64 and double point values.
Strings, booleans, distribution and money are not supported.
See cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.metricDescriptors#ValueType
"""
pval = point['value']
int64_value = pval.get('int64Value')
if int64_value is not None:
return int(int64_value)
double_value = pval.get('doubleValue')
if double_value is not None:
return float(double_value)
raise ValueError('point must have int or double value', point)
|
def _scale(x, lb, ub):
"""Scales the values to be normalized to [lb, ub]."""
return (x - lb) / (ub - lb)
|
def join_name(name_parts: list, separator: str = "__", ignore_none: bool = True) -> str:
"""
joins individual parts of a name (i.e., file name consisting of different elements)
:param name_parts: the elements to join
:param separator: the separator to be used to join
:param ignore_none: if True, None values will not be shown in the joined string
:return: the joined string representation of the `name_parts`
"""
# create name by joining all of the following elements with a `separator` (maybe: remove empty strings / None)
return separator.join(e for e in name_parts if not ignore_none or e is not None)
|
def get_area_raster(raster: str) -> str:
"""Determine the path of the area raster for a given backscatter raster based on naming conventions for HyP3 RTC
products
Args:
raster: path of the backscatter raster, e.g. S1A_IW_20181102T155531_DVP_RTC30_G_gpuned_5685_VV.tif
Returns:
area_raster: path of the area raster, e.g. S1A_IW_20181102T155531_DVP_RTC30_G_gpuned_5685_area.tif
"""
return '_'.join(raster.split('_')[:-1] + ['area.tif'])
|
def calc_euclid_distance_2d_sq(p1: tuple, p2: tuple):
"""
Returns the square of the euclidian distance between p1 and p2
Useful as it's much cheaper than calculating the actual distance
(as it save a call to sqrt())
and if checking a < b, then a^2 < b^2 will also give the correct value
"""
return (float(p2[0]) - float(p1[0]))**2 + (float(p2[1]) - float(p1[1]))**2
|
def hammingDistance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1, s2))
|
def get_uniq(my_list):
""" Get the unique elements of a list
while preserving the order (order preserving)
"""
target_list = []
[target_list.append(i) for i in my_list if not target_list.count(i)]
return target_list
|
def to_terminal(group):
"""Create a terminal node value"""
outcomes = [row[-1] for row in group]
return max(set(outcomes), key=outcomes.count)
|
def hyperlink(text: str, link: str):
"""Turns text into a hyperlink.
Parameters
----------
text : str
The text that turns `blue`.
link : str
The link
Returns
-------
str
The hyperlink.
"""
ret = "[{}]({})".format(text, link)
return ret
|
def list_to_dict(config):
"""
Convert list based beacon configuration
into a dictionary.
"""
_config = {}
list(map(_config.update, config))
return _config
|
def valid_str_only(item, allow_bool: bool = False) -> bool:
"""
Removes empty strings and other invalid values passed that aren't valid strings.
:param item: Check if valid str
:param allow_bool: Allow the use of bool only if True
:return: bool
"""
if isinstance(item, str) and len(item) > 0:
return True
if allow_bool and item:
return True
return False
|
def other_reverse_invert(lst):
"""Best practice solution from codewars."""
from math import copysign as sign
return [-int(sign(int(str(abs(x))[::-1]), x)) for x in lst
if isinstance(x, int)]
|
def _toVersionTuple(versionString):
"""Split a version string like "10.5.0.2345" into a tuple (10, 5, 0, 2345).
"""
return tuple((int(part) if part.isdigit() else part)
for part in versionString.split("."))
|
def cleaner_unicode(string):
"""
Objective :
This method is used to clean the special characters from the report string and
place ascii characters in place of them
"""
if string is not None:
return string.encode('ascii', errors='backslashreplace')
else:
return string
|
def decode_alt_info(cigar_count, ref_base, depth, minimum_allele_gap):
"""
Decode the input read-level alternative information
cigar_count: each alternative base including snp, insertion and deletion of each position
pileup_bases: pileup bases list of each read in specific candidate position from samtools mpileup 1.10
reference_sequence: the whole reference sequence index by contig:start-end. 0-based.
ref_base: upper reference base for cigar calculation.
depth: depth of candidate position for calculation.
minimum_allele_gap: default minimum allele frequency for candidate to consider as a potential true variant for unification.
"""
alt_type_list = [] # SNP I D
seqs = cigar_count.split(' ')
seq_alt_bases_dict = dict(zip(seqs[::2], [int(item) for item in seqs[1::2]])) if len(seqs) else {}
if '*' in seq_alt_bases_dict:
del seq_alt_bases_dict['*']
max_del_cigar = ""
del_list = []
ref_represatation = ref_base
alt_list = sorted(list(seq_alt_bases_dict.items()), key=lambda x: x[1], reverse=True)
seq_insertion_bases_list = alt_list[:2]
af_list = []
for alt_type, count in seq_insertion_bases_list:
count = int(count)
if '*' in alt_type or '#' in alt_type:
continue
if count / float(depth) < minimum_allele_gap:
continue
af_list.append(count/ float(depth))
if alt_type[0] == 'X':
alt_type_list.append(alt_type[1])
elif alt_type[0] == 'I':
alt_type_list.append(alt_type[1:])
elif alt_type[0] == 'D':
if len(alt_type[1:]) > len(max_del_cigar):
max_del_cigar = alt_type[1:]
del_list.append(ref_base + alt_type[1:])
new_del_list = []
if len(max_del_cigar):
ref_represatation = ref_base + max_del_cigar
alt_type_list = [item + max_del_cigar for item in alt_type_list]
for idx, item in enumerate(del_list):
start_pos = len(item[1:])
append_del_bases = max_del_cigar[start_pos:]
new_del_list.append(
ref_base + append_del_bases) # ACG-> A, ACGTT -> A, max_del_cigar is CGTT, represent ACG-> A to ACGTT->ATT
alt_base_list = alt_type_list + new_del_list
return ref_represatation, alt_base_list,af_list, alt_list
|
def getSequenceDifference(lst):
"""
Returns an array of the subtracted value from each nth + 1 element and the nth element.
:param lst: A list of numerics from which the differences between following elements will be retrieved. \t
:type lst: [numerics] \n
:returns: The subtracted values from each nth + 1 element and the nth element. \t
:rtype: : [numerics] \n
"""
return [a - b for a, b in zip(lst[1:], lst[:-1])]
|
def _get_coordinator(hostname, port=9001):
""" Generates the coordinator section of a Myria deployment file """
return '[master]\n' \
'0 = {}:{}\n\n'.format(hostname, port)
|
def _join_lists(obj):
"""
Return *obj* with list-like dictionary objects converted to actual lists.
:param obj: Arbitrary object
Example::
{'0': 'apple', '1': 'pear', '2': 'orange'}
... returns ...
['apple', 'pear', 'orange']
"""
# If it's not a dict, it's definitely not a dict-list
if not isinstance(obj, dict):
# If it's a list-list then we want to recurse into it
if isinstance(obj, list):
return [_join_lists(v) for v in obj]
# Otherwise just get out
return obj
# If there's not a '0' key it's not a possible list
if '0' not in obj and 0 not in obj:
# Recurse into it
for key, value in obj.items():
obj[key] = _join_lists(value)
return obj
# Make sure the all the keys parse into integers, otherwise it's not a list
try:
items = [(int(k), v) for k, v in obj.items()]
except ValueError:
return obj
# Sort the integer keys to get the original list order
items = sorted(items)
# Check all the keys to ensure there's no missing indexes
i = 0
for key, value in items:
# If the index key is out of sequence we abandon
if key != i:
return obj
# Replace the item with its value
items[i] = value
# Increment to check the next one
i += 1
return items
|
def is_service_named(service_name: str, service: dict) -> bool:
"""Handles a case where DC/OS service names sometimes don't contain the first slash.
e.g.: | SDK service name | DC/OS service name |
|--------------------------+-------------------------|
| /data-services/cassandra | data-services/cassandra |
| /production/cassandra | /production/cassandra |
"""
return service.get("name") in [service_name, service_name.lstrip("/")]
|
def niceGetter(thing, *args):
"""
Given a nested dictionary "thing", Get any nested field by the path described:
eg niceGetter(thing, 'cars', 'mustang', 'cobra')
will return thing['cars']['mustang']['cobra']
or None if such item doesn't exist.
"""
if thing == None: return None
subthing = thing
for arg in args:
if arg not in subthing: return None
subthing = subthing[arg]
return subthing
|
def get_greater(children: list):
"""Return greater value among the children node"""
if len(children) == 0:
return None, float('inf')
if len(children) == 1:
return children[0]
else:
return children[0] if children[0][1] > children[1][1] else children[1]
|
def elk_index(hashDict):
""" Index setup for ELK Stack bulk install """
index_tag_full = {}
index_tag_inner = {}
index_tag_inner['_index'] = "hash-data"
index_tag_inner['_id'] = hashDict['hashvalue']
index_tag_full['index'] = index_tag_inner
return index_tag_full
|
def parseData(txt):
"""Auxiliary function.
Takes plain text description of binary data
from protocol specification and returns binary data"""
import re
result = ""
for a in re.split('\s+', txt):
if re.match('x[0-9a-f]{2}', a, re.IGNORECASE):
result += chr(int(a[1:], 16))
else:
result += a
return result
|
def br_to_us_number_format(numb_str: str) -> str:
"""
Removes dot as thousand separator and replaces comma decimal separator with dot
>>> br_to_us_number_format('10.000,00')
'10000.00'
"""
return numb_str.replace(".", "").replace(",", ".")
|
def parse_project_version(version):
"""
Parse project version to a tuple of integer.
That can be used for a lexicographical comparison of values.
Arguments:
version (str): project version code as a string.
Returns:
Parsed project version as a tuple with integer values.
"""
components = version.split('.')
return tuple(int(component) for component in components)
|
def coding_problem_23(matrix, start, end):
"""
You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall.
Each False boolean represents a tile you can walk on. Given this matrix, a start coordinate, and an end coordinate,
return the minimum number of steps required to reach the end coordinate from the start. If there is no possible
path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap
around the edges of the board.
Examples:
>>> matrix = [[False] * 4] * 4
>>> matrix[1] = [True, True, False, True]
>>> coding_problem_23(matrix, (3, 0), (0, 0))
7
>>> matrix[1][2] = True # close off path
>>> coding_problem_23(matrix, (3, 0), (0, 0)) # None
"""
walkable = {(r, c) for r, row in enumerate(matrix) for c, is_wall in enumerate(row) if not is_wall}
steps, to_visit = 0, {start}
while to_visit:
steps += 1
walkable -= to_visit
to_visit = {(nr, nc) for r, c in to_visit for nr, nc in walkable if abs(r - nr) + abs(c - nc) == 1}
if end in to_visit:
return steps
return None
|
def get_descr_full(tables,description):
"""List descriptors, with unit and name/description"""
desc_text = []
for d in description:
d = int(d)
if d > 0 and d < 100000:
desc_text.append(str(tables.tab_b[d]))
elif d >= 100000 and d < 200000:
lm = d // 1000 - 100
ln = d % 1000
desc_text.append("%06d : LOOP, %d desc., %d times" % (d, lm , ln))
elif d >= 200000 and d < 300000:
en = tables.tab_c.get(d)
am = d // 1000 - 200
an = d % 1000
if en is None:
en = (str(am), "")
if d < 222000:
desc_text.append("%06d : OPERATOR %s: %d" % (d, en[0], an))
else:
desc_text.append("%06d : OPERATOR '%s'" % (d, en[0]))
return desc_text
|
def get_delta_of_fedmd_nfdp(n, k, replacement=True):
"""Return delta of FedMD-NFDP
Args:
n (int): training set size
k (int): sampling size
replacement (bool, optional): sampling w/o replacement. Defaults to True.
Returns:
float: delta of FedMD-NFDP
"""
if replacement:
return 1 - ((n - 1) / n) ** k
else:
return k / n
|
def RelogOptionsSet(options):
"""
Are any of the 'relog_*' options set to True?
If new relog_* options are added, then make sure and
add them to this method.
"""
return options.relog_code_exclude != '' or options.relog_focus or \
options.relog_name != '' or options.relog_no_cleanup or \
options.relog_no_init or options.relog_no_mpi_spin or \
options.relog_no_mpi_spin
|
def encode_string_link(text):
"""Replace special symbols with its codes."""
text = text.replace("<", "%3C")
text = text.replace(">", "%3E")
text = text.replace("[", "%5B")
text = text.replace("]", "%5D")
text = text.replace("{", "%7B")
text = text.replace("}", "%7D")
text = text.replace("|", "%7C")
return text
|
def dmse(f_x, y):
"""
dMSE(f_x,y) = 2* (f_x-y)
"""
return 2 * (f_x - y)
|
def third(n) -> int:
"""Calculates one-third of a given value.
Args:
n: the integer to calculate one-third of
Returns:
int: one-third of n, rounded down
"""
return int(n / 3)
|
def separate(text):
"""
Process a text to get its parts.
:param text:
:return: [head,body,end]
"""
right = text.rstrip()
left = text.lstrip()
return (text[0:-len(left)], text[-len(left):len(right)], text[len(right):])
|
def replace_values_in_dict_by_value(replace_values, target_dict):
"""
Takes a dict with value-replacement pairs and replaces all values in the
target dict with the replacement. Returns the resulting dict.
"""
ret_dict = target_dict.copy()
for val, replacement in replace_values.items():
for key, dict_val in target_dict.items():
if str(dict_val) == val:
ret_dict[key] = replacement
return ret_dict
|
def is_mt_str(my_str) -> bool:
"""Check to see if the given input is an empty string
Function that checks the given parameter my_str to see if it is an empty
string. Uses the innate identity __eq__ to check.
:param my_str: String to check if it is empty
:type my_str: str
:return: Boolean indicating if the input is an empty string
:rtype: bool
"""
if not isinstance(my_str, str):
return False
elif "".__eq__(my_str):
return True
else:
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.