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_pag... |
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('_')
... |
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 th... |
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... |
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 ... |
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=' + pass... |
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:
# ... |
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 c... |
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
"""
... |
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... |
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,... |
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):
... |
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():
i... |
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 i... |
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].... |
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_r... |
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.... |
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]
... |
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
... |
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 ... |
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')):
s... |
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]
... |
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... |
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... |
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": ... |
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 explic... |
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.
- ... |
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 +... |
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,idx... |
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.
... |
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 = {
... |
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?lo... |
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 == "defaul... |
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, a... |
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... |
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 n... |
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... |
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",
... |
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 lis... |
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 PointerAlig... |
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
ar... |
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 <= ... |
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 sto... |
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
... |
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 ... |
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:
... |
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 ... |
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":
... |
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 i... |
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=subpro... |
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... |
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] = ... |
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)+... |
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.