content stringlengths 42 6.51k |
|---|
def compare_strings(first, second):
"""
Returns the greater of the two strings
:param first:
:param second:
:return: string
"""
return first if first > second else second |
def check_dead(left_hp: int, right_hp: int) -> bool:
"""
Method to check if either player is dead
:param left_hp: Hit points of priority player
:param right_hp: Hit points of right player
:return: True if somebody is dead, else False
"""
if left_hp <= 0:
return True
elif right_h... |
def prior_knolwedge_categorized(price, n_bins = 12):
"""
function of prior knowledge for categorized price
:param price: input price - this price should already be bucketized. The value is in the range [0, n_bin)
:param n_bins: number of bins
:return: expected prob.
"""
# The winning probabl... |
def get_vector16():
"""
Return the vector with ID 16.
"""
return [
0.5714286,
0.5000000,
0.4285714,
] |
def P_total(pressures=[]):
"""Returns a float of the total pressure of a gas in a container
\npressure: ```list``` \n\tList of pressures in a container"""
total = 0.0
for pressure in pressures:
total += pressure
return float(total) |
def square(number):
"""
this function returns a square of a number
"""
result = number ** 2
return result |
def exclude_from_string(k_string, exclude):
"""Exclude string if at least one given substring is detected.
Parameters
----------
k_string : str
String to check.
exclude : list
List of substrings to search for in k_string.
Returns
-------
bool
Returns True if a s... |
def _int_or_str(c):
"""Return parameter as type integer, if possible
otherwise as type string
"""
try:
return int(c)
except ValueError:
return c |
def recursive_fibonacci(n: int) -> int:
"""
Returns n-th Fibonacci number
n must be more than 0, otherwise it raise a ValueError.
>>> recursive_fibonacci(0)
0
>>> recursive_fibonacci(1)
1
>>> recursive_fibonacci(2)
1
>>> recursive_fibonacci(10)
55
>>> recursive_fibonacci(... |
def postcode_split(postcode):
"""
If the postcode has no space in the middle add one
"""
if postcode:
if " " not in postcode.strip():
return postcode[:-3] + " " + postcode[-3:]
else:
return postcode.strip()
else:
return postcode |
def get_offer_address(html_parser):
"""
This method returns the offer address.
:param html_parser: a BeautifulSoup object
:rtype: string
:return: The offer address
"""
try:
address = html_parser.find(class_="address-text").text
except AttributeError:
return
else:
... |
def receptor_expression(receptor_abundance, endo, kRec, sortF, kDeg):
""" Uses receptor abundance (from flow) and trafficking rates to calculate receptor expression rate at steady state. """
rec_ex = (receptor_abundance * endo) / (1.0 + ((kRec * (1.0 - sortF)) / (kDeg * sortF)))
return rec_ex |
def _matches_app_id(app_id, pkg_info):
"""
:param app_id: the application id
:type app_id: str
:param pkg_info: the package description
:type pkg_info: dict
:returns: True if the app id is not defined or the package matches that app
id; False otherwize
:rtype: bool
"""
... |
def validate_products_data(data):
"""validate product details"""
try:
# check if description is empty
if data["description"] is False:
return "product description required"
# check if product description has content
elif data["description"] == "":
retu... |
def fizz_buzz_function(number):
"""_summary_
Args:
number (_type_): _description_
"""
if number % 3 == 0:
if number % 5 == 0:
return 'FizzBuzz'
return 'fizz'
if number % 5 == 0:
return 'buzz'
return number |
def in_between(now, start, end):
"""Determine timing for schedules."""
if start <= end:
return start <= now < end
return start <= now or now < end |
def get_update_old(d_included):
"""Parse a dict and returns, if present, the post old string
:param d_included: a dict, as returned by res.json().get("included", {})
:type d_raw: dict
:return: Post old string. Example: '2 mo'
:rtype: str
"""
try:
return d_included["actor"]["subDesc... |
def singularize(word):
"""
A poor replacement for the pattern.en singularize function, but ok for now.
"""
units = {
"cups": u"cup",
"tablespoons": u"tablespoon",
"teaspoons": u"teaspoon",
"pounds": u"pound",
"ounces": u"ounce",
"cloves": u"clove",
... |
def _contains_date(format):
"""
Check if a format contains tokens related to date.
:param format:
:type format: str
:return: True if format contains tokens related to date, false otherwise.
:rtype: boolean
"""
part_of_date_tokens = "aAwdbBmyYjUW"
for token in part_of_date_tokens:
... |
def values(var_list):
"""Takes in a list of variables and returns a list of those variables' values."""
return [v.value for v in var_list] |
def _check_brackets(term):
"""
Check if term contains correct number of round brackets and square brackets.
Parameters
----------
term: str
The search term.
Returns
-------
bool
True if term contains correct number of round brackets and square brackets, otherwise False.... |
def to_postorder_iterative(root: dict, allow_none_value: bool = False) -> list:
"""
Convert a binary tree node to depth-first post-order list (iteratively).
"""
node, node_list, stack = root, [], []
stack.append(node) # push root into the stack
while len(stack) > 0:
node = stack[-1]
... |
def solution(array):
"""
Computes number of distinct values in an array.
"""
# Sets only have distinct values
# and creating a set from a list has a good time complexity, as it uses hash tables
return len(set(array)) |
def remap_clocks(ports, clock_map):
"""
Remaps clock dependencies of all ports and returns a new port map.
Does not remap clocks for "P1" and "P2" ports.
"""
new_ports = {
"input": set(),
"clock": set(),
"output": set(),
}
for key in ["input", "clock", "output"]:
... |
def twobyte(val):
"""Convert an int argument into high and low bytes"""
assert isinstance(val, int)
return divmod(val, 256) |
def PatternStrToList(pattern):
"""Return a list of integers for the given pattern string.
PatternStrToList('531') -> [5, 3, 1]
"""
return [ord(p)-ord('0') for p in pattern] |
def get_opposite_num(num, opposite):
"""get opposite number for string"""
if num[0] == "-":
return num[1:]
if opposite and num[0] != "-":
return "-" + num
return num |
def castlingmove(movetuples):
"""Determine if we have a tuple of tuples or just a simple move."""
if isinstance(movetuples[0], tuple) and isinstance(movetuples[1], tuple):
return True
else:
return False |
def strip_end_sections(text):
"""Strip useless parts at end (refs, see also, etc)"""
References_start = text.rfind("References")
See_also_start = text.rfind("See also")
External_links_start = text.rfind("External links")
Further_reading_start = text.rfind("Further reading")
end_of_document = Re... |
def scheming_field_by_name(fields, name):
"""
Simple helper to grab a field from a schema field list
based on the field name passed. Returns None when not found.
"""
for f in fields:
if f.get('field_name') == name:
return f |
def noisy_reclassifier(original_classifier, noise):
"""Function to reclassify the strategy"""
if noise not in (0, 1):
original_classifier["stochastic"] = True
return original_classifier |
def minimumSwaps(arr):
"""
1 3 5 2 4 6 7 <=
1 5 3 2 4 6 7
1 4 3 2 5 6 7
1 2 3 4 5 6 7
"""
swap, i = 0, 0
while i < len(arr):
if arr[i] == (i + 1):
i += 1
continue
arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1]
swap += 1
return swap |
def hypergeometric_expval(n, m, N):
"""
Expected value of hypergeometric distribution.
"""
return 1. * n * m / N |
def _next_legen_der(n, x, p0, p01, p0d, p0dd):
"""Compute the next Legendre polynomial and its derivatives."""
# only good for n > 1 !
old_p0 = p0
old_p0d = p0d
p0 = ((2 * n - 1) * x * old_p0 - (n - 1) * p01) / n
p0d = n * old_p0 + x * old_p0d
p0dd = (n + 1) * old_p0d + x * p0dd
return p... |
def _test_suite_name_aliases(suiteName):
"""Cope with the test result naming convention change in #2195.
If the given suiteName has path info, return it and its leaf name. Otherwise just return
suiteName.
"""
if '-' in suiteName:
return (suiteName, suiteName[1+suiteName.rfind('-'):])
... |
def _full_table_name(schema_name, name):
"""
Return the full name of a table, which includes the schema name.
"""
return "{}.{}".format(schema_name, name) |
def _convert_to_args(sig, args, kwargs):
"""
Given the signature of a function, convert the positional and
keyword arguments to purely positional arguments.
"""
new_args = []
for i, param in enumerate(sig):
if param in kwargs:
# first check if the name is provided in the keyw... |
def build_essential_plots(lr: float, batch_size: int, eval_metric: str, eval_metric_color: str) -> list:
"""Create a list of plot definitions for the trainer to build from dumped logs.
The plots included here correspond to the training loss and the performance on dev.
:param lr: learning rate value
:pa... |
def human_range_to_slice(from_val=None, to_val=None):
"""
Prepare a human from - to range (including from, including to) for a python slice
"""
if from_val:
from_val -= 1
if to_val:
to_val += 1
return dict(slice_i=from_val,
slice_j=to_val) |
def part2(input):
"""
The scanner will be in pos0 every range*2 picoseconds, and the pkg will be
at layer[depth] after exactly [depth] picoseconds. Thus we can find out the smallest delay such that
for each layer, delay + depth != n * (range-1) * 2, where n can be any number.
This works for the gi... |
def _validate_int(value, content):
"""Return parameter value as an integer.
:param str value: The raw parameter value.
:param dict content: The template parameter definition.
:returns: int
"""
try:
original = str(value)
value = int(value)
except (ValueError, UnicodeEncodeErro... |
def _list_cpes(nodes):
"""List all CPEs from configurations.nodes of NVD object
Node objects has nested CPEs with logical combinations.
"""
def eval_eq(eq):
if 'children' in eq:
return [cpe
for child in eq['children']
for cpe in eval_eq(child)... |
def todosIguales(list):
"""Retorna si todos los elementos de la lista son iguales o si esta vacia"""
return not list or list == [list[0]] * len(list)
# return False if not list == [list[0]] * len(list) else True |
def change_name_hash(name, digest):
"""Change name from prefix_uuid to prefix_digest."""
name = name.split('_')
name[-1] = digest
return '_'.join(name) |
def get_instance_name_to_id_map(instance_info):
"""
generate instance_name to instance_id map.
Every instance without a name will be given a key 'unknownx', where x is an incrementing number of instances without a key.
"""
instance_name_to_id = {}
unknown_instance_count = 0
for instance_id ... |
def _resample_params(N, samples):
"""Decide whether to do permutations or random resampling
Parameters
----------
N : int
Number of observations.
samples : int
``samples`` parameter (number of resampling iterations, or < 0 to
sample all permutations).
Returns
------... |
def can_be_token(text):
"""
checks entered text can be a token
:param text:
:return:
"""
# todo 0.2.2: can we use jwt package itself for check?
if len(text) > 0:
return True
return False |
def score_to_scorestring(score):
"""
Converts score to the score string.
"""
fill_depth = 10
return str(score).zfill(fill_depth) |
def determine_perc(time, period, width):
"""
Models a rise time of width/2 followed immediately by a fall time of width/2
Each instance is separated by (period - width) milliseconds
"""
cur_time = time%period
if cur_time < width//2:
return float(cur_time)/(width/2)
elif cur_t... |
def _sort(peptide):
"""Sort the residues of a peptide"""
return "".join(sorted(peptide)) |
def _parse_bool_default_value(property_name, default_value_string):
"""Parse and return the default value for a boolean property."""
lowercased_value_string = default_value_string.lower()
if lowercased_value_string in {"0", "false"}:
return False
elif lowercased_value_string in {"1", "true"}:
... |
def get_source_files(source_ID, sofia_dir_path, name_base):
"""Return the full path of the files for a given source generated by
SoFiA. The source ID is equivalent to the ID in the catalog generated
by SoFiA.
This code is minimalistic, and works on a 'standard' output of SoFiA
see the code for the ... |
def build_obj_trailer():
"""Add closing elements to object"""
ret = ''
ret += f'</div>\n'
ret += f'</pre>\n</div>\n'
return ret |
def range_overlap(a_min, a_max, b_min, b_max):
"""Neither range is completely greater than the other."""
return (a_min < b_max) and (b_min < a_max) |
def hexify(i, digits=4):
""" convert an integer into a hex value of a given number of digits"""
format_string = "0%dx" % digits
return format(i, format_string).upper() |
def drop_entries_on_failure(values):
"""
if we failed we drop the folowing sections
Failure may happen late in the log, so we may still end up parsing them
"""
if "exit" in values:
if values["exit"] != 0:
for sections in [
# all the statistical values are not rele... |
def parameter_types(default_parameters):
"""
Convert a set of parameters into the data types used to represent them.
Returned result has the same structure as the parameters.
"""
# Recurse through the parameter data structure.
if isinstance(default_parameters, dict):
return {key: paramet... |
def cut(string, l):
""" Cut a string and add ellipsis if it's too long. """
if len(string) <= l:
return string
return string[:l-3]+"..." |
def check_not_finished_board(board: list):
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*',\
'*?????5', '*?????*', '*?????*', '*2*1***'])
False
>>> check... |
def isPalindrome(n):
"""
n: an str
output: True if the str is a palindrome
"""
aString = str(n)
length = len(aString)
for i in range(int(length / 2)):
if aString[i] != aString[length - i - 1]:
return False
return True |
def saturation(p):
"""
Returns the saturation of a pixel, defined as the ratio of chroma to value.
:param p: A tuple of (R,G,B) values
:return: The saturation of a pixel, from 0 to 1
"""
max_c = max(p)
min_c = min(p)
if max_c == 0:
return 0
return (max_c - min_c) / float(max_... |
def findFunctionsDictionary(controlDictLines):
"""
This method will find functions dictionary in the controlDict
"""
for line in controlDictLines:
if line.startswith("functions"):
return (True, controlDictLines.index(line) + 2)
return [False, controlDictLines.count] |
def dimension(rank):
"""Returns the dimension of the spherical harmonics basis for a given
rank.
"""
return (rank + 1) * (rank + 2) / 2 |
def is_hue_admin(user):
"""
Hue service super user. Can manage global settings of the services used by all the organization.
Independent of ENABLE_ORGANIZATIONS.
"""
return hasattr(user, 'is_superuser') and user.is_superuser |
def count_upper(s):
"""
Given a string s, count the number of uppercase vowels in even indices.
For example:
count_upper('aBCdEf') returns 1
count_upper('abcdefg') returns 0
count_upper('dBBE') returns 0
"""
count = 0
for i in range(0, len(s), 2):
if s[i] in "AEIOU":
... |
def string_ancilla_mask(location, length):
"""Returns a bit string with a 1 in a certain bit and the 0 elsewhere.
Parameters
----------
location : int
location of the bit which should be set to '1' in the mask
length : int
length of string in the mask
Returns
------... |
def vt_calc(m,Vdc):
"""Inverter terminal voltage - Phase A/B/C"""
return m*(Vdc/2) |
def combine_dict(list_dict):
"""
Combine type function. Combines list of dicts into a single dict. Assumes keys don't clash
:param list_dict: list of lists
:return: single list
"""
return_dict = {}
for res in list_dict:
return_dict = {**return_dict, **res}
return return_dict |
def sum_box(box1, box2):
"""
return the sum of two bounding boxes
"""
return tuple(tuple(sum(offs) for offs in zip(dim[0], dim[1])) for dim in zip(box1, box2)) |
def count_good_days(records):
"""A "good" day is a day when the user brought lunch"""
return sum(1 for record in records if record["did_bring_lunch"]) |
def get_min_max(ints):
"""
Return a tuple(min, max) out of list of unsorted integers.
Args:
ints(list): list of integers containing one or more integers
"""
n = len(ints)
if n == 0:
return (None, None)
low, high = ints[0], ints[1]
if low > high:
high, low = low,... |
def get_statements(c=None, pageNumber=None, pageSize=None, keywords=None, semgroups=None):
"""
get_statements
Given a list of [CURIE-encoded](https://www.w3.org/TR/curie/) identifiers of exactly matching concepts, retrieves a paged list of concept-relations where either the subject or object concept matches... |
def b(s):
"""Impacket PY2/3 compat wrapper"""
return s.encode("latin-1") |
def get_desired_asg_count(topic_list, max_size):
"""Create the asg count to use as a string.
Arguments:
topic_list (array): The topics to use
max_size (string): The max size of the asg
"""
min_number = min(int(max_size), len(topic_list))
return str(min_number) |
def get_fqn(the_type):
"""Get module.type_name for a given type."""
module = the_type.__module__
name = the_type.__qualname__
return "%s.%s" % (module, name) |
def transpose_inds(inds, nrow, ncol):
"""Given a set of flattened indices into an array of shape (nrow,ncol),
return the indices of the corresponding elemens in a transposed array."""
row_major = inds
row, col = row_major//ncol, row_major%ncol
return col*nrow + row |
def get_issue_list(summary, threshold = 0.05) -> str:
"""Returns a list of potential issues checking against a deviation threshold"""
issues = []
if summary['invalid_rate'] >= threshold:
issues.append('invalid_rate')
if summary['missing_rate'] >= threshold or summary['missing_rate'] <= -threshol... |
def angle_difference(a1, a2):
"""
return the difference in angle between two angles in range [0, 180]
"""
abs_diff = abs(a1 - a2)
return min(abs_diff, 360 - abs_diff) |
def abs_hist(data):
"""Returns x and y for bar-plot representing absolute histogram of the input list data"""
hist_dict = dict()
# Initialize dictionary for every class of elements in list
classes = set(data)
for element in classes:
hist_dict[element] = 0
# Count the instances
for ... |
def find_substr_itimes(_str, _substr, i):
"""
find the location of the substr appered i times in str
:param _str:
:param _substr:
:param i:
:return:
"""
count = 0
while i > 0:
index = _str.find(_substr)
if index == -1:
return -1
else:
_... |
def calc_cost(distance):
"""
distance = 1; answer = 1
distance = 2; answer = 3 (distance + 1) * (distance / 2)
distance = 3; answer = 6
distance = 4; answer = 10 (distance + 1) * (distance / 2)
distance = 5; answer = 15
distance = 6; answer = 21 (distance + 1) * (distance / 2)
"""
if... |
def float_or_none(val, default=None):
"""
Arguments:
- `x`:
"""
if val is None:
return default
else:
try:
ret = float(val)
except ValueError:
ret = default
return ret |
def markdownify_objectid(objectid):
"""
"""
objectid_markdown = '[{}](/{})'.format(
objectid,
objectid
)
return objectid_markdown |
def multiplicative_schedule(
initial_temperature, current_iteration, cooling_factor=10, **kwargs
):
"""Computes the current temperature using the multiplicative schedule
formula, which is a function of the number of iterations and the initial
temperature. The current temperature is equal to.
.. mat... |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
new_line = []
merge_line = []
merged = False
indx2 = 0
for indx1 in range(len(line)):
new_line.append(0)
for indx1 in range(len(line)):
if (line[indx1] != 0):
... |
def previus_day(day,month,year):
"""
day: Int
month: Int
year: Int
"""
if(day>1): return (day-1,month,year)
elif(month>1): return (0,month-1,year)
else: return (0,0,year-1) |
def is_power2(n):
"""Check if an integer is a power of 2."""
return bool(n and not n & (n - 1)) |
def newton(f, x, eps, nitermax=1000):
"""
Newton method to solve f(x)=0
the algorithm is stopped when |f(x)| < eps
"""
xold = x+2*eps
f_x, df_x = f(x)
niter = 0
while abs(f_x) > eps and abs(x-xold) > eps and niter < nitermax:
xold = x
x -= f_x/df_x
f_x, df_x = f(x... |
def arithmetic_series_dp(n):
"""Arithmetic series by bottom-up DP.
Time complexity: O(n).
Space complexity: O(n)
"""
T = [0 for _ in range(n + 1)]
T[0] = 0
T[1] = 1
for k in range(2, n + 1):
T[k] = k + T[k - 1]
return T[n] |
def vi_g_action(vi_cmd_data):
"""This doesn't do anything by itself, but tells global state to wait for a second action that
completes this one.
"""
vi_cmd_data['motion_required'] = True
# Let global state know we still need a second action to complete this one.
vi_cmd_data['is_digraph_... |
def split_data_target(dataset):
"""Split the input CSV files into X, y vectors for sklearn implementations.
Args:
dataset (list): List of list of floats.
[
[0...n - 1]: X, feature vector
[-1]: y, label
]
Returns:
tuple: (X, y) for skl... |
def parse_custom_data(custom_str):
"""Parse SCOUT_CUSTOM info field
Input: "key1|val1,key2|val2"
Output: [ ["key1","val1"], ["key2", "val2"] ]
"""
pair_list = []
for pair in custom_str.split(","):
pair_list.append(pair.split("|"))
return pair_list |
def __digit(value):
"""
Converts hex to digit
"""
return int(value, 16) |
def getSlotFromCardName(cardName):
"""
cardName is expected to be of the form 'gem-shelfXX-amcYY' where XX & YY are integers
"""
slot = (cardName.split("-")[2])
slot = int(slot.strip("amc"))
return slot |
def split_rules_and_strings(arr):
"""
Given a list of strings,
representing the rules
and the query strings,
split the rules and strings
into a dictionary and a list
for further use.
:param arr: A list of strings.
:return: A tuple of dict and list
representing the ruleset and th... |
def get_info_cls(value, base_class='col-md-7'):
"""Return info element class"""
c = base_class
if value == '':
c += ' text-muted'
return c |
def to_camel_case(snake_case):
"""
Convert snake_case string to camelCase
:param snake_case: snake_case string to convert
:type snake_case: str
:return: camelCase string
:rtype: str
"""
words = snake_case.split('_')
return words[0] + ''.join(x.capitalize() for x in words[1:]) |
def find_duplicates(arr1, arr2):
"""
differing sizes
>= ints
sorted
unique ints in each arr
arr1 = [1, 2, 3, 5, 6, 7], arr2 = [3, 6, 7, 8, 20]
# Brute force -
- iterative
- quadratic
# Idea - Sets
{1, 2, 3, 5, 6, 7}
[3]
{3, 6, 7} = [3, 6, 7]
S = smaller arr... |
def disjoin(functions, *args, **kwargs):
"""Returns True if any of the component functions return True."""
for f in functions:
if f(*args, **kwargs):
return True
return False |
def falling(n, k):
"""
Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
prod = 1
while k > 0:
prod *= n
k -= 1
n -= 1
return prod |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.