content stringlengths 42 6.51k |
|---|
def _ros(veos, vpos, eos, pos):
"""
ROG = Rate of Senescing (Days)
"""
return (veos - vpos) / (eos - pos) |
def annual_child_care_expenses(responses, derived):
""" Return the annual cost of the monthly cost of child care expense """
try:
return float(responses.get('annual_child_care_expenses', 0))
except ValueError:
return 0 |
def BinarySearch(arr, val):
"""
Arguments: A list and value to search for
Output: The index of the matched value, or -1 if no match
"""
if len(arr) == 0:
return -1
counter = 0
for item in arr:
counter += 1
if item == val:
return counter - 1
return -1 |
def check_pair_sum(k: int, nums: list):
"""
1. Go through all the numbers
2. As you iterate, add complement to a set
3. Two numbers add up to k if number is in complements
Parameters:
k (int): desired sum
nums (list): available numbers
Returns
boolean: tru if there are 2 numbers in... |
def endowment_effect(mkt_val, ref_val, time_held, scale_factor):
"""
A simple endowment effect calculation method.
Given an item with a market value, reference value (i.e, value item was
purchased at), the amount of time it has been held, and a scale factor,
return the price accounting for a simple... |
def signedmin(val, w):
""" Signed minimum value function """
val = min(val, abs(w))
val = max(val, -abs(w))
return val |
def reverse(x):
"""
:type x: int
:rtype: int
"""
x_max = 2 ** 31 - 1
x_min = -x_max
if 0 <= x < x_max:
x = str(x)
x = x[::-1]
y = int(x)
elif x_min < x < 0:
y = -reverse(abs(x))
else:
y = 0
if x_min < y < x_max:
return y
else:
return 0 |
def titleize(phrase):
"""Return phrase in title case (each word capitalized).
>>> titleize('this is awesome')
'This Is Awesome'
>>> titleize('oNLy cAPITALIZe fIRSt')
'Only Capitalize First'
"""
return phrase.title() |
def bigger_price(limit: int, data: list) -> list:
"""
TOP most expensive goods
"""
bigger_dict = []
price_filter = sorted([d['price'] for d in data], reverse=True)[:limit]
print(price_filter)
while price_filter:
price_target = price_filter.pop(0)
for price_dict in data:
... |
def modal_details_tempport(n, is_open):
""" """
if n:
return {"is_open":not is_open}
return {"is_open":is_open} |
def qrel_entry(quest_id, answ_id, rel_grade):
"""Produces one QREL entry
:param quest_id: question ID
:param answ_id: answer ID
:param rel_grade: relevance grade
:return: QREL entry
"""
return f'{quest_id}\t0\t{answ_id}\t{rel_grade}' |
def _remove_missing(dict_):
"""
Remove fields from the dict whose values are None.
Returns a new dict.
:type dict_: dict
:rtype dict
>>> _remove_missing({'cpf': 'L7CPF20050101_20050331.09', 'rlut': None})
{'cpf': 'L7CPF20050101_20050331.09'}
>>> sorted(
... _remove_missing({
... |
def max_contig_sum(L):
""" L, a list of integers, at least one positive
Returns the maximum sum of a contiguous subsequence in L """
n = len(L)
maxSum = max(L)
for i in range(n):
for j in range(n-i):
maxSum = max(maxSum, sum(L[i:i+j+1]))
return maxSum |
def filter_moust_rating_app(data, categoria):
""" filter data to get news app """
report = sorted(
list(filter(lambda d: d["prime_genre"] == categoria, data)),
key=lambda k: float(k["rating_count_tot"]),
reverse=True,
)
return report[:1][-1] |
def invert(dictionary):
"""
Invert keys and values.
"""
return {v: k for k, v in dictionary.items()} |
def get_road_index_of_lane(lane_id, road_lane_set):
"""Get road index of lane"""
for i, lane_set in enumerate(road_lane_set):
if lane_id in lane_set:
return i
return -1 |
def lostf(x):
"""
Fonction de X qui renvoie, pour x < 7 les valeurs de "Lost":
4 8 15 16 23 42
>>> lostf(1.0)
4.0
>>> lostf(3.0)
15.0
"""
return (
60.0 -
((612.0 * x) / 5.0) +
((367.0 * x * x) / 4.0) -
((235.0 * x * x * x) / 8.0) +
((17.0 * x... |
def number_format_filter(num):
"""
A filter for formatting numbers with commas.
"""
return '{:,}'.format(num) if num is not None else '' |
def _walk_equal(bstree_left, bstree_right):
"""
Compare every node using recursive, once two node are not equal, return
False, or return True.
Args:
bstree_left: a Node object
bstree_right: a Node object
Returns:
True: two BinarySearchTree are equal
False: two Binar... |
def list_of_lists(input_, len_, default):
"""
Processes a list (or tuple), in which the default item is a list (or tuple) as well, specified by default.
E.g.:
input = ((1, 2), (3, 4)), len=2, default=None -> everything ok -> return as is
input = [5, 7], len=1, default=(5, 5) -> input is not a list o... |
def find_selected_options(option_prefix: str, redcap_record:dict) -> list:
"""
Find all choosen options within *redcap_record* where option begins with
provided *option_prefix*.
Note: Values of options not choosen are empty strings.
"""
return [
value
for key, value
in r... |
def to_hex(number: int) -> str:
"""Convert number to hex and made a basic formatting."""
return hex(number)[2:].zfill(2) |
def standardise_name(name):
"""
Standardise field names: Survey (Title) -> survery_title
"""
result = name.lower().replace(" ", "_").replace("(", "").replace(")", "")
# remove any starting and ending "_" that have been inserted
start_loc = 1 if result[0] == "_" else 0
loc = result.rfind("_"... |
def findRoot(x, power, epsilon):
"""Assumes x and epsilon an int or float, power an int, epsilon > 0
& power >= 1
Returns float y such that y**power is within epsilon of x.
If such float does not exist, it returns None"""
if x < 0 and power%2 ==0:
return None #since negative numbers have no ... |
def get_deconv_outsize(size, k, s, p, cover_all=False, d=1):
"""Calculates output size of deconvolution.
This function takes the size of input feature map, kernel, stride, and
pooling of one particular dimension, then calculates the output feature
map size of that dimension.
.. seealso:: :func:`~c... |
def remove_unicharacter(sent, return_str=True):
"""
Remove the single letter from the sentence
:param sent: str, the sentence to remove non-alphabetic
:param return_str: bool, return str when set to True, otherwise return tokenized list. default True
:return: str, the sentense after single characte... |
def is_numeric(val: str) -> bool:
""" Returns True if the input value can be casted to numeric type
"123.456" -> True
"pi" -> False
Args:
val (str): input value to test
Returns:
bool: True if `val` can be casted to numeric type
"""
try:
float(val)
return Tr... |
def check_tensor_name(t, name):
"""
We need a try, except block to check tensor names because
regu loss tensors do not allow access to their .name in eager mode.
"""
try:
return name in t.name
except AttributeError:
return False |
def get_duplicate_items_in_list(items):
"""Find duplicate entries in a list.
:param list items: list of items with possible duplicates.
:return: the items that occur more than once in input list. Each duplicated
item will be mentioned only once in the returned list.
:rtype: list
"""
s... |
def stations_to_dicts(stations):
"""Utility function to dict-ify the station attrs set by station_distributor()"""
return [{'number': station.number, 'gender': station.gender, 'roll': station.roll} for
station in stations] |
def condense_byte_ranges(byte_ranges):
"""
any overlapping byte-ranges can be consolidated into a single range.
This makes the ranges simpler and more compact.
:param byte_ranges:
:return: list
"""
byte_ranges = sorted(byte_ranges)
new_byte_ranges = []
i = 0
byte_range_len = len... |
def is_available_command(command):
"""Checks if ``command`` is available in TBot commands"""
available_commands = [
"/start",
"/help",
"/weather",
"/translate",
"/calculate",
"/tweet",
"/ocr_url",
"/stop",
]
if command in available_command... |
def _get_or_create_preprocess_rand_vars(generator_func,
function_id,
preprocess_vars_cache,
key=''):
"""Returns a tensor stored in preprocess_vars_cache or using generator_func.
If the tensor was... |
def Dist(p1,p2):
"""
Euclidean distance between 2 points
"""
x1, y1 = p1
x2, y2 = p2
return (((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)))**0.5 |
def sanitize_name(s,new_char='_'):
"""
Replace 'unsafe' characters in HTML link targets
Replaces 'unsafe' characters in a string used as a
link target in an HTML document with underscore
characters.
Arguments:
s (str): string to sanitize
replace_with (str): string to replace 'unsaf... |
def project_template(name, description):
"""
:param name: Project Name
:param description: Project Description
:return: Project Template
"""
return {
'name': name,
'description': description,
'capabilities': {
'versioncontrol': {
'sourceControl... |
def get_sub_path(path, start, end=None, symbol='.'):
"""Returns a split subpath of a string by symbol.
:param str path: The path to be split
:param int start: The start index to be split off
:param int end: Optional - The end index to be split off
:param str symbol: Optional (*.*) - The symbol that... |
def overlap_indices(a1, n_a, b1, n_b):
"""Given interval [a1, a1 + n_a), and [b1, b1 + n_b) of integers,
return indices [a_start, a_end), [b_start, b_end) of overlapping region.
"""
if n_a < 0 or n_b < 0:
raise ValueError("Negative interval length passed to overlap test")
if n_a == 0 or n_b... |
def _remove_pos_tags(sent):
"""
Args:
sent - list of (word, pos) tuples
Returns:
A list of only lexical items.
Convert a list of (word, pos) tuples back to a list of only words.
"""
output = []
for word_pos in sent:
output.append(word_pos[0])
return output |
def rotate_ccw(puzzle):
"""Rotate the puzzle 90 degrees counter-clockwise"""
result = []
for col in reversed(range(4)):
temp = []
for row in range(4):
temp.append(puzzle[row][col])
result.append(temp)
return result |
def no_more_olga(client, channel, nick, message, matches):
"""
Make sure people are talking to helga and not olga
"""
return '{0}, you should talk to me instead. Olga is no more'.format(nick) |
def is_threepid_reserved(reserved_threepids, threepid):
"""Check the threepid against the reserved threepid config
Args:
reserved_threepids([dict]) - list of reserved threepids
threepid(dict) - The threepid to test for
Returns:
boolean Is the threepid undertest reserved_user
"""... |
def round_from_32(f_val):
"""
converts a 32th of nautical miles into a distance
@return distance in nautical miles
"""
# logger
# M_LOG.info(">> round_from_32")
# return
return f_val / 32. |
def match_slice_to_shape(slparent, nparent):
"""
Refine a slice for a parent array that might not contain a full child
"""
nchild = slparent.stop - slparent.start
if (slparent.start > nparent) | (slparent.stop < 1):
null = slice(0,0)
return null, null
if slpare... |
def dict_partial_cmp(target_dict, dict_list, ducktype):
"""
Whether partial dict are in dict_list or not
"""
for called_dict in dict_list:
# ignore invalid test case
if len(target_dict) > len(called_dict):
continue
# get the intersection of two dicts
intersect... |
def _check_lists(present, absent) -> bool:
"""
Compares two lists to see if they share common elements. If they do this is used to reject them and prompt the
User to correct their input.
:param present: List of characters present in a word.
:param absent: List of characters absent from a word.
... |
def is_constant_fill(bytes, fill_byte):
"""Check a range of bytes for a constant fill"""
return all(b == fill_byte for b in bytes) |
def make_response(request, code, data=None):
"""Make response based on passed request, status code and data."""
return {
'action': request.get('action'),
'time': request.get('time'),
'data': data,
'code': code,
} |
def remove_multiPV(opt):
"""delete MultiPV from the options"""
del opt["MultiPV"]
return opt |
def _str_conv(number, rounded=False):
"""
Convenience tool to convert a number, either float or int into a string.
If the int or float is None, returns empty string.
>>> print(_str_conv(12.3))
12.3
>>> print(_str_conv(12.34546, rounded=1))
12.3
>>> print(_str_conv(None))
<BLANKLINE... |
def assignment_two_params(one, two):
"""Expected assignment_two_params __doc__"""
return "assignment_two_params - Expected result: %s, %s" % (one, two) |
def rgb2hex(pix):
"""Given a tuple of r, g, b, return the hex value """
r, g, b = pix[:3]
return "#{:02x}{:02x}{:02x}".format(r, g, b) |
def list_placeholder(length, is_pg=False):
"""Returns a (?,?,?,?...) string of the desired length"""
return '(' + '?,'*(length-1) + '?)' |
def switch_relation(rel):
"""Switches the relation string (e.g., turns "<" into ">", and "<=" into ">=")
Args:
rel: The relation string.
Returns:
The switched relation string.
"""
if rel == '<':
return '>'
if rel == '<=':
return '>='
if rel == '>=':
... |
def convert_to_string(liste):
"""
Function creates strings with '+' in place of ' '
Input=list of string Output=string with + in place of ' '
"""
if not liste:
return ''
if len(liste) == 1:
return liste[0]
els... |
def clip(value, lower, upper):
""" clip a value between lower and upper """
if upper < lower:
lower, upper = upper, lower # Swap variables
return min(max(value, lower), upper) |
def normalize(s):
"""
Given a text, cleans and normalizes it. Feel free to add your own stuff.
From: https://www.kaggle.com/mschumacher/using-fasttext-models-for-robust-embeddings
"""
s = s.lower()
# Replace numbers and symbols with language
s = s.replace('&', ' and ')
s = s.replace('@'... |
def decimal_to_binary(n, i):
"""
Converts i to a binary list that contains n bits
:param n: total number of bits (integer)
:param i: number to convert (integer)
:return: (list)
"""
return list(map(int, list(format(i, "0{0}b".format(n))))) |
def str_point(string: str):
"""
Convert string to point
"""
return [int(v) for v in string.split(";")[:2]] |
def get_ngrams(n, text):
"""Calculates n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
... |
def guess_file_extension(url):
""" Used by the image mirroring service """
url = url.lower()
if '.jpg' in url or '.jpeg' in url:
return '.jpg'
elif '.gif' in url:
return '.gif'
elif '.png' in url:
return '.png'
elif '.svg' in url:
return '.svg'
else:
r... |
def set_extra_info(extra, name, value):
"""
Sets optional transport information.
Parameters
----------
extra : `None`, `dict` of (`str`, `Any`) items
Optional transform information.
name : `str`
The extra info's name.
value : `Any`
The value to set.
Retu... |
def get_dra_st(line, c):
"""
Get state of DRA.
"""
for i in range(0, len(line)):
if 'DRA' in line[i]:
if 'n/a' in line[i + 1]:
return ''
else:
return str(int(line[i + 1]) - 1 + int(c)) |
def parse_sourceparams(sourceparams):
"""
Split sourceparams string of the form key1=val1[,key2=val2,...]
into a dict. Also accepts valueless keys i.e. without =.
Returns dict of param key/val pairs (note that val may be None).
"""
params_dict = {}
params = sourceparams.split(',')
if ... |
def isAnOperator( x ):
"""Return True if x is '+','-','*','/'"""
return (x=='+') or (x=='-') or (x=='*') or (x=='/') |
def remove_request(record, command):
"""Return record with request for "command" removed"""
requests = record["requests"]
new_requests = []
for i in requests:
if i.split("|")[1] != command:
new_requests.append(i)
record["requests"] = new_requests
return record |
def bracket(s,m=''):
"""add a bracket around s and append m.
@rtype: string
@return: a bracketed string s and a suffixed message m
"""
return '[%s] %s' % (s,str(m)) |
def configlets_get_from_facts(cvp_device):
"""
Return list of devices's attached configlets from CV Facts.
Parameters
----------
cvp_device : dict
Device facts from CV.
Returns
-------
list
List of existing device's configlets.
"""
if "deviceSpecificConfiglets" ... |
def clamp(value, low, high):
"""Clamp value between low and high (inclusive).
Args:
value (int, float): The value.
low (int, float): Lower bound.
high (int, float): Upper bound.
Returns
int, float: Value such that low <= value <= high.
"""
return max(low, min(value,... |
def _attachment_v2_to_v1(vol):
"""Converts v2 attachment details to v1 format."""
d = []
attachments = vol.pop('attachments', [])
for attachment in attachments:
a = {'id': attachment.get('id'),
'attachment_id': attachment.get('attachment_id'),
'volume_id': attachment.ge... |
def replace_chrom_name_in_call_line(line, name_map):
"""
Replaces the Chrom name from call line.
Returns new call line.
:param line: line from VCF
:param name_map: name-mapping dict
:return: new call line
"""
# split on whitespace THEN ':',
# bc not all VCF will have the source_fil... |
def radix_sort(arr):
"""Return list sorted by radix sort."""
len_arr = len(arr)
modulus = 10
div = 1
while True:
# empty array, [[] for i in range(10)]
new_list = [[], [], [], [], [], [], [], [], [], []]
for value in arr:
least_digit = value % modulus
... |
def get_pyomo_input_dictionary(data_dict, namespace=None):
"""
- For all fields which are not dictionaries already (i.e. if they are not indexed),
it returns a dict like None:field.
- it also returns the whole dictionary as namespace:dictionary, as required by PYOMO.
"""
for k, v in data_dict.i... |
def format_seconds(seconds: int) -> str:
"""
Returns a string in format of HH:MM:DD which represents the number of seconds given as the argument
:param seconds: The number of seconds to format
:return: A formatted string
"""
sec = seconds % 60
minute = (seconds // 60) % 60
hour = seconds... |
def palette_to_rgb(palette_color_summary, rgb_color_summmary):
"""
palette_color_summary : number of pixel per index
rgb_color_summmary : number of pixel per rgb
output : rgb per index
"""
index_pixel_count = [None] * len(palette_color_summary)
palette_rgb = [None] * len(palette_... |
def _find_biggest_value(list):
"""
Get the intex of the largest value in list of values
:return: -1 if list empty, otherwise index of biggest value
"""
if len(list) < 1:
return -1
max = 0
for idx, val in enumerate(list):
if val > list[max]:
max = idx
return ... |
def _tanh_to_255(x):
"""
range [-1. 1] to range [0, 255]
:param x:
:return:
"""
return x * 127.5 + 127.5 |
def packmeta(meta, text):
"""Add metadata to fulltext to produce revision text."""
keys = sorted(meta)
metatext = b''.join(b'%s: %s\n' % (k, meta[k]) for k in keys)
return b'\x01\n%s\x01\n%s' % (metatext, text) |
def _s_dist(circ_val1: float, circ_val2: float, r: float) -> float:
"""
Returns the length of the directed walk from circ_val1 to circ_val2, with the lowest
value length as distance. based on
https://www.codeproject.com/Articles/190833/Circular-Values-Math-and-Statistics-with-Cplusplus
:param circ_... |
def find_it(seq):
"""function finds the integer that has the odd number of values once collected into a dictionary."""
counter = {}
for item in seq:
if item in counter:
counter[item] += 1
else:
counter[item] = 1
for item in counter:
if counter[item] % 2 !=... |
def find(lis, predicate):
"""
Finds the first element in lis satisfying predicate, or else None
"""
return next((item for item in lis if predicate(item)), None) |
def samples_to_master_mix( samples ):
"""
returns the master-mix for the given pca plate
assumes that each plate has one and only one condition, which can be determined by looking @ the sample in well A1
"""
try:
# FIXME: there's a million ways this can go wrong...
mix = samples[0].o... |
def _generate_magic_packet(mac_address):
"""Generate WoL magic packet.
A WoL 'magic packet' payload consists of six FF (255 decimal) bytes
followed by sixteen repetitions of the target's 6-byte MAC address.
Parameters
----------
mac_address : str
12-digit hexadecimal MAC address witho... |
def switch_bit(bit):
""" Function that replaces a bit 0 to 1 and bit 1 to 0. """
if bit != -1:
return 1 - bit
return bit |
def lerp(a, b, t):
"""Linearly interploate between a and b by t."""
return (1.0 - t) * a + t * b; |
def get_network_version(name):
"""
Returns the network name and version (everything after _)
Useful to customize the network on the fly
"""
idx = name.rfind('_')
if idx < 0:
return name, None
else:
return name[:idx], name[idx + 1:] |
def merge_data(data_list, tmp_data, **kwargs):
"""Function: merge_data
Description: Adds a series of similar token data into a single string
and adds the token type and string as set to a list.
Arguments:
(input) data_list -> List of summarized categorized tokens.
(input) tmp_da... |
def remove_file_suffix(path):
"""
Remove the deployment/develop file prefix in the path, for example, the develop of java is .java and the deployment is .class.
This is to match if the file name of the path has a prefix like .java, and the deploy path may have the prefix like .class,
in this case, it sh... |
def anagrams(word, words):
"""
A function that will find all the anagrams of a word
from a list. You will be given two inputs a word and
an array with words. You should return an array of all
the anagrams or an empty array if there are none.
"""
template = sorted([char for char in word])
... |
def normalize(district, purpose, cube_dictionary_list):
""" Add various entries to a cube dictionary and sort by socket index """
for gui_index, cube_dictionary in enumerate(cube_dictionary_list):
cube_dictionary["district"] = district
cube_dictionary["purpose"] = purpose
cube_dictionary... |
def bmp_emoji_safe_text(text):
"""
Returns bmp emoji safe text
ChromeDriver only supports bmp emojis - unicode < FFFF
"""
transformed = [ch for ch in text if ch <= '\uFFFF']
return ''.join(transformed) |
def ugly_numbers(n: int) -> int:
"""
Returns the nth ugly number.
>>> ugly_numbers(100)
1536
>>> ugly_numbers(0)
1
>>> ugly_numbers(20)
36
>>> ugly_numbers(-5)
1
>>> ugly_numbers(-5.5)
Traceback (most recent call last):
...
TypeError: 'float' obj... |
def calc_opp_goal_position(shootingDirection, pitchLength):
"""
Outputs either +1 or -1 if team shooting left-to-right or right-to-left, respectively.
"""
# 1 = left-to-right
if shootingDirection == 1:
return (pitchLength/2, 0)
# -1 = right-to-left
else:
return (-1*pitchLeng... |
def dwi_container_from_filename(bids_dwi_filename):
""" Generate subjects/sub-<participant_id>/ses-<session_id> folder
from BIDS filename.
"""
import re
from os.path import join
m = re.search(r'(sub-[a-zA-Z0-9]+)_(ses-[a-zA-Z0-9]+)_', bids_dwi_filename)
if m is None:
raise ValueErro... |
def reconcile(current, desired):
"""Return sets (to_add, to_remove) indicating elements that should be
added to or removed from ``current`` to produce ``desired``.
"""
to_remove = current - desired
to_add = desired - current
return to_add, to_remove |
def changeFormatRNA(imgFormat):
""" Changes the image format for the iCLIP plot
Positional arguments:
imgFormat -- Image format to use.
"""
return {'toImageButtonOptions' : {'filename' : 'RNA', 'width' : None,
'scale' : 1.0, 'height' : None, 'format' : imgFormat} } |
def overlap_indices(a1, n_a, b1, n_b):
"""Given interval [a1, a1 + n_a), and [b1, b1 + n_b) of integers,
return indices [a_start, a_end), [b_start, b_end) of overlapping region.
"""
if n_a < 0 or n_b < 0:
raise ValueError("Negative interval length passed to overlap test")
if n_a == 0 or n_b... |
def format_with_default_value(handle_missing_key, s, d):
"""Formats a string with handling of missing keys from the dict.
Calls s.format(**d) while handling missing keys by calling
handle_missing_key to get the appropriate values for the missing keys.
Args:
handle_issing_key: A function that t... |
def any_match(first_string, second_string):
"""Return whether two strings share a word.
:param first_string: The first string to check
:param second_string: The second string to check
"""
if first_string is None or second_string is None:
return False
for first_word in first_string.strip... |
def pairwiseSetDist(recomA, recomB, thres):
"""Calculates the set intersection between two output lists
! pairwiseSetDist(x,y) != pairwiseSetDist(y,x)
Args:
recomA, recomB (lists): see recom.py#surprise_recom()
thres (int): see setDist()
Returns:
float: set distance
"""
# derive the per-user and... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.