content stringlengths 42 6.51k |
|---|
def Any(cls):
"""Used to call assert_called_with with any argument.
Usage: Any(list) => allows any list to pass as input
"""
class Any(cls):
def __eq__(self, other):
return isinstance(other, cls)
return Any() |
def move_j(joints, accel, vel):
"""
Function that returns UR script for linear movement in joint space.
Args:
joints: A list of 6 joint angles (double).
accel: tool accel in m/s^2
accel: tool accel in m/s^2
vel: tool speed in m/s
Returns:
script: UR script
"... |
def clean(line):
"""
Clean a given line so it has only the output required.
Split by `:` once and then take the second half and remove the \n
"""
return line.split(':', 1)[1].strip() |
def split_conf_str(conf_str):
"""Split multiline strings into a list or return an empty list"""
if conf_str is None:
return []
else:
return conf_str.strip().splitlines() |
def bytes2human(n):
"""
>>> bytes2human(10000)
'9K'
>>> bytes2human(100001221)
'95M'
"""
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
... |
def sum(total,temp):
"""
:param total: the total amount of previously input temperatures
:param temp: the temperature that the user input
:return: total plus temp
"""
sum = total + temp
return sum |
def common_start(stra, strb):
""" returns the longest common substring from the beginning of stra and strb """
def _iter():
for a, b in zip(stra, strb):
if a == b:
yield a
else:
return ""
return ''.join(_iter()) |
def imul(a, b):
"""Same as a *= b."""
a *= b
return a |
def get_word_dist(idx1, idx2):
"""
get distance between two index tuples. Each index tuple contains (starting index, ending index)
"""
dist = None
for k in idx1:
for j in idx2:
curdist = abs(k - j)
if dist is None:
dist = curdist
else:
... |
def format_num(num, digit=4):
"""Formatting the float values as string."""
rounding = f".{digit}g"
num_str = f"{num:{rounding}}".replace("+0", "+").replace("-0", "-")
num = str(num)
return num_str if len(num_str) < len(num) else num |
def formatString(para, pageWidth):
"""Format a string to have line lengths < pageWidth"""
para = " ".join(para.split("\n")).lstrip()
outStr = []
outLine = ""
for word in para.split():
if outLine and len(outLine) + len(word) + 1 > pageWidth:
outStr.append(outLine)
ou... |
def right_pair(k1, k2, triplets):
"""
We have right word and searching for left
(variants..., <our_words>)
"""
lefts = [(l, v)
for (l, m, r), v in triplets.items()
if m == k1 and r == k2]
total = sum([v for (_, v) in lefts])
return sorted([(r, v/total) for (r, v)... |
def get_correct_answer_dict(label_segments):
"""
Function that returns dictionary with the input as keys
Input: array of tuples; (start index of answer, length of answer)
Output: dict with string versions of tuples as keys
"""
label_dict = {}
for a in label_segments:
key = str(a[0])... |
def get_ansi_color(color):
"""
Returns an ANSI-escape code for a given color.
"""
colors = {
# attributes
'reset': '\033[0m',
'bold': '\033[1m',
'underline': '\033[4m',
# foregrounds
'grey': '\033[30m',
'red': '\... |
def flatten_json_recursive(entry, cumulated_key=''):
"""
Recursively loop through the json dictionary and flatten it out in a column structure.
For every value in the tree, we use the path to the value as a key. This method returns
2 lists, 1 with keys and 1 with values, which later can be accumulated to form c... |
def get_bool_from_text_value(value):
""" to be deprecated
It has issues, as accepting into the registry whatever=value, as False, without
complaining
"""
return (value == "1" or value.lower() == "yes" or value.lower() == "y" or
value.lower() == "true") if value else True |
def get_output(job_output):
"""
Return all outputs name
Return value can be used for WPS.execute method.
:return: output names
:rtype:list
"""
the_output = []
for key in job_output.keys():
the_output.append((key, job_output[key]['asReference']))
return the_output |
def to_futurenow_level(level):
"""Convert the given Home Assistant light level (0-255) to FutureNow (0-100)."""
return int((level * 100) / 255) |
def getFansInZone(zone_num, profiles, fan_data):
"""
Parses the fan definition YAML files to find the fans
that match both the zone passed in and one of the
cooling profiles.
"""
fans = []
for f in fan_data['fans']:
if zone_num != f['cooling_zone']:
continue
#... |
def _test_rgb(h):
"""SGI image library"""
if h.startswith(b'\001\332'):
return 'rgb' |
def linear_interp(x, in_min, in_max, out_min, out_max):
""" linear interpolation function
maps `x` between `in_min` -> `in_max`
into `out_min` -> `out_max`
"""
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min |
def is_int(n):
""" checks if a number is float. 2.0 is True while 0.3 is False"""
return round(n) == n |
def _get_dropbox_path_from_dictionary(info_dict, account_type):
"""
Returns the 'path' value under the account_type dictionary within the main dictionary
"""
return info_dict[account_type]['path'] |
def packSplittedBytes(pSplitted):
"""
Unsplit splitted array of bytes.
Output: byterarray
"""
packed = bytearray()
for elt in pSplitted:
packed += elt
return packed |
def form(time):
"""Checks if the input parameter is a time played.
parameters:
- time: A string that is checked to have the time played format
returns:
- ret: A boolean represeting the conformaty of the input parameter
time
raises:
"""
ret = -1
temp = []
... |
def M_TO_N_ONLY(m, n, e):
"""
:param:
- `m`: the minimum required number of matches
- `n`: the maximum number of matches
- `e`: the expression t match
"""
return r"\b{e}{{{m},{n}}}\b".format(m=m, n=n, e=e) |
def format_button(recipient_id, button_text, buttons):
""" Ref: https://developers.facebook.com/docs/messenger-platform/send-api-reference/button-template """
return {
"recipient": {"id": recipient_id},
"message": {
"attachment": {
"type": "template",
... |
def complement(s):
"""
>>> complement('01100')
'10011'
"""
t = {"0": "1", "1": "0"}
return "".join(t[c] for c in s) |
def get_line_number(node):
"""Try to get the line number for `node`.
If no line number is available, this returns "<UNKNOWN>".
"""
if hasattr(node, 'lineno'):
return node.lineno
return '<UNKNOWN>' |
def find_island_id(phospho_islands, phospho_site):
""" Find the phospho island containing the specified phospho site.
:returns: the phospho island ID of the matching phospho island
"""
matching_island_id = None
for island_id, island in phospho_islands.items():
if phospho_site <= island['hi... |
def prepare_windowed_executions_colors(executions, center_commit_hash):
"""
This function will mark all the commit executions to be from other branch except for the passed commit.
This is because we want to emphatize the centered commit.
"""
for item in executions:
for execution in item['dat... |
def check_uniqueness_in_rows(board: list) -> bool:
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length, False otherwise.
>>> check_uniqueness_in_rows(['***21**', '412453*', '423145*', '*543215', '*35214*',\
'*41532*', '*2*1***'])
True
... |
def get_label(timestamp, commercials):
"""Given a timestamp and the commercials list, return if
this frame is a commercial or not. If not, return label."""
for com in commercials['commercials']:
if com['start'] <= timestamp <= com['end']:
return 'ad'
return commercials['class'] |
def bin_str(tok):
"""Returns a binary string equivalent to the input value.
Given a string that represents a binary number (with or without a '0b') or
a hex value with a '0x' in front, converts the value to a string of 1s and
0s. If a hex value is specified, each hex digit specifies four bits.
"""
... |
def get_bcs_x(shift=0, stimulus='reyes_puerta', seed=170, middle=False):
"""
restored variability
:param dt:
:return:
"""
shift_string = ''
shift_string_2 = ''
if stimulus == 'exp_25' or shift > 0:
shift_string = '_shift'
shift_string_2 = 'shift%d/' % shift
middle_st... |
def _validate_version(version: int) -> bool:
"""Validate all supported protocol versions."""
return version in [4] |
def mapper2(lines):
"""Mapper mapping to 2D Matrix"""
mapped_matrix = []
for word in lines.split():
mapped_matrix.append((word.strip(",")))
return mapped_matrix |
def _inject_mutations_3D(phi, dt, xx, yy, zz, theta0, frozen1, frozen2, frozen3):
"""
Inject novel mutations for a timestep.
"""
# Population 1
# Normalization based on the multi-dimensional trapezoid rule is
# implemented ************** here ***************
if not froz... |
def _trim_zeros(str_floats, na_rep='NaN'):
"""
Trims zeros, leaving just one before the decimal points if need be.
"""
trimmed = str_floats
def _cond(values):
non_na = [x for x in values if x != na_rep]
return (len(non_na) > 0 and all([x.endswith('0') for x in non_na]) and
... |
def format_fold_run(fold=None, run=None, mode='concise'):
"""Construct a string to display the fold, and run currently being executed
Parameters
----------
fold: Int, or None, default=None
The fold number currently being executed
run: Int, or None, default=None
The run number curren... |
def _one_contains_other(s1, s2):
"""
Whether one set contains the other
"""
return min(len(s1), len(s2)) == len(s1 & s2) |
def _varint_final_byte(char):
"""Return True iff the char is the last of current varint"""
return not ord(char) & 0x80 |
def _all(itr):
"""Similar to Python's all, but returns the first value that doesn't match."""
any_iterations = False
val = None
for val in itr:
any_iterations = True
if not val:
return val
return val if any_iterations else True |
def replace_dict_value(d, bad_val, good_val):
"""
IN PLACE replacement of bad_val to good_val ues
"""
for key, val in d.items():
if bad_val == val:
d[key] = good_val
print(d)
return d |
def convert_readable(size_to_convert):
"""
This function will convert size to human readable string
:param size_to_convert: size in bytes
:return: human-readable string with size
"""
i = 0
size_to_convert = int(size_to_convert)
units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB']
for i in ran... |
def _block_format_index(index):
"""
Convert a list of indices ``[0, 1, 2]`` into ``"arrays[0][1][2]"``.
"""
idx_str = "".join("[{}]".format(i) for i in index if i is not None)
return "arrays" + idx_str |
def render_build_args(options, ns):
"""Get docker build args dict, rendering any templated args.
Args:
options (dict):
The dictionary for a given image from chartpress.yaml.
Fields in `options['buildArgs']` will be rendered and returned,
if defined.
ns (dict): the namespace used... |
def format_model_type(mt):
"""
Converts the model type identifier into a human-readable string.
e.g. "random_forest" -> "random forest"
:param mt: string: the model type ID
:return: a human-readable version with underscores stripped and capitalised words
"""
components = mt.split('_')
fo... |
def head(list, n):
"""Return the firsts n elements of a list """
return list[:n] |
def process_template(template: str, arg1: str) -> str:
"""Replaces placeholder in a template with argument"""
if "<1>" in template and arg1 == "":
raise Exception(
f'Template string "{template}" includes a placeholder, but no argument was provided'
)
return template.replace("<1>"... |
def remove_none(obj):
"""
Remove empty values recursively from an iterable dictionary.
:param obj:
:return:
"""
if isinstance(obj, (list, tuple, set)):
return type(obj)(remove_none(x) for x in obj if x is not None)
elif isinstance(obj, dict):
return type(obj)(
... |
def getRecurringLen(n):
""" Returns the length of the recurring part of the fraction 1/n """
index = {}
rem, curIndex = 1, 0
while rem > 0 and rem not in index:
index[rem] = curIndex
rem = rem * 10
ext = 0
while rem < n:
rem = rem * 10
ext += 1
... |
def targetFeatureSplit( data ):
"""
given a numpy array like the one returned from
featureFormat, separate out the first feature
and put it into its own list (this should be the
quantity you want to predict)
return targets and features as separate lists
(sklearn c... |
def _catmull_rom_weighting_function(x: float) -> float:
"""Catmull-Rom filter's weighting function.
For more information about the Catmull-Rom filter, see
`Cubic Filters <https://legacy.imagemagick.org/Usage/filter/#cubics>`_.
Args:
x (float): distance to source pixel.
Returns:
fl... |
def normalize(x: float, x_min: float, x_max: float) -> float:
"""
Rescaling data to have values between 0 and 1
"""
return (x - x_min) / (x_max - x_min) |
def lerp_np(x, y, w):
"""Helper function."""
fin_out = (y - x) * w + x
return fin_out |
def has_palindrome ( i, start, length ):
"""Checks if the string representation of i has a palindrome.
i: integer
start: where in the string to start
length: length of the palindrome to check for
"""
s = str(i)[start: length]
return s == s[::-1] |
def check_true(option):
"""Check if option is true.
Account for user inputting "yes", "Yes", "True", "Y" ...
"""
option = option.lower()
if 'y' in option or 't' in option:
return True
else:
return False |
def build_oai_url(handle: str,
prefix: str,
base_url: str = "https://air.uniud.it/oai/request?") -> str:
"""build the url for an oai request of a single record (in the case of
institutional repository, one record corresponds to a publication)
Parameters
----------
... |
def sort_and_prioritize(lst, to_prioritize):
"""Usage:
>>> sort_and_prioritize(["B", "C", "D", "A", "F", "E"], ["C", "D"])
>>> ['C', 'D', 'A', 'B', 'E', 'F']
"""
queue = [lst.pop(lst.index(item)) for item in to_prioritize]
lst = sorted(lst)
for item in sorted(queue, reverse=True):
ls... |
def sort_top_editors_per_country(editors, editcount_index, top_n):
"""
Takes a list of lists of editors with editcounts
and a top editor cutoff int, returns a sorted top list.
"""
editors.sort(key=lambda x: int(x[2]), reverse=True)
if len(editors) > top_n:
editors = editors[:top_n]
return editors |
def ext_euclid_alg (m, n):
""" Extended Euclidean algorithm for gcd.
Finds the greatest common divisor of
two integers a and bm and solves for integer
x, y such that ax + by = 1. From Knuth, TAOCP
vol. I, p. 14.
Variables --
q, r -- quotient and remainder
a, b -- am + bn = gcd
... |
def count_stars(chars):
"""
Count the number of trailing '#' (~== '#+$')
>>> count_stars("http://example.org/p?q#fragment####")
<<< 4
"""
count = 0
for c in chars[::-1]:
if c != '#':
break
count += 1
return count |
def extract_data_from_dict(d1, keys, mandatory_keys=()):
"""
Given a dictionary keeps only data defined by the keys param
Args:
d1: dictionary to extract the data from
keys: keys to extract
mandatory_keys: if any of this keys isn't in the d1, exception will be risen
Returns:
... |
def mel2hz(mel):
"""Convert a value in Hertz to Mels
Parameters
----------
hz : number of array
value in Hz, can be an array
Returns:
--------
_ : number of array
value in Mels, same type as the input.
"""
return 700 * (10 ** (mel / 2595.0) - 1) |
def A006577(n: int) -> int:
"""Give the number of halving and tripling steps to reach 1 in '3x+1' problem."""
if n == 1:
return 0
x = 0
while True:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
x += 1
if n < 2:
break
return x |
def parse_frontmatter(raw_text: str) -> dict:
"""
Parser for markdown file front matter. This parser has the following features:
* Simple key-value pairings (`key: value`)
* Comma-separated lists between brackets (`list: ['value1', 'value2']`)
* Keys are case insensitive
Args:
... |
def get_license_tag_issue_type(issue_category):
"""
Classifies the license detection issue into one of ISSUE_TYPES_BY_CLASSIFICATION,
where it is a license tag.
"""
if issue_category == "false-positive":
return "tag-false-positive"
else:
return "tag-tag-coverage" |
def normalize_control_field_name(name):
"""
Return a case-normalized field name string.
Normalization of control file field names is not really needed when reading
as we lowercase everything and replace dash to underscore internally, but it
can help to compare the parsing results to the original fi... |
def hexval2val(hexval):
"""Unconvert a decimal digit equivalent hex byte to int."""
ret = 10*(hexval>>4) # tens 0x97 -> 90
ret += hexval&0x0f # ones 0x97 -> 7
return ret |
def get_string(fh):
"""fh is the file handle """
mystr = b''
byte = fh
if fh != '':
mystr = bytearray(fh, 'ascii')
else:
mystr = bytes(1)
return mystr |
def count_elements(seq) -> dict:
"""Tally elements from `seq`."""
hist = {}
for i in seq:
hist[i] = hist.get(i, 0) + 1
return hist |
def _get_full_text(tweet):
"""Parses a tweet json to retrieve the full text.
:param tweet: a Tweet either from the streaming or search API
:type tweet: a nested dictionary
:returns: full_text field hidden in the Tweet
:rtype: str
"""
if isinstance(tweet, dict):
if "extended_tweet" ... |
def is_plenary_agenda_item(assignment):
"""Is this agenda item a regular session item?
A regular item appears as a sub-entry in a timeslot within the agenda
>>> from collections import namedtuple # use to build mock objects
>>> mock_timeslot = namedtuple('t2', ['slug'])
>>> mock_assignment = name... |
def celsius_to_fahrenheit(deg_C):
"""Convert degrees Celsius to Fahrenheit."""
return (9 / 5) * deg_C + 32 |
def from_time(year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None):
"""Convenience wrapper to take a series of date/time elements and return a WMI time
of the form `yyyymmddHHMMSS.mmmmmm+UUU`. All elements may be int, string or
omitted altogether. If omi... |
def escape(text):
"""Escape some Markdown text"""
for char in '*_`[]':
text = text.replace(char, '\\'+char)
return text |
def time_in_range(start: int, end: int, current_time: int) -> bool:
""" Return true if current_time is in the range [start, end] """
if start <= end:
return start <= current_time < end
else:
return start <= current_time or current_time <= end |
def read_varint(readfn):
"""
Reads a variable-length encoded integer.
:param readfn: a callable that reads a given number of bytes,
like file.read().
"""
b = ord(readfn(1))
i = b & 0x7F
shift = 7
while b & 0x80 != 0:
b = ord(readfn(1))
i |= (b & 0x7F) << shift
... |
def reverseSentence(s):
"""i am a student. -> student. a am i"""
s = s[::-1]
sNums = s.split(' ')
for i in range(len(sNums)):
sNums[i] = sNums[i][::-1]
return " ".join(sNums) |
def is_float(v):
"""
Check for valid float
>>> is_float(10)
True
>>> is_float(10.2)
True
>>> is_float("10.2")
True
>>> is_float("Ten")
False
>>> is_float(None)
False
"""
try:
v = float(v)
except ValueError:
return False
except TypeError:
... |
def pythoncross(v1, v2):
"""Take the cross product between v1 and v2, slightly faster than np.cross"""
c = [v1[1]*v2[2] - v1[2]*v2[1],
v1[2]*v2[0] - v1[0]*v2[2],
v1[0]*v2[1] - v1[1]*v2[0]]
return c |
def separate_substructures(tokenized_commands):
"""Returns a list of SVG substructures."""
# every moveTo command starts a new substructure
# an SVG substructure is a subpath that closes on itself
# such as the outter and the inner edge of the character `o`
substructures = []
curr = []
... |
def get_object_type(object_id):
"""
Obtain object type
Parameters
----------
object_id : int
object identifier
Returns
-------
object_type : str
type of object
"""
# https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/req/naif_ids.html
if object_id < -100000:
... |
def M(metric_name):
"""Make a full metric name from a short metric name.
This is just intended to help keep the lines shorter in test
cases.
"""
return "django_model_%s" % metric_name |
def unifom_distr_moment(d,sigma):
""" computes the moments E[X] for X uniformly (-sigma,sigma) distributed """
if 1==d%2:
return 0
else:
return sigma**d/(d+1.) |
def comment_lines(lines, prefix):
"""Return commented lines"""
if not prefix:
return lines
return [prefix + ' ' + line if line else prefix for line in lines] |
def common_elements(left, right) -> int:
""" Returns the number of elements that are common between `left` and `right`"""
common = set(left) & set(right)
return len(common) |
def csort(objs, key=lambda x: x):
"""Order-preserving sorting function."""
idxs = dict((obj, i) for (i, obj) in enumerate(objs))
return sorted(objs, key=lambda obj: (key(obj), idxs[obj])) |
def turn(orient_index, direction):
"""
change the current orientation according to
the new directions
Args:
orient_index (int): index in the orient list for the
current orientations
direction (str): R or L
Returns:
int
"""
if direction == 'R':
or... |
def remove_nulls(input_dict):
"""Remove keys with no value from a dictionary."""
output = {}
for k, v in input_dict.items():
if v is not None:
output[k] = v
return output |
def get_sci_val(decimal_val):
"""
returns the scientific notation for a decimal value
:param decimal_val: the decimal value to be converted
:return: the scientific notation of the decimal value
"""
sci_val = ''
if decimal_val is not None:
if decimal_val == 0:
sci_val = '0... |
def row_sum_odd_numbers3(n):
"""
Time complexity: O(n).
Space complexity: O(n).
"""
start_odd = n * (n - 1) + 1
row = []
for i in range(1, n + 1):
row.append(start_odd + (i - 1) * 2)
return sum(row) |
def calc_triangle_area(base, height):
"""
Calculates the area of the triangle
:param base:
:param height:
:return: area
"""
return (base * height) / 2 |
def twoNumberSum(array, targetSum):
"""
This works completely on pointers, here we are having two pointers
One is left pointer and another being right pointer
idea here is to have left+right=sum, this can have three outcomes
1. First outcome
targetsum = sum
2. Second outcome
tar... |
def ratio(value, count):
"""compute ratio but ignore count=0"""
if count == 0:
return 0.0
else:
return value / count |
def create_category_index(categories):
"""Creates dictionary of COCO compatible categories keyed by category id.
Args:
categories: a list of dicts, each of which has the following keys:
'id': (required) an integer id uniquely identifying this category.
'name': (required) string representi... |
def _repr_pen_commands(commands):
"""
>>> print(_repr_pen_commands([
... ('moveTo', tuple(), {}),
... ('lineTo', ((1.0, 0.1),), {}),
... ('curveTo', ((1.0, 0.1), (2.0, 0.2), (3.0, 0.3)), {})
... ]))
pen.moveTo()
pen.lineTo((1, 0.1))
pen.curveTo((1, 0.1), (2, 0.2), (3, 0.3... |
def solution(A): # O(N)
"""
Given a variable length array of integers, partition them such that the even
integers precede the odd integers in the array. Your must operate on the array
in-place, with a constant amount of extra space. The answer should sc... |
def time_sep(t1: int, t2: int, time_max: int):
""" Calculate the separation amount and direction of two time slices"""
if not (isinstance(t1, int) and isinstance(t1, int)):
raise TypeError(f"t1={t1} and t2={t2} must be ints")
i = (t1 - t2) % time_max
j = (t2 - t1) % time_max
if j > i:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.