content stringlengths 42 6.51k |
|---|
def made_elements_lowercace(items):
"""Recieve list and return list with lowercased elements"""
return list(map(str.lower, items)) |
def subst_to_cds(substitutions, offset):
"""Convert a set of substitutions to CDS coordinates.
:arg dict substitutions: Set of single nucleotide substitutions indexed by
position.
:arg int offset: Codon position in the CDS.
:returns set: Substitutions in CDS coordinates.
"""
variants =... |
def update_event(self, event_id, *,
title=None, start_date=None, end_date=None, time=None, description=None,
location=None, gps=None, gps_location=None, category=None, color=None,
whatsapp_link=None):
"""Update an event in the database
Force use of keyworded arguments to prevent from field mismatch and ... |
def idnencode(domain, encoding='utf-8', errors='strict'):
"""Encode International domain string."""
if not isinstance(domain, bytes):
return domain.encode('idna', errors).decode(encoding)
else:
return domain.decode(encoding, errors).encode('idna', errors) |
def calculateOnlineVariance(data):
"""
Returns the variance of the given list.
:param data: A list of numbers to be measured (ie. the window)
:returns: The variance of the data.
"""
n, mean, M2 = 0, 0, 0
for x in data:
n = n + 1
delta = x - mean
mean = mean + delta/n
M2 = M2 + delta*(x-... |
def id2url(_id):
"""Generate a URL for the given compact URI (CURIE), if possible.
:param curie: A compact URI (CURIE) in the form of `prefix:identifier`
:returns: A URL string if the Bioregistry can construct one, otherwise None.
>>> id2url("mesh:D009369")
'https://bioregistry.io/mesh:D009369'
... |
def camel_to_capwords(s: str, validate: bool = False) -> str:
"""Coverts camelCase to CapWords
Examples:
>>> camel_to_capwords('camelCase')
'CamelCase'
>>> camel_to_capwords('salt')
'Salt'
>>> camel_to_capwords('')
''
"""
if validate:
raise NotImp... |
def flatten(nested_list):
"""
Return a flattened list of items from a nested list.
"""
lst = []
for item in nested_list:
if isinstance(item, (list, tuple)):
lst.extend(flatten(item))
else:
lst.append(item)
return lst |
def perfect_score(student_info):
"""
:param student_info: list of [<student name>, <score>] lists
:return: First [<student name>, 100] found OR "No perfect score."
"""
result = "No perfect score."
for student in student_info:
if student[1] == 100:
return student
return ... |
def returnListWithoutOutliers(data, outlierRange):
"""
An outlier is defiend as a datapoint not in [Q1 - 1.5*IQR*outlierRange, Q3 + 1.5*IQR*outlierRange],
where IQR is the interquartile range: Q3 - Q1
"""
data.sort()
dataPointsBefore = len(data)
Q1 = data[dataPointsBefore//4]
Q3... |
def indefinite_article(w):
"""Generate an indefinite article for the given phrase: a, an, or empty string"""
if (len(w) == 0):
return ""
if w.lower().startswith("a ") or w.lower().startswith("an ") or w.lower().startswith("the "):
return ""
return "an " if w.lower()[0] in list('aeiou') e... |
def create_container_headers(
slug='',
link='<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'):
"""
Create a header dictionary to be used when creating a cointainer resource.
The slug is a string used to identify the container, which may be
modified to be a valid URL path segment
""... |
def description_from_url_bjs(link):
"""
:param link:
:return:
"""
description = ""
try:
remove_initial = link.replace("https://www.bjs.com/product/", "")
print(remove_initial)
for i in remove_initial:
if i != "/":
description += i
... |
def solve(n):
"""Clever solution."""
# return "0" if n == 0 else "01" if n == 1 else solve(n-1) + solve(n-2)
if n == 0:
return '0'
elif n == 1:
return '01'
else:
return solve(n - 1) + solve(n - 2) |
def create_dict_with_multicity_inputs(multicity_results):
"""Creates a dictionary based on user's input."""
multicity_dict = {'departure': multicity_results[0],
'arrival': multicity_results[1],
'departure_date': multicity_results[2],
'number_of_... |
def _get_bucket(url):
"""
Retrieves the bucket based on the URL
:param string url: URL to parse
:return: bucket name
:rtype: string
"""
first_slash_index = url.find('/')
return url[:first_slash_index] |
def _demo_coverage(tier):
"""Return a value between [0,100]."""
if tier == 'Tier 1':
return 95.7
elif tier == 'Tier 2':
return 94.6
elif tier == 'Tier 3':
return 95.1
else:
raise ValueError(tier) |
def KToF(temp):
"""
Converts temperature from Kelvin to Fahrenheit
:param temp: temperature
:return: Return the temperature in Fahrenheit
"""
C = temp - 273
F = (C * 9/5) + 32
F = round(F, 0)
return F |
def getFoodDetail(food_id):
"""
#
---
GET method
pake path berupa id-nya food
"""
# Initialize data
data = {}
# Do querying and check for the result
# Currently using dummy data
result = {
'success' : True,
'message' : 'Some message',
'd... |
def _parse_session(session):
"""Return a request mapping for a notification from the given session."""
return dict( (str(k), str(v)) for (k, v) in session.items() ) |
def n_choose_2(n):
"""Returns number of combinations for N choose 2"""
return n*(n-1)/2. |
def generate_blocked_task(name, blocking_source):
"""Returns a stream_action config, with the given blocking source."""
name = name.replace(" ", "_")
kernel_action = {
"delay": 0.2,
"type": "kernel",
"label": "K3",
"parameters": {
"duration": 250000000
}
... |
def find(haystack, needle):
"""
>>> find("ll", "hello")
-1
>>> find("", "")
0
>>> find("hello", "ll")
2
>>> find("aaaaabba", "bba")
5
>>> find("bbaaaaaa", "bba")
0
>>> find("aaaaa", "bba")
-1
"""
m = len(haystack)
n = len(needle)
if m < n:
retu... |
def _rssi_convert(value):
"""Rssi is given as dBm value."""
if value is None:
return None
return f"{value*8-120}" |
def _find(match=lambda item: False, list=[]):
""" Returns the first item in the list for which match(item)=True, or None.
"""
for item in list:
if match(item): return item |
def _generate_output_dictionary(optimal_params, min_value, good_params, optimizer_name, graph_type, p, weight_matrix,
problem):
"""Generates a dictionary that stores important fields extracted from a workflow output."""
dic = {}
dic["problem_name"] = problem
dic["hamilton... |
def greet (who):
"""
Greet someone or something
Parameters - who (string) - who or what to greet
Return - (string) - greeting
"""
return "Hello {0}".format(who) |
def _is_expecting_event(event_recv_list):
""" check for more event is expected in event list
Args:
event_recv_list: list of events
Returns:
result: True if more events are expected. False if not.
"""
for state in event_recv_list:
if state is False:
return True
... |
def default_current_guess(length):
"""
Get the default guess hint by the length of answer.
:param length: the length of random answer.
:return: str, the default guess hint, which is all blind by "-".
"""
current_guess = ""
for i in range(length):
current_guess += "-"
return curre... |
def write_file(filename="", text=""):
"""write file."""
with open(filename, mode='w', encoding='UTF8') as f:
chars = f.write(text)
return chars |
def wikipedia(langcode: str) -> str:
"""Returns the Wikipedia website for the language given by
`langcode`.
:param langcode: The language code of the desired language
"""
return "https://{}.wikipedia.org".format(langcode) |
def arg_min(weights,args = None):
"""Returns the index of the list weights which contains the minimum
item. If vals is provided, then this indicates the index"""
if args == None: args = range(len(weights))
return min(zip(weights,args))[1] |
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
if not name:
return ''
return name.replace('_', ' ').capitalize() |
def check_update_tasks_data(tasks_data):
"""
Function to check that all required fields are populated
required fields: '@odata.etag'
"""
if tasks_data.get("@odata.etag") and tasks_data.get("id"):
return "ok"
else:
return (f"Missing required field @odata.etag ={tasks_data.get(... |
def happy(number) -> bool:
"""It will check whther the entered number is a happy one or not"""
p = 0
n = number
if(n > 0 and n < 10):
return False
else:
while True:
s = 0
while(n != 0):
r = n % 10
s = s+(r*r)
n =... |
def datetoday(day, month, year):
"""Passed in a date, in integers, it returns the day of the week.
Output is expressed as an integer from 0-6.
0 is Sunday, 1 is Monday....... """
# dayofweek would have been a better name for this function :-(
d = day
m = month
y = year
if m < 3:
... |
def _merge_yaml(ret, data, profile=None):
"""
Merge two yaml dicts together
"""
if 'stat' not in ret:
ret['stat'] = []
for key, val in data.get('stat', {}).items():
if profile and isinstance(val, dict):
val['nova_profile'] = profile
ret['stat'].append({key: val})
... |
def chunk(seq, num):
"""
cut list into n chunks
"""
avg = len(seq) / float(num)
out = []
last = 0.0
while last < len(seq):
out.append(seq[int(last) : int(last + avg)])
last += avg
return out |
def PSMessage(action, options):
"""Builds a message
"""
return 'PSMessage', action, options |
def param_to_string(metric) -> str:
"""Convert a list / tuple of parameters returned from IE to a string"""
if isinstance(metric, (list, tuple)):
return ', '.join([str(x) for x in metric])
else:
return str(metric) |
def my_round(x, digits=0):
"""
Round the floating point number or list/tuple of floating point
numbers to ``digits`` number of digits.
Calls Python's ``round()`` function.
EXAMPLES::
>>> print(my_round(1./7, 6))
0.142857
>>> print(my_round((1./3, 1./7), 6))
(... |
def safe_repr(obj, short=False, max_length=80) -> str:
"""
Create a string representation of this object using :py:func:`repr`. If the
object doesn't have a repr defined, then falls back onto the default
:py:func:`object.__repr__`. Finally, if ``short`` is true, then the string
will be truncated to ... |
def remove_gate_from_line(local_qasm_line, gate_symbol, qubit_index):
"""
Removes the application of a specific gate on a specific qubit.
Args:
local_qasm_line: The line from which this call should be removed.
gate_symbol: The symbol representing the gate
qubit_index: The index of t... |
def isNullOrEmpty(value):
"""
Evaluates if the supplied value is null or empty.
:type value: Any
:rtype: bool
"""
if hasattr(value, '__len__'):
return len(value) == 0
elif value is None:
return True
else:
raise TypeError('isNullOrEmpty() expects a sequence ... |
def next_p2(num):
""" If num isn't a power of 2, will return the next higher power of two """
rval = 1
while (rval < num):
rval <<= 1
return rval |
def getfuture_connaddr(pack):
"""
get future from conaddr
"""
return (pack) & 0xffff |
def set_bit(v, index, x):
"""Set the index:th bit of v to 1 if x is truthy, else to 0, and return the new value."""
mask = 1 << index # Compute mask, an integer with just bit 'index' set.
v &= ~mask # Clear the bit indicated by the mask (if x is False)
if x:
v |= mask #... |
def replace_from_to(text, start_position, end_position, new_text):
""" Replaces the substring within the given range against another text."""
return "{}{}{}".format(text[:start_position], new_text, text[end_position:]) |
def crc64(input_string):
"""
Python re-implementation of SWISS::CRC64
Adapted from:
http://code.activestate.com/recipes/259177-crc64-calculate-the-cyclic-redundancy-check/
"""
POLY64REVh = 0xD8000000
CRCTableh = [0] * 256
CRCTablel = [0] * 256
isInitialized = False
crcl = 0
... |
def f_gamma_star_ip(tau_bar, gamma_bar, gamma_hat, delta_star, n):
"""This is the function to calculate gamma star given delta_star"""
# INPUT
# tau_bar: tau estimate in batch i
# gamma_bar: gamma mean estimate for batch i
# gamma_hat: sample mean for each OTU p in batch i
# delta_star: posterio... |
def crit_func(test_statistic, left_cut, right_cut):
"""
A generic critical function for an interval,
with weights at the endpoints.
((test_statistic < CL) + (test_statistic > CR) +
gammaL * (test_statistic == CL) +
gammaR * (test_statistic == CR))
where (CL, gammaL) = left_cut... |
def _prep_categorical_return(truth, description, verbose):
"""
Return `truth` and `description` if `verbose is True` else return
`description` by itself.
"""
if verbose:
return truth, description
else:
return truth |
def PickleResortDataDICT(Dict_Index):
"""Dictionary for switching the normalisation used on loading prefs"""
switcher = {
0 : 'Data',
1 : 'Raman_Shift',
2 : 'Raman_Intensity',
3 : 'Vec_Norm_Intensity',
4 : 'std_var_Norm_Intensity',
5 : 'Zero_to_One_Intensity',
6 : 'Series_Fi... |
def entuple(x,n=2):
"""
Make sure given value is a tuple. It is useful, for example, when you want to provide dimentions of an image either
as a tuple, or as an int - in which case you can use `(w,h) = entuple(x)`.
:param x: Either atomic value or a tuple. If the value is atomic, it is converted to a tu... |
def setup_element(format_element, element_count, max_element_count):
"""Interpolate element specific setup string."""
return format_element.format(
max_element_count=max_element_count, element_count=element_count
) |
def _mpi_param_value(mpi_args, env, param_name, default=None):
"""Placeholder docstring"""
return mpi_args.get(param_name) or env.additional_framework_parameters.get(param_name, default) |
def changeTally(tallyDict, keysList):
"""
Takes a tally in form of a dictionary. Iterates over all
elements in keyList and for those that exist in the dict,
"""
for i in keysList:
if i in list(tallyDict.keys()):
tallyDict[i] -= 1
return tallyDict |
def rm_trailing_slash(path):
"""Removes the trailing slash from a given path"""
return path[:-1] if path[-1] == '/' else path |
def _stft_frames_to_samples(
frames, size, shift, fading=None
):
"""
Calculates samples in time domain from STFT frames
:param frames: Number of STFT frames.
:param size: window_length often equal to FFT size.
The name size should be marked as deprecated and replaced with
... |
def convertListDomainToDict(list_domains:list):
"""
convert a list of domains objects to a dictionary with the designation in the key and the id in value
:param list_domains: list of domains json objects
:type list_domains: list[DomainJ]
:return: dictionary
:rtype: dict[designation] = id
... |
def check_val_of_forecast_settings(param):
"""
Background:
This function is used to check to see if there is a value (submitted from the user in the UI) for a given Prophet Hyper Parameter. If there is no value or false or auto, return that, else we'll return a float of the param given that the value may ... |
def merge_snapshots(frames):
"""Extract a subset of atoms from a given frame."""
snapshot = {
'header': 'Merged.',
'box': frames[0]['box'],
'residunr': [],
'residuname': [],
'atomname': [],
'atomnr': [],
}
for key in ('residunr', 'residuname', 'atomname', ... |
def dict_quick_merge(d1,d2):
"""
Simply combine the two dicts, assuming keys are disjoint.
"""
return dict([(k,v) for k,v in d1.items()]+[(k,v) for k,v in d2.items()]) |
def _get_output_filename(dataset_dir, split_name):
"""Creates the output filename.
Args:
dataset_dir: The directory where the temporary files are stored.
split_name: The name of the train/test split.
Returns:
An absolute file path.
"""
return '%s/%s.tfrecord' % (dataset_dir, spli... |
def ordinal(n):
"""Determines The ordinal for a given integer."""
return f'{n}{"tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4]}' |
def _append_newline(source):
"""Add newline to a string if it does not end with a newline."""
return source if source.endswith('\n') else source + '\n' |
def objective(k, p):
""" The objective function.
Delta is *negative* when p exceeds the maximum.
A k less than 1.13 also produces a negative value, but by a
much smaller amount.
"""
delta = 0.0
if k < 1.1 :
delta = k - 1.1
return 1.0 * (1.5 - p) + 50.0 * delta |
def is_py(file_path):
"""
:param file_path: the path of a file
:return: true if file is a python file(ends with .py)
"""
return file_path.split(".")[-1] == "py" |
def unproxy(obj):
"""Return the Python interface from a proxy object"""
if hasattr(obj, "__moyapy__"):
return obj.__moyapy__()
return obj |
def builtin_sqrt(x):
"""USes builtin"""
from math import sqrt
return sqrt(x) |
def minimum_shock_angle(m):
"""
Calculates the shock angle
for which the deflection angle is zero
Input:
m - Mach number
"""
import math
return math.asin(1/float(m)) |
def mysqrt(a, epsilon=0.0000000000000001):
"""Uses Newton's Method to return an estimate of sqrt(a)
a: nonnegative number
epsilon: final step size/accuracy
"""
if a<0:
print("a must be nonnegative.")
return
x=a/2
while True:
#print(x)
y = (x + a/x) / 2
... |
def encode_special_characters(user_string):
"""
Encode Special Characters for user's search Strings
Args:
user_string(string): raw string to encode
Returns:
Encode string for elasticsearch
"""
if user_string is None:
return ""
sp_chars = ['+', '-', '=', '|', '<', '... |
def levelFromHtmid(htmid):
"""
Find the level of a trixel from its htmid. The level
indicates how refined the triangular mesh is.
There are 8*4**(d-1) triangles in a mesh of level=d
(equation 2.5 of
Szalay A. et al. (2007)
"Indexing the Sphere with the Hierarchical Triangular Mesh"
ar... |
def to_signed_byte(num):
"""
Convert given byte number to signed byte number.
:param num: Unsigned byte number in range from 0 to 255.
:return: Signed number in range from -128 to 127.
"""
assert 0 <= num <= 255, 'Value out of range (0 - 255): {0}!'.format(num)
if num <= 127:
ret =... |
def requires_mfa(profile):
"""Checks to see if the given profile requires MFA.
Parameters
----------
- profile - the profile to inspect
Returns
-------
True if the profile requires MFA, False if it doesn't.
"""
return 'mfa_serial' in profile |
def cmpBoundaryAreas(A,B):
"""
Compares two rectangles and return true if Area(A)>Area(B).
"""
area_A=(A[2]-A[0])*(A[3]-A[1])
area_B=(B[2]-B[0])*(B[3]-B[1])
if area_A>area_B:
return 1
elif area_A==area_B:
return 0
else:
return -1 |
def fuel_required(mass):
"""
Calculates the amount of fuel required for a given mass. Returns 0 if no fuel required (because less than zero).
"""
new_fuel_required = mass // 3 - 2
#Base case
if new_fuel_required <= 0:
return 0
return new_fuel_required + fuel_required(new_fuel_... |
def inplace_buffer_merge(buffer, data, timesteps, model):
"""
Merges the new text from the current frame with the previous text contained in the buffer.
The alignment is based on a Longest Common Subsequence algorithm, with some additional heuristics leveraging
the notion that the chunk size is >= the ... |
def parse_tle_decimal(s):
"""Parse a floating point with implicit leading dot.
>>> parse_tle_decimal('378')
0.378
"""
return float('.' + s) |
def get_associations_from_users(users):
"""get_associations_from_users(users)"""
associations=[]
for user in users:
user_association=user["association"]
if (user_association not in associations):
associations.append(user_association)
return associations |
def sum_digits(number):
"""
Write a function named sum_digits which takes a number as input and
returns the sum of the absolute value of each of the number's decimal digits.
"""
return sum(int(n) for n in str(number) if n.isdigit()) |
def insertion_sort2(A):
"""
Sort list A into order, in place.
From Cormen/Leiserson/Rivest/Stein,
Introduction to Algorithms (second edition), page 17,
modified to adjust for fact that Python arrays use
0-indexing.
"""
for j in range(len(A)):
key = A[j]
# ins... |
def _isSubRange(value):
"""
Check if the input string represents a valid subRange.
Return a tuple, first element in the tuple is a boolean tells the validation result, while
the second element contains the error message if there is one.
"""
contents = value.split("-")
if len(contents) != 2:... |
def truncate_words(val: str, num: int, end: str = "...") -> str:
"""Truncates a string down to the number of words passed as the first parameter."""
# Replaces consecutive whitespace with a single newline.
words = val.split()
if len(words) < num:
return " ".join(words)
return " ".join(word... |
def compute_energy_spectrum(wave_spectral_density, gravity, density):
"""Compute energy density from wave spectral density."""
return wave_spectral_density * gravity * density |
def find_row(boarding_pass):
""" To find row from the boarding pass """
rows_range = [0, 127]
for i in range(0, 6):
mid = (rows_range[0] + rows_range[1]) // 2
if boarding_pass[i] == "F":
rows_range[1] = mid
elif boarding_pass[i] == "B":
rows_range[0] = mid + ... |
def get_short_id_from_ec2_arn(arn: str) -> str:
"""
Return the short-form resource ID from an EC2 ARN.
For example, for "arn:aws:ec2:us-east-1:test_account:instance/i-1337", return 'i-1337'.
:param arn: The ARN
:return: The resource ID
"""
return arn.split('/')[-1] |
def extract_txt(list_timeseries):
"""
Method to extract txt file containing
roi timeseries required for dual regression
"""
if isinstance(list_timeseries, str):
if list_timeseries.endswith('.txt'):
return list_timeseries
out_file = None
for timeseries in list_timeseries:... |
def longest_common_prefix(strs):
"""Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string
https://leetcode.com/submissions/detail/465245104/
#Runtime: 16 ms, faster than 94.96% of Python online submissions for Longest ... |
def PtknsToStr(path_tokens):
"""
There are three ways to store paths:
As a single string: '/Protein/Phe/Ca' <- the format entered by the user
As a list of tokens ['Protein', 'Phe', 'Ca'] <- split into tokens
As a list of nodes in a tree (pointers to nodes in a tree hierarchy)
This functio... |
def crop_area(crop):
"""calculate the area of a crop (x1, y1, x2, y2).
Adapted from https://github.com/danvk/oldnyc/blob/master/ocr/tess/crop_morphology.py
Copyright 2015 danvk.
http://www.apache.org/licenses/LICENSE-2.0
:param crop: crop coordinates
:type crop: tuple
:return: area of the ... |
def putBitsIntoList_1(n, L):
"""Takes an integer and puts L of it's least sig bits into a list"""
binstr = bin(n)[2:]
ret = [0]*L
for i in range(L):
try:
ret[i] = int(binstr[-i-1])
except IndexError:
pass
return ret |
def largest_palindrome_product(n):
""" largest palindrome of product of 2 x n-digit numbers
:param n: num of digit"""
a = int("9"*n)
lst = []
for i in range(1, a+1):
for j in range(1, a+1):
product = i * j
palin = str(product)
palin_rev = palin[::-1]
... |
def pack_bitstring(bits):
""" Creates a string out of an array of bits
:param bits: A bit array
example::
bits = [False, True, False, True]
result = pack_bitstring(bits)
"""
ret = b''
i = packed = 0
for bit in bits:
if bit:
packed += 128
i += 1
... |
def get_chunks(seg_dur, audio_id, audio_duration):
"""Get all chunk segments from a utterance
Args:
seg_dur (float): segment chunk duration, seconds
audio_id (str): utterance name,
audio_duration (float): utterance duration, seconds
Returns:
List: all the chunk segments
... |
def lda_filter_articles(ids, articles):
"""From sets of ids to set of sentences (str)
:argument ids: dictionary (keys are topics and values are ids of articles
:argument articles: list of str
:returns a dictionary, keys are topics and values are sentences (str)
"""
articles_per_topic = {}
fo... |
def pad(base, fill, count, right = False):
"""Pad base string with given fill until count, on either left or right."""
while len(base) < count:
if right:
base += fill
else:
base = fill + base
return base |
def open_save_file(path, mode, data_string=None, callback=None):
"""Return string or array or [type]callback
RW string to files. Modes are: r w
"""
with open(path, mode=mode, encoding="utf-8") as f:
output = ""
if mode is "r":
output = f.read()
elif mode is "w":
... |
def _after(node):
"""
Returns the set of all nodes that are after the given node.
"""
try:
pos = node.treeposition()
tree = node.root()
except AttributeError:
return []
return [tree[x] for x in tree.treepositions() if x[: len(pos)] > pos[: len(x)]] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.