content stringlengths 42 6.51k |
|---|
def mobilicious(url, mobile, mcanonical):
"""Compare the URL of desktop version with the mobile canonical and return Pass if the same."""
if mobile:
if url == mcanonical:
return "Pass"
else:
return "Fail"
else:
return "Fail" |
def get_oldest_compatible_version(config):
"""Return the current oldest compatible version of the config.
:return: current oldest compatible config version or 0 if not defined
"""
return config.get('CONFIG_VERSION', {}).get('OLDEST_COMPATIBLE', 0) |
def find_question_type_from_dataset(question, qa_dataset, similarity_func):
"""Returns query_type of the datapoint from ms_marco QA dataset
for the first match.
"""
for datapoint in qa_dataset:
if similarity_func(question["text_raw"], datapoint["query"]):
return datapoint["query_t... |
def mul_add_simplify(expr):
"""Turns Mul(Add(.), .) into Add(Mul(.), Mul(.),...)"""
if expr[0] != '#Mul':
return None
for i in range(1, len(expr)):
if expr[i][0] == '#Add':
other_args = expr[1:i] + expr[i + 1:]
return ('#Add',) + tuple((('#Mul',) + other_args + (j,)
... |
def bubble_sort(lst):
"""Applies a bubble sort algorithm to a list.
Bubble sort is the simplest sorting algorithm that works by repeatedly
swapping the adjacent elements if they are in wrong order.
No error handling is provided on this function - we assume that the input
is of the Integer type
... |
def add_connection_node(connection_nodes, postgis_connection_node):
"""Add hydx.connection_node into threedi.connection_node and threedi.manhole"""
# get connection_nodes attributes
connection_node = {
"id": postgis_connection_node[0],
"code": postgis_connection_node[1],
"initial_wa... |
def all_non_consecutive(arr):
"""
Find all the elements of an array that are non consecutive. A number is non consecutive if it is not exactly one
larger than the previous element in the array. The first element gets a pass and is never considered non consecutive.
:param arr: An array of integers.
:... |
def updatedict(d, key, val):
"""
Recursively iterates through a dict and updates a given key's value.
"""
new_d = {}
for k, v in d.items():
if key == k:
new_d[key] = val
elif isinstance(v, dict):
new_d[k] = updatedict(v, key, val)
else:
new... |
def summation(n, term):
"""Return the sum of the first n terms in the sequence defined by term.
Implement using recursion!
>>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
225
>>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
54
>>> summation(5, lamb... |
def isfloat(value):
"""
returns true if a value can be typecasted as a float, else false
"""
try:
float(value)
return True
except ValueError:
return False |
def flatten(items, seqtypes=(list, tuple)):
"""Extract a single element if it is unnecessarily nested in a list"""
while isinstance(items, seqtypes) and len(items) == 1:
items = items[0]
return items |
def count_combination(genotypes_combinations):
"""
Calculate the Cartesian product required for all genotype combinations
"""
product = 1
for gc in genotypes_combinations:
product *= len(gc)
return product |
def find_unique_dates_and_metrics(aggregate_metrics):
"""
Function is used to find all of the unique dates
and metrics. Each date/metric combination should
warrant its own AggregateMetricForDate object.
Parameter
---------
aggregate_metrics (list): contains AggregateMetricForHPO
obj... |
def rabin_miller(possiblePrime, aTestInteger):
""" The Rabin-Miller algorithm to test possible primes
taken from HAC algorithm 4.24, without the 't'
"""
assert( 1<= aTestInteger <= (possiblePrime-1) ), 'test integer %d out of range for %d'%(aTestInteger,possiblePrime)
#assert( possiblePrime... |
def lines2str(lines, sep = "\n"):
"""Merge a list of lines into a single string"""
return sep.join(lines) |
def word_before_after(a, sep):
"""
returns word before and after :sep: in string :a:
"""
word_before, word_after = "", ""
if sep in a:
word_before = a.split(str(sep))[0].strip().split(" ")[-1]
word_after = a.split(str(sep))[1].strip().split(" ")[0]
return word_before, word_after |
def map_div_js(context, center_latitude, center_longitude, zoom_level, map_div_id):
"""
Standardize map display
zoom_level should be 14 or higher for individual trees.
map_div_id may be: map or tree-map
"""
return {
'geojson': context['geojson'],
'zoom_level': zoom_level,
... |
def _round8(v: float, divisor: int = 8) -> int:
"""Ensure that number rounded to nearest 8, and error is less than 10%
This function is taken from the original tf repo.
It ensures that all layers have a channel number that is divisible by 8
It can be seen here:
https://github.com/tensorflow/models/... |
def str2type_name(str2type_function):
"""
Return the function name of the function returned from
str2type, or any function obtained by the type() operation.
Useful when reporting conversion str-to-value errors.
"""
import inspect
s2t = str2type_function
if "<type '" in str(s2t):
... |
def truesi(xs):
""" indices for which x[i] is True """
return [i for i, x in enumerate(xs) if x] |
def multiply_dicts(dict1, dict2):
"""
Multiply 2 dictionaries in the sense of developing a product of 2 sums.
Args:
dict1 (dict): any dictionary
dict2 (dict): any dictionary
Returns:
product_dict (dict): the keys are the couple of keys of dict1 and dict2
... |
def escape_quotes(text):
"""Function to escape any ' or " symbols present in the string
:param text: Input string
:param type: str
:returns: Escaped string
:rtype: str
"""
if text is not None:
return text.replace("'","\\'").replace('"','\\"') |
def ParseIssueNumber(issueCode):
"""Notes: Issue code comes in a five digit number.
The first three numbers are the issue number padded in zeroes
The fouth number is for varient covers starting at 1
The fith number seems to always be 1
"""
if len(issueCode) == 5:
issueNumber = issueCode[... |
def calc_depth(vertex_count: int, graph):
"""Calculates depth of rooted tree.
Assumption:
The graph is connected.
Args:
vertex_count : The number of vertices in rooted tree.
graph : Rooted tree (0-indexed).
Returns:
depth : Depth of rooted tree (0-indexed).
... |
def region_from_environment(environment):
"""
Returns the AWS region of the environment.
"""
provider_opts = environment['provider_options']
if environment['provider'] == 'aws':
if 'region' in provider_opts['aws']:
return provider_opts['aws']['region']
else:
r... |
def size_gb(size):
"""
Helper function when creating database
:param size: interger (size in Gb)
:return: integer (bytes)
"""
return int(1024*1024*1024*size) |
def merge_rates(rates, graph_width=40):
"""Merge rates to have entries equal to the width, returns list."""
merged_rates = []
offset = 0
slice_width = int(len(rates) / graph_width)
# Merge rates
for _i in range(graph_width):
merged_rates.append(sum(rates[offset:offset+slice_width])/slice_width)
off... |
def translate(codon):
"""
Translate a three letter DNA string into
a one letter amino acid code.
Parameters
----------
codon : str
three letter DNA sequence
Returns
-------
str
one letter amino acid code
Raises
------
AssertionError
error if c... |
def use_edge_def_or_num(given_value, default_func):
"""Transform a value of type (None, int, float, Callable) to an edge annotation function."""
# Default: use pre-defined function from this module
if given_value is None:
func = default_func
# Transform: value to function that returns the value
... |
def generate_package(
release_version,
package,
resource,
marathon_template,
config,
command):
"""Returns v3 package object for package. See
repo/meta/schema/v3-repo-schema.json
:param release_version: package release version
:type release_version: int
... |
def is_based_on(something, base):
"""
Checks whether or not 'something' is a class that is a subclass of a class
by name. This is a terrible hack but it removes a direct dependency on
existing macros.
Used by macro_translator.
"""
options = [str(klass.__name__) for klass in something.__base... |
def num(s):
"""
convert a string to integer or float
:param s: a string of number
:return: an int or float type number
"""
try:
return int(s)
except ValueError:
return float(s)
else:
raise ValueError('Expected integer or floating point number.') |
def list_roll(list_, n):
"""
Like numpy.roll for python lists
Args:
list_ (list):
n (int):
Returns:
list:
References:
http://stackoverflow.com/questions/9457832/python-list-rotation
Example:
>>> list_ = [1, 2, 3, 4, 5]
>>> n = 2
>>> res... |
def get_depth(od):
"""Function to determine the depth of a nested dictionary.
Parameters:
od (dict): dictionary or dictionary-like object
Returns:
int: max depth of dictionary
"""
if isinstance(od, dict):
return 1 + (max(map(get_depth, od.values())) if od else 0)
return... |
def _relative_time_string(time_seconds, no_ms=False):
"""Converts the given `time_seconds` into a relative, human-readable
string representation.
Args:
time_seconds (int or float): The relative time to convert
no_ms (bool): If set the `999ms` style representation is not chosen
Returns:... |
def _ensure_prefix_is_set(chunk_info, telstate):
"""Augment `chunk_info` with chunk name prefix if not set."""
for info in chunk_info.values():
if 'prefix' not in info:
info['prefix'] = telstate['chunk_name']
return chunk_info |
def _format_2(raw):
"""
Format data with protocol 2.
:param raw: returned by _load_raw
:return: formatted data
"""
return raw[1:], raw[0] |
def _get_total(rows, has_steps=False):
"""Returns total rows and steps if applicable."""
total = len(rows)
if has_steps:
total += sum([len(row.statements) for row in rows])
return total |
def _broadcast(a, b, array1, array2):
"""Broadcast two given dimensions"""
# Equivalent dimensions, done
return (array1, array2) |
def _shape_to_size(shape):
"""
Compute the size which corresponds to a shape
"""
out = 1
for item in shape:
out *= item
return out |
def count_of(thing_list, thing_name, plural_name=None, colon=False):
"""Return a string representing a count of things, given in thing_list.
Example:
>>> count_of([1, 2, 3], 'number')
'3 numbers'
>>> count_of([1], 'number')
'1 number'
>>> count_of(['salmon', 'carp'], 'fish', 'fishi... |
def convertAnnotationtoBinary(row, field):
""" return binary (0,1), where 1 = permission_statement """
if str(row[field]).__contains__('NON'):
return 0
else:
return 1 |
def slice_by_value(sequence, start=None, end=None, step=1):
"""Returns the earliest slice of the sequence bounded by the
start and end values. Omitted optional parameters work as expected
for slicing.
slice_by_value('hello there world', 'o', 'w', 2) -> 'otee'
"""
i_start = i_end = None
if s... |
def has_few_assignments(example, minimum=4):
"""Check if file uses symbol '=' less than `minimum` times."""
lines = example["content"].splitlines()
counter = 0
for line in lines:
counter += line.lower().count("=")
if counter > minimum:
return {"has_few_assignments": False}
... |
def closest_symbol(addr_to_name, addr, max_offset=0x1000):
"""
Find the symbol which is closest to addr, alongside with its offset.
Returns:
- (symbol_name, offset_to_symbol) if a symbol exists with an offset of a maximum of max_offset
- Otherwise, (None, None) is returned in case no symbol... |
def change_path_for_metric(path):
"""
Replace the '/' in the metric path by '_' so grafana can correctly use it.
:param path: path of the metric (example: runs/search)
:return: path with '_' instead of '/'
"""
if 'mlflow/' in path:
path = path.split('mlflow/')[-1]
return path.replace... |
def culggroup_donecount(group, dones):
""" How many culgs in this group are done? """
return sum(dones[l] for l in group) |
def int2color(color):
"""Convert color integer value from ctb-file to rgb-tuple plus a magic number.
"""
magic = (color & 0xff000000) >> 24 # is 0xc3 or 0xc2 don't know what this value means
red = (color & 0xff0000) >> 16
green = (color & 0xff00) >> 8
blue = color & 0xff
return (red, green, ... |
def max_multiple(divisor: int, bound: int) -> int:
"""
Given a Divisor and a Bound , Find the
largest integer N , Such That ,
Conditions:
1. N is divisible by divisor
2. N is less than or equal to bound
3. N is greater than 0.
Notes:
1. The parameters (divisor, boun... |
def name_value(obj):
"""
Convert (key, value) pairs to HAR format.
"""
return [{"name": k, "value": v} for k, v in obj.items()] |
def add_slash(url):
"""Adds a trailing slash for consistency in urls."""
if not url.endswith('/'):
url = url + '/'
return url |
def check(expected, computed, label):
"""Checks the test result, if wrong then prints a fail message."""
success = True
if expected != computed:
success = False
print("FAILED TEST AT: ", label)
return success |
def is_prime(n):
"""Return True if n is prime."""
if n == 2 or n == 3:
return True
if n < 2 or n % 2 == 0:
return False
if n < 9:
return True
if n % 3 == 0:
return False
r = int(n**0.5)
f = 5
while f <= r:
if n % f == 0:
return False
... |
def render_condition_fullname(data, query):
"""
condition_fullname (C)
"""
found = None
for key, val in data.items():
if key.startswith('lang_'):
found = val
break
if not found:
found = data['weatherDesc']
try:
weather_condition = found[0]['v... |
def parse_constraints(params, std_const=1e5):
"""Transforms a string to list of parameters taken by appropriate method
of ForceField object. String should be in one of the following forms:
P x min [const]
D x x rel min max [const]
A x x x rel min max [const]
T x x x x rel min max... |
def find_last_index(l, x):
"""Returns the last index of element x within the list l"""
for idx in reversed(range(len(l))):
if l[idx] == x:
return idx
raise ValueError("'{}' is not in list".format(x)) |
def _is_octal(c):
"""Ensures character is an octal digit."""
return c in '01234567' |
def z2v(z, zc):
"""Convert the redshift to km/s relative to the cluster center"""
return 2.99792458e5 * (z - zc) / (1 + zc) |
def get_mean(list_in_question):
"""Computes the mean of a list of numbers.
:param list list_in_question: list of numbers
:returns: mean of the list of numbers
:rtype : float
"""
return sum(list_in_question) / float(len(list_in_question)) |
def sylk(item):
"""
Gives the sylk representation of an object
:param item: item to get the sylk representation of
:return: sylk representation of item
"""
if hasattr(item, "__sylk__"):
return item.__sylk__()
else:
return item.__repr__() |
def convert_hour(hour):
"""Convert time (hour) to icon name to display appropriate clock icon"""
clock = "wi-time-" + hour
return clock |
def create_arguments(test):
"""
Arguments for a test include everything but the test type. Arguments is a test minus the type.
:param test:
:return: arguments
"""
arguments = dict(test)
del arguments['type']
return arguments |
def ceiling_division(n, d):
"""
math.ceil can have problems with 'large' integers as it converts from ints to
floats and back. This isn't very fast and it may have rounding issues.
This function adapts floor division and semi non-intuitive negative integer
interaction wherein -1.1 floor division do... |
def if_no_nulls_in(result, offset, how_many=1):
"""
Check if null not exist from offset until offset+how_many
:param result: aggregation result
:param offset: current offset
:param how_many: check number
:return: true if not exist, else false
"""
for index in range(offset, offset + how_m... |
def compute_retriever_precision(true_fiches, retrieved_results, weight_position=False):
"""
Computes an accuracy-like score to determine the fairness of the retriever. Takes the k *retrieved* fiches' names
and counts how many of them exist in the *true* fiches names
:param retrieved_fiches:
:para... |
def get_sorted_respondents(participants):
"""
Returns the respondents in a MUR sorted in the order of most important to least important
"""
SORTED_RESPONDENT_ROLES = ['Primary Respondent', 'Respondent', 'Previous Respondent']
respondents = []
for role in SORTED_RESPONDENT_ROLES:
responde... |
def serialize_company_address_form(cleaned_data):
"""
Return the shape directory-api-client expects for updating address.
@param {dict} cleaned_data - All the fields in
`CompanyAddressVerificationForm`
@returns dict
"""
return {
'postal_full_name': cle... |
def return_second_list_present_only(xs, ys):
""" merge sorted lists xs and ys. Return a sorted result """
result = []
xi = 0
yi = 0
while True:
if xi >= len(xs):
result.extend(ys[yi:])
return result
if yi >= len(ys):
return result
if xs[... |
def X1X2_to_Xa(X1, X2):
"""Convert dimensionless spins X1, X2 to anti-symmetric spin Xa"""
return (X1-X2)/2. |
def line_generator(points):
"""
Create line from few points (set of pixels)
Arg:
points: few points list
Return:
line (set of pixels) list
"""
before_point = None
line_list = []
for point in points:
if before_point is None:
line_list.append(point)
... |
def evaluation_star(value):
"""Tag for displaying the rating in the form of stars.
Args:
value (int): Evaluation.
Returns:
dict: The return value as a dict for use in the template.
"""
return {'value': value} |
def calc_request_description(params):
"""
Returns a flatted string with the request description, built from the params dict.
Keys should appear in alphabetical order in the result string.
Example:
params = {'foo': 1, 'bar': 4, 'baz': 'potato'}
Returns:
"bar=4&baz=potato&foo=1"
"""
... |
def maybe(obj, name, default=None):
"""Return atributte if it exists or default"""
if hasattr(obj, name):
return getattr(obj, name)
return default |
def fizzbuzz(i):
"""Basic implementation."""
if i % 15 == 0:
return "FizzBuzz"
elif i % 5 == 0:
return "Buzz"
elif i % 3 == 0:
return "Fizz"
else:
return i |
def example(text):
"""Renders example description contents"""
result = ['**Example**', '']
lines = text.split('\n')
for line in lines:
result.append('| {}'.format(line))
result.extend(['|', ''])
return result |
def standardize_single_array(x, expected_shape=None):
"""Expand data of shape (x,) to (x, 1), unless len(expected_shape)==1."""
if x is None:
return None
if (x.shape is not None and len(x.shape) == 1 and
(expected_shape is None or len(expected_shape) != 1)):
if tensor_util.is_tensor(x):
x = a... |
def _nsenter(pid):
"""
Return the nsenter command to attach to the named container
"""
return "nsenter --target {} --mount --uts --ipc --net --pid".format(pid) |
def _partition(array, low, high):
"""Choose the first element of `array`, put to the left of it
all elements which are smaller, and to the right all elements which
are bigger than it.
Return the final position of this element.
"""
if low >= high:
return
i = low + 1
j = high
... |
def area_triangle(length, breadth):
"""
Calculate the area of a triangle
>>> area_triangle(10,10)
50.0
"""
return 1 / 2 * length * breadth |
def state_indices(*states):
"""
State indices
"""
state_inds = dict(
[
("m", 0),
("h", 1),
("j", 2),
("x_kr", 3),
("x_ks", 4),
("x_to_s", 5),
("y_to_s", 6),
("x_to_f", 7),
("y_to_f", 8),
... |
def make_rules(adict, attr_name, if_required, types, scpoe=None):
"""Make new rule in dict for attr."""
if attr_name not in adict:
adict[attr_name] = {}
adict[attr_name]['required'] = if_required
adict[attr_name]['type'] = types
if scpoe:
adict[attr_name]['scope'] = scpoe
return ... |
def add_neighbors_of_bad_images(all_images, bad_images):
"""Given a list of images in all_images, and a subset of them
in bad_images, create a list of images that has all the images
in bad_images, and for each such image also has the image
before it and the image after it, as they show in all_images. Th... |
def deserialize(string, size):
"""Deserializes sudoku grid strings into lists.
Args:
string (str): This string represents a sudoku grid in the standard
format.
size (int): A number specifying the size of the sudoku grid
encoded in `string`.
Returns:
list: The list ... |
def div_growth_rateYr(t, dt, d0):
"""
Calculates the growth rate of a dividend using the dividend growth rate
valuation model where dividend is paid yearly.
parameters:
-----------
t = time
dt = current price of dividend
d0 = base year dividend price
"""
t = t - 1
growth_rate = (((dt/d0) ** (1/t)) - 1) *... |
def GetPackage(module):
"""Gets the package name containing a module.
Returns the module itself if it's top level.
"""
if '.' in module:
return module.rpartition('.')[0]
return module |
def tree_names (tree):
"""Get the top-level names in a tree (including files and directories)."""
return [x[0] for x in list(tree.keys()) + tree[None] if x is not None] |
def changed_algo_config(child_config):
"""Create a child config with a changed dimension"""
child_config['algorithms'] = 'stupid-grid'
return child_config |
def be(i):
"""Returns the form of the verb 'to be' based on the number i."""
if i == 1:
return 'is'
else:
return 'are' |
def convert_value(val):
"""
Convert string to the most appropriate type, one of:
bool, str, int, None or float
:param str val: the string to convert
:return bool | str | int | float | None: converted string to the
most appropriate type
"""
if not isinstance(val, str):
try:
... |
def encode_varint(num):
"""return an encoded int32, int64, uint32, uint64, sint32, sint64, bool, or
enum"""
_next = 1
values = []
while _next:
_next = num >> 7
shift = 128 if _next else 0
part = (num & 127) | shift
values.append(part)
num = _next
return v... |
def find_keys(info: dict) -> dict:
"""Determines all the keys and their parent keys.
"""
avail_keys = {}
def if_dict(dct: dict, prev_key: str):
for key in dct.keys():
if key not in avail_keys:
avail_keys[key] = prev_key
if type(dct[key]) == d... |
def __sort_set_of_str_elems(elems):
"""Returns a sorted list of the strings contained in elems.
:param elems: set of strings
:return:
"""
return [str(x) for x in sorted(map(lambda x: int(x), list(elems)))] |
def ConvertToCamelCase(name):
"""Converts snake_case name to camelCase."""
part = name.split('_')
return part[0] + ''.join(x.title() for x in part[1:]) |
def group_by_and_transform(grouper, transformer, iterable): # pragma: no cover
""" Sort & Group iterable by grouper, apply transformer to each group.
Grouper must be a function that takes an item in the iterable and
returns a sort key.
Returns a dictionary of group keys matched to lists.
... |
def page_not_found(error):
"""Renders error page."""
return 'Poll does not exist.', 404 |
def convfloat(string):
"""
>>> convfloat(' -76.85446015010548,-12.22286259231198,')
[-76.85446015010548, -12.22286259231198]
"""
values = string.split(',')
return [float(value) for value in values if value] |
def str2bool(value):
"""
Convert a string boolean to a boolean value.
Parameters
----------
value : str or bool
The value to convert.
Return
------
value : bool
The string converted into a boolean value.
"""
if isinstance(value, bool):
return value
... |
def extract_from_dict(data, path):
"""
Navigate `data`, a multidimensional array (list or dictionary), and return the object
at `path`.
"""
value = data
try:
for key in path:
value = value[key]
return value
except Exception:
return '' |
def _matches(o, pattern):
"""Match a pattern of types in a sequence."""
if not len(o) == len(pattern):
return False
comps = zip(o,pattern)
return all(isinstance(obj,kind) for obj,kind in comps) |
def get_timestamps(frames, fps, offset=0.0):
"""Returns timestamps for frames in a video."""
return [offset + x/float(fps) for x in range(len(frames))] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.