content stringlengths 42 6.51k |
|---|
def _format_time(seconds):
"""seconds: number
returns a human-friendly string describing the amount of time
"""
minute = 60.00
hour = 60.00 * minute
if seconds < 30:
return '{} ms'.format(int(seconds * 1000))
if seconds < 90:
return '{} seconds'.format(round(seconds, 2))
if seconds < 90 * minute:
return '{} minutes'.format(round(seconds / minute, 2))
return '{} hours'.format(round(seconds / hour, 2)) |
def resolve_secrets(vault_client, rendered_template):
"""Parse a rendered template, extract any secret definitions, retrieve them
from vault and return them to the caller.
This is used in situations where direct Vault support is not available e.g.
Chronos.
"""
resolved_secrets = {}
secrets = rendered_template.get("secrets", {})
for name, definition in secrets.items():
# parse the secret source and retrieve from vault
path, key = definition["source"].split(":")
secret = vault_client.read(path)
if secret:
resolved_secrets[name] = secret["data"][key]
else:
logger.info("Couldn't locate secret in Vault: {0}".format(path))
return resolved_secrets |
def sanitize_filename(filename):
"""
Return a sanitized file path with certain characters replaced.
"""
return filename.replace(":", "_").replace("/", "_") |
def primitive_path(name):
"""Gets the relative path to the primitive file with the specified name.
Args:
name (str): The name of the primitive.
"""
return 'primitives/' + name + '.pc' |
def keywithmaxval(d):
""" a) create a list of the dict's keys and values;
b) return the key with the max value"""
v = list(d.values())
k = list(d.keys())
return k[v.index(max(v))] |
def pick_n(items, n):
"""Pick n items, attempting to get equal index spacing.
"""
if not (n > 0):
raise ValueError("Invalid number of items to pick")
spacing = max(float(len(items)) / n, 1)
spaced = []
i = 0
while int(i) < len(items) and len(spaced) < n:
spaced.append(items[int(i)])
i += spacing
return spaced |
def linear_dist_sphere(radius: float, surf_dist: float, depth_a: float, depth_b: float) -> float:
"""
The purpose of this function is to find the actual, linear distance between the hypocenter of
and earthquake and the bottom of a fracking well. It's a more general problem/solution, though:
returns c: Linear distance through a sphere between two points at or beneath the surface of a sphere
inputs:
radius: radius of the sphere;
surf_dist: 'great circle' distance between the epicenters of the two points;
depth_a, depth_b: depth of each of the two points beneath the surface.
"""
from math import cos, pi, sqrt
circumferance = 2 * pi * radius
theta_rad = (surf_dist / circumferance) * ( 2 * pi )
a = radius - depth_a
b = radius - depth_b
c = sqrt(a**2 + b**2 - 2 * a * b * cos(theta_rad))
return c |
def train_get_surrounding_syms(s, position, featureprefix, lookright = True):
"""Get surrounding symbols from a list of chunks and position.
>>> s = ['<', u'a', u'b', u'u', u'_', u't', u'a', u'n', u'doka', '>']
>>> train_get_surrounding_syms(s, 4, 'in_')
set([u'nin_ta', u'nin_t', u'nin_tan', u'pin_u', u'pin_bu', u'pin_abu'])
"""
leftfeats = set()
rightfeats = set()
if position == 0:
leftfeats |= {u'p' + featureprefix + u'none'}
if (position == len(s)) and lookright:
rightfeats |= {u'n' + featureprefix + u'none'}
if position > 0:
left = ''.join(s[:position]).replace(u'_', u'')
leftfeats |= {u'p' + featureprefix + left[x:] for x in [-1,-2,-3]}
if (position < len(s)) and lookright:
right = ''.join(s[position:]).replace(u'_', u'')
rightfeats |= {u'n' + featureprefix + right[:x] for x in [1,2,3]}
return leftfeats | rightfeats |
def euclids_algorithm(m: int, n: int) -> int:
"""
Given unsigned int m, n. Find the highest common denominator.
:rtype: int
:param m: first number in question
:param n: second number in question
:return: Highest common denominator
"""
# Check if m is greater than n to skip the first loop.
if m < n:
m, n = n, m
# Initialize the remainder value.
r = 1
while r:
r = m % n
if r != 0:
m = n
n = r
return n |
def get_from_nested_dict(nested_dicts, path):
"""
Retrieves a value from a nested_dict.
Args:
path (str)
"""
value = nested_dicts
for key in path.split("/"):
if type(value) is dict:
value = value[key]
elif type(value) is list:
value = value[int(key)]
return value |
def FindByWireName(list_of_resource_or_method, wire_name):
"""Find an element in a list by its "wireName".
The "wireName" is the name of the method "on the wire", which is the raw name
as it appears in the JSON.
Args:
list_of_resource_or_method: A list of resource or methods as annotated by
the Api.
wire_name: (str): the name to fine.
Returns:
dict or None
"""
for x in list_of_resource_or_method:
if x.values['wireName'] == wire_name:
return x
return None |
def count_vowels(string):
"""
#### returns amount of vowels in given string
#### Example:
x = count_vowels("The meaning of life, 42 to proof this, is this text"*3)
### print(x)
### 42
"""
vowels,counter = ("aeiou"),0
for i in string:
if i.lower() in vowels : counter+=1
return counter |
def get_entry_or_none(base: dict, target, var_type=None):
""" Helper function that returns an entry or None if key is missing.
:param base: dictionary to query.
:param target: target key.
:param var_type: Type of variable this is supposed to be (for casting).
:return: entry or None.
"""
if target not in base:
return None
if var_type is not None:
return var_type(base[target])
return base[target] |
def get_login_url(client_id: str, redirect_uri: str) -> str:
"""
Returns the url to the website on which the user logs in
"""
return f"https://login.live.com/oauth20_authorize.srf?client_id={client_id}&response_type=code&redirect_uri={redirect_uri}&scope=XboxLive.signin%20offline_access&state=<optional;" |
def ramp(e, e0, v0, e1, v1):
"""
Return `v0` until `e` reaches `e0`, then linearly interpolate
to `v1` when `e` reaches `e1` and return `v1` thereafter.
Copyright (C) 2017 Lucas Beyer - http://lucasb.eyer.be =)
"""
if e < e0:
return v0
elif e < e1:
return v0 + (v1-v0)*(e-e0)/(e1-e0)
else:
return v1 |
def check_anagrams(a: str, b: str) -> bool:
"""
Two strings are anagrams if they are made of the same letters
arranged differently (ignoring the case).
>>> check_anagrams('Silent', 'Listen')
True
>>> check_anagrams('This is a string', 'Is this a string')
True
>>> check_anagrams('There', 'Their')
False
"""
return sorted(a.lower()) == sorted(b.lower()) |
def nl_capitalize(string: str):
""" Capitalize first character (the rest is untouched)
:param string:
:return:
"""
return string[:1].upper() + string[1:] |
def fill_valid_next_words(pos, word2index_y, last_word, bpe_separator, wrong_chars=[]):
"""
Searches all the valid words for a last_word and a list of wrong_chars to continue it
:param pos: Position on the hypothesis of the last word
:param word2index_y: Dictionary to convert words to indeces
:param last_word: Word to correct
:param bpe_separator: Combination of characters used by the BPE to mark all the non end subwords
:param wrong_chars: List of wrong chars to continue the last_word
:return: Dictionary of valid next words
"""
find_ending = False
valid_next_words = dict()
prefix = dict()
# As we need a dictionary for the end words, all of them will refer this empty dictionary
empty_dict = dict()
# Create the starting dictionary of subwords for the position "pos"
if valid_next_words.get(pos) == None:
valid_next_words[pos] = dict()
# Check if the space appear as a wrong char
plus_len = 0
for c in wrong_chars:
if c == u' ':
plus_len = 1
break
# Insert the empty element
prefix[""] = valid_next_words[pos]
list_cor_hyp = [[None, valid_next_words[pos], "", -1]]
while len(list_cor_hyp) != 0:
# Take the last element of the list
element = list_cor_hyp.pop()
# Lo separamos en sus tres valores
c_dict = element[0]
c_father = element[1]
c_pre = element[2]
c_word = element[3]
for w in word2index_y:
# Create the new prefix of the word C_PRE + W
last = True
if w[-2:] == bpe_separator:
word = c_pre + w[:-2]
last = False
else:
word = c_pre + w
# Check if the new prefix is contained in the last_word
if not (last_word[:len(word)] == word or word[:len(last_word)] == last_word):
continue
# Check if the length of the word is equal or larger than the minimum needed
index_w = word2index_y[w]
if len(word) == len(last_word) + plus_len:
c_father[index_w] = empty_dict
find_ending = True
elif len(word) > len(last_word) + plus_len:
if word[len(last_word)] in wrong_chars:
continue
c_father[index_w] = empty_dict
find_ending = True
elif not last:
if prefix.get(word) != None:
c_father[index_w] = prefix[word]
else:
# Add the element
new_dict = dict()
prefix[word] = new_dict
c_father[index_w] = new_dict
list_cor_hyp.append([c_father, new_dict, word, index_w])
if not c_father and c_dict is not None:
c_dict.pop(c_word)
if not find_ending:
return None
else:
return valid_next_words |
def to_lower(string: str) -> str:
"""
Converts :string: to lower case. Intended to be used as argument converter.
Args:
string: string to format
Returns:
string to lower case
"""
return string.lower() |
def solve(task: str) -> int:
"""Find number of steps required to jump out of maze."""
current_index = 0
steps = 0
data = [int(item) for item in task.strip().split("\n")]
while 0 <= current_index < len(data):
offset = data[current_index]
next_index = current_index + offset
if offset >= 3:
data[current_index] -= 1
else:
data[current_index] += 1
current_index = next_index
steps += 1
return steps |
def get_polygon_from_file_settings(settings):
"""
:param settings:
:return:
"""
try:
return settings['step'], settings['x_pos'], settings['y_pos']
except ValueError:
print('Not Valid Settings') |
def devide_zero_prefix_index(number):
"""
Split the zero prefix
"""
if not number.startswith("0"):
return None, int(number)
i = 0
while i < len(number):
if number[i] != "0":
break
i += 1
return number[0:i], 0 if i >= len(number) else int(number[i:]) |
def get_boundaries(bucket_names):
"""
Get boundaries of pandas-quantized features.
>>> bucket_names = ["whatever_(100.0, 1000.0)", "whatever_(-100.0, 100.0)"]
>>> get_boundaries(bucket_names)
[(100.0, 1000.0), (-100.0, 100.0)]
"""
boundaries = []
for bucket_name in bucket_names:
boundaries_str = bucket_name.split("_")[-1]
lo_str, hi_str = boundaries_str.strip("[]() ").split(",")
boundaries.append((float(lo_str), float(hi_str)))
return boundaries |
def get_bond_from_num(n: int) -> str:
"""Returns the SMILES symbol representing a bond with multiplicity
``n``. More specifically, ``'' = 1`` and ``'=' = 2`` and ``'#' = 3``.
:param n: either 1, 2, 3.
:return: the SMILES symbol representing a bond with multiplicity ``n``.
"""
return ('', '=', '#')[n - 1] |
def query_data(data_to_process, query_type=None):
"""Query data.
"""
if query_type == 'lines':
lines = 0
for _, contents in data_to_process.items():
if isinstance(contents, bytes):
text = contents.decode('utf-8')
else:
text = contents
lines += len(text.split('\n'))
return lines
return None |
def never_swap(doors, past_selections):
"""
Strategy that never swaps when given a chance.
"""
return past_selections[-1] |
def session_device(request, var, Session="auth_device"):
"""
Set a Session variable if logging in via a subacc
This will be linked to a decorator to control access to
sections of the site that will require the master account to be used
:param request:
:param session: default is auth_device
:param var: this should be the var to add to the session
:return:
"""
if not var:
return None
if Session == "auth_device":
request.session['auth_device'] = var
else:
request.session[Session] = var
return "%s:%s" % (Session,var) |
def dimensions_to_resolutions(value):
"""
## dimensions_to_resolutions
Parameters:
value (list): list of dimensions (e.g. `640x360`)
**Returns:** list of resolutions (e.g. `360p`)
"""
supported_resolutions = {
"256x144": "144p",
"426x240": "240p",
"640x360": "360p",
"854x480": "480p",
"1280x720": "720p",
"1920x1080": "1080p",
"2560x1440": "1440p",
"3840x2160": "2160p",
"7680x4320": "4320p",
}
return (
list(map(supported_resolutions.get, value, value))
if isinstance(value, list)
else []
) |
def odds(p):
"""Computes odds for a given probability.
Example: p=0.75 means 75 for and 25 against, or 3:1 odds in favor.
Note: when p=1, the formula for odds divides by zero, which is
normally undefined. But I think it is reasonable to define Odds(1)
to be infinity, so that's what this function does.
p: float 0-1
Returns: float odds
"""
if p == 1:
return float('inf')
return p / (1 - p) |
def comp_1st(n):
"""takes a binary number (n) in string fomat
returns the 1's complement of the number"""
n=str(n)
result=[]
for digit in n:
a=str(1-int(digit))
result.append(a)
return "".join(result) |
def parse_dependencies_unix(data):
""" Parses the given output from otool -XL or ldd to determine the list of
libraries this executable file depends on. """
lines = data.splitlines()
filenames = []
for l in lines:
l = l.strip()
if l != "statically linked":
filenames.append(l.split(' ', 1)[0])
return filenames |
def roundu(x: int, y: int, z: int) -> int:
"""Run calculation, round up, and return result."""
w = x * y / z
iw = int(w)
if iw - w != 0:
return iw + 1
return iw |
def sanitize_bool_for_api(bool_val):
"""Sanitizes a boolean value for use in the API."""
return str(bool_val).lower() |
def PS_custom_get_process(v):
"""convert string to proper float value, for working with the PS 120-10 """
return float(v[1:]) * 1e-2 |
def secureCompare(s1, s2):
"""Securely compare two strings"""
return sum(i != j for i, j in zip(s1, s2)) == 0 |
def get_age_distribution_max(selectpicker_id: str) -> int:
"""
:param selectpicker_id:
:return:
"""
min_values = {
"0": 18,
"1": 25,
"2": 35,
"3": 45,
"4": 55,
"5": 99
}
return min_values.get(selectpicker_id, 99) |
def _to_bgr(rgb):
"""excel expects colors as BGR instead of the usual RGB"""
if rgb is None:
return None
return ((rgb >> 16) & 0xff) + (rgb & 0xff00) + ((rgb & 0xff) << 16) |
def trim_spaces(s: str) -> str:
"""Trims excess spaces
Examples:
>>> trim_spaces(' pretty')
'pretty'
>>> trim_spaces(' CHEDDAR CHEESE')
'CHEDDAR CHEESE'
>>> trim_spaces(' salt ')
'salt'
"""
return ' '.join(_ for _ in s.split(' ') if _) |
def header_line_to_anchor( line ):
"""
duplicate (approximately) the GitLab algorithm to make a header anchor
"""
s1 = line[3:].strip().replace( '=', '' )
s2 = ' '.join( s1.split() )
s3 = s2.lower()
return s3 |
def _in_tag(text, tag):
"""Extracts text from inside a tag.
This function extracts the text from inside a given tag.
It's useful to get the text between <body></body> or
<pre></pre> when using the validators or the colorizer.
"""
if text.count('<%s' % tag):
text = text.split('<%s' % tag, 1)[1]
if text.count('>'):
text = text.split('>', 1)[1]
if text.count('</%s' % tag):
text = text.split('</%s' % tag, 1)[0]
text = text.strip().replace('\r\n', '\n')
return text |
def get_comma_sep_string_from_list(items):
"""Turns a list of items into a comma-separated string."""
if not items:
return ''
if len(items) == 1:
return items[0]
return '%s and %s' % (', '.join(items[:-1]), items[-1]) |
def get_numeric_ratio(s):
"""
gets the ratio of numeric characters to the total alphanumerics
:type s: str
:rtype: float or NoneType
"""
num_numeric = 0
num_alphabetic = 0
if len(s) == 0:
return None
else:
for character in s:
if character.isnumeric():
num_numeric += 1
elif character.isalpha():
num_alphabetic += 1
return num_numeric / (num_numeric + num_alphabetic) |
def romanFromInt(integer):
"""
Code taken from Raymond Hettinger's code in Victor Yang's "Decimal
to Roman Numerals" recipe in the Python Cookbook.
>>> r = [romanFromInt(x) for x in range(1, 4000)]
>>> i = [intFromRoman(x) for x in r]
>>> i == [x for x in range(1, 4000)]
True
"""
coding = zip(
[1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1],
["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V",
"IV", "I"])
if integer <= 0 or integer >= 4000 or int(integer) != integer:
raise ValueError("expecting an integer between 1 and 3999")
result = []
for decimal, roman in coding:
while integer >= decimal:
result.append(roman)
integer -= decimal
return "".join(result) |
def make_vars(spec):
"""Returns configurable variables for make"""
return f"AZURE_REGION={spec['region']} RESOURCE_GROUP_NAME={spec['resource_group']} STORAGE_ACCOUNT_NAME={spec['storage_acc_name']} FUNCTION_APP_NAME={spec['app_name']} APPINSIGHTS_NAME={spec['app_insights_name']}" |
def u_init(x, y, xmin, xmax, ymin, ymax):
"""
initial condition
"""
center = (
.75*xmin + .25*xmax,
.50*ymin + .50*ymax
)
radius = 0.1
height = 0.5
return 1 + height * ((x-center[0])**2+(y-center[1])**2 < radius**2) |
def _indent(s, amount):
"""
Indents string `s` by `amount` doublespaces.
"""
pad = ' ' * amount
return '\n'.join([pad + i for i in s.splitlines(False)]) |
def __operator(x, w, c, noise):
"""
Operator is used to generate artificial datasets
:param w:
:param c:
:param noise:
:return:
"""
return x * w + c + noise |
def generate_network_url(project, network):
"""Format the resource name as a resource URI."""
return 'projects/{}/global/networks/{}'.format(project, network) |
def _AdditionalCriteriaAllPassed(additional_criteria):
"""Check if the all the additional criteria have passed.
Checks for individual criterion have been done before this function.
"""
return all(additional_criteria.values()) |
def rgb(red, green, blue):
"""
Make a tkinter compatible RGB color.
"""
return "#%02x%02x%02x" % (red, green, blue) |
def gradient_descent(x0, grad, step_size, T):
"""run gradient descent for given gradient grad and step size for T steps"""
x = x0
for t in range(T):
grad_x = grad(x)
x -= step_size * grad_x
return x |
def only_source_name(full_name):
"""Helper function that strips SNAPPY suffixes for samples."""
if full_name.count("-") >= 3:
tokens = full_name.split("-")
return "-".join(tokens[:-3])
else:
return full_name |
def equal_probs(num_values):
"""Make an array of equal probabilities."""
prob = 1.0 / num_values
probs = [prob for i in range(num_values)]
return probs |
def csv_to_set(x):
"""Convert a comma-separated list of strings to a set of strings."""
if not x:
return set()
else:
return set(x.split(",")) |
def nsubset(dictionary, keys):
"""Creates a new dictionary from items from another one. The 'n' stands
for 'negative', meaning that the keys form an excluded list. All keys
from the other dictionary will be extracted except for the ones explicitly
indicated. The original dictionary is left untouched.
:param dictionary: The dictionary to extract items from.
:type dictionary: dict
:param keys: The keys to not get from the dictionary.
:type keys: list
:return: The new dictionary.
:rtype: dict
"""
result = {}
for key in dictionary.keys():
# Ignore keys on the excluded list
if key in keys:
continue
result[key] = dictionary[key]
return result |
def lazy_value(value):
"""
Evaluates a lazy value by calling it when it's a callable, or returns it unchanged otherwise.
"""
return value() if callable(value) else value |
def range_ranges(ranges):
"""
Return int array generated starting on the smallest range start to the
highest range end.
"""
ranges = [n for r in ranges for n in range(r[0], r[-1] + 1)]
return sorted(list(set(ranges))) |
def serialize(tokens):
"""
Serialize tokens:
* quote whitespace-containing tokens
* escape semicolons
"""
ret = []
for tok in tokens:
if " " in tok:
tok = '"%s"' % tok
if ";" in tok:
tok = tok.replace(";", "\;")
ret.append(tok)
return " ".join(ret) |
def get_voltage_extremes(voltages):
""" Finds and returns the minimum and maximum voltages measured in the
ECG signal.
:param voltages: List of voltage measurements
:return: Tuple containing min and max voltages (floats)
"""
return min(voltages), max(voltages) |
def heatCapacity_f1(T, hCP):
"""
heatCapacity_form1(T, hCP)
slop vapor & solid phases: T in K, heat capaity in J/mol/K;
heat capacity correlation
heat capacity = A + B*T + C/T^2
Parameters
T, temperature
hCP, A=hCP[0], B=hCP[1], C=hCP[2]
A, B, and C are regression coefficients
Returns
heat capacity at T
"""
return hCP[0] + hCP[1]*T + hCP[2]/T**2 |
def display_scoped_map_with_bombs(scope, element_id, data, bombs, fills):
"""Renders a map with a close-up look to the scope the country belongs to.
Args:
scope -> datamaps scope instance.
element_id -> ID for the DOM element where the map is going to render.
This element should contain the following css rules: position, (relative),
width and height. You can set the width and a height to be a percentage but
map will not render correctly cross-browser.
data -> Json object that contains data for the popup template.
bombs -> JSON object that contains info about the bombs that the map will
render. This object needs at a minimum the lat, lon, and radius as
attributes.
fills -> JSON object with info about colors to be use for our data. It should
at least contain a defaultFill attribute.
"""
# template variables
return {'element_id': element_id, 'map_data': data,
'map_bombs': bombs, 'fills': fills, 'scope': scope} |
def to_binary(int_value: int):
"""
This method converts an int to its binary representation.
:param int_value: The int value to convert.
:return: The binary representation as str.
"""
# The implementation does not build on to_numeral
# because the native Python conversion is faster
result = bin(int_value)
if len(result) > 2:
result = result[2:len(result)]
return result |
def typed(var, types):
"""
Ensure that the "var" argument is among the types passed as the "types" argument.
@param var: The argument to be typed.
@param types: A tuple of types to check.
@type types: tuple
@returns: The var argument.
>>> a = typed('abc', str)
>>> type(a)
<type 'str'>
>>> b = typed('abc', int) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
AssertionError: Value 'abc' of type <type 'str'> is not among the allowed types: <type 'int'>
>>> c = typed(None, int) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Traceback (most recent call last):
...
AssertionError: Value None of type <type 'NoneType'> is not among the allowed types: <type 'int'>
"""
assert isinstance(var, types), \
'Value %r of type %r is not among the allowed types: %r' % (var, type(var), types)
return var |
def get_namespace(title):
"""Parses a Wiktionary page title and extracts the namespace from it.
Parameters
----------
title : str
The page title to parse.
Returns
-------
str or None
The namespace, in text, of the given title, or None for the
main namespace.
"""
if ":" in title:
return title.split(":", 2)[0]
else:
return None |
def validate_number(num, low, high):
"""
Takes user input as a string and validates that it is
an integer between low and high
"""
try:
num = int(num)
except ValueError:
return False
if num < low or num > high:
return False
return True |
def translate_version_str2int(version_str):
"""Translates a version string in format x[.y[.z[...]]] into a 000000 number.
Each part of version number can have up to 99 possibilities."""
import math
parts = version_str.split('.')
i, v, l = 0, 0, len(parts)
if not l:
return v
while i < 3:
try:
v += int(parts[i]) * int(math.pow(10, (2 - i) * 2))
l -= 1
i += 1
except ValueError:
return v
if not l:
return v
return v
try:
v += 10000 * int(parts[0])
l -= 1
except ValueError:
return v
if not l:
return v
try:
v += 100 * int(parts[1])
l -= 1
except ValueError:
return v
if not l:
return v
try:
v += int(parts[0])
l -= 1
except ValueError:
return v
if not l:
return v |
def add_segment_final_space(segments):
"""
>>> segments = ['Hi there!', 'Here... ', 'My name is Peter. ']
>>> add_segment_final_space(segments)
['Hi there! ', 'Here... ', 'My name is Peter.']
"""
r = []
for segment in segments[:-1]:
r.append(segment.rstrip() + " ")
r.append(segments[-1].rstrip())
return r |
def do_prepend(value, param='/'):
"""Prepend a string if the passed in string exists.
Example:
The template '{{ root|prepend('/')}}/path';
Called with root undefined renders:
/path
Called with root defined as 'root' renders:
/root/path
"""
if value:
return '%s%s' % (param, value)
else:
return '' |
def get_group(yaml_dict):
"""
Return the attributes of the light group
:param yaml_dict:
:return:
"""
group_name = list(yaml_dict["groups"].keys())[0]
group_dict = yaml_dict["groups"][group_name]
# Check group_dict has an id attribute
if 'id' not in group_dict.keys():
print("Error, expected to find an 'id' attribute in the group object")
return group_dict |
def message_prefix(file_format, run_type):
"""Text describing saved case file format and run results type."""
format_str = ' format' if file_format == 'mat' else ' format'
if run_type == ['PF run']:
run_str = run_type + ': '
else:
run_str = run_type + ':'
return 'Savecase: ' + file_format + format_str + ' - ' + run_str |
def mean(X):
""" Calculate mean of a list of values.
Parameters
----------
X : a list of values
"""
return sum(X) / float(len(X)) |
def is_term(uri):
"""
>>> is_term('/c/sv/kostym')
True
>>> is_term('/x/en/ify')
True
>>> is_term('/a/[/r/RelatedTo/,/c/en/cake/,/c/en/flavor/]')
False
"""
return uri.startswith('/c/') or uri.startswith('/x/') |
def target_name_conversion(targetname):
"""
NAME:
target_name_conversion
PURPOSE:
to convert targetname to string used to plot graph
INPUT:
targetname (string)
OUTPUT:
converted name (string)
HISTORY:
2017-Nov-25 - Written - Henry Leung (University of Toronto)
"""
targetname.replace("/H]", "")
targetname.replace("/Fe]", "")
targetname.replace("[", "")
if targetname == 'C1':
fullname = 'CI'
elif len(targetname) < 3:
fullname = f'[{targetname}/H]'
elif targetname == 'teff':
fullname = r'$T_{\mathrm{eff}}$'
elif targetname == 'alpha':
fullname = '[Alpha/M]'
elif targetname == 'logg':
fullname = '[Log(g)]'
elif targetname == 'Ti2':
fullname = '[TiII/H]'
else:
fullname = targetname
return fullname |
def choices_from_dict(source, prepend_blank=True):
"""
Convert a dict to a format that's compatible with WTForm's choices.
It also optionally prepends a "Please select one..." value.
Example:
# Convert this data structure:
STATUS = OrderedDict([
('unread', 'Unread'),
('open', 'Open'),
('contacted', 'Contacted'),
('closed', 'Closed')
])
# Into this:
choices = [("", "Please select one..."), ("unread", "Unread") ... ]
:param source: Input source
:type source: dict
:param prepend_blank: An optional blank item
:type prepend_blank: bool
:return: list
"""
choices = []
if prepend_blank:
choices.append(("", "Please select one..."))
for key, value in source.items():
pair = (key, value)
choices.append(pair)
return choices |
def euclidean_gcd(a,b):
"""Euclidean Algorithm to find greatest common divisor.
Euclidean algorithm is an efficient method for computing
the greatest common divisor (GCD) of two integers (numbers),
the largest number that divides them both without a remainder [Wiki].
Args:
a (int): The first integer, > 0,
b (int): The second integer, > 0.
Returns:
int: the greatest common divisor.
"""
if a < b:
a,b = b,a
while a > b:
a = a - b
if (a != b):
#print("a =", a, "b =", b)
a = euclidean_gcd(b, a)
return a |
def concat(arrays):
"""
Concatenates an array of arrays into a 1 dimensional array.
"""
concatenated = arrays[0]
if not isinstance(concatenated, list):
raise ValueError(
"Each element in the concatenation must be an instance "
"of `list`."
)
if len(arrays) > 1:
for array in arrays[1:]:
if not isinstance(array, list):
raise ValueError(
"Each element in the concatenation must be an instance "
"of `list`."
)
concatenated += array
return concatenated |
def clean_row(review):
"""
Cleans out a review and converts to list of words.
Currently only removes empty elements left after removing some punctuations.
Args:
review(str): The review in string format.
Returns:
List of words in the accepted review, cleaned.
"""
return [word for word in review.split(' ') if word != ''] |
def prepend_xpath(pre, xpath, glue=False):
"""Prepend some xpath to another, properly joining the slashes
"""
if (not pre) or xpath.startswith('//'):
# prefix doesn't matter
return xpath
if pre.endswith('./'):
if xpath.startswith('./'):
return pre[:-2] + xpath
elif xpath.startswith('/'): # including '//'
return pre[:-1] + xpath
elif pre.endswith('//'):
return pre + xpath.lstrip('/')
elif pre.endswith('/') and xpath.startswith('/'):
return pre[:-1] + xpath
elif pre.endswith('/') and xpath.startswith('./'):
return pre + xpath[2:]
elif pre.endswith('::'):
if xpath.startswith('.//'):
return pre + '*/descendant-or-self::' + xpath[3:]
elif xpath.startswith('./'):
return pre + xpath[2:]
else:
return pre + xpath.lstrip('/')
elif xpath.startswith('./'):
return pre + xpath[1:]
elif glue and not pre.endswith('/') and xpath[0].isalpha():
if glue is True:
glue = '/'
return pre + glue + xpath
return pre + xpath |
def get_label(genotype_type):
"""
Get genotype label for a type of genotype
:param genotype_type: Genotype in string
:return: Integer label for the type
"""
if genotype_type == "Hom":
return 0
elif genotype_type == "Het":
return 1
elif genotype_type == "Hom_alt":
return 2 |
def remove_hyphens(s):
"""
:param s:
:return:
"""
return ' - '.join([x.replace('-', ' ') for x in s.split(' - ')]) |
def join_authors(list):
"""Joins pubmed entry authors to a single string"""
return ", ".join([x["name"] for x in list]) |
def transit_mask(time, t0, duration, porb):
"""
Mask out transits
Args:
t0 (float): The reference time of transit in days.
For Kepler data you may need to subtract 2454833.0 off this
number.
duration (float): The transit duration in hours.
porb (float): The planet's orbital period in days.
"""
dur = float(duration) / 24.
inv_mask = ((time - (t0 - .5*dur)) % porb) < dur
mask = inv_mask == False
return mask |
def expand_dic(vid_vidx, l_vid_new):
"""Expands a dictionnary to include new videos IDs
vid_vidx: dictionnary of {video ID: video idx}
l_vid_new: int list of video ID
Returns:
- dictionnary of {video ID: video idx} updated (bigger)
"""
idx = len(vid_vidx)
for vid_new in l_vid_new:
if vid_new not in vid_vidx:
vid_vidx[vid_new] = idx
idx += 1
return vid_vidx |
def dot_prod(a, b):
"""
Calculates the dot product of two lists with values
:param a: first list
:param b: second list
:return: dot product (a . b)
"""
return sum([i*j for (i, j) in zip(a, b)]) |
def PNT2QM_Pv4(XA,chiA):
""" TaylorT2 2PN Quadrupole Moment Coefficient, v^4 Phasing Term.
XA = mass fraction of object
chiA = dimensionless spin of object """
return -25.*XA*XA*chiA*chiA |
def round_to_second(time):
"""Rounds a time in days to the nearest second.
Parameters
----------
time: int
The number of days as a float.
Returns
-------
float
The number of seconds in as many days.
"""
return(round(time * 86400)/86400.0) |
def divisors(number, primes):
"""Finds number of divisors of a number using prime factorization."""
prime_factors_pow = []
if number < 2:
prime_factors_pow.append(0)
for p in primes:
if p > number:
break
n = 0
while number % p == 0:
n += 1
number //= p
prime_factors_pow.append(n)
num_divisors = 1
for k in prime_factors_pow:
num_divisors *= k + 1
return num_divisors |
def zero_plentiful3(arr):
"""."""
four_plus = 0
res = []
for char in arr:
if char == 0:
res.append(char)
if char != 0:
if len(res) >= 4:
four_plus += 1
for x in res:
res.pop()
if len(res) < 4 and len(res) > 0:
return 0
return four_plus |
def find_download_urls(release_page_body):
"""
find_download_urls is parse and grep tarfind_urls.
:param release_page_body:
"""
file_urls = []
if isinstance(release_page_body, list):
for paresr in release_page_body:
file_urls.extend(find_download_urls(paresr))
elif isinstance(release_page_body, dict):
if release_page_body.get("browser_download_url"):
file_urls.append(release_page_body.get("browser_download_url"))
else:
for value in release_page_body.values():
file_urls.extend(find_download_urls(value))
return file_urls |
def base62_encode(num: int) -> str:
"""
http://stackoverflow.com/questions/1119722/base-62-conversion
"""
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
num, rem = divmod(num, base)
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr) |
def encode_varint(number: int) -> bytes:
"""
Encode varint into bytes
"""
# Shift to int64
number = number << 1
buf = b""
while True:
towrite = number & 0x7F
number >>= 7
if number:
buf += bytes((towrite | 0x80,))
else:
buf += bytes((towrite,))
break
return buf |
def minimal_roman(value):
"""
Return minimal form of value in roman numeral
"""
tmp = ''
# First the thousands
quot = value//1000
res = value%1000
for i in range(quot):
tmp += 'M'
# Second the centuries
quot = res//100
res = res%100
if quot==9:
tmp += 'CM'
elif quot==4:
tmp += 'CD'
elif quot<4:
for i in range(quot):
tmp += 'C'
else:
tmp +='D'
for i in range(quot-5):
tmp += 'C'
# Third the decades
quot = res//10
res = res%10
if quot==9:
tmp += 'XC'
elif quot==4:
tmp += 'XL'
elif quot<4:
for i in range(quot):
tmp += 'X'
else:
tmp +='L'
for i in range(quot-5):
tmp += 'X'
# And fourth the units
if res==9:
tmp += 'IX'
elif res==4:
tmp += 'IV'
elif res<4:
for i in range(res):
tmp += 'I'
else:
tmp +='V'
for i in range(res-5):
tmp += 'I'
return tmp |
def op_inv(x):
"""Finds the inverse of a mathematical object."""
if isinstance(x, list):
return [op_inv(a) for a in x]
else:
return 1 / x |
def convert_nt(nt: int) -> float:
""" Convert a nucleotide position/width to a relative value.
Used to calculate relative values required for polar plots.
Args:
nt: position/width in nucleotides
Returns:
relative value
"""
return (nt * 6.29) / 16569 |
def get_attributes(attrs):
"""return attributes string for input dict
format: key="value" key="value"...
spaces will be stripped
"""
line = ''
for i,j in attrs.items():
s = ''
# Caution! take care when value is list
if isinstance(j,list):
for k in j: s += k + ' '
s = s.strip()
else:
s = j
line += '%s="%s" ' % (i,s)
return line.strip() |
def _unmangle_name(mangled_name, class_name):
"""Transform *mangled_name* (which is assumed to be a
"_ClassName__internal" name) into an "__internal" name.
:arg str mangled_name:
a mangled "_ClassName__internal" member name
:arg str class_name:
name of the class where the (unmangled) name is defined
:return:
the transformed "__internal" name
:rtype:
str
"""
return mangled_name.replace("_%s" % class_name.lstrip('_'), "") |
def get_gender_it(word, context=""):
"""
In Italian to define the grammatical gender of a word is necessary
analyze the article that precedes the word and not only the last
letter of the word.
"""
gender = None
words = context.split(' ')
for idx, w in enumerate(words):
if w == word and idx != 0:
previous = words[idx - 1]
gender = get_gender_it(previous)
break
if not gender:
if word[-1] == 'a' or word[-1] == 'e':
gender = 'f'
if word[-1] == 'o' or word[-1] == 'n' \
or word[-1] == 'l' or word[-1] == 'i':
gender = 'm'
return gender |
def join_germanic(iterable, capitalize=True, quoteChars="\"", concat="'"):
"""Like "".join(iterable) but with special handling, making it easier to just concatenate a list of words.
Tries to join an interable as if it was a sequence of words of a generic western germanic language. Inserts a space between each word.
If capitalize=True any word following a single period character ("."), will be capitalized.
quoteChars specifies a string of characters that specifies a quote. It tries to be smart about the quotes and keep track of when they start and end.
The following conditions yield a space before the current "word":
- Current is not "." and the previous was ".".
- Previous is not in quoteChars or deemed a start quote.
- Current is not in quoteChars and deemed a start quote.
- Current is not "!?,:;".
Any word in concat, will never have spaces around it.
The above rules should ensure that things like [".", ".", "."] yields a "... ", that quotes look reasonably okay ["Hey", "\"", "Friend", "\""] yields "Hey \"Friend\"".
The function has no concept of semantics, and is thus limited in what it can do.
For example if quoteChars="'", it won't know whether an apostrophe is an apostrophe or a quote.
"""
def mkcapital(w):
return w.capitalize()
def nopmkcapital(w):
return w
capital = mkcapital if capitalize else nopmkcapital
quoteLevels = {c: 0 for c in quoteChars}
# Check whether c is a quote, and handle it.
def checkQuote(c):
if c in quoteChars:
ql = quoteLevels[c]
# If we have already seen this quote, decrement, if not we increment.
# This way we can know how many start quotes we have seen
if ql > 0:
ql -= 1
else:
ql += 1
quoteLevels[c] = ql
s = ""
last = ""
for w in iterable:
w = str(w)
space = True if last != "" else False
# Don't add spaces around concat-words.
if w in concat or last in concat:
space = False
# "."" followed by more "."
elif last.endswith("."):
w = capital(w)
if w.startswith("."):
space = False
# Remove space after last word in a sentence or certain punctuation.
elif w in ".!?,;:":
space = False
# The last two takes care of end and start quotes.
elif w in quoteChars:
ql = quoteLevels[w]
if ql == 1:
space = False
elif last != "" and last in quoteChars:
ql = quoteLevels[last]
if ql == 1:
space = False
checkQuote(w)
if space:
s += " "
s += w
last = w
return s |
def _label_tuple_to_text(label, diff, genes=None):
"""
Converts the variant label tuple to a string.
Parameters
----------
label : tuple(str)
A tuple of (chrom, pos, ref, alt).
diff : float
The max difference score across some or all features in the model.
genes : list(str) or None, optional
Default is None. If the closest protein-coding `genes` are specified,
will display them in the label text.
Returns
-------
str
The label text.
"""
chrom, pos, ref, alt = label
if genes is not None:
if len(genes) == 0:
genes_str = "none found"
else:
genes_str = ', '.join(genes)
text = ("max diff score: {0}<br />{1} {2}, {3}/{4}<br />"
"closest protein-coding gene(s): {5}").format(
diff, chrom, pos, ref, alt, genes_str)
else:
text = "max diff score: {0}<br />{1} {2}, {3}/{4}".format(
diff, chrom, pos, ref, alt)
return text |
def maybe_int(string):
"""Convert string to an integer and return the integer or None."""
try:
return int(string)
except ValueError:
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.