content stringlengths 42 6.51k |
|---|
def combination_memo(n, r):
"""This function calculates nCr using memoization method."""
memo = {}
def recur(n, r):
if n == r or r == 0:
return 1
if (n, r) not in memo:
memo[(n, r)] = recur(n - 1, r - 1) + recur(n - 1, r)
return memo[(n, r)]
return recur(n... |
def fix_eol(text, eol):
"""Fix end-of-lines in a text."""
lines = text.splitlines()
lines.append('')
return eol.join(lines) |
def of_type(param, valid_types):
"""Function to check the type of a parameter.
It tries to match the type of the parameter with the
types passed through `valid_types` list.
Args:
param: A value of any type.
valid_types(list): A list of acceptable types.
Returns:
bool: True/False... |
def _get_indentation(line):
"""Return leading whitespace."""
if line.strip():
non_whitespace_index = len(line) - len(line.lstrip())
return line[:non_whitespace_index]
else:
return '' |
def crear_tablero (num_filas, num_columnas):
"""
nada --> matrix
OBJ: crear matriz
"""
tablero = []
for i in range (num_filas):
tablero.append(['-']*num_columnas)
return tablero |
def ucfirst(text):
"""
Template filter for capitalizing the first letter of a word
Args:
text: the text to be modified
Returns:
A string with the first letter uppercase.
"""
return text[0].upper() + text[1:] |
def parse_battery(charge):
"""
Parses the battery value to an integer
"""
try:
return int(charge)
except ValueError:
return None |
def _skip_common_stack_elements(stacktrace, base_case):
"""Skips items that the target stacktrace shares with the base stacktrace."""
for i, (trace, base) in enumerate(zip(stacktrace, base_case)):
if trace != base:
return stacktrace[i:]
return stacktrace[-1:] |
def decodeBytesToUnicode(value, errors="strict"):
"""
Accepts an input "value" of generic type.
If "value" is a string of type sequence of bytes (i.e. in py2 `str` or
`future.types.newbytes.newbytes`, in py3 `bytes`), then it is converted to
a sequence of unicode codepoints.
This function is u... |
def plural(quantity, extension="s"):
"""
:param quantity: list or integer.
:param extension: how do extend to plural form.
:return: plural extension if required.
"""
if type(quantity) == list:
count = len(quantity)
elif type(quantity) == int:
count = quantity
else:
... |
def plural(quantity: int, singular: str, plural: str) -> str:
"""Return the singular or plural word."""
return singular if quantity == 1 else plural |
def compare(item1, item2):
"""Custom sort function comparing first two string characters"""
item1, item2 = item1[:2], item2[:2]
if item1 != item2:
if item1 > item2:
return 1
return -1
return 0 |
def combine(list_of_list):
"""
Generates all combinations (x, y, ...) where x is an element of
list_of_list[0], y an element of list_of_list[1], ...
\param list_of_list the list of lists of possible values.
\return The list of all possible combinations (therefore, a list of
lists).
"""
... |
def top_3_words(text: str) -> list:
"""
Given a string of text (possibly with punctuation and line-breaks),
returns an array of the top-3 most occurring words, in descending
order of the number of occurrences.
:param text: a string of text
:return: an array of the top-3 most occurring words
... |
def quartic_easein(pos):
"""
Easing function for animations: Quartic Ease In
"""
return pos * pos * pos * pos |
def sqrt(x):
"""
Square root.
"""
return pow(x, 1/2) |
def process_patch(patch):
"""
Rather dirty function to remove any lines that would being removed by the
patch prior to checking it for keywords.
"""
if not patch.startswith("@@"):
raise Exception("This is not a unidiff")
return "\n".join(line for line in patch.split("\n") if not line.s... |
def convert_to_two_bytes(value):
"""
@type value: C{int}
@rtype: C{bytearray}
@return: least-significatn byte, most significant byte
"""
return bytearray([value % 128, value >> 7]) |
def rearrange(widgets: list):
"""
Sort widget boxes according to priority.
"""
mapping = {
'small': 1,
'big': 2,
'full': 3,
}
def sort_key(element):
return (
element.get('priority', 1),
mapping.get(element.get('display_size', 'small'), 1),... |
def to_bytes(bytes_or_str):
"""
to_bytes(python3)
:param bytes_or_str:
:return:
"""
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
else:
value = bytes_or_str
return value |
def check_for_default_value_for_missing_params(missing_params, method_params):
"""
:param missing_params: Params missing from Rule
:param method_params: Params defined on method, which could have default value for missing param
[{
'label': 'action_label',
'name': 'action_parameter',
'fiel... |
def f1_score(precision, recall):
"""
Compute f1 score.
"""
if precision or recall:
return 2 * precision * recall / (precision + recall)
else:
return 0 |
def GetEst(coeff):
"""Extracts the estimated coefficient from a coeff tuple."""
name, est, stderr = coeff
return est |
def find_list_item_position(l, item):
"""
:param l:
:param item:
:return:
"""
return [i for i, element in enumerate(l) if element == item] |
def prime_sieve(n):
""" returns a list of primes < n """
sieve = [True] * n
for i in range(3, int(n ** 0.5) + 1, 2):
if sieve[i]:
sieve[i * i::2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
return [2] + [i for i in range(3, n, 2) if sieve[i]] |
def camel_case(snake_str):
"""Convert string to camel case."""
title_str = snake_str.title().replace("_", "")
return title_str[0].lower() + title_str[1:] |
def kelvin_to_celsius(value):
"""
Convert Kelvin to Celsius
"""
return value - 273.15 if value is not None else None |
def get_para_distributed_mode(arg):
"""Get distributed mode parameter"""
if arg not in ["horovod", "tf_strategy"]:
raise ValueError("--distributed_mode or -d must be one of ['horovod', 'tf_strategy']")
return arg |
def smartsplit(path, on):
"""
Splits the string "path" with the separator substring "on" ignoring the escaped separator chars
@param path
@param on: separator substring
"""
escape = "\\" + on
if escape in path:
path = path.replace(escape, chr(1))
pathList = path.split(on)
... |
def arvi( redchan, nirchan, bluechan ):
"""
Atmospheric Resistant Vegetation Index: ARVI is resistant to atmospheric effects (in comparison to the NDVI) and is accomplished by a self correcting process for the atmospheric effect in the red channel, using the difference in the radiance between the blue and the red cha... |
def statistical_range(estimate, margin_of_error):
"""
The minimum and maximum values for a statistical estimate.
Args:
estimate (int): An estimate value from the U.S. Census Bureau
margin_or_error (float): The bureau's estimate of the value's margin of error
Returns:
A two-item... |
def mode(ls):
"""
Takes a list as an argument and returns the mode of (most common item in)
that list.
"""
return max(set(ls), key=ls.count) |
def sign(x):
"""Return sign of value as 1 or -1"""
if x >= 0:
return 1
else:
return -1 |
def pchange(x1, x2) -> float:
"""Percent change"""
x1 = float(x1)
x2 = float(x2)
return round(((x2 - x1) / x1) * 100., 1) |
def consecutive(numbers):
"""
takes input of a list of numbers and starts counting consecutively increasing numbers.
the count resets after a number breaks the pattern.
stores largest count to output.
"""
pos = 0
count = 1
limit = len(numbers)
while limit > 0:
i... |
def gcd(m,n,buffer):
"""Returns the GCD through recursion, and the quotient buffer"""
if ((m % n) == 0):
return n
else:
buffer.append(-1*(m // n))
return gcd(n, (m % n), buffer) |
def parse_instruction(_bv, instruction, _lifted_il_instrs):
""" Removes whitespace and commas from the instruction tokens """
tokens = [x for x in [str(token).strip().replace(",", "") for token in str(instruction).split(" ")] if len(x) > 0]
return tokens |
def fixtures_friction_loss(vel_head, *args):
"""
Func takes velocity_head output as well as K constants for each of the piping fixtures.
ex:
>>> x = tdh.velocity_head(Q = 1000.0, d = 10.0)
>>> y = tdh.friction_loss(x, *[1.3, 0.27, 1.5]) Where 1.3,0.27,1.5 are all K's found in reference charts
... |
def empty_cells(state):
"""
Each empty cell will be added into cells' list
:param state: the state of the current board
:return: a list of empty cells
"""
cells = []
for x, row in enumerate(state):
for y, cell in enumerate(row):
if cell == 0:
cells.append... |
def pick_wm_0(probability_maps):
"""
Returns the csf probability map from the list of segmented probability maps
Parameters
----------
probability_maps : list (string)
List of Probability Maps
Returns
-------
file : string
Path to segment_prob_0.nii.gz is returned
... |
def windows_notify(title: str, message: str) -> str:
"""Display notification for Windows systems"""
command = f"""powershell -command "$wshell = New-Object -ComObject Wscript.Shell;\
$wshell.Popup('{message}', 64, '{title}', 0)" """
return command |
def splitline(line, size):
""" Chop line into chunks of specified size. """
result = []
ptr = 0
while ptr < len(line):
chunk = line[ptr:ptr+size]
result.append(chunk)
ptr += size
return result |
def convert_to_number(str_float):
"""Converts a number retrieved as str from the csv file to float.
Also does curation of inputs.
"""
if not str_float:
return False
elif str_float[-1] is "%":
return float(str_float[:-1])
elif str_float[-1] is "+":
return float(str_float[... |
def tokenize_annotations(annotations):
"""
Recibe una lista de textos y los tokeniza: "hola como estas" -> ["hola", "como", "estas"]
"""
return [ann.split() for ann in annotations] |
def monomial_max(*monoms):
"""Returns maximal degree for each variable in a set of monomials.
Consider monomials `x**3*y**4*z**5`, `y**5*z` and `x**6*y**3*z**9`.
We wish to find out what is the maximal degree for each of `x`, `y`
and `z` variables::
>>> from sympy.polys.monomialtoo... |
def get_weekday(current_weekday: int, days_ahead: int) -> int:
"""Return which day of the week it will be days_ahead days from
current_weekday.
current_weekday is the current day of the week and is in the
range 1-7, indicating whether today is Sunday (1), Monday (2),
..., Saturday (7).
days_ah... |
def authorlist_to_string(authorlist):
"""
Function to convert a list of author names
into a readable string, for example,
['X', 'Y', 'Z'] -> 'X, Y and Z'.
"""
if len(authorlist) > 1:
authors = '{} and {}'.format(', '.join(authorlist[:-1]), authorlist[-1])
else:
authors = auth... |
def splitLines(s):
"""Same as g.splitLines(s)"""
return s.splitlines(True) if s else [] |
def _get_jax_to_tf_batch_norm_mapping(tf_bn_layer_name):
"""Returns a dictionary from JAX naming to tf naming for batch norm parameters.
Args:
tf_bn_layer_name: String denoting the name of the batch norm layer in tf.
Returns:
A dictionary from JAX naming to tf naming for batch norm parameters.
"""
re... |
def _find_and_replace_fields_arcade(text, field_mapping):
"""Perform a find and replace for field names in an arcade expression.
Keyword arguments:
text - The arcade expression to search and replace fields names
field_mapping - A dictionary containing the pairs of original field names and new field... |
def minimum_grade(parsed_list, passing_grade, overall_min=True):
"""
This function calculates the minimum grade from the given grades.
:param parsed_list: the parsed list of the grades
:param passing_grade: the grade passing threshold
:param overall_min: True, when calculating the minimum of all th... |
def is_list(s):
"""
Returns True if the given object has list type or False otherwise
:param s: object
:return: bool
"""
return type(s) in [list, tuple] |
def backup_yaml_parse(yamlin):
"""for absolute compatibility, a very very simple yaml reader
built to purpose. strips all helpful yaml stuff out, so be careful!"""
head_dict = {}
try:
decoded = yamlin.decode()
except:
decoded = yamlin[0].decode()
split = decoded.split('\n')
#... |
def strip_zeros(file_name):
"""Sometimes the covers don't have the same leading characters as
the .nfo and .sfv file. In this case the .nfo file is most likely
renamed too. e.g. Gentleman-Runaway-EP-2003-TLT"""
if file_name.startswith(("00-", "00_", "01-", "01_")):
return file_name[3:]
elif file_name.startswith(... |
def imc(peso: float, estatura: float) -> float:
"""Devuele el IMC
:param peso: Peso en kg
:peso type: float
:param estatura: Estatura en m
:estatura type: float
:return: IMC
:rtype: float
>>> imc(78, 1.83)
23.29
"""
return round(peso/(estatura**2), 2) |
def idx2off(i):
""" Produces [0, 32, 64, 88, 120, 152, 176, 208, 240, 264, 296, 328]
These are the byte offsets when dividing into 44-coeff chunks"""
return i * 32 - (8 * (i//3)) |
def location_custom_properties(domain, loc_type):
"""
This was originally used to add custom properties to specific
location types based on domain or simply location type.
It is no longer used, and perhaps will be properly deleted
when there is a real way to deal with custom location properties.
... |
def ensure_list(obj, valid=lambda x: True):
"""Convert `obj` to a list if it is not already one"""
if isinstance(obj, list):
if all(valid(o) for o in obj):
return obj
else:
if valid(obj):
return [obj]
return [] |
def count_sentences(data):
"""
The following function counts the sentences in the string by checking that the i'th' character
is '!', '.' or '?'
"""
countSentences = 0
for character in data:
if (character == '!' or character == '.' or character == '?'):
countSentences += 1... |
def is_right_bracket(token):
""" Returns true if right bracket """
return token == ")" |
def add_street_to_items(street, items):
"""
Adding each element of a list to another list
:param street: List of elements to be added
:param items: List where elements will be added to
:return: list with all elements
"""
for item in street:
items.append(item)
return items |
def word_count(text,separator=' '):
"""
Simple word count of words split by a separator
:param text: Text for character count
:type text: String
:returns: Text character count
:rtype: Integer
"""
return len(text.split(separator)) |
def check_if_unremovable(source, patterns):
"""comment annotation must be the first line and started with #"""
for s in source:
ss = s.strip()
if ss.startswith("#") and any(x in ss for x in patterns):
return True
return False |
def th(ranking, fraction):
"""The total number of correctly recovered relations between pairs that include an exam paper
that is ranked in the top "fraction" in the ground truth. (Section 4.2)
:param ranking: grading algorithm output
:param fraction:
:return:
"""
limit = int(len(ran... |
def majority_element(nums, k):
"""
Find the majority elements in given array
:param nums: list[int]
:type nums: given array of numbers
:param k: k for 1/k times
:type k: int
:return: the majority elements
:rtype: list[int]
"""
if len(nums) == 0:
return -1
counter = {... |
def map_keys(pvs, keys):
"""
Add human readable key names to dictionary while leaving any existing key names.
"""
rs = []
for pv in pvs:
r = dict((v, None) for k, v in keys.items())
for k, v in pv.items():
if k in keys:
r[keys[k]] = v
r[k] = v
... |
def _get_single_channel_feature_names(chan_dict):
"""Helper function for getting feature extractors."""
feature_list = []
for feature in chan_dict:
if isinstance(chan_dict[feature], dict) and chan_dict[feature]['run']:
feature_list.append(feature)
return feature_list |
def _compute_step_lower_bound(loss: float, blown_up: bool, relative_improvement_bound: float = 0.8) -> float:
"""problem this addresses: on a small fraction of steps, the free energy estimate may be grossly unreliable
away from target, typically indicating an instability was encountered.
detect if this occu... |
def filter_relation_suggestions(relation_suggestions):
"""Remove unwanted relation from provided suggestion.
:return:
"""
filtered_relations = []
for relation in relation_suggestions:
if relation.startswith('http'):
# Cannot ignore base here because it is needed
# for... |
def basis_function(degree, knot_vector, span, t):
"""Computes the non-vanishing basis functions for a single parameter t.
Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller.
Uses recurrence to compute the basis functions, also known as Cox - de
Boor recursion formula.
"""
le... |
def _convert_month_to_date_str(month_str):
"""
Convert string of month format to date format. If it is not a month
format, return the value without converting.
Parameters
----------
month_str : str
String to be converted. e.g., 2019-01
Returns
-------
date_str :... |
def get_color_map_list(num_classes):
"""
Returns the color map for visualizing the segmentation mask,
which can support arbitrary number of classes.
Args:
num_classes (int): Number of classes.
Returns:
(list). The color map.
"""
num_classes += 1
color_map = num_classes... |
def count_steps(x, y):
"""Count steps back to 0,0"""
steps_back = 0
while x != 0 or y != 0:
if x > 0:
if y > 0:
# sw
y -= 1
elif y < 0:
# n
x -= 1
y += 1
else:
# nw
... |
def ltypeOfLaueGroup(tag):
"""
Yield lattice type of input tag.
Parameters
----------
tag : TYPE
DESCRIPTION.
Raises
------
RuntimeError
DESCRIPTION.
Returns
-------
ltype : TYPE
DESCRIPTION.
"""
if not isinstance(tag, str):
raise R... |
def int_to_en(num):
"""
This is taken from https://stackoverflow.com/a/32640407 and slightly modified.
:param num: int32 integer.
:return: English version of num.
"""
int_to_english = {
0: "zero",
1: "one",
2: "two",
3: "three",
4: "four",
5: "five... |
def b_varchar_encode(text):
"""
encode with utf-16-le
Byte *Varchar
:param str text:
:return:
"""
if not text:
return '\x00'
length = len(text)
return chr(length) + text.encode('utf-16-le') |
def bool_to_str(boolean: bool) -> str:
"""Converts a bool such as True to 'true'."""
return 'true' if boolean else 'false' |
def _nscale8x3_video(r, g, b, scale):
"""Internal Use Only"""
nonzeroscale = 0
if scale != 0:
nonzeroscale = 1
if r != 0:
r = ((r * scale) >> 8) + nonzeroscale
if g != 0:
g = ((g * scale) >> 8) + nonzeroscale
if b != 0:
b = ((b * scale) >> 8) + nonzeroscale
re... |
def program_entry(program):
"""
Template tag {% program_entry program %} is used to display a single
program.
Arguments
---------
program: Program object
Returns
-------
A context which maps the program object to program.
"""
return {'program': program} |
def get_bit_percentage(bits, total_bits):
"""
Return a formatted percentage of bits out of the total_bits.
"""
percentage = bits / total_bits * 100.0
return '{0:.1f}'.format(percentage) + "%" |
def camel_to_snake_case(value: str) -> str:
"""Converts strings in camelCase to snake_case.
:param str value: camalCase value.
:return: snake_case value.
:rtype: str
"""
return "".join(["_" + char.lower() if char.isupper() else char for char in value]).lstrip("_") |
def chaincalls(callables, x):
"""
:param callables: callable objects to apply to x in this order
:param x: Object to apply callables
>>> chaincalls([lambda a: a + 1, lambda b: b + 2], 0)
3
"""
for c in callables:
assert callable(c), "%s is not callable object!" % str(c)
x = ... |
def classifyTriangle(a, b, c):
"""
This function returns a string with the type of triangle from three integer values
corresponding to the lengths of the three sides of the Triangle.
return:
If all three sides are equal, return 'Equilateral'
If exactly one pair of sides are equal, r... |
def _index_to_alphabet(index):
""" Convert the index to the alphabet.
"""
return chr(ord("A") + index) |
def eh_estrategia(strat):
"""
Verificar se uma determinada string e uma estrategia valida
Parametros:
start (string): possivel estrategia
Retorna:
(bool): True caso a estrategia seja valida e False caso contrario
"""
strats = ("basico", "normal", "perfeito")
ret... |
def escape_text(text):
"""
This function takes a text and makes it html proof
:param text: The text to escape
:return: The escaped text
"""
return str(text.replace('<', '<').replace('>', '>')) |
def standardize_json_string(json_string):
"""
Replace " with ' if they occur within square brackets
eg {"key":"["Key":"value"]"} => {"key":"['Key':'value']"}
"""
inside_brackets_flag = False
standard_json_string = ""
for i in range(0, len(json_string)):
if json_string[i] == '[':
... |
def top_files(query, files, idfs, n):
"""
Given a `query` (a set of words), `files` (a dictionary mapping names of
files to a list of their words), and `idfs` (a dictionary mapping words
to their IDF values), return a list of the filenames of the the `n` top
files that match the query, ranked accord... |
def process_answer(ans, ot, ct):
"""
A function, which strips all the unnecessary parts from the translations
ans - a list of translations
ot - opening tag
ct - closing tag
"""
parsed_ans = []
for entry in ans:
parsed_entry = entry[1:-1]
if parsed_entry.startswith(ot):
... |
def has_netscaler_error(s):
"""Test whether a string seems to contain a NetScaler error."""
tests = (
s.startswith('ERROR: '),
'\nERROR: ' in s,
s.startswith('Warning: '),
'\nWarning: ' in s,
)
return any(tests) |
def forward2reverse(dna):
"""Converts an oligonucleotide(k-mer) to its reverse complement sequence.
All ambiguous bases are treated as Ns.
"""
translation_dict = {"A": "T", "T": "A", "C": "G", "G": "C", "N": "N",
"K": "N", "M": "N", "R": "N", "Y": "N", "S": "N",
... |
def user_event_day_top_voted(msg):
""" day top voted """
isclick = msg['MsgType'] == 'event' \
and msg['Event'] == 'CLICK' and msg['EventKey'] == 'DAY_TOP_VOTED'
iscmd = msg['MsgType'] == 'text' and \
(msg['Content'].lower() == '1' \
or msg['Content'].lower() == 'dtv' \
... |
def _maybe_convert_to_number(v):
"""Convert v to int or float, or leave it as is."""
try:
return int(v)
except Exception:
pass
try:
return float(v)
except Exception:
pass
return v |
def _cell_outputs(cell):
"""Return the output of an ipynb cell."""
outputs = cell.get('outputs', [])
return outputs |
def get_value_from_json(json_dict, sensor_type, group, tool):
"""Return the value for sensor_type from the JSON."""
if group in json_dict:
if sensor_type in json_dict[group]:
if sensor_type == "target" and json_dict[sensor_type] is None:
return 0
else:
... |
def format_time(seconds, total=None, short=False):
"""
Format ``seconds`` (number of seconds) as a string representation.
When ``short`` is False (the default) the format is:
HH:MM:SS.
Otherwise, the format is exacly 6 characters long and of the form:
1w 3d
2d 4h
1h 5m... |
def from_datastore(entity):
"""Translates Datastore results into the format expected by the
application.
Datastore typically returns:
[Entity{key: (kind, id), prop: val, ...}]
This returns:
[ name, email, date, message ]
where name, email, and message are Python strings
and whe... |
def xlrd_float_to_str(x):
"""
When importing a cell with a float in it, XLRD (or
perhaps Excel) represents it as a float, e.g. a cell
with 1000 will appear as 1000.0. This is annoying if you
want to keep everything as strings.
This function checks whether X can be cast down to an
int, and ... |
def generate_parameter_field_number(parameter, used_indexes, field_name_suffix=""):
"""Get unique field number for field corresponding to this parameter in proto file.
If field number is not stored in metadata of parameter, get the next unused integer value."""
field_name_key = f"grpc{field_name_suffix}_field_... |
def categorize_path(xmlfilename):
"""
Return case name from full path.
"""
parts = xmlfilename.split("/")
for part in parts:
if "manhattan" in part:
return part |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.