content stringlengths 42 6.51k |
|---|
def get_shard_basename(shard: int) -> str:
"""Get the basename for a streaming dataset shard.
Args:
shard (int): Shard index.
Returns:
str: Basename of file.
"""
return f'{shard:06}.mds' |
def get_timeout_error_regex(rpc_backend_name):
"""
Given an RPC backend name, returns a partial string indicating the error we
should receive when an RPC has timed out. Useful for use with
assertRaisesRegex() to ensure we have the right errors during timeout.
"""
if rpc_backend_name in ["P... |
def corrected_proj_param(big_H, lil_h, R):
"""
Eq. 4.11
Calculates the corrected projection parameter for a cloud target
Parameters
------------
big_H : int
Satellite's height above the Earth's surface, in km
lil_h : int
Cloud's altitude above the Earth's surface, in km
... |
def validate_input(lang):
"""
function to validate the input by user
"""
if lang.lower() not in ('en', 'fr', 'hi', 'es'):
return False
else:
return True |
def associate(first_list, second_list, offset, max_difference):
"""
Associate two dictionaries of (stamp,data). As the time stamps never match exactly, we aim
to find the closest match for every input tuple.
Input:
first_list -- first dictionary of (stamp,data) tuples
second_list -- second dict... |
def __strip_string(value):
"""Simple helper - strip string, don't change numbers"""
if not type(value) == str:
pass
else:
value = value.replace(' ','').replace(',','').strip()
return value |
def bit_get(val, idx):
"""Gets the bit value.
Args:
val: Input value, int or numpy int array.
idx: Which bit of the input val.
Returns:
The "idx"-th bit of input val.
"""
return (val >> idx) & 1 |
def replicate(l):
"""
Replicates if there is only one element.
"""
if(len(l) == 1):
l.append(l[0])
return l |
def bounding_box_half_values(bbox_min, bbox_max):
"""
Returns the values half way between max and min XYZ given tuples
:param bbox_min: tuple, contains the minimum X,Y,Z values of the mesh bounding box
:param bbox_max: tuple, contains the maximum X,Y,Z values of the mesh bounding box
:return: tuple(... |
def first(iterable):
"""Returns the first item of ``iterable``.
"""
try:
return next(iter(iterable))
except StopIteration:
return None |
def get_windows_version(windows_version: str = 'win7') -> str:
"""
valid windows versions : 'nt40', 'vista', 'win10', 'win2k', 'win2k3', 'win2k8', 'win31', 'win7', 'win8', 'win81', 'win95', 'win98', 'winxp'
>>> import unittest
>>> assert get_windows_version() == 'win7'
>>> assert get_windows_versio... |
def in_box(boxes, x, y):
"""Finds out whether a pixel is inside one of the boxes listed"""
for box in boxes:
x1, y1, x2, y2 = box
if x>=x1 and x<=x2 and y>=y1 and y<=y2:
return True
return False |
def verify_positive(value):
"""Throws exception if value is not positive"""
if not value > 0:
raise ValueError("expected positive integer")
return value |
def create_hue_success_response(entity_number, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = f"/lights/{entity_number}/state/{attr}"
return {"success": {success_key: value}} |
def _minor(x, i, j):
"""The minor matrix of x
:param i: the column to eliminate
:param j: the row to eliminate
:returns: x without column i and row j
"""
return [[x[n][m] for m in range(len(x[0])) if m != j]
for n in range(len(x)) if n != i] |
def multiply_2(factor):
"""
Example without using annotations. Better example of how to use assert.
:param factor:
:return: results: int
"""
assert type(factor) is int or type(factor) is float, "MAMMA MIA!"
# Above example shows that we need that type of variable factor has to either int or ... |
def ordinal(number: int) -> str:
"""
>>> ordinal(5)
'5th'
>>> ordinal(151)
'151st'
"""
if number < 20:
if number == 1:
pripona = 'st'
elif number == 2:
pripona = 'nd'
elif number == 3:
pripona = 'rd'
else:
pripon... |
def conn_string_with_embedded_password(conn_string_password):
"""
A mock connection string with the `conn_string_password` fixture embedded.
"""
return f"redshift+psycopg2://no_user:{conn_string_password}@111.11.1.1:1111/foo" |
def get_pseudo_id_code_number(pseudo_ids):
"""
:param self:
:param pseudo_ids:
:return: pseudo_id prefix
pseudo_id number
"""
if len(pseudo_ids) == 0:
return None, 0
elif pseudo_ids[-1] and '-' in pseudo_ids[-1]:
prefix, znumber_str = pseudo_ids[-1].split('-')
... |
def _reGlue(words):
"""Helper function to turn a list of words into a string"""
ret = ""
for i in range(len(words)):
ret += words[i] + " "
ret = ret.strip()
return ret |
def longest(s1, s2):
"""This function takes two strings and gives you a string of the unique letters from each string."""
x = s1 + s2
y = (''.join(set(x)))
z = sorted(y)
return ''.join(z) |
def ezip(*args):
"""
Eager version of the builtin zip function.
This provides the same functionality as python2 zip.
Note this is inefficient and should only be used when prototyping and
debugging.
"""
return list(zip(*args)) |
def int_to_bin_string(x, bits_for_element):
"""
Convert an integer to a binary string and put initial padding
to make it long bits_for_element
x: integer
bit_for_element: bit length of machine words
Returns:
string
"""
encoded_text = "{0:b}".format(x)
len_bin = len(... |
def reverse_ordering(ordering_tuple):
"""
Given an order_by tuple such as `('-created', 'uuid')` reverse the
ordering and return a new tuple, eg. `('created', '-uuid')`.
"""
def invert(x):
return x[1:] if (x.startswith('-')) else '-' + x
return tuple([invert(item) for item in ordering_t... |
def get_class_name_value(obj):
"""
Returns object class name from LLDB value.
It returns type name without asterisk or ampersand.
:param lldb.SBValue obj: LLDB value object.
:return: Object class name from LLDB value.
:rtype: str | None
"""
if obj is None:
return None
t = ... |
def compare_multiset_states(s1, s2):
"""compare for equality two instances of multiset partition states
This is useful for comparing different versions of the algorithm
to verify correctness."""
# Comparison is physical, the only use of semantics is to ignore
# trash off the top of the stack.
f... |
def lr_decay(N, step, learning_rate):
"""
learning rate decay
Args:
learning_rate: base learning rate
step: current iteration number
N: total number of iterations over which learning rate is decayed
"""
min_lr = 0.00001
res = learning_rate * ((N - step) / N) ** 2
retu... |
def find_matching_peering(from_cluster, to_cluster, desired_provider):
"""
Ensures there is a matching peering with the desired provider type
going from the destination (to) cluster back to this one (from)
"""
peering_info = to_cluster['peering']
peer_connections = peering_info['connections']
... |
def rectangles_circum(n: int):
"""Return `n` fixed circumference rectangles, w + h = n"""
output = list()
for i in range(1, n + 1):
output.append((i, n - i + 1))
output.sort(key=lambda x: x[1], reverse=True)
return output |
def check_criteria(header):
"""Check file if we want the file
Parameters
----------
header : fits header object
from astropy.io.fits.open function
Returns
-------
Bool
True or False
"""
image_list = ['sky', 'object']
try:
if header['... |
def scale_to_range(value, min_value, max_value):
""" Convert 0-1 value to value between min_value and max_value (inclusive) """
scaled_value = min_value + int(value * (max_value - min_value + 1))
return scaled_value if scaled_value <= max_value else max_value |
def convert_kelvin_to_rankine(temp):
"""Convert the temperature from Kelvin to Rankine scale.
:param float temp: The temperature in degrees Kelvin.
:returns: The temperature in degrees Rankine.
:rtype: float
"""
return (temp * 9) / 5 |
def make_key_constant(key):
"""
Convert a key into an C enum value constant label.
"""
return 'k' + str(key) |
def decimal_to_hex(number):
"""
Calculates the hex of the given decimal number.
:param number: decimal number in string or integer format
:return string of the equivalent hex number
"""
if isinstance(number, str):
number = int(number)
hexadec = []
hex_equivalents = {... |
def box(text1, text2=''):
"""Create an HTML box of text"""
raw_html = '<div align=left style="padding:8px;font-size:28px;margin-top:5px;margin-bottom:5px">' + text1 + '<span style="color:red">' + text2 + '</div>'
return raw_html |
def is_str(object):
"""RETURN : True/False """
return isinstance(object, str) |
def hard_decision(y):
"""
Hard decision of a log-likelihood.
"""
if y >= 0:
return 0
else:
return 1 |
def get_success_builds(builds):
"""Get number of success builds."""
return [b for b in builds if b["result"] == "SUCCESS"] |
def is_string(s):
"""
Portable function to answer whether a variable is a string.
Parameters
----------
s : object
An object that is potentially a string
Returns
-------
isstring : bool
A boolean decision on whether ``s`` is a string or not
"""
return isinstance... |
def get_AQI_level(value):
"""calculate AQI
:param value:
:return: string
"""
if 50 >= value >= 0:
return "Good"
elif 100 >= value >= 51:
return "Moderate"
elif 150 >= value >= 101:
return "Unhealthy for Sensitive Groups"
elif 200 >= value >= 151:
return "... |
def _create_axis(axis_type, variation="Linear", title=None):
"""
Creates a 2d or 3d axis.
:params axis_type: 2d or 3d axis
:params variation: axis type (log, line, linear, etc)
:parmas title: axis title
:returns: plotly axis dictionnary
"""
if axis_type not in ["3d", "2d"]:
retu... |
def baseNumbers(seq):
"""
Counts the number of each base in the string. Currently only accepts g,c,a,t bases.
Input
seq = string of valid DNA bases
Output
storage = dict with lowercase base letters as keys and count of each in seq as values.
"""
# Expects a string
# Returns a dict with the counts for each ... |
def isBalanced(s):
"""
Checks if a string has balanced parentheses. This method can be easily extended to
include braces, curly brackets etc by adding the opening/closing equivalents
in the obvious places.
"""
expr = ''.join([x for x in s if x in '()'])
if len(expr)%2!=0:
return Fals... |
def distance_paris(lat1, lng1, lat2, lng2):
"""
Distance euclidienne approchant la distance de Haversine
(uniquement pour Paris).
@param lat1 lattitude
@param lng1 longitude
@param lat2 lattitude
@param lng2 longitude
@return distance
"""
... |
def exception_class(name):
"""declare exception class"""
return "class {0}(UserError):\n pass".format(name) |
def avg_dicts(dict1, dict2):
"""
merge two dictionaries and avg their values
:param dict1:
:param dict2:
:return:
"""
from collections import Counter
sums = Counter()
counters = Counter()
for itemset in [dict1, dict2]:
sums.update(itemset)
counters.update(itemset.... |
def bin_retweet_count(retweets: float) -> str:
"""Fcn to bin retweet counts via if-else statements, rather than cut()
function, to compare performance of computation in Class 5.
Arguments:
- retweets: number of retweets in millions
Returns:
- categorical variable groupin... |
def cut(value, arg):
"""Removes all values of arg from the given string"""
if arg:
return value.replace(arg, '')
else:
return "#" |
def try_parse_float(possible_float):
"""Try to parse a float."""
try:
return float(possible_float)
except (TypeError, ValueError):
return 0.0 |
def ConvertLotType(aLotType,aIncludePossible):
"""
Returns a list of strings to query LotType on
Keyword arguments:
aLotType -- integer value representing Lot Type -- 0 = both, 1 = Vacant Lot, 2 = Vacant Building
aIncludePossible -- boolean value, if true will include possible vacant lot or possibl... |
def title_case(value):
"""Return the specified string in title case."""
return " ".join(word[0].upper() + word[1:] for word in value.split()) |
def split_polygon(polygon):
"""Split polygon array to string.
:param polygon: list of array describing polygon area e.g.
'[[28.01513671875,-25.77516058680343],[28.855590820312504,-25.567220388070023],
[29.168701171875004,-26.34265280938059]]
:type polygon: list
:returns: A string of polygon e.... |
def best_ss_to_expand_greedy(new_set, supersets, ruleWeights, max_mask):
""" Returns index of the best superset to expand, given the rule
weights and the maximum allowed mask size. -1 if none possible.
"""
bestSuperset = None
bestCost = float('inf')
new_set = set(new_set)
for superset... |
def GMLstring2points(pointstring):
"""Converts the list of points in string (GML) to a list."""
listPoints = []
#-- List of coordinates
coords = pointstring.split()
#-- Store the coordinate tuple
assert(len(coords) % 3 == 0)
for i in range(0, len(coords), 3):
listPoints.append([coord... |
def is_empty (l):
"""
Returns true if the list is empty, false else.
:param l: The list
:type l: dict
:rtype: boolean
"""
return l == { "head" : None, "tail" : None } |
def prob17(limit=1000):
"""
If the numbers 1 to 5 are written out in words: one, two, three, four,
five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out
in words, how many letters would be used?
NOTE: Do n... |
def gray_code_sequence_string(bit_count: int) -> list:
"""
Will output the n-bit grey sequence as a
string of bits
>>> gray_code_sequence_string(2)
['00', '01', '11', '10']
>>> gray_code_sequence_string(1)
['0', '1']
"""
# The approach is a recursive one
# Base case achieved w... |
def get_distance(sigma_phi_1, sigma_phi_2, mean_phi_1, mean_phi_2, phi_1, phi_2):
"""
Returns the "distance" that an object has relative to a specific region in terms of phi_1 and phi_2 considering the standar deviation.
Arguments:
sigma_phi_1 {float} - Standard deviation in phi_1 axis.
sigm... |
def arr_startswith(input_str, match_arr):
"""
Test if string starts with any member of array.
Arguments:
input_str (str): String to check against.
match_arr (list): List of items to check for.
Returns:
True if input_str starts with amy member of match_arr
"""
for item ... |
def validate_new_patient(in_data): # test
"""Validates input to add_new_patient for correct fields
Args:
in_data: dictionary received from POST request
Returns:
boolean: if in_data contains the correct fields
"""
expected_keys = {"patient_id", "attending_email", "patient_age"}
... |
def compare_dataIds(dataIds_1, dataIds_2):
"""Compare two list of dataids.
Return a list of dataIds present in 'raw' or 'eimage' (1) but not in 'calexp' (2).
"""
print("INFO %i input dataIds found" % len(dataIds_1))
print("INFO %i calexp dataIds found" % len(dataIds_2))
dataIds_1 = [{k: v for k... |
def is_int(string):
"""
Check if string is an integer
:param string:
:return: True or false
"""
try:
int(string)
return True
except ValueError:
return False |
def compute_hash(test):
"""
Computes a unique hash for a test
"""
result = ""
for val in test:
result += val
return result |
def get_key_value(obj, key):
"""Get value for a nested key using period separated accessor
:param dict obj: Dict or json-like object
:param str key: Key, can be in the form of 'key.nestedkey'
"""
keys = key.split(".")
if len(keys) == 1:
return obj.get(keys[0])
else:
return ... |
def autocomplete_query(term, orgtype="all"):
"""
Look up an organisation using the first part of the name
"""
doc = {
"suggest": {
"suggest-1": {
"prefix": term,
"completion": {"field": "complete_names", "fuzzy": {"fuzziness": 1}},
}
... |
def to_decimal(num, base, alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
"""Converts a number from some base to decimal.
alphabet: 'digits' that the base system uses"""
using = str(num)[::-1]
res = 0
for i in range(len(using)):
res += alphabet.find(using[i])*base**i
return res |
def flatten(lst):
"""Flatten a 2D array."""
return [item for sublist in lst for item in sublist] |
def _dump_multilinestring(obj, fmt):
"""
Dump a GeoJSON-like MultiLineString object to WKT.
Input parameters and return value are the MULTILINESTRING equivalent to
:func:`_dump_point`.
"""
coords = obj['coordinates']
mlls = 'MULTILINESTRING (%s)'
linestrs = ('(%s)' % ', '.join(' '.join(... |
def get_html_result(params):
"""
Get the result html string of the macro
"""
html_str = """<div> Model succesfully deployed to API designer </div>
<div>Model folder : %s</div>
<div>API service : %s</div>
<div>Endpoint : %s</div>
<a href="https://www.w3schools.com">See Service in API designer</a>
""" % ... |
def longest_increasing_subsequence_optimized2(sequence):
"""
Optimized dynamic programming algorithm for
counting the length of the longest increasing subsequence
using segment tree data structure to achieve better complexity
type sequence: list[int]
rtype: int
"""
length = len(sequence)... |
def remove_non_printable_chars(s):
"""
removes
'ZERO WIDTH SPACE' (U+200B)
'ZERO WIDTH NO-BREAK SPACE' (U+FEFF)
"""
return s.replace(u'\ufeff', '').replace(u'\u200f', '') |
def file_to_string(filename):
""" file contents into a string """
data = ""
try:
with open(filename, 'r') as myfile:
data = myfile.read()
except IOError:
pass
return data |
def wilight_to_hass_hue(value):
"""Convert wilight hue 1..255 to hass 0..360 scale."""
return min(360, round((value * 360) / 255, 3)) |
def is_special_name(word):
""" The name is specific if starts and ends with '__' """
return word.startswith('__') and word.endswith('__') |
def single_element(s, or_else=...):
"""Get the element out of a set of cardinality 1"""
if len(s) == 0:
if or_else is not ...:
return or_else
raise ValueError("Set is empty.")
if len(s) > 1:
set_string = " " + "\n ".join(map(repr, s))
raise ValueError("Se... |
def visit_data_missing(idx,row):
"""
Generate a report indicating which Visit Dates are missing.
"""
error = dict()
if row.get('exclude') != 1:
if row.get('visit_ignore___yes') != 1:
if type(row.get('visit_date')) != str:
error = dict(subject_site_id = idx[0],
... |
def join_s3_uri(bucket, key):
"""
Join AWS S3 URI from bucket and key.
:type bucket: str
:type key: str
:rtype: str
"""
return "s3://{}/{}".format(bucket, key) |
def leap_year(year, calendar='standard'):
"""Determine if year is a leap year
Args:
year (numeric)
"""
leap = False
if ((calendar in ['standard', 'gregorian',
'proleptic_gregorian', 'julian']) and
(year % 4 == 0)):
leap = True
if ((calendar == 'proleptic_greg... |
def _get_y_offset(value, location, side, is_vertical, is_flipped_y):
"""Return an offset along the y axis.
Parameters
----------
value : float
location : {'first', 'last', 'inner', 'outer'}
side : {'first', 'last'}
is_vertical : bool
is_flipped_y : bool
Returns
-------
floa... |
def has_filtering_tag(task):
"""
Indicates if an Asana task has the opt-out tag
"""
for tag in task["tags"]:
if tag["name"] == "roadmap_ignore":
return False
return True |
def irb_decay_to_gate_infidelity(irb_decay, rb_decay, dim):
"""
Eq. 4 of [IRB], which provides an estimate of the infidelity of the interleaved gate,
given both the observed interleaved and standard decay parameters.
:param irb_decay: Observed decay parameter in irb experiment with desired gate interle... |
def format_time(time_us):
"""Defines how to format time in torch profiler Event.
"""
US_IN_SECOND = 1000.0 * 1000.0
US_IN_MS = 1000.0
if time_us >= US_IN_SECOND:
return '{:.3f}s'.format(time_us / US_IN_SECOND)
if time_us >= US_IN_MS:
return '{:.3f}ms'.format(time_us / US_IN_MS)
... |
def info_to_context(info):
"""
Convert a CMGroup's ``info`` into a context for HTML templating.
Use some sensible defaults for ordering items.
"""
top_keys = ['notes', 'method_doc', 'sql']
more_keys = [key for key in info.keys() if key not in top_keys]
ordered_keys = top_keys + sorted(more_... |
def _how(how):
"""Helper function to return the correct resampler
Args:
how:
"""
if how.lower() == "average":
return "mean"
elif how.lower() == "linear":
return "interpolate"
elif how.lower() == "no":
return "max"
else:
return "max" |
def rotate(scale, n):
""" Left-rotate a scale by n positions. """
return scale[n:] + scale[:n] |
def nearby_cells(number_of_rows, number_of_columns, index: tuple):
""""
Receives the size of the diagram and an index and returns the cells that are close to it.
"""
row_index = index[0]
column_index = index[1]
is_upper_vertical_edge = row_index == 0
is_lower_vertical_edge = row_index =... |
def number_to_name(number):
"""
Converts an integer called number to a string.
Otherwise, it sends an error message letting you know that
an invalid choice was made.
"""
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
... |
def bash(cmd):
"""
Run a bash-specific command
:param cmd: the command to run
:return: 0 if successful
:raises
CalledProcessError: raised when command has a non-zero result
Note: On Windows, bash and the gcloud SDK binaries (e.g. bq, gsutil) must be in PATH
"""
import subprocess
... |
def strpos(string, search_val, offset = 0):
"""
Returns the position of `search_val` in `string`, or False if it doesn't exist. If `offset` is defined, will start looking if `search_val` exists after the `offset`.
"""
try:
return string[offset:].index(search_val) + offset
except ValueError:... |
def ek_R56Q(cell):
"""
Returns the R56Q reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -96.0,
2: -95.0,
3: -90.5,
4: -94.5,
5: -94.5,
6: -101.0
}
return reversal_potentials[cell] |
def create_delete_marker_msg(id):
""" Creates a delete marker message.
Marker with the given id will be delete, -1 deletes all markers
Args:
id (int): Identifier of the marker
Returns:
dict: JSON message to be emitted as socketio event
"""
return {'id': id} |
def choice(value, choices):
"""OpenEmbedded 'choice' type
Acts as a multiple choice for the user. To use this, set the variable
type flag to 'choice', and set the 'choices' flag to a space separated
list of valid values."""
if not isinstance(value, str):
raise TypeError("choice accepts a s... |
def button_string(channel, function):
"""Returns the string representation of an Extended Mode button."""
return 'CH{:s}_{:s}'.format(channel, function) |
def is_circular_pattern(digit: int):
"""
Circular primes:
2, 3, 5, 7, 13, 17, 37, 79,
113, 197, 199, 337, 1193, 3779,
11939, 19937, 193939, 199933
:param digit:
:return:
"""
pattern = '1379'
if len(str(digit)) > 1:
for d in str(digit):
if d not in pattern:... |
def avg_relative_error(ground_truth, predictions):
"""calculate the relative error between ground truth and predictions
Args:
ground_truth (dict): the ground truth, with keys and values
predictions (dict): the predictions, with keys and values
Returns:
float: the average relative e... |
def user_from_face_id(face_id: str) -> str:
"""Returns the name from a face ID."""
return face_id.split("_")[0].capitalize() |
def get_container_links(name):
"""retrieve the links relevant to the container to get various input arguments, etc."""
api_links = {
"args": "/api/container/args/%s" % (name),
"selflink": "/api/container/%s" % (name),
"labels": "/api/container/labels/%s" % (name),
}
actions = {"... |
def sad_merge_segments(segments):
"""For SAD, segments given a single speaker label (SPEECH) and overlapping segments are merged."""
prev_beg, prev_end = 0.0, 0.0
smoothed_segments = []
for seg in segments:
beg, end = seg[0], seg[2]
if beg > prev_beg and end < prev_end:
conti... |
def splitList(listToSplit, num_sublists=1):
"""
Function that splits a list into a given number of sublists
Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half
"""
length = len(listToSplit)
return [
listToSplit[i * length // num_sublists : (i... |
def convert_name(name):
""" Convert a python distribution name into a rez-safe package name."""
return name.replace('-', '_') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.