content stringlengths 42 6.51k |
|---|
def clean_txt(text):
"""
Strips formatting
"""
if isinstance(text, str):
return text.replace('\n', '. ').replace('.. ', '. ').rstrip()
elif hasattr(text, '__iter__'):
return [clean_txt(one_text) for one_text in text] |
def toggle_popover_tab2(n, is_open):
"""
:return: Open pop-over callback for how to use button for tab 2.
"""
if n:
return not is_open
return is_open |
def format_org_name(name):
"""
Format the name of an organism so normalize all species names
Args:
name (:obj:`bool`): the name of a spcies (e.g. escherichia coli str. k12)
Returns:
:obj:`str`: the normalized version of the strain name (e.g. escherichia coli k12)
""... |
def is_mbi_format_synthetic(mbi):
"""
Returns True if mbi format is synthetic.
This is the case where there is an "S" in the 2nd position
denoting a synthetic MBI value.
"""
# Check if NoneType.
if mbi is None:
return None
else:
return len(mbi) == 11 and mbi[1] == "S" |
def _wrapper(page):
"""
Wraps some text in common HTML.
"""
return (
"""
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
max-width: 24em;
... |
def binning2string(binspectral, binspatial):
"""
Args:
binspectral (int):
binspatial (int):
Returns:
str: Binning in binspectral, binspatial order, e.g. '2,1'
"""
return '{:d},{:d}'.format(binspectral, binspatial) |
def sum_items(a_list):
"""
@purpose Returns the sum of all items in a_list, and return 0 if empty list
@param
a_list: a list of items passed to this function to sum
@complexity:
Worst Case - O(N): When summing all values of a list with N items
Best Case - O(1): when passing empty... |
def recursive_merge(a, b):
"""Recursively merge two dicts. Updates a."""
if not isinstance(b, dict):
return b
for k, v in b.items():
if k in a and isinstance(a[k], dict):
a[k] = recursive_merge(a[k], v)
else:
a[k] = v
return a |
def make_rectangle(x1, x2, y1, y2):
"""Return the corners of a rectangle."""
xs = [x1, x1, x2, x2, x1]
ys = [y1, y2, y2, y1, y1]
return xs, ys |
def _extract_node_text(node):
"""Extracts `text` and `content-desc` attribute for a node."""
text = node.get('text')
content = node.get('content-desc', [])
all_text = [text, content] if isinstance(content, str) else [text] + content
# Remove None or string with only space.
all_text = [t for t in all_text if... |
def separate_symbols(s):
"""
Adds a dash to a symbol pair. btcusd -> btc-usd
"""
return s[:3] + '-' + s[3:] |
def str_to_list_of_pairs(_str1, _str2, _sep=','):
"""
Attempts to convert 2 strings containing tokens separated by some _sep to a list of pairs, e.g. "a1,a2", "b1,b2" -> [['a1','b1'],['a2','b2']]
:param _str1: input string #1
:param _str2: input string #2
:param _sep: token separator in the strings
... |
def PNT2Tidal_Tv14(XA,chiA=0,chiB=0,AqmA=0,AqmB=0,alpha2PNT=0):
""" TaylorT2 2PN Quadrupolar Tidal Coefficient, v^14 Timing Term.
XA = mass fraction of object
chiA = aligned spin-orbit component of object
chiB = aligned spin-orbit component of companion object
AqmA = dimensionless spin-induced quadrupol... |
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
>>> friendly_number(102)
'102'
>>> friendly_number(10240)
'10k'
>>> friendly_number(12341234, ... |
def flatten(l):
"""
Flatten a list of lists
:param l: List of lists
:return: flattened list
"""
try:
return [item for sublist in l for item in sublist]
except TypeError:
return l |
def candies(n, ratings):
"""https://www.hackerrank.com/challenges/candies"""
result = [1] * n
for i in range(1, n):
if ratings[i] > ratings[i - 1]:
result[i] = result[i - 1] + 1
else:
result[i] = 1
for i in range(n - 2, -1, -1):
if ratings[i] > ratings[i... |
def preprocess_stanza(stanza: str):
"""
A function to process Stanza to remove all unnecessary blank
param sentence: stanza to process
return: stanza processed
"""
sentences = stanza.split("\n")
sentences_out = []
for sentence in sentences:
words = sentence.split(" ")... |
def removeprefix(value: str, *prefixes: str) -> str:
"""Works almost like str.removeprefix that comes with Python 3.9+"""
for prefix in prefixes:
while value.startswith(prefix):
value = value[len(prefix) :]
return value |
def getFitVars(fitdata):
"""Returns list of fit variables"""
fitvars = []
for var in sorted(fitdata.keys()):
if var != 'model' and var != 'error':
fitvars.append(fitdata[var])
return fitvars |
def travel_worktime (full_hours, half_hours, daily_hours) :
"""Compute the time taking halved travel into account. Return a
tuple consisting of the travel work-time and the ratio by which
the work-time was reduced.
>>> travel_worktime ( 8, 4, 8)
(8, 1.0)
>>> travel_worktime ... |
def multiple_replace(text, word_dict):
"""Replace all occurrences in text of key value pairs in word_dict."""
for key in word_dict:
text = text.replace(key, word_dict[key])
return text |
def jobs_from_path(path):
""" helper for finding jobs from path"""
return [(path[i], path[i + 1]) for i in range(len(path) - 1)] |
def get_item(list_of_dictionaries, key):
"""
Given a list of dictionaries, it returns the first dictionary that
contains the given key, and the item for that key.
:param list_of_dictionaries: list(dict())
:param key: key of dictionary wanted
:return: contents of list(dict[key])
"""
retu... |
def split_s3_url(s3_url):
"""
Breaks up s3 URL into
bucket
path under bucked
tail (file or folder)
:param s3URL:
:return: 3 tuple (bucket, folder, tail)
"""
s3_url_arr = s3_url.rsplit('/')[2:]
if len(s3_url_arr) > 1:
return s3_url_arr[0], '/'.join(s3_url_arr[1:-1]), s3_ur... |
def normalize(qualName):
"""
Turn a fully-qualified Python name into a string usable as part of a
table name.
"""
return qualName.lower().replace('.', '_') |
def _update_task_result_failure(result, detail):
"""Update task result => unified api call output. Return message for TaskException"""
msg = 'Got bad return code (%s)' % result['returncode']
result['message'] = msg
return '%s. Error: %s' % (msg, detail) |
def getShape(sMin, sMax, tau):
"""
Take in sMin, sMax, and tau
Determine best fit and return it
"""
if sMin < (tau * sMax):
return "line"
else:
return "ellipse" |
def voxel_hash(x, y, z):
"""
Computes a hash given the int coordinates of a 3D voxel
Args:
x (np.int64): the x coordinate of a voxel
y (np.int64): the y coordinate of a voxel
z (np.int64): the z coordinate of a voxel
"""
return 73856093 * x + 19349669 * y + 83492791 * z |
def sex2dec(hour, minute, second, microsecond=0.0):
""" Convert a sexagesimal time to decimal hours.
Parameters
----------
hour, min, sec : int, float
Returns
-------
Time in decimal hours
"""
return float(hour) + minute / 60.0 + (second + microsecond / 1E6) / 3600.0 |
def pivotFlip(string, pivot):
"""Reverses a string past a pivot index."""
flip = list(string[pivot:])
flip.reverse()
return string[:pivot]+''.join(flip) |
def task_all():
"""Perform all build task."""
return {
'actions': None,
'task_dep': ['check', 'mo', 'fill_db'],
} |
def option_to_dict(options):
"""Convert user input options into dictionary."""
new_opts = {}
for opt in options:
if "=" in opt:
splt_opt = opt.split("=")
new_opts[splt_opt[0]] = splt_opt[1]
else:
new_opts[opt] = True
return new_opts |
def helper(n, current_max):
"""
:param n: int, the number to find largest digit.
:param current_max: int, current max digit was found.
:return: int, largest digit was found.
"""
# get positive int
if n < 0:
n *= -1
# get last digit num
digit_num = n - (n // 10) * 10
if 0 < digit_num <= 9 and digit_num > cur... |
def intepret_year(value):
# type: (str) -> int
"""Handle two-digit years with heuristic-ish guessing
Assumes 50-99 becomes 1950-1999, and 0-49 becomes 2000-2049
..might need to rewrite this function in 2050, but that seems like
a reasonable limitation
"""
year = int(value)
# No need ... |
def sanitize_text(text):
"""Basic cleanning text helper. Remove trailing and ending spaces and '\n' chars
Can be improved if needed
Args:
text (str): the string to sanitize
Returns:
str: the string sanitized
"""
return text.replace('\n', '').strip() |
def search_in_line(line, pattern):
""" Splits string line by patterns.
Pattern MUST be compiled regexp and MUST contain enclosing parenthesis.
Returns list of strings, always odd number of element and pattern matches are at odd positions.
If there were no occurences, returns None.
"""
matches = pattern.split(line... |
def top_down(num_steps: int, cache: dict = {1: 1, 2: 2, 3: 4}) -> int:
"""Same as `recursive()` but using a dict as a cache
cache will have num_steps elements
Args:
num_steps: number of total steps
cache:
Returns:
The number of possible ways to climb the stairs
"""
if ... |
def _StripUnusedNotation(string):
"""Returns string with Pythonic unused notation stripped."""
if string.startswith('_'):
return string.lstrip('_')
unused = 'unused_'
if string.startswith(unused):
return string[len(unused):]
return string |
def _magni_test_var_in_globals_func(*args, **kwargs):
"""Test function used in some tests."""
return 'magni_test_var' in globals() |
def ed_find(filename, search_str):
""" PART 2: Returns a list of index positions where 'search_str' was found in 'filename'. An empty list is returned if search_str is not found within 'filename'. """
with open(filename, 'r') as f:
line_list = f.readlines() # read each line into a list of lines
... |
def make_set_from_list(word_list):
"""
Make a set of unic element from a list
:type word_list: list(str)
:param word_list: The list of word to transform into a set
"""
lower_list = list()
for word in word_list:
lower_list.append(word.lower())
return set(lower_list) |
def underline(content):
"""Corresponds to ``_text_`` in the markup.
:param content: HTML that will go inside the tags.
>>> 'i said ' + underline('do it')
'i said <u>do it</u>'
"""
return '<u>' + content + '</u>' |
def clean_buffer(vertices, bounds):
"""Cleans the vertices index from unused vertices3"""
new_bounds = list()
new_vertices = list()
i = 0
for bound in bounds:
new_bound = list()
for vertex_id in bound:
new_vertices.append(vertices[vertex_id])
new_bound.appen... |
def last(s):
"""Return a word string sorted alpha-ly by last char in each word.
input = string, words
output = string, sorted words alphabetically by last char
ex: "man i need a taxi up to ubud") ==>["a", "need", "ubud", "i", "taxi", "man", "to", "up"]
"""
alpha = list(map(chr, range(97, 123))... |
def get_lines(filename):
"""
Read in lines from file, stripping new line markers
Parameters
----------
filename : str, pathlike
Path to file.
Returns
-------
lines : list
List containing each line.
"""
lines = []
try:
fh = open(filename, 'r')
ex... |
def chute_find_field(chute, key, default=Exception):
"""
Find a field in a chute definition loading from a paradrop.yaml file.
"""
if key in chute:
return chute[key]
elif 'config' in chute and key in chute['config']:
return chute['config'][key]
elif isinstance(default, type):
... |
def request_too_large(e):
"""Generates a valid ELG "failure" response if the request is too large"""
return {'failure':{ 'errors': [
{ 'code':'elg.request.too.large', 'text':'Request size too large' }
] } }, 400 |
def has_duplicates(list) :
"""Returns True if there are duplicate in list, false otherwise"""
copy = list[:]
copy.sort()
for item in range(len(list)-1):
if copy[item] == copy[item + 1]:
return True;
return False; |
def list_a_minus_list_b(list_a, list_b):
"""This method assumes input is two lists with unique elements aka sets.
It then returns all unique elements in list_a, not present in list_b.
:param list_a:
:param list_b:
:return: list of elements only in list_a OR an empty list
"""
return list(se... |
def b2a(b):
"""01110100011001010111001101110100 -> test"""
return ''.join(chr(int(''.join(x), 2)) for x in zip(*[iter(b)]*8)) |
def get_nb_new(emails):
"""Return formatted string with number of new emails"""
if emails:
return '{}/'.format(len(emails))
return '' |
def check_two_dcm_folder(dicom_path, bids_folder, image_uid):
"""[summary].
Check if a folder contains more than one DICOM and if yes, copy the DICOM related to
image id passed as parameter into a temporary folder called tmp_dicom_folder.
Args:
dicom_path (str): path to the DICOM folder
... |
def format_y(n, pos):
"""Format representation of yticks with K,M metric prefixes"""
if n >= 1e6:
return '%1.0fM' % (n * 1e-6)
if n >= 1e3:
return '%1.0fK' % (n * 1e-3)
return '%1.0f' % n |
def convert_encoding(text, convert_from, convert_to="UTF-8"):
"""Try to convert the input encoding"""
return text.encode('latin1').decode(convert_from).encode(convert_to) |
def _find_startswith(x, s):
"""Finds the index of a sequence that starts with s or returns -1.
"""
for i, elem in enumerate(x):
if elem.startswith(s):
return i
return -1 |
def int_to_roman(value):
"""
Convert from decimal to Roman
"""
if not 0 <= value < 4000:
raise ValueError("Argument must be between 1 and 3999")
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I')
... |
def add_filter_to_request(data, additional_fieldname, exclusive_operator, operator, value):
"""
Adding additional filter to API-request.
:param data: prepared request
:param additional_fieldname: fieldname is used to create an additional filter.
:param exclusive_operator: exclusive_operator is used... |
def to_number(s):
"""Takes str s and returns int (preferentially) or float."""
if s.find(".") > -1:
return float(s)
return int(s) |
def get_json_field(json_obj, attribute_name, json_filename=None,
suppress_err_msg=False):
"""Retrieves a value from a JSON object (dict).
Args:
json_obj (dict): The JSON file to retrieve a value from.
attribute_name (str): The attribute to look up. If there are nested
... |
def _split_addresses(recipients, max_bcc, primary_recipient):
"""Split addresses into a list of tuples of (recipient,bcclist).
Args:
recipients: List of intended email recipients.
Returns:
List of tuples, where each tuple consists of:
- Email recipient.
- list of recipients... |
def custom_context(request):
"""
Custom items that are available to the templates
"""
return {'DJANGO_VER': 'django 1.8.9 LTS'} |
def isStringLike(s):
"""
Returns True if s is a string-like object.
The condition to test is:
type(s) is str or type(s) is bytes
"""
return type(s) is str or type(s) is bytes |
def createContextSingle(obj, id=None, keyTransform=None, removeNull=False):
"""Receives a dict with flattened key values, and converts them into nested dicts
:type obj: ``dict`` or ``list``
:param obj: The data to be added to the context (required)
:type id: ``str``
:keyword id: The ID of the cont... |
def is_prolog_variable(json_term):
"""
True if json_term is Prolog JSON representing a Prolog variable. See `swiplserver.prologserver` for documentation on the Prolog JSON format.
"""
return isinstance(json_term, str) and (
json_term[0].isupper() or json_term[0] == "_"
) |
def airtovac(wave):
""" Convert air-based wavelengths to vacuum
Parameters:
----------
wave: ndarray
Wavelengths
Returns:
----------
wavelenght: ndarray
Wavelength array corrected to vacuum wavelengths
"""
# Assume AA
wavelength = wave
# Standard conversion for... |
def get_zamid_s(zamid):
"""Gets the state of a nuclide from a its z-a-m id. 1 = first excited state, 0 = ground state.
Parameters
----------
zamid: str
z-a-m id of a nuclide
"""
s = int(zamid[-1])
return s |
def json_element(input_dict, query, default=None):
"""Runs through a data structure and returns the selected element."""
for element in query:
is_list_index = isinstance(element, int) and isinstance(input_dict, (list, tuple))
if is_list_index or element in input_dict:
input_dict = in... |
def shunt(infix):
"""Convert an expression in infix notation to postfix notation
:param infix: regular expression
:type infix: string
:return: infix converted to postfix
"""
infix = list(infix)[::-1]
print(f"\nREVERSED INFIX: {infix}")
# Operator stack, Output list
opstack, postfix ... |
def birch(V, E0, B0, B1, V0):
"""
From Intermetallic compounds: Principles and Practice, Vol. I: Principles
Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos paper downloaded from Web
case where n=0
"""
E = (E0
+ 9.0/8.0*B0*V0*((V0/V)**(2.0/3.0) - 1.0)**2
+... |
def find_insensitive(str, lst):
"""
Finds string str in list of strings lst ignoring case and spaces. If the string is
found, returns the actual value of the string. Otherwise, returns None.
"""
str = str.upper().replace(" ", "")
for entry in lst:
if entry.upper().replace(" ", "") == s... |
def outputsNormalized2Physical(y, A, B):
"""Rescales outputs y from normalized to physical units (if A and B correspond to saved normalization constants."""
return A*y + B |
def safe_get(dictionary, *keys):
"""For accessing deeply nested data from dictionaries"""
for key in keys:
try:
dictionary = dictionary[key]
except KeyError as err:
print(f"Dictionary KeyError!: {key} : {err}")
return None
except AttributeError as err:... |
def positive_sum(arr):
"""Return positive sum"""
return sum([elem for elem in arr if elem >0]) |
def triangular_root(x):
"""Inverse of triangular_number(n). Given a triangular number x (int or
float), return n (float), such that the nth triangular number is x. Since
values of x that are not perfectly triangular will not have an integer n
value, but will fall between two integer n-offsets, we return... |
def prior_knolwedge_normalized_v2(price):
"""
function of prior knowledge for normalized price
:param price: input price
:return: expected prob.
"""
winning_prob = 0.8 - 0.7 * price
return winning_prob |
def copy_base_doc_to_subclass_doc(subclass):
"""Use the docstring from a parent class methods in derived class.
The docstring of a parent class method is prepended to the
docstring of the method of the class wrapped by this decorator.
Parameters
----------
subclass : wrapped class
Clas... |
def get_other_class_probabilities(class_probabilities):
"""
:param class_probabilities: probabilities of each class calculated using user input and Naive Bayes word_probabilities
:return: sum of all probabilities
"""
return sum(class_probabilities[c] for c in class_probabilities) |
def callable_or_raise(obj):
"""Check that an object is callable, else raise a :exc:`ValueError`.
"""
if not callable(obj):
raise ValueError('Object {0!r} is not callable.'.format(obj))
return obj |
def merge(left_list, right_list):
"""
Merge the given lists into a single list whose items are in descending order
:param left_list: list
:param right_list: list
:return: list
"""
merged_list = []
left_index = 0
right_index = 0
while left_index < len(left_list) and right_index... |
def bubble_sort(items):
"""
Sort items with a bubble sort.
"""
working = True
while working:
working = False
for index, item in enumerate(items):
if index < len(items) - 1:
next_index = index + 1
next_item = items[next_index]
... |
def get_data_mac(data):
"""Extract mac address of the sensor. This also is the loic where we identify the firmware flavour
# ref: https://github.com/pvvx/ATC_MiThermometer#bluetooth-advertising-formats
# this code will support both ATC format and pvvx's custom format.
# https://github.com/pvvx/ATC... |
def octal(val):
"""Parse a string into an octal value"""
return int(val, 8) |
def getClues(guess, secretNum):
"""Returns a string with the pico, fermi, bagels clues."""
if guess == secretNum:
return 'You got it!'
clues = []
for i in range(len(guess)):
if guess[i] == secretNum[i]:
clues.append('Fermi')
elif guess[i] in secretNum:
c... |
def ordered_deduplicate(sequence):
"""
Returns the sequence as a tuple with the duplicates removed,
preserving input order. Any duplicates following the first
occurrence are removed.
>>> ordered_deduplicate([1, 2, 3, 1, 32, 1, 2])
(1, 2, 3, 32)
Based on recipe from this StackOverflow post... |
def get_max_draw_down(ts_vals):
"""
@summary Returns the max draw down of the returns.
@param ts_vals: 1d numpy array or fund list
@return Max draw down
"""
MDD = 0
DD = 0
peak = -99999
for value in ts_vals:
if (value > peak):
peak = value
el... |
def get_primes(n):
"""
Iterate through all the possible divisors of n and return a list of all of
the actual divisors in sorted order.
"""
result = []
for i in range(2, n + 1):
s = 0
while n % i == 0:
n = n / i
s += 1
if s > 0:
for k in... |
def get_minutes(value):
"""
0 - 32767 minutes
"""
return "minutes:{}".format(value) |
def metadata_url(match_id, cluster, replay_salt, app_id=570):
"""Form url for match metadata file
:param match_id: match id
:type match_id: :class:`int`
:param cluster: cluster the match is saved on
:type cluster: :class:`int`
:param replay_salt: salt linked to the replay
:type replay_sa... |
def suite_from_name(name: str):
"""
Get a test suite name from an artifact name. The artifact
can have matrix partitions, pytest marks, etc. Basically,
just lop off the front of the name to get the suite.
"""
return "-".join(name.split("-")[:3]) |
def _is_float(val):
"""
Checks if a token can be converted into a float
Returns a boolean indicating if the given token can be converted to a float
:param val: input to be tested, meant to be a string but can be any type
:type val: string (though any other type is also acceptable)
:returns: bo... |
def fib_mem(n, computed={0:0,1:1}):
"""find fibonacci number using memoization"""
if n not in computed:
computed[n] = fib_mem(n-1, computed) + fib_mem (n-2, computed)
return computed[n] |
def format_time(value: float) -> str:
"""Convert time to nicer format"""
if value <= 0.005:
return f"{value * 1000000:.0f}us"
elif value <= 0.1:
return f"{value * 1000:.1f}ms"
elif value > 86400:
return f"{value / 86400:.2f}day"
elif value > 1800:
return f"{value / 36... |
def get_resources_to_delete(resources):
"""returns a list of all resource ids to delete
Args:
resources (list(dict)): resources to compare to the paths
Returns:
list(str): list of ids of resources to remove
"""
resources_to_delete = [(resource['id'], resource["path"])
... |
def get_ij_from_index(r, m, n):
"""
The inverse of get_y_indicator_variable_index(): given the indiator
variable index, return the (i ,j) pair for y_{ij} to which it
corresponds. So when we get a solution from MiniSat+, the variable
index given to this function gets converted to (i,j) our y_{ij}, me... |
def dH_atoms(at):
"""
Returns the enthalpy corrections of the element.
Parameters:
at (char): Symbol of the element
Returns:
dH_atoms (float): Enthalpy corrections of the element
"""
h = 6.626070040*(10**-34) #6.626070040d-34
Ry =... |
def sort_notes(note_list):
"""Returns a sorted copy of note_list with duplicates removed."""
return sorted(list(dict.fromkeys(note_list)), key=lambda x:x[2]*1000+x[0]) |
def null_terminated(byte):
"""Filter to return true when the byte is 0x00."""
return byte == b"\x00" |
def packages(project_name):
"""Return list of packages distributed by project based on its name.
>>> packages('foo')
['foo']
>>> packages('foo.bar')
['foo', 'foo.bar']
>>> packages('foo.bar.baz')
['foo', 'foo.bar', 'foo.bar.baz']
>>> packages('FooBar')
['foobar']
Implements "Us... |
def header_length(bytearray):
"""Return the length of s when it is encoded with base64."""
groups_of_3, leftover = divmod(len(bytearray), 3)
# 4 bytes out for each 3 bytes (or nonzero fraction thereof) in.
n = groups_of_3 * 4
if leftover:
n += 4
return n |
def _repack(linear, n=3):
"""This ridiculous function returns chunks of n from a linear list.
For example, _repack([1, 2, 3, 4, 5, 6], n=3) -> [[1, 2, 3], [4, 5, 6]]
Good for unravelling ravelled data
"""
return list(zip(*[iter(linear)]*3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.