content stringlengths 42 6.51k |
|---|
def isiterable(iterable):
"""
https://stackoverflow.com/a/36407550/3356840
"""
if isinstance(iterable, (str, bytes)):
return False
try:
_ = iter(iterable)
except TypeError:
return False
else:
return True |
def is_pr_comment(event):
"""Determine if a comment applies to a pull request."""
try:
right_type = event.type == 'IssueCommentEvent'
right_payload = 'pull_request' in event.payload['issue'].to_json()
return right_type and right_payload
except (KeyError, IndexError, AttributeError, T... |
def bound(low, value, high):
"""
If value is between low and high, return value.
If value is below low, return low.
If value is above high, return high.
If low is below high, raise an exception.
"""
assert low <= high
return max(low, min(value, high)) |
def build_preferences(first, second, third):
"""Given three preferences, reduces them in order to unique choices.
Args:
first: project name
second: project name
third: project name
Returns:
List[str]
"""
end_result = []
for pref in (first, second, third):
... |
def map_pathogen_id_to_name(pathogen_id):
"""
"""
mapping = {
"p00": "Acinetobacter baumannii",
"p01": "Baceroides fragilis",
"p02": "Burkholderia cepacia",
"p03": "Candida albicans",
"p04": "Candida giabrata",
"p05": "Candida parapsilosis",
"p06": "Ca... |
def get_missing_coordinate(x1: float, y1: float, x2: float, angular_coefficient: float = -1.0) -> float:
"""Returns the y2 coordinate at the point (x2, y2) of a line which has an angular coefficient of
"angular_coefficient" and passes through the point (x1, y1)."""
linear_coefficient = y1 - (angular_coeffic... |
def metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""Given a prediction and multiple valid answers, return the score of
the best prediction-answer_n pair given a metric function.
"""
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = metric_fn(pre... |
def remove_template(s):
"""Remove template wikimedia markup.
Return a copy of `s` with all the wikimedia markup template removed. See
http://meta.wikimedia.org/wiki/Help:Template for wikimedia templates
details.
Note: Since template can be nested, it is difficult remove them using
regular expr... |
def CompareResults(manifest, actual):
"""Compare sets of results and return two lists:
- List of results present in ACTUAL but missing from MANIFEST.
- List of results present in MANIFEST but missing from ACTUAL.
"""
# Collect all the actual results not present in the manifest.
# Results in this set w... |
def nova_except_format(logical_line):
"""
nova HACKING guide recommends not using assertRaises(Exception...):
Do not use overly broad Exception type
N202
"""
if logical_line.startswith("self.assertRaises(Exception"):
return 1, "NOVA N202: assertRaises Exception too broad" |
def get_page_as_ancestor(page_id):
"""
Get ancestors object accepted by the API from a page id
:param page_id: the ancestor page id
:return: API-compatible ancestor
"""
return [{'type': 'page', 'id': page_id}] |
def get_array_slice_start_end(length, num_slices, slice_index):
"""
"""
if not (length > 0):
raise Exception("Invalid length, must be > 0")
if not (1 <= num_slices <= length):
raise Exception("Invalid number of slices, must be >= 1 and <= length")
if not (0 <= slice_index < lengt... |
def _real_2d_func(x, y, func):
"""Return real part of a 2d function."""
return func(x, y).real |
def meta_caption(meta) -> str:
"""makes text from metadata for captioning video"""
caption = ""
try:
caption += meta.title + " - "
except (TypeError, LookupError, AttributeError):
pass
try:
caption += meta.artist
except (TypeError, LookupError, AttributeError):
... |
def truncate(text, maxlen=128, suffix='...'):
"""Truncates text to a maximum number of characters."""
if len(text) >= maxlen:
return text[:maxlen].rsplit(' ', 1)[0] + suffix
return text |
def sqlite3_call(database, query):
"""
Differentiate between SELECT and INSERT, UPDATE, DELETE
(hack -> wont work with sub-selects in e.g. update)
"""
if query == "" or query is None:
return "Warning: Empty query string!"
elif query and query.lower().find("select") >= 0:
return d... |
def validate_int(value):
"""
Validate an int input.
Parameters:
value (any): Input value
Returns:
boolean: True if value has type int
"""
return isinstance(value, int) |
def slot_id(hsm):
"""Provide a slot_id property to the template if it exists"""
try:
return hsm.relation.plugin_data['slot_id']
except Exception:
return '' |
def calcSurroundingIdxs(idxs, before, after, idxLimit=None):
"""
Returns (idxs - before), (idxs + after), where elements of
idxs that result in values < 0 or > idxLimit are removed; basically,
this is useful for extracting ranges around certain indices (say,
matches for a substring) that are contained fully in an ... |
def _is_fileobj(obj):
""" Is `obj` a file-like object?"""
return hasattr(obj, 'read') and hasattr(obj, 'write') |
def is_known_mersenne_prime(p):
"""Returns True if the given Mersenne prime is known, and False otherwise."""
primes = frozenset([2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049, 216091,
... |
def midpoint(f, a, b, N):
"""
f ... function to be integrated
[a,b] ... integration interval
N ... number steps(bigger the better but slower)
This method uses rectangles to approximate the area under the curve.
Rectangle width is determined by the interval of integration.
The interv... |
def rat(n, d, nan=float('nan'), mul=1.0):
""" Calculate a ratio while avoiding division by zero errors.
Strictly speaking we should have nan=float('nan') but for practical
purposes we'll maybe want to report None (or 0.0?).
"""
try:
return ( float(n) * mul ) / float(d)
except (Ze... |
def is_unsigned_integer(value):
"""
:param value:
:return:
>>> is_unsigned_integer(0)
True
>>> is_unsigned_integer(65535)
True
>>> is_unsigned_integer(-1)
False
>>> is_unsigned_integer(65536)
False
>>> is_unsigned_integer('0')
False
>>> is_unsigned_integer(0.0)
... |
def norm2d(x, y):
"""Calculate norm of vector [x, y]."""
return (x * x + y * y) ** 0.5 |
def clamp(minimum, value, maximum):
"""Clamp value between given minimum and maximum."""
return max(minimum, min(value, maximum)) |
def safe_float(string, default=None):
"""
Safely parse a string into a float.
On error return the ``default`` value.
:param string string: string value to be converted
:param float default: default value to be used in case of failure
:rtype: float
"""
value = default
try:
v... |
def ucfirst(msg):
"""Return altered msg where only first letter was forced to uppercase."""
return msg[0].upper() + msg[1:] |
def tsorted(a):
"""Sort a tuple"""
return tuple(sorted(a)) |
def selection_sort(a: list) -> list:
"""Given a list of element it's return sorted list of O(n^2) complexity"""
a = a.copy()
n = len(a)
for i in range(n):
mni = i
for j in range(i+1, n):
if a[j] < a[mni]:
mni = j
a[i], a[mni] = a[mni], a[i]
return ... |
def urlify(str, length=None):
"""Write a method to replace all spaces with '%20'.
Args:
str - String whose spaces should be replaced by '%20'
length - length of str minus any spaces padded at the beginning or end
Returns:
A string similar to str except whose spaces have been replace... |
def get_table_schema_query(schema_table, source_table_name):
"""
Query to get source schema for table from BQ (previously ingested).
"""
return f" select distinct * from (select COLUMN_NAME, DATA_TYPE from `{schema_table}` \
where TABLE_NAME = '{source_table_name}' order by ORDINAL_POSITION)" |
def boarding_pass_to_seat_id(boarding_pass: str) -> int:
"""Convert a boarding pass string into seat ID
Because the strings are just binary representations of integers, we can abuse
Python's booleans and convert them from FBFBBFFRLR to 0101100101
"""
seat_id = "".join(str(int(char in {"B", "R"})) f... |
def validateUnits(cmodel, layers):
"""Validate model units.
Args:
cmodel (dict): Sub-dictionary from config for specific model.
layers (dict): Dictionary of file names for all input layers.
Returns:
dict: Model units.
"""
units = {}
for key in cmodel['layers'].keys():
... |
def selection_sort(to_be_sorted):
"""
O(n^2) as there are two nested loops
:param to_be_sorted:
:return:
"""
if len(to_be_sorted) < 2:
return to_be_sorted
for i1 in range(len(to_be_sorted)):
min = i1
for i2 in range(i1 + 1, len(to_be_sorted)):
if to_be_s... |
def get_pairs(word):
"""
Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs |
def subvector(y, head, tail):
"""Construct a vector with the elements v[head], ..., v[tail-1]."""
result = []
for i in range(head, tail, 1):
result.append(y[i])
return result |
def add_color_to_scheme(scheme, name, foreground, background, palette_colors):
"""Add foreground and background colours to a color scheme"""
if foreground is None and background is None:
return scheme
new_scheme = []
for item in scheme:
if item[0] == name:
if foreground is N... |
def interpret_as_slice(column):
"""Interprets the 'column' argument of loadFitnessHistory into a slice()"""
if column is None: # No specific column is requested, return everything
return slice(None)
elif isinstance(column, int): # One specific column is requested
return slice(column, colum... |
def state_utility(ufuncs, state):
"""computes utility for a state"""
utility = 0
for attr, value in state.items():
if attr in ufuncs:
utility += ufuncs[attr](state[attr])
return utility |
def sieve(n):
""" Input n>=6, Returns a list of primes, 2 <= p < n """
correction = (n % 6 > 1)
n = {0:n, 1:n - 1, 2:n + 4, 3:n + 3, 4:n + 2, 5:n + 1}[n % 6]
sieve = [True] * (n // 3)
sieve[0] = False
for i in range(int(n ** 0.5) // 3 + 1):
if sieve[i]:
k = 3 * i + 1 | 1
... |
def validate_bst(root):
"""
This solution does an inorder traversal, checking
if the BST conditions hold for every node
in the tree.
"""
if root is not None:
validate_bst(root.left)
if root.left is not None:
if root.left.data > root.data:
ret... |
def sort_012(input_list):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Args:
input_list(list): List to be sorted
"""
start_pos_0 = 0
end_pos_2 = len(input_list) - 1
front_index = 0
count = 0
if len(input_list) < 0:
... |
def is_kwarg(argument: str) -> bool:
"""`True` if argument name is `**kwargs`"""
return "**" in argument |
def is_2d_vector(block):
"""
Returns True if ``block is a 2-d list.
:param block: A list.
"""
return all([isinstance(r, list) for r in block]) and all([len(r) == 1 for r in block]) |
def iou(box1, box2, x1y1x2y2 = True):
""" Intersection Over Union """
if x1y1x2y2:
mx = min(box1[0], box2[0])
Mx = max(box1[2], box2[2])
my = min(box1[1], box2[1])
My = max(box1[3], box2[3])
w1 = box1[2] - box1[0]
h1 = box1[3] - box1[1]
w2 = box2[2] - bo... |
def make_edges(nodes, directed=True):
"""
Create an edge tuple from two nodes either directed
(first to second) or undirected (two edges, both ways).
:param nodes: nodes to create edges for
:type nodes: :py:list, py:tuple
:param directed: create directed edge or not
:type directed: ... |
def parse_mime_type(mime_type):
"""Parses a mime-type into its component parts.
Carves up a mime-type and returns a tuple of the (type, subtype, params)
where 'params' is a dictionary of all the parameters for the media range.
For example, the media range 'application/xhtml;q=0.5' would get parsed
... |
def g_logv(s):
"""read a logical variable
:param str s:
:return bool:
"""
return s == '1' or s.lower() == 'yes' or s.lower() == 'true' |
def convert_filter_for_tator_search(filter_condition: dict) -> str:
""" Converts the given filter condition into a Tator REST compliant search string
"""
modifier_str = filter_condition["modifier"]
modifier_end_str = ""
if filter_condition["modifier"] == "==":
modifier_str = ""
elif fil... |
def _make_package(x):
"""Get the package name and drop the last '.' """
package = ''
for p in x:
package += p[0] + p[1]
if package and package[-1] == '.':
package = package[:-1]
return package |
def method_func(klass, method_name):
"""
Get the function object from a class and a method name.
In Python 2 doing getattr(SomeClass, 'methodname') returns an
instancemethod and in Python 3 a function. Use this helper to reliably get
the function object
"""
method = getattr(klass, method_na... |
def parseFlows(flows):
"""
Parse out the string representation of flows passed in.
Example:
NXST_FLOW reply (xid=0x4):
cookie=0x0, duration=4.329s, table=0, n_packets=0, n_bytes=0, idle_timeout=120,hard_timeout=120,in_port=3 actions=output:4
"""
switchFlows = {}
for flow in flows.spli... |
def fahrenheit_to_celsius(temp_fahrenheit, difference=False):
"""Transform Fahrenheit temperatures to Celsius
Args:
temp_fahrenheit (float): temperature in fahrenheit
difference (bool, optional): relative difference to zero. Defaults to False.
Returns:
[type]: temperature in Celsiu... |
def get_start_vertex(searchers_info):
"""Return list of searchers start position
start indexing follow model style [1,2..]"""
start = []
for k in searchers_info.keys():
dummy_var = searchers_info[k]['start']
my_var = dummy_var
start.append(my_var)
return start |
def isPrime(x):
"""
Checks whether the given
number x is prime or not
"""
if x == 5:
return True
if x % 2 == 0:
return False
for i in range(3, int(x**0.5)+1, 2):
if x % i == 0:
return False
return True |
def form_gene_str(gene):
"""Form the string form of a gene."""
return ''.join(str(i) for i in gene) |
def index(haystack, needle, start=1):
"""returns the character position of one string, needle, in
another, haystack, or returns 0 if the string needle is not found
or is a null string. By default the search starts at the first
character of haystack (start has the value 1). You can override
this by s... |
def int_to_binary_string(n):
"""
Return the binary representation of the number n
:param n: a number
:return: a binary representation of n as a string
"""
return '{0:b}'.format(n) |
def get_avg_duration(persons, fps):
"""
Compute the average duration of detection for an array of persons
:param persons: array of the detected persons
:param fps: frame-per-second rate for the video
:return: None
"""
if len(persons) > 0:
total_nb_frames = 0
for person in per... |
def colorTransfer(val):
"""Convert 0-1 into a grayscale terminal color code"""
minCol = 235
maxCol = 256
return int((maxCol-minCol)*val + minCol) |
def _LookupMeOrUsername(cnxn, username, services, user_id):
"""Handle the 'me' syntax or lookup a user's user ID."""
if username.lower() == 'me':
return user_id
return services.user.LookupUserID(cnxn, username) |
def convert_geographic_coordinate_to_pixel_value(refpx, refpy, transform):
"""
Converts a lat/long coordinate to a pixel coordinate given the
geotransform of the image.
Args:
refpx: The longitude of the coordinate.
refpx: The latitude of the coordinate.
transform: The geotransf... |
def speed2dt(speed):
"""Calculate the time between consecutive fall steps using the *speed* parameter; *speed* should be an int between 1 and 9 (inclusively). Returns time between consecutive fall steps in msec."""
return (10-speed)*400 |
def getPercentIdentity(seq1, seq2, gap_char="-"):
"""get number of identical residues between seq1 and seq2."""
ntotal = 0
nidentical = 0
for a in range(len(seq1)):
if seq1[a] != gap_char and seq2[a] != gap_char:
ntotal += 1
if seq1[a] == seq2[a]:
nidenti... |
def part_2_fuel(pos, list_):
"""gives the fuel amount for a specific position according to rules of part 2"""
fuel = [(abs(pos - i)*(abs(pos-i)+1))/2 for i in list_]
return sum(fuel) |
def find_mean(values):
"""Gets the mean of a list of values
Args:
values (iterable of float): A list of numbers
Returns:
float
"""
mean = sum(values) / len(values)
return mean |
def get_data_from_region(region_url_list, rent_or_sale):
"""
Given a list of urls of different regions and the listing type (rent or buy), returns a list of urls with all
the properties for this specific listing type, each url for a particular region.
"""
regional_data = []
for url in region_url... |
def _get_valid_bool(section, option, provided):
"""Validates a boolean type configuration option.
Returns False by default if the option is unset.
"""
if provided is None:
return False
if not isinstance(provided, bool):
error = "Value provided for '{0}: {1}' is not a valid boolean... |
def commastring_to_list(string, capitalize=False):
"""Turn a comma separated list in a string to a python list."""
if capitalize:
return [item.strip().capitalize() for item in string.split(',')]
return [item.strip() for item in string.split(',')] |
def check_bool_is_false(val):
"""Check if a value is a false bool."""
if not val and isinstance(val, bool):
return True
raise ValueError('Value should be "False"; got {}'.format(val)) |
def scalar_multiply(c, u):
""" return the vector u scaled by the scalar c """
return tuple((c * a for a in u)); |
def dyadic_string_lists(l1,l2):
"""Compute the dyadic product of two lists of strings"""
if(len(l1)==1):
l1 = ([l1[0],[]],)
l = [[[str(l1v[0])+str(l2v),[t for t in l1v[1]]+[l2v]] for l1v in l1] for l2v in l2]
return [item for sublist in l for item in sublist] |
def _merge_lists(one, two, keyfn, resolvefn):
"""Merges two lists. The algorithm is to first iterate over the first list. If the item in the first list
does not exist in the second list, add that item to the merged list. If the item does exist in the second
list, resolve the conflict using the resolvefn. Af... |
def clean_library_name(assumed_library_name):
"""
Most CP repos and library names are look like this:
repo: Adafruit_CircuitPython_LC709203F
library: adafruit_lc709203f
But some do not and this handles cleaning that up.
Also cleans up if the pypi or reponame is passed in instead of the... |
def multi_lstrip(txt: str) -> str:
"""Left-strip all lines in a multiline string."""
return "\n".join(line.lstrip() for line in txt.splitlines()).strip() |
def evaluate_ensemble(data, prediction):
"""
Evaluate the prediction (List[int]) base on the valid/test data (dict)
"""
total_prediction = 0
total_accurate = 0
for i in range(len(data["is_correct"])):
if prediction[i] >= 0.5 and data["is_correct"][i]:
total_accurate += 1
... |
def cell_get_units(value, default_units):
"""
Given a single string value (cell), separate the name and units.
:param value: str
:param default_units: indicate return units string subset
:return: unit for row
"""
if '(' not in value:
return default_units
spl = value.split(' ')
... |
def dummy_task(**kwargs):
"""Use this one for testing mule"""
print("Hi! I'm dummy! My kwargs are: %s", kwargs)
return True |
def torch_dim_to_trt_axes(dim):
"""Converts torch dim, or tuple of dims to a tensorrt axes bitmask"""
if not isinstance(dim, tuple):
dim = (dim,)
# create axes bitmask for reduce layer
axes = 0
for d in dim:
axes |= 1 << (d - 1) # -1 to remove batch dimension
return axes |
def get_slope(x1, y1, x2, y2):
"""slope is used to seperate the lines to left and right
"""
if round(x1 - x2, 2) == 0:
return None
else:
return (y2 - y1) / (x2 - x1) |
def _split_docstring(docstring: str):
"""Splits the docstring into a summary and description."""
if not docstring:
docstring = ""
lines = docstring.splitlines()
if not lines:
return "", ""
# Skip leading blank lines.
while lines and not lines[0]:
lines = lines[1:]
if len(lines) > 2:
retur... |
def make_id_response(id):
"""
Usually used for requests that create single resources.
:param id: ID of of the created resource.
:return: Single ID response.
"""
return {'id': id} |
def append_key(stanzas, left_struc, keypath=None):
"""Get the appropriate key for appending to the sequence ``left_struc``.
``stanzas`` should be a diff, some of whose stanzas may modify a
sequence ``left_struc`` that appears at path ``keypath``. If any of
the stanzas append to ``left_struc``, the ret... |
def guessPeriodicity(srcBounds):
"""
Guess if a src grid is periodic
Parameters
----------
srcBounds : the nodal src set of coordinates
Returns
-------
1 if periodic, warp around, 0 otherwise
"""
res = 0
if srcBounds is not None:
res = 1
# assume longitude ... |
def split_v(v):
"""Given V-gene, returns that V-gene, its subgroup, name and allele.
If a part cannot be retrieved from v, empty string will be returned for that part"""
star = '*' in v
if '-' in v:
vs = v.split('-')
subgroup = vs[0]
if star:
vs=vs[-1].split('*')
... |
def get_pgsnapshot(module, array):
"""Return Snapshot (active or deleted) or None"""
try:
snapname = module.params['name'] + "." + module.params['suffix']
for snap in array.get_pgroup(module.params['name'], pending=True, snap=True):
if snap['name'] == snapname:
return... |
def dfs(grid, x, y):
"""When find a `0` in the grid, visit all neighbor `0` s and decide whether
it is an island."""
height, width = len(grid), len(grid[0])
is_island = True
if (x == 0 or x == height - 1) or (y == 0 or y == width - 1):
is_island = False
# When visited, set grid[x][y] = ... |
def call_put_split(current_price, call_chain, put_chain):
""" Returns true if the call volume and impliedint point to rise """
if len(call_chain) > len(put_chain):
if abs(float(call_chain[0][0]) - current_price) > abs(float(put_chain[0][0]) - current_price):
# if spread is greater for c... |
def getPooledVariance(data):
"""return pooled variance from a
list of tuples (sample_size, variance)."""
t, var = 0, 0
for n, s in data:
t += n
var += (n - 1) * s
assert t > len(data), "sample size smaller than samples combined"
return var / float(t - len(data)) |
def set_to_provider_client(unparsed_set):
"""Take a oai set and convert into provider_id and client_id"""
# Get both a provider and client_id from the set
client_id = None
provider_id = None
if unparsed_set:
# Strip any additional query
if "~" in unparsed_set:
unparsed_... |
def multiply_nums(n1, n2):
"""Function to multiplies two numbers.
n1 : Must be a numeric type
n2 : Must be a numeric type
"""
result = n1 * n2
return result |
def isfalsy(x):
"""Given an input returns True if the input is a "falsy" value. Where
"falsy" is defined as None, '', or False."""
return x is None or x == '' or x == False |
def ifact(n):
"""Iterative"""
for i in range(n - 1, 0, -1): n *= i
return n |
def collate_fn(x_y_list):
"""
:param x_y_list: len(N * (x, y))
:return: x_list, y_list
"""
return [list(samples) for samples in zip(*x_y_list)] |
def get_urls_from_object(tweet_obj):
"""Extract urls from a tweet object
Args:
tweet_obj (dict): A dictionary that is the tweet object, extended_entities or extended_tweet
Returns:
list: list of urls that are extracted from the tweet.
"""
url_list = []
if "entities" in tweet_ob... |
def transpose_and_multiply(m, multiplier=1):
"""swap values along diagonal, optionally adding multiplier"""
for row in range(len(m)):
for col in range(row + 1):
temp = m[row][col] * multiplier
m[row][col] = m[col][row] * multiplier
m[col][row] = temp
return m |
def caesar_cipher_decryptor(key: int, encrypted_message: str) -> str:
"""Decrypts a message which has been encrypted using a Caesar Cipher.
Args:
encrypted_message (str): Message to be decrypted.
key (int): Original shift.
Returns:
decrypted_message (str): Decrypted message.
""... |
def not_empty(data):
"""Checks if not empty"""
if data != "":
return True
else:
return False |
def has_checked_all_boxes(array, total):
"""
Return a string indicating length of array compared with expected total
:param array eg ["value"]:
:param total eg 2:
:return "failed":
"""
if len(array) < total:
return "failed"
else:
return "passed" |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.