content stringlengths 42 6.51k |
|---|
def escape(text: str) -> str:
"""Make escaped text."""
return text.replace('&', '&').replace('<', '<').replace('>', '>') |
def format_(string):
"""dos2unix and add newline to end if missing."""
string = string.replace('\r\n', '\n').replace('\r', '\n')
if not string.endswith('\n'):
string = string + '\n'
return string |
def _get_pages(current_page, last_page):
"""Return a list of pages to be used in the rendered template from the
last page number."""
pages = []
if current_page > 3:
pages.append(1)
if current_page > 4:
pages.append('...')
pages.extend(
range(
max(current_page - 2, 1), min(current_page + 3, last_page)
)
)
if current_page < last_page - 3:
pages.append('...')
if last_page not in pages:
pages.append(last_page)
return pages |
def scrap_last_name(file):
"""
Getting folder name from the splitted file_name
If the file_name is data_FXVOL_20130612.xml, then the folder name returned will be '201306'
"""
if file.startswith('data_') and file.endswith('.xml') and file.count('_') == 2:
split_name = file.split('_')
return split_name[2][0:6] |
def index( items ):
"""Index of the first nonzero item.
Args:
items: Any iterable object
Returns:
The index of the first item for which bool(item) returns True.
"""
for i, item in enumerate(items):
if item:
return i
raise ValueError |
def regex_join(*regexes: str) -> str:
"""Join regular expressions with logical-OR operator '|'.
Args:
*regexes: regular expression strings to join.
Return:
Joined regular expression string.
"""
regex = "|".join([r for r in regexes if r])
return regex |
def get_line_data(line, separator=None):
"""Converts a line scraped from a web page into a list.
Parameters:
- line, a line scraped (read) from a web page. The type is <class 'bytes'>.
- separator (optional, default value None). If set, becomes the optional
separator argument to the .split() method to determine where one element
in the returned list ends and the next begins. If separator is omitted,
or None, whitespace is used as an elements separator.
Assumptions:
- line is of type <class 'bytes'> (a raw line of input from a web page).
Returned value:
- A list of non-separator tokens from line, the elements of which are
numbers if the original tokens appear to be numeric, and strings
otherwise.
"""
decoded = line.decode('utf-8') # Turn line into a str.
decoded = decoded.rstrip() # Get rid of trailing newline character
# Allow for whitespace separator (or not)
if separator is not None:
lst = decoded.split(separator) # separator is not whitespace
else:
lst = decoded.split(); # separator IS whitespace (default)
# Turn elements that look like numbers into numbers
for i in range(len(lst)):
try: # try conversion of the element to an int first...
lst[i] = int(lst[i])
except ValueError:
try: # ... then try conversion to a float...
lst[i] = float(lst[i])
except ValueError: # ... then give up (leave element as a str)
pass
return lst |
def roi_to_zoom(roi, resolution):
"""Gets x,y,w,h zoom parameters from region of interest coordinates"""
((x1,y1),(x2,y2)) = roi
z0 = round(x1 / resolution[0],2)
z1 = round(y1 / resolution[1],2)
z2 = round((x2-x1) / resolution[0],2)
z3 = round((y2-y1) / resolution[1],2)
return (z0, z1, z2, z3) |
def count_in_progress(state, event):
"""
Count in-progress actions.
Returns current state as each new produced event,
so we can see state change over time
"""
action = event['action']
phase = event['phase']
if phase == 'start':
state[action] = state.get(action, 0) + 1
elif phase == 'complete':
state[action] = state[action] - 1
elif phase.startswith('fail'):
# Using startswith because some events use 'failure' vs 'failed'
state[action] = state[action] - 1
state[f'{action}.failed'] = state.get(f'{action}.failed', 0) + 1
state['timestamp'] = event['timestamp']
return state, state |
def format_action(action):
"""Format request action."""
return '<name>{0}</name>'.format(action) |
def count_iter(iterator):
"""Efficiently count number of items in an iterator"""
return sum(1 for _ in iterator) |
def mk_url(address, port, password):
""" construct the url call for the api states page """
url = ''
if address.startswith('http://'):
url += address
else:
url += 'http://' + address
url += ':' + port + '/api/states?'
if password is not None:
url += 'api_password=' + password
return url |
def promptNsfwDownload(postSafetyLevel : int) -> bool:
"""Prompts the user if the download should continue on sensitive/NSFW posts"""
# prompt for NSFW download:
while True:
#prompt response
nsfwPrompt = ""
# verify post safetly level
# newly-discovered criteria:
# SL = 4: potentially sensitive post, not necessarily NSFW
# SL = 6: NSFW (R18+) post
if postSafetyLevel == 4:
nsfwPrompt = input("WARNING: This post may contain sensitive media. Proceed with download? [y/N] ")
elif postSafetyLevel == 6:
nsfwPrompt = input("WARNING: This post contains explicit (e.g. sexual) content. Proceed with download? [y/N] ")
if (str(nsfwPrompt).lower() == "n") or (nsfwPrompt == ""):
# if N or no answer is entered, abort
print("Aborting download for this post.")
return False
elif str(nsfwPrompt).lower() == "y":
# download
return True |
def input_validation(input):
"""
This function is used to test the stock ticker inputs and validate that they
pass the two key characteristics tests: being less than 5 characters in length
and having no digits.
@param: input is a string argument that represents the given input the consumer gave as a ticker.
"""
result_bool = True
if any(char.isdigit() for char in input) == True:
result_bool = False
if len(input) > 5:
result_bool = False
return result_bool |
def sum_distributions(actual, update):
"""
Sum distributions of two distribution arrays
:param actual: first dict with distribution array
:param update: second dict with distribution array
:return: Dictionary with sum of distribution as a value of "distributions" key and output information
"""
for key in actual['distributions'].keys():
actual['distributions'][key] = [x + y for x, y in zip(actual['distributions'][key], update['distributions'][key])]
return {'distributions': actual['distributions'], 'output': actual['output']} |
def count_common_words(x, y):
""" Extract number of common word between two strings """
try:
words, cnt = x.split(), 0
for w in words:
if y.find(w) >= 0:
cnt += 1
return cnt
except Exception as e:
print(f"Exception raised:\n{e}")
return 0 |
def is_happy(n):
"""
Determine whether or not a number is happy
:param n: given number
:type n: int
:return: whether or not a number is happy
:rtype: bool
"""
def digits_square(num):
"""
Compute the sum of the squares of digits of given number
:param num: given number
:type num: int
:return: result
:rtype: int
"""
new_num = 0
while num > 0:
new_num += (num % 10) ** 2
num //= 10
return new_num
if n < 0:
return False
elif n == 1:
return True
count = []
while n != 1:
n = digits_square(n)
if n == 1:
return True
elif n in count:
return False
else:
count.append(n) |
def url_validator(value):
"""A custom method to validate any website url """
import re
regex = re.compile(
r'^https?://|www\.|https?://www\.' # http:// or https:// or www.
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' #domain...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$',
re.IGNORECASE)
if value and not regex.match(value):
raise AssertionError("Please enter a valid website URL")
return value |
def pathway(nodes):
"""
Converts a list of joined nodes into the pairwise steps
Parameters
----------
nodes : list
list of integers of nodes to convert
Returns
-------
List of tuples of edges involved in pathway
"""
steps = []
for i in range(len(nodes) - 1):
steps.append((nodes[i], nodes[i + 1]))
steps.append((nodes[-1], nodes[0]))
return steps |
def nested_dict_var_dicts(var, var_list=[]):
"""Searches a nested dictionary for a key and returns the first key it finds.
Returns None if not found.
Warning: if key is in multiple nest levels,
this will only return one of those values."""
if hasattr(var, 'iteritems'):
for k, v in var.items():
if 'nom' in v:
var_list.append(str(k))
break
if isinstance(v, dict):
var_list = nested_dict_var_dicts(var, var_list)
return var_list |
def celsius(value: float, target_unit: str) -> float:
"""
Utility function for Celsius conversion in Kelvin or in Fahrenheit
:param value: temperature
:param target_unit: Celsius, Kelvin or Fahrenheit
:return: value converted in the right scale
"""
if target_unit == "K":
# Convert in Kelvin scale
return value + 273.15
else:
# Convert in Fahrenheit scale
return value * 1.8 + 32 |
def convertBytes(num):
"""
this function will convert bytes to MB.... GB... etc
"""
for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if num < 1024.0:
return "%3.1f %s" % (num, x)
num /= 1024.0 |
def get_loss_and_metrics(fcn, **kwargs):
"""Get both loss and metrics from a callable."""
loss = fcn(**kwargs)
metrics = {}
if isinstance(loss, dict):
metrics = loss.get('metrics', {})
loss = loss['loss']
return loss, metrics |
def pmvAtomStrip(atom, mol_name = None):
""" transform PDB(QT) atoms to PMV syntax
"ATOM 455 N GLY A 48 -2.978 5.488 6.818 1.00 11.64 -0.351 N" (xJ1_xtal)
|
\./
'
xJ1_xtal:A:GLY48:N
"""
chain = atom[21].strip()
res_name = atom[16:21].strip()
res_num = atom[22:26].strip()
atom = atom[12:16].strip()
if not mol_name:
return "%s:%s%s:%s" % (chain, res_name, res_num, atom)
else:
return "%s:%s:%s%s:%s" % (mol_name, chain, res_name, res_num, atom) |
def cver(verstr):
"""Converts a version string into a number"""
if verstr.startswith("b"):
return float(verstr[1:])-100000
return float(verstr) |
def is_a_pooling_layer_label(layer_label):
""" Returns true if a pooling layer. """
return 'pool' in layer_label |
def feature_collection(
data, lat_field="latitude", lon_field="longitude", spatial_ref=4326
):
"""
Assemble an ArcREST featureCollection object
spec: http://resources.arcgis.com/en/help/arcgis-rest-api/#/Feature_object/02r3000000n8000000/
"""
features = []
for record in data:
new_record = {
"attributes": {},
"geometry": {"spatialReference": {"wkid": spatial_ref}},
}
new_record["attributes"] = record
if record.get("paths"):
# Handle polyline geometry
new_record["geometry"]["paths"] = record.pop("paths")
elif record.get(lat_field) and record.get(lon_field):
# Handle point geometry
new_record["geometry"]["x"] = record.get(lon_field)
new_record["geometry"]["y"] = record.get(lat_field)
else:
# strip geometry from records with missing/unkown geometry data
new_record.pop("geometry")
features.append(new_record)
return features |
def cohort_aggregator(results):
""" Aggregate the number of individuals included in the cohort
definition.
"""
count = {}
for result in results:
count[result[0]] = result[1]
return count |
def extract_hashtags(text):
"""
Extracts a list with the hashtags that are included inside a text.
Args:
text: (str) The raw text.
Returns:
List with the found hashtags.
"""
return list(set(part for part in text.split() if part.startswith('#'))) |
def format_changes_plain(oldf, # type: str
newf, # type: str
changes, # type: list
ignore_ttl=False
): # type: (...) -> str
"""format_changes(oldfile, newfile, changes, ignore_ttl=False) -> str
Given 2 filenames and a list of changes from diff_zones, produce diff-like
output. If ignore_ttl is True, TTL-only changes are not displayed"""
ret = "--- {}\n+++ {}\n".format(oldf, newf)
for name, old, new in changes:
ret += "@ %s\n" % name
if not old:
for r in new.rdatasets:
ret += "+ %s\n" % str(r).replace('\n', '\n+ ')
elif not new:
for r in old.rdatasets:
ret += "- %s\n" % str(r).replace('\n', '\n+ ')
else:
for r in old.rdatasets:
if r not in new.rdatasets or (
r.ttl != new.find_rdataset(r.rdclass, r.rdtype).ttl and
not ignore_ttl
):
ret += "- %s\n" % str(r).replace('\n', '\n+ ')
for r in new.rdatasets:
if r not in old.rdatasets or (
r.ttl != old.find_rdataset(r.rdclass, r.rdtype).ttl and
not ignore_ttl
):
ret += "+ %s\n" % str(r).replace('\n', '\n+ ')
return ret |
def k_to_f(degrees):
"""
Convert degrees kelvin to degrees fahrenheit
"""
return degrees * 9/5 - 459.67 |
def read_DDTpos(inhdr):
"""
Read reference wavelength and DDT-estimated position from DDTLREF and
DDT[X|Y]P keywords. Will raise KeyError if keywords are not available.
"""
try:
lddt = inhdr['DDTLREF'] # Ref. wavelength [A]
xddt = inhdr['DDTXP'] # Predicted position [spx]
yddt = inhdr['DDTYP']
except KeyError as err:
raise KeyError("File has no DDT-related keywords (%s)" % err)
# Some sanity check
if not (abs(xddt) < 7 and abs(yddt) < 7):
raise KeyError(
"Invalid DDT position: %.2f x %.2f is outside FoV" % (xddt, yddt))
return lddt, xddt, yddt |
def _reg2float(reg):
"""Converts 32-bit register value to floats in Python.
Parameters
----------
reg: int
A 32-bit register value read from the mailbox.
Returns
-------
float
A float number translated from the register value.
"""
if reg == 0:
return 0.0
sign = (reg & 0x80000000) >> 31 & 0x01
exp = ((reg & 0x7f800000) >> 23) - 127
if exp == 0:
man = (reg & 0x007fffff) / pow(2, 23)
else:
man = 1 + (reg & 0x007fffff) / pow(2, 23)
result = pow(2, exp) * man * ((sign * -2) + 1)
return float("{0:.2f}".format(result)) |
def Join(sourcearray, delimeter=" "):
"""Join a list of strings"""
s_list = map(str, sourcearray)
return delimeter.join(s_list) |
def recvall(sock, n):
"""helper function to receive n bytes from (sock)et or return None if EOF is hit"""
data = b''
while len(data) < n:
packet = sock.recv(n - len(data))
if not packet:
return None
data += packet
return data |
def get_with_path(d, path):
"""In a nested dict/list data structure, set the entry at path.
In a data structure composed of dicts, lists and tuples, apply each
key in sequence, return the result.
Args:
d: Dict/list/tuple data structure
path: List of keys
Returns:
Whatever is in the data structure at that path.
"""
my_d = d
for key in path:
my_d = my_d[key]
return my_d |
def n_considered_cells(cc, look_at):
"""
Calculates the number of considered cells
"""
count = 0
for p in cc:
if not look_at[p]:
continue
if p==0 or cc[p]==0:
continue
count += 1
return count |
def create_index_query(node_type, indexed_property):
""" Create the query for the index statement. See:
https://neo4j.com/docs/cypher-manual/current/indexes-for-search-performance/
"""
print(f'CREATE INDEX ON :{node_type}({indexed_property});')
return f'CREATE INDEX ON :{node_type}({indexed_property});' |
def insertionSort(array):
"""returns sorted array"""
length = len(array)
for i in range(1, length):
key = array[i]
j = i - 1
while(j>=0 and key < array[j]):
array[j+1] = array[j]
j -= 1
array[j+1] = key
return array |
def get_coords_animal(position, animal):
"""
Retourne toutes les coordonnes de l'animal
a parti de la position du coin en bas a gauche
"""
lvects = animal[2]
lpos = []
for v in lvects:
lpos.append((position[0]+v[0], position[1] + v[1]))
return lpos |
def parse_version(s):
"""poor man's version comparison"""
return tuple(int(p) for p in s.split('.')) |
def get_domain(email):
"""Get a domain from the e-mail address.
"""
split = email.split('@')
if len(split) < 2:
return ''
domain = split[1]
# FIXME Quick hack: foo.example.com -> example.com
if (domain != 'users.noreply.github.com'
and domain.endswith('.com')):
split = domain.rsplit('.', 3)
if len(split) > 2:
domain = '.'.join(split[-2:])
return domain |
def validate_cISSN(issn:str) -> bool:
"""
Validates the last character (c) of the ISSN number, based on the first 7 digits
returns: boolean: True if c is valid False otherwise
"""
assert type(issn) == str, "issn must be a string"
issn_num = issn[:4] + issn[5:-1]
issn_c = issn[-1]
# check c validity
issn_num_sum = 0
inv_index = 8
for num in issn_num:
num = int(num)
issn_num_sum += num*inv_index
inv_index -= 1
mod = issn_num_sum%11
if mod == 0: c = 0
else:
c = 11-mod
if c == 10: c = 'X'
return str(c) == issn_c |
def fizz_buzz(number: int) -> str:
"""
Play Fizz buzz
:param number: The number to check.
:return: 'fizz' if the number is divisible by 3.
'buzz' if it's divisible by 5.
'fizz buzz' if it's divisible by both 3 and 5.
The number, as a string, otherwise.
"""
if number % 15 == 0:
return "fizz buzz"
elif number % 3 == 0:
return "fizz"
elif number % 5 == 0:
return "buzz"
else:
return str(number) |
def average(a, b):
"""Return the average of two RGB colors."""
return (
(a[0] + b[0]) // 2,
(a[1] + b[1]) // 2,
(a[2] + b[2]) // 2) |
def is_snp(var):
"""
Check if var is a SNP (not an indel)
Args:
var: A variant string
Returns:
True if var represents a SNP, False otherwise.
"""
if '.' in var or 'd' in var:
return False # Variant is an indel
return True |
def find_cl_max_length(codelist):
"""
find and return the length of the longest term in the codelist
:param codelist: codelist of terms
:return: integer length of the longest codelist item
"""
max_length = 0
for term in codelist.split(", "):
if len(term) > max_length:
max_length = len(term)
return max_length |
def RMS(goal, output):
"""
Calc the RMS for a single element
"""
return ((goal - output) ** 2) / 2 |
def filter_dict(regex_dict, request_keys):
"""
filter regular expression dictionary by request_keys
:param regex_dict: a dictionary of regular expressions that
follows the following format:
{
"name": "sigma_aldrich",
"regexes": {
"manufacturer": {
"regex": "[C|c]ompany(?P\u003cdata\u003e.{80})",
"flags": "is"
},
"product_name": {
"regex": "\\s[P|p]roduct\\s(?P\u003cdata\u003e.{80})",
"flags": "is"
},
...
}
returns
{
'sigma_aldrich': {
"manufacturer": {
"regex": "[C|c]ompany(?P\u003cdata\u003e.{80})",
"flags": "is"
},
}
:param request_keys: a list of dictionary keys that correspond to valid
regex lookups i.e. ['manufacturer', 'product_name']
"""
out_dict = dict()
nested_regexes = regex_dict['regexes']
for request_key in request_keys:
if request_key in nested_regexes:
out_dict[request_key] = nested_regexes[request_key]
return {'name': regex_dict['name'], 'regexes': out_dict} |
def _parse_nyquist_vel(nyquist_vel, radar, check_uniform):
""" Parse the nyquist_vel parameter, extract from the radar if needed. """
if nyquist_vel is None:
nyquist_vel = [radar.get_nyquist_vel(i, check_uniform) for i in
range(radar.nsweeps)]
else: # Nyquist velocity explicitly provided
try:
len(nyquist_vel)
except: # expand single value.
nyquist_vel = [nyquist_vel for i in range(radar.nsweeps)]
return nyquist_vel |
def get_clean_lnlst(line):
"""
Clean the input data so it's easier to handle
"""
# Split line
lnlst = line.split()
# Return proper value
if "Label" in line:
return [lnlst[1], lnlst[-1]]
elif "star" in line:
return lnlst
else:
return None |
def getIter(object):
"""Return an iterator (if any) for object
"""
iterator = None
try:
iterator = iter(object)
except TypeError:
pass
return iterator |
def determine_keypress(index):
"""
Determines the appropriate key to press for a given index. Utility function to convert the index of the maximum
output value from the neural net into a string containing w, a, s, or d. Returns None if the maximum value from the
output layer is found at index 4.
- :param index:
An int containing the index of the maximum value from the output layer of the neural network.
- :return:
A string containing "w", "a", "s", or "d", or None.
"""
if index == 0:
return "w"
elif index == 1:
return "a"
elif index == 2:
return "s"
elif index == 3:
return "d"
else:
return None |
def _make_retry_timeout_kwargs(retry, timeout):
"""Helper for methods taking optional retry / timout args."""
kwargs = {}
if retry is not None:
kwargs["retry"] = retry
if timeout is not None:
kwargs["timeout"] = timeout
return kwargs |
def _alphabetically_first_motif_under_shift(motif):
"""Return the permutation of the given repeat motif that's first alphabetically.
Args:
motif (str): A repeat motif like "CAG".
Return:
str: The alphabetically first repeat motif.
"""
minimal_motif = motif
double_motif = motif + motif
for i in range(len(motif)):
current_motif = double_motif[i:i+len(motif)]
if current_motif < minimal_motif:
minimal_motif = current_motif
return minimal_motif |
def isgrashof(l1,l2,l3,l4):
"""
Determine if a four-bar linkage is Grashof class.
"""
links = [l1,l2,l3,l4]
S = min(links) # Shortest link
L = max(links) # Largest link
idxL = links.index(L)
idxS = links.index(S)
P, Q = [links[idx] for idx in range(len(links)) if not(idx in (idxL,idxS))] #other links
if (S + L) <= (P + Q): # Checks Grashof condition
return True
else:
return False |
def guess_rgb(shape):
"""
Guess if the passed shape comes from rgb data.
If last dim is 3 or 4 assume the data is rgb, including rgba.
Parameters
----------
shape : list of int
Shape of the data that should be checked.
Returns
-------
bool
If data is rgb or not.
"""
ndim = len(shape)
last_dim = shape[-1]
if ndim > 2 and last_dim < 5:
rgb = True
else:
rgb = False
return rgb |
def is_special(name):
"""
Return True if the name starts and ends with a double-underscore.
Such names typically have special meaning to Python, e.g. :meth:`__init__`.
"""
return name.startswith('__') and name.endswith('__') |
def get_dict_for_required_fields(required_fields):
"""This function places the required fields in a properly formatted dictionary.
:param required_fields: The board ID, title and type
:type required_fields: tuple, list, set
:returns: Dictionary containing the required fields
"""
field_dict = {
'id': required_fields[0],
'title': required_fields[1],
'conversation_style': required_fields[2]
}
return field_dict |
def bool_deserializer(x):
"""
This is to be used to deserialize boolean : we consider that if
the value is "", then we should return true in order to be
able to parse boolean from query strings.
eg: http://myhost.com/index?loggedin&admin&page=5
is equivalent to
http://myhost.com/index?loggedin=True&admin=True&page=5
"""
return x is not None and (x == "" or x.lower() == "true" ) |
def bubbleSort(lst: list) -> list:
"""Return a new list in acsending order."""
over = False
while not over:
over = True
for i in range(len(lst) - 1):
if lst[i] > lst[i + 1]:
lst[i], lst[i + 1] = lst[i + 1], lst[i]
over = False
return lst |
def header_name_to_django(header_name):
"""
Convert header into Django format with HTTP prefix.
Args:
header_name: HTTP header format (ex. X-Authorization)
Returns:
django header format (ex. HTTP_X_AUTHORIZATION)
"""
return '_'.join(('HTTP', header_name.replace('-', '_').upper())) |
def find_main_field(field_str):
"""Find main (most frequent) field of a researcher."""
from collections import Counter
try:
fields = field_str.split("|")
return Counter(fields).most_common(1)[0][0]
except AttributeError:
return None |
def service_plan_resource_name(value: str) -> str:
"""Retreive the resource name for a Azure app service plan.
The reason to make this conditional is because of backwards compatability;
existing environments already have a `functionapp` resource. We want to keep that intact.
"""
if value == "default":
return "functionapps"
return f"functionapps_{value}" |
def short_name(name, max_subparts=1):
"""
Take only first subpart of string if it contains more than one part.
Used to extract only first part of first name.
"""
return ' '.join(name.split(' ')[:max_subparts]) |
def to_readable_bytes(byte_count: int or None) -> str:
"""Take in a number of bytes (integer) and write it out in a human readable format (for printing). This
method will output a number like "23.52 GiBs", "1.3 MiBs", or "324.45 KiBs" for the corresponding byte count.
1 GiB = 1024 MiBs, 1 MiB = 1024 KiBs, and 1 KiB = 1024 Bytes.
:param byte_count: The number of bytes to format
:return: The human-readable string
"""
if type(byte_count) != int:
return "??? Bytes"
if byte_count < 2 ** 20: # MiB = 2^20
return str(round(byte_count / 2 ** 10, 2)) + ' KiBs'
if byte_count < 2 ** 30: # GiB = 2^30
return str(round(byte_count / 2 ** 20, 2)) + ' MiBs'
else:
return str(round(byte_count / 2 ** 30, 2)) + ' GiBs' |
def escape_tex(text):
"""Substitutes characters for generating LaTeX sources files from Python."""
return text.replace(
'%', '\%').replace(
'_', '\_').replace(
'&', '\&') |
def lerp_color(cold, hot, t):
"""
Linearly interpolates between two colors
Arguments:
color1 - RGB tuple representing a color
color2 - RGB tuple representing a color
t - float between 0 and 1
"""
r1, g1, b1 = cold
r2, g2, b2 = hot
r = int(r1 + (r2 - r1) * t)
g = int(g1 + (g2 - g1) * t)
b = int(b1 + (b2 - b1) * t)
return (r, g, b) |
def collect_context_modifiers(instance, include=None, exclude=None, extra_kwargs=None):
"""
helper method that updates the context with any instance methods that start
with `context_modifier_`. `include` is an optional list of method names
that also should be called. Any method names in `exclude` will not be
added to the context.
This helper is most useful when called from get_context_data()::
def get_context_data(self, **kwargs):
context = super(MyViewClass, self).get_context_data(**kwargs)
context.update(collect_context_modifiers(self, extra_kwargs=kwargs))
return context
"""
include = include or []
exclude = exclude or []
extra_kwargs = extra_kwargs or {}
context = {}
for thing in dir(instance):
if (thing.startswith('context_modifier_') or thing in include) and \
not thing in exclude:
context.update(getattr(instance, thing, lambda x:x)(**extra_kwargs))
return context |
def sum_range(nums, start=0, end=None):
"""Return sum of numbers from start...end.
- start: where to start (if not provided, start at list start)
- end: where to stop (include this index) (if not provided, go through end)
>>> nums = [1, 2, 3, 4]
>>> sum_range(nums)
10
>>> sum_range(nums, 1)
9
>>> sum_range(nums, end=2)
6
>>> sum_range(nums, 1, 3)
9
If end is after end of list, just go to end of list:
>>> sum_range(nums, 1, 99)
9
"""
return_num = 0
i = -1
for num in nums:
i = i + 1
if (i >= start) and (end == None or i <= end):
return_num = return_num + num
return return_num |
def eq_props(prop, object1, object2):
"""Reports whether two objects have the same value, in R.equals
terms, for the specified property. Useful as a curried predicate"""
return object1[prop] == object2[prop] |
def clamp(x, lower=0, upper=1):
"""Clamp a value to the given range (by default, 0 to 1)."""
return max(lower, min(upper, x)) |
def norm_angle(a):
"""Normalizes an angle in degrees to -180 ~ +180 deg."""
a = a % 360
if a >= 0 and a <= 180:
return a
if a > 180:
return -180 + (-180 + a)
if a >= -180 and a < 0:
return a
return 180 + (a + 180) |
def pl_to_eng(unit: str) -> str:
"""Converts Polish terminology to English"""
switcher = {
"pikinier": "spear",
"miecznik": "sword",
"topornik": "axe",
"lucznik": "archer",
"zwiadowca": "spy",
"lekki kawalerzysta": "light",
"lucznik na koniu": "marcher",
"ciezki kawalerzysta": "heavy",
"taran": "ram",
"katapulta": "catapult",
"szlachcic": "snob"
}
return switcher.get(unit, "error") |
def npf_show_address_group_one(ag, hc1, hc0w=0, hc1w=0, hc2w=0,
ac0w=2, ac1w=14, ac2w=0):
"""For displaying one address-group"""
# Is this an address-group?
if not ag or "name" not in ag or "id" not in ag:
return
#
# Inner function to display entries in a list. Entries are either address
# ranges or prefixes. This is re-entrant as sub-lists *may* be present
# for range entries
#
def _inner_show_list(ag_list, ac0w, ac1w, ac2w):
#
# Entry format specifier. The three fields are:
# <indent> <entry type> <entry> for example:
#
# Prefix 10.10.1.0/28
#
afmt = "%*s%-*s %*s"
# For each address-group entry ...
for ae in ag_list:
#
# Type 0 contain a prefix and mask, or an address. The "Prefix"
# and "Address" strings mirror the config option used to create
# the entry.
#
if ae["type"] == 0:
if "mask" in ae:
ae_type = "Prefix"
val = "%s/%u" % (ae["prefix"], ae["mask"])
else:
ae_type = "Address"
val = "%s" % (ae["prefix"])
print(afmt % (ac0w, "", ac1w, ae_type, ac2w, val))
#
# Type 1 is an address range. This may have a sub-list of
# prefixes derived from the range.
#
elif ae["type"] == 1:
ae_type = "Address-range"
val = "%s to %s" % (ae["start"], ae["end"])
print(afmt % (ac0w, "", ac1w, ae_type, ac2w, val))
#
# Has the address-range been broken down into constituent
# prefixes?
#
if "entries" in ae:
_inner_show_list(ae["entries"], ac0w+2, ac1w-2, ac2w)
else:
print(afmt % (ac0w, "", ac1w, "Unknown", ac2w, ""))
#
# Headline format specifier. The three fields are:
# <indent> <description> <group name and ID> for example:
#
# Address-group SRC_MATCH1 (4)
#
# The description is typically just "Address-group", but may be different
# when displaying an address-group from within another object, e.g. CGNAT
# blacklist.
#
hfmt = "%*s%-*s %*s"
# Display name and table ID
name = "%s (%u)" % (ag["name"], ag["id"])
# Print headline and address-group name and ID
print(hfmt % (hc0w, "", hc1w, hc1, hc2w, name))
addr_list = []
def _inner_get_entries(ag, af):
if af in ag and "entries" in ag[af]:
return ag[af]["entries"]
return []
#
# Get the per-address family entries. Note that an address-group may
# contain both.
#
addr_list.extend(_inner_get_entries(ag, "ipv4"))
addr_list.extend(_inner_get_entries(ag, "ipv6"))
# Display the list of entries
_inner_show_list(addr_list, ac0w, ac1w, ac2w) |
def option_rep(optionname, optiondef):
"""Returns a textual representation of an option.
option_rep('IndentCaseLabels', ('bool', []))
=> 'IndentCaseLabels bool'
option_rep('PointerAlignment', ('PointerAlignmentStyle',
[u'Left', u'Right', u'Middle']))
=> 'PointerAlignment PointerAlignmentStyle
Left
Right
Middle'
"""
optiontype, configs = optiondef
fragments = [optionname + ' ' + optiontype]
for c in configs:
fragments.append(" " * 8 + c)
rep = "\n".join(fragments)
return rep |
def sanitize_result(data):
"""Sanitize data object for return to Ansible.
When the data object contains types such as docker.types.containers.HostConfig,
Ansible will fail when these are returned via exit_json or fail_json.
HostConfig is derived from dict, but its constructor requires additional
arguments. This function sanitizes data structures by recursively converting
everything derived from dict to dict and everything derived from list (and tuple)
to a list.
"""
if isinstance(data, dict):
return dict((k, sanitize_result(v)) for k, v in data.items())
elif isinstance(data, (list, tuple)):
return [sanitize_result(v) for v in data]
else:
return data |
def getPositionAtTime(t):
"""
Simulation time t runs from 0 to 99
First quarter: walking right from 50, 50 to 250, 50
Second quarter: walking down from 250, 50 to 250, 250
Third quarter: walking left from 250, 250 to 50, 250
Fourth quarter: walking up from 50, 250 to 50, 50
"""
if 0 <= t < 25:
return 50 + ((t - 0) * 8), 50, 'right'
elif 25 <= t < 50:
return 250, 50 + ((t - 25) * 8), 'front'
elif 50 <= t < 75:
return 250 - ((t - 50) * 8), 250, 'left'
elif 75 <= t < 100:
return 50, 250 - ((t - 75) * 8), 'back' |
def _update_config_reducer(store_dict, data):
"""
:type store_dict: dict
:type data: dict
:rtype: dict
"""
# gather frequency needs always to be positive and not too fast
if data.get('gather_frequency', 0) < 30:
data['gather_frequency'] = 30
store_dict.update(data)
return store_dict |
def insertion_sort(list,n):
"""
sort list in assending order
INPUT:
list=list of values to be sorted
n=size of list that contains values to be sorted
OUTPUT:
list of sorted values in assending order
"""
for i in range(0,n):
key = list[i]
j = i - 1
#Swap elements witth key iff they are
#greater than key
while j >= 0 and list[j] > key:
list[j + 1] = list[j]
j = j - 1
list[j + 1] = key
return list |
def _getClientName(client):
""" Return the unique id for the client
Args:
client list<>: the client which send the message of the from [ip (str), port (int)]
Return:
str: the id associated with the client
"""
return 'room-' + client[0] + '-' + str(client[1]) |
def wrap_p(msg):
"""wraps text in a paragraph tag for good desploy"""
return "<p>{}</p>".format(msg) |
def color_pvalues(value):
"""
Color pvalues in output tables.
"""
if value < 0.01:
color = "darkorange"
elif value < 0.05:
color = "red"
elif value < 0.1:
color = "magenta"
else:
color = "black"
return "color: %s" % color |
def count_spaces(docstring):
"""
Hacky function to figure out the minimum indentation
level of a docstring.
"""
lines = docstring.split("\n")
for line in lines:
if line.startswith(" "):
for t in range(len(line)):
if line[t] != " ":
return t
return 0 |
def flatten_officer_search(officers):
"""
Expects a messy list of officer searches record from paginate_search().
Unpacks nested results into one, long manageable list.
"""
flat_officers = []
for i in officers:
try:
if len(i) > 1:
for x in i:
for z in x:
flat_officers.append(z)
if len(i) == 1:
for x in i:
if len(x) == 1:
flat_officers.append(x[0])
except (TypeError, KeyError) as e:
print(e)
pass
return flat_officers |
def count_circles_of_2d_array(array):
"""
Returns: Total number of circles in array
"""
total_circles = 0
for row in range(len(array)):
total_circles += len(array[row])
return total_circles |
def heartRateSignleMeasurementHandler(data):
"""
For get this answer need to sent AB 05 FF 31 09 00 FF
"""
# Only for testing - no detailed parsing, just form answer
return bytearray([0xAB, 0x04, 0xFF, 0x31, 0x09, 0x44]) |
def get_command_from_state(state):
"""
This method gets appropriate command name for the state specified. It
returns the command name for the specified state.
:param state: The state for which the respective command name is required.
"""
command = None
if state == 'present':
command = 'vrouter-ospf-add'
if state == 'absent':
command = 'vrouter-ospf-remove'
return command |
def str2bool(str0):
"""Convert a string to a Boolean value.
Parameters
----------
str0 : str
String to convert.
Returns
-------
bool
``True`` when successful, ``False`` when failed.
"""
if str0.lower() == "false":
return False
elif str0 == "true":
return True
else:
return "" |
def _iscomment(line):
"""
Comment lines begin with the character '#', '', or all whitespace.
"""
if line == '':
return True
if line.isspace():
return True
elif line.strip()[0] == '#':
return True
else:
return False |
def get_fileno(fd_or_obj):
"""Returns the file descriptor number for the given `fd_or_obj`"""
try:
return int(fd_or_obj)
except:
if hasattr(fd_or_obj, 'fileno') and callable(fd_or_obj.fileno):
return fd_or_obj.fileno()
raise TypeError("Unable to get fd from %s" % fd_or_obj) |
def is_sorted(items):
"""Return a boolean indicating whether given items are in sorted order.
Running time: O(n) because at most loop through the entire array
Memory usage: O(1) because not creating any new space and everything is done in place"""
for i in range(len(items) - 1):
# if next item is smaller than current, then list not sorted
if items[i+1] < items[i]:
return False
return True |
def cancel_job(job_id):
"""
Cancel job
:param job_id: int, job id
:return: if success, return 1, else return 0
"""
import subprocess
try:
step_process = subprocess.Popen(('bkill', str(job_id)), shell=False, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
stdout, stderr = step_process.communicate()
return 1
except Exception as e:
print(e)
return 0 |
def ru2ra(x, ra1=0., ra2=360.):
"""Transform a random uniform number to a RA between
the RA specified as an input"""
return x*(ra2-ra1)+ra1 |
def listToStr(lst):
"""This method makes comma separated list item string"""
return ','.join(lst) |
def tolist(arg, length=None):
"""Makes sure that arg is a list."""
if isinstance(arg, str):
arg = [arg]
try:
(e for e in arg)
except TypeError:
arg = [arg]
arg = list(arg)
if length is not None:
if len(arg) == 1:
arg *= length
elif len(arg) == length:
pass
else:
raise ValueError('Cannot broadcast len {} '.format(len(arg)) +
'to desired length: {}.'.format(length))
return arg |
def num_decodings(s):
"""
dp[i]: ways to decode s[:i]
dp[0] = dp[1] = 1 if s[0] != '0'
dp[i] = 0 if s[i-1] == "0"
+ dp[i-1] if s[i-1] != "0"
+ dp[i-2] if "09" < s[i-2:i] < "27"
"""
if not s or s[0] == '0': return 0
n = len(s)
dp = [0] * (n + 1)
dp[0] = dp[1] = 1
for i in range(2, n + 1):
if s[i-1] != "0":
dp[i] += dp[i-1]
if s[i-2] != "0" and int(s[i-2:i]) <= 26:
dp[i] += dp[i-2]
return dp[-1] |
def W2020_2021(number):
"""
The week of the year
Parameters
----------
:param number: A specific number
:type number: int
Returns
-------
:return: week of the year
:Examples:
>>> W200_2021("2020-S35")
"""
if (number == 53):
return "202"+str(number//54)+f"-S{number:02}"
return "202"+str(number//54)+f"-S{number%53:02}" |
def is_poly(segm):
"""Determine if segm is a polygon. Valid segm expected (polygon or RLE)."""
assert isinstance(segm, (list, dict)), \
'Invalid segm type: {}'.format(type(segm))
return isinstance(segm, list) |
def prefix0(h):
"""Prefixes code with leading zeros if missing."""
if len(h) < 6:
h = '0'*(6-len(h)) + h
return h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.