content stringlengths 42 6.51k |
|---|
def eval_poly(coeff,x):
"""
Evaluate polynomial represented as integer coefficients at x in linear time.
Test f(x)=4x^3+3x^2+2x+1, f(1)=10
>>> abs(eval_poly([1,2,3,4],1.0)-10) < 1e-7
True
Test f(x)=4x^3+2x, f(2)=36
>>> abs(eval_poly([0,2,0,4],2.0)-36) < 1e-7
True
"""
sum = coef... |
def _isInt(argstr):
""" Returns True if and only if the given string represents an integer. """
try:
int(argstr, 0) # hex values must have the "0x" prefix for this to work
return True
except (ValueError, TypeError):
return False |
def get_int_pos(x, l, i):
"""
index from base 1
:param x:
:param l:
:param i:
:return:
"""
return x % (10 ** (l - i + 1)) // 10 ** (l - i) |
def range_bind(min_value, max_value, value):
""" binds number to a type and range """
if value not in range(min_value, max_value + 1):
value = min(value, max_value)
value = max(min_value, value)
return int(value) |
def dump_uint_b_into(n, width, buffer, offset=0):
"""
Serializes fixed size integer to the buffer
:param n:
:param width:
:return:
"""
for idx in range(width):
buffer[idx + offset] = n & 0xff
n >>= 8
return buffer |
def generate_bigrams(text):
"""Tokenizes normalized license text into a list of bigrams.
Arguments:
text {string} -- text is the license text of the license.
Returns:
list -- A list of bigrams formed from the normalized license text.
"""
# Break the sentence into tokens as well as ... |
def md_convert(val):
"""Try to convert raw metadata values from text to integer, then float if that fails"""
try:
return int(val)
except (ValueError, TypeError):
try:
return float(val)
except (ValueError, TypeError):
if val.lower() == 'n/a':
re... |
def _convert_write_result(operation, command, result):
"""Convert a legacy write result to write command format."""
# Based on _merge_legacy from bulk.py
affected = result.get("n", 0)
res = {"ok": 1, "n": affected}
errmsg = result.get("errmsg", result.get("err", ""))
if errmsg:
# The wr... |
def FormatBytes(p_message):
"""Print all the bytes of a message as hex bytes.
"""
l_len = len(p_message)
l_message = ''
if l_len == 0:
l_message = "<NONE>"
else:
for l_x in range(l_len):
try:
l_message += " {:#04x}".format(int(p_message[l_x]))
... |
def safe_string(value):
"""
Coerce a type to string as long as it isn't None
"""
if value is None or isinstance(value, bool):
return value
else:
return str(value) |
def get_implementation_files_size_data(sources_dir, implementation_files_by_size, rows_count):
"""
Builds table rows list containing data about implementation files sizes (largest/smallest).
:param sources_dir: configured sources directory
:param implementation_files_by_size: list of implementation fil... |
def NormalizeCounter(counter):
"""Returns a normalized version of the dictionary `counter`.
Does not modify `counter`.
Returns:
A new dictionary, in which every value in `counter`
has been divided by the total to sum up to 1.
"""
total = sum(counter.values())
return {key: counter[key] / total for ... |
def attendance_object_factory(meeting_id, person_id):
"""Cook up a fake attendance json object from given ids."""
attendance = {
'meetingId': meeting_id,
'personId': person_id
}
return attendance |
def is_similar_mag(a, b, small=1E-5):
"""
Evaluates similar magnitudes to within small.
"""
return abs(abs(a)-abs(b)) <= small |
def sig_cmp(u, v, O):
"""
Compare two signatures by extending the term order to K[X]^n.
u < v iff
- the index of v is greater than the index of u
or
- the index of v is equal to the index of u and u[0] < v[0] w.r.t. O
u > v otherwise
"""
if u[1] > v[1]:
return -1
... |
def midpoint(point_1=None, point_2=None):
"""
Calculate a new coordinate pair between two points
:param point_1: coordinate pair
:param point_2: coordinate pair
:returns: coordinate pair midway between the parameter points or False
:raises TypeError: none
"""
if point_1 and poi... |
def _make_list_default(value, defval):
"""
Converts value into a list and uses default if the value is not passed.
:param value: a single value (that will be converted into a list with one item) or a list or tuple of values
:param defval: the default that is used if value is empty
:return: list ... |
def mcb(l, bit, mlb, tiebreaker = "1"):
"""
l = list of bits, e.g. ["00100", "11110", "10110"]
bit = index of the bit to consider, integer
mlb = most ("1") or least ("0") bit
tiebreaker = if there's an even split, default to this value.
returns the most common occurrencs, subjec... |
def generic_cmp(x,y):
"""
Compare x and y and return -1, 0, or 1.
This is similar to x.__cmp__(y), but works even in some cases
when a .__cmp__ method isn't defined.
"""
if x<y:
return -1
elif x==y:
return 0
return 1 |
def is_valid_bucket_name(name):
"""
Checks if an S3 bucket name is valid according to https://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html#bucketnamingrules
"""
# Bucket names must be at least 3 and no more than 63 characters long.
if (len(name) < 3 or len(name) > 63):
ret... |
def RGBToHSB(r, g, b):
"""Converts three color channels of the RGB color model to the HSB color model and returns the corresponding result."""
maxv, minv = max(r, g, b), min(r, g, b)
if maxv == minv:
return 0, maxv == 0 and 0 or (1 - minv / maxv), maxv / 255
elif maxv == r and g >= b:
... |
def flatten_list(input_list):
"""Flattens a nested list.
Args:
input_list: A (possibly) nested list.
Returns:
A flattened list, preserving order.
"""
if not input_list:
return []
if isinstance(input_list[0], list):
return flatten_list(input_list[0]) + flatten_lis... |
def filter_by_word(lines, word_index, expected_word):
"""Exclude all lines without that word at that index
>>> lines = [['one', 'two', 'three'], ['four', 'five']]
>>> filter_by_word(lines, 1, 'five') == [['four', 'five']]
True
"""
return [l for l in lines if l and l[word_index] == expected_word... |
def reconstructTypeFunctionType(typeFunction, args, kwargs):
"""Reconstruct a type from the values returned by 'isTypeFunctionType'"""
#note that our 'key' objects are dict-in-tuple-form, because dicts are
#not hashable. So to keyword-call with them, we have to convert back to a dict...
return typeFunc... |
def approx_equal(x,y,tol):
""" approx_equal(x,y,tol) tests whether or not x==y to within tolerance tol
"""
return (abs(y-x) <= tol) |
def __reference_type(typestr, is_reference):
"""Adapt the type string depending on whether it is used as a reference.
Arguments:
typestr -- the type string to be modified
is_reference -- boolean defining usage as reference (or not)
Returns:
the adapted type string"""
if is_refer... |
def changeColorEvent(r, g, b, dataset, oldColors):
"""Callback to set new color values.
Positional arguments:
r -- Red value.
g -- Green value.
b -- Blue value.
dataset -- Currently selected dataset.
oldColors -- Previous colors in case none values are provided for r/g/b.
"""
if r =... |
def year_intervals(years_list):
""" Find the coverage of an ordered list of years"""
years_list = list(map(int, years_list))
years_list.sort()
n = len(years_list)
start_y = list()
end_y = list()
start_y.append(years_list[0])
if n > 1:
for i in range(n-1):
if(yea... |
def comma_separated_string_list(string_list):
"""
Formats a list of strings into a single string, with each element properly separated.
Arguments:
string_list (list): A list of strings to be formatted.
Returns:
formatted_string (string): The resulting formatted string.
"""
... |
def kmp(m_str, s_str) -> int:
"""
The string matching algorithms
:param m_str: main string
:param s_str: pattern string
:return: matching location or -1 if there is no matching
"""
next_ls = [-1] * len(s_str)
m = 1
s = 0
next_ls[0] = -1
while m < len(s_str) - 1:
if s... |
def sort_by_camera_view(a, idx):
"""Sort an array by camera view"""
return sorted(a, key=lambda t: int(t[idx].split("-")[0])*1000+int(t[idx].split("-")[1])) |
def DEFAULT_H_COLORS_DARK(c):
"""Make new dictionary, in case the calling function wants to change value."""
return dict(
textFill='lightest%d'%c, fill='black',
textFillDiap='darkest%d'%c, fillDiap='white',
textLink='lighter%d'%c, textHover='light%d'%c,
textLinkDiap='darkest%d'%c... |
def chebNorm(x, xmin, xmax):
"""Normalization [xmin,xmax] to [-1,1]"""
return ( 2*x - (xmax+xmin) ) / (xmax-xmin) |
def index(sequence, i):
"""
returns the ith element in the sequence, otherwise returns an empty string
:param sequence:
:param i:
:return:
"""
try:
return sequence[i]
except IndexError:
return u"" |
def count_group_matches(v, prefix, suffix):
"""Counts reluctant substring matches between prefix and suffix.
Equivalent to the number of regular expression matches "prefix.+?suffix"
in the string v.
"""
count = 0
idx = 0
for i in range(0, len(v)):
if idx > i:
continue
... |
def get_human_readable_size(size, precision=0):
"""Convert n bytes into a human readable string based on format.
Arguments:
size {float} -- File size
Keyword Arguments:
precision {int} -- Number of digits after the decimal point.
(default: {2})
Returns:
str -- Size byt... |
def ytb_atom(user):
"""Return the url for the atom format."""
return "http://gdata.youtube.com/feeds/base/users/{0}/uploads".format(user) |
def choose(n,k):
"""Binomial coefficient"""
if n < k:
raise Exception("n cannot be less than k")
if k < 0:
raise Exception("k must be nonnegative")
# Calculate the numerator and denominator seperately in order to avoid loss
# of precision for large numbers.
N = 1
D =... |
def find_dep_dict(graph, locktable):
"""
returns set containing number of transactions dependent on corresponding transaction
read operations do not depend on other read operations
"""
dep_dict = {}
for transaction in graph:
items = graph[transaction]
variables = []
for item in items:
variables.append(it... |
def get_pF(a_F, ecc_F):
"""
Computes the orbital parameter (semi-latus) rectum of the fundamental
ellipse. This value is kept constant for all the problem as long as the
boundary conditions are not changed.
Parameters
----------
a_F: float
Semi-major axis of the fundamental ellipse.... |
def reorder_exons(exon_ids):
"""
Reorder exons if they were out of order.
Parameters:
exon_ids (list of str): List of exons 'chrom_coord1_coord2_strand_exon'
Returns:
exons (list of str): List of same exon IDs ordered based on strand
and genomic location
"""
strand = exon_ids[0].split('_')[-2]
coords = ... |
def convert_date(date):
"""
Convert date of form MM/DD/YYYY into YYYY-MM-DD. Assumes date is correct
form.
"""
mdy = date.split("/")
m = mdy[0]
d = mdy[1]
y = mdy[2]
newDate = "%s-%s-%s" % (y, m, d)
return newDate |
def find_smallest(arr):
"""Return the address of the smallest element in an array.
Args:
arr: a Python iterable
Returns:
int: index of the smallest element
"""
# Store the first element and assume it's the smallest
smallest = arr[0]
smallest_index = 0
# Loop over every ... |
def simulationTimeLine(simTimeInFs):
"""
Scales simulation time and returns line including units.
"""
if simTimeInFs > 1.0E27:
# years
simTime = "%.3f years" % ((simTimeInFs / 1.0E15) / 31557600.0,)
elif simTimeInFs > 1.0E24:
# days
simTime = "%.3f days" % (... |
def build_pairwise_indicies(target_indicies, debug_print=False):
""" Builds pairs of indicies from a simple list of indicies, for use in computing pairwise operations.
Example:
target_indicies = np.arange(5) # [0, 1, 2, 3, 4]
out_pair_indicies = build_pairwise_indicies(target_indicies)
... |
def pairs(ar):
"""Solution by the_Hamster in CodeWars best practices."""
count = 0
for i in range(0, len(ar), 2):
try:
a, b = ar[i], ar[i + 1]
except IndexError:
return count
if abs(a - b) == 1:
count += 1
return count |
def _find_sis_from_backselect(backselect_stack, threshold):
"""Constructs SIS using result of backward selection.
Implements the FindSIS procedure in the SIS paper [1].
Args:
backselect_stack: List containing (idx, value) tuples, where idx identifies
a position masked during backward selecti... |
def check_i(i):
"""simply skips the urls without a comic or that the comic isn't an image"""
if i == 404:
# this one took me a while to figure out
# turns out he skipped 404 for 'obvious reasons'
return False
if i == 1350 or i == 1608 or i == 2198:
print("Visit https://xkcd.c... |
def sortPeaksByLength(peaks):
"""
Sort peaks from longer to shoter.
"""
#sort peaks according to size, from small to big
peaks = sorted( peaks, key=lambda peak: peak.length )
return peaks |
def _sort_list_float(elem):
"""Get the first element of the array as float. for sorting.
Args:
elem: The 2d list
Returns:
The a float value of the first list element.
"""
return float(elem[0]) |
def split_cond(f, iterable):
"""
Splits a list based on a condition
Eg. with f = lambda x: x < 5
[1, 9, 9, 1, 9, 1] => [[1, 9, 9], [1, 9], [1]]
[1] => [[1]]
[9] => []
"""
split_point = [i for i, e in enumerate(iterable) if f(e)]
split_point += [len(iterable)]
return [... |
def counter(items):
"""
Simplest required implementation of collections.Counter. Required as 2.6
does not have Counter in collections.
"""
results = {}
for item in items:
results[item] = results.get(item, 0) + 1
return results |
def calc(a, b, op):
"""
Returns a string like this: a op b = c
where c is the computed value according to the opeartor
"""
if op not in '+-/*':
return 'Please only type one of these characters: "+, -, *, /"!'
if op == '+':
return(str(a) + ' ' + op + ' ' + str(b) + ' = ' + str(a... |
def replacement_traverse(obj, opts, replace):
"""clone the given expression structure, allowing element
replacement by a given replacement function."""
cloned = {}
stop_on = set([id(x) for x in opts.get('stop_on', [])])
def clone(elem, **kw):
if id(elem) in stop_on or \
'no_rep... |
def to_erd_type(pg_type, modifier):
"""Map from postgres-style datatypes to ERDplus-style."""
if pg_type == 'int4':
dataType, dataTypeSize = 'int', 4
elif pg_type == 'int8':
dataType, dataTypeSize = 'int', 8
elif pg_type == 'date':
dataType, dataTypeSize = 'date', None
elif p... |
def _parse_int(token, default=0):
"""Returns an integer from a string token.
Returns the default value if the token cannot be converted to int"""
return int(token) if token.isdigit() else default |
def output_aws_credentials(awscreds, awsaccount):
"""
Format the credentials as a string containing the commands to define the ENV variables
"""
aws_access_key_id = awscreds["data"]["access_key"]
aws_secret_access_key = awscreds["data"]["secret_key"]
shellenv_access = "export AWS_ACCESS_KEY_ID=%... |
def _prune(greedy_errors, proj_matrix, num):
"""Prune arrays to have size num."""
return greedy_errors[:num], proj_matrix[:num] |
def _get_padding(K, mode):
""" Helper method to compute padding size """
if mode == 'valid':
return 0
elif mode == 'same':
assert K % 2 == 1, 'Invalid kernel size %d for "same" padding' % K
return (K - 1) // 2 |
def _get_line_element_value(element, line, current_exception):
"""
Given an element to search for in a line of text,
return the element's value if found.
Otherwise, raise the appropriate exception.
"""
if element in line:
return line[line.rfind('>')+1:]
else:
raise current_ex... |
def check_categorical_values(observation):
"""
Validates that all categorical fields are in the observation and values are valid
Returns:
- assertion value: True if all provided categorical columns contain valid values,
False otherwise
- error mes... |
def getNpsCategory(npsNum):
"""
Return: {string} The user category (detractor/passive/promoter) of the given NPS rating.
"""
if npsNum < 7:
return 'detractor'
elif npsNum < 9:
return 'passive'
else:
return 'promoter' |
def aliquot_sum(number: int) -> int:
"""
Calculate aliquot sum of a number.
:param number: the number.
:return: aliquot sum of given number.
>>> aliquot_sum(1)
0
>>> aliquot_sum(2)
1
>>> aliquot_sum(3)
1
>>> aliquot_sum(15)
9
>>> aliquot_sum(21)
11
>>> aliquot... |
def get_main_package_name(module_name):
"""
gets the main package name from given module name.
for example for `pyrin.database.manager` module, it
returns `pyrin` as the main package name.
:param str module_name: module name to get its root package name.
:rtype: str
"""
return module... |
def isiterable(obj):
"""
Test if object is iterable.
Python str, list, dict, and tuple are all builtin iterable types.
Parameters:
obj Some pythonic object.
name String name of a parent class to test.
Returns
True or False.
"""
try:
_ = (e for e in obj)
return True
except TypeE... |
def is_number(s):
"""
:param s:
:return:
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False |
def BitGet(n, N, pos):
"""Gets bit value at position pos from the left of the length-N bit-representation of n"""
return (n >> (N-1-pos) & 1) |
def secant(f,x0,x1, TOL=0.001, NMAX=100):
"""
Takes a function f, start values [x0,x1], tolerance value(optional) TOL and
max number of iterations(optional) NMAX and returns the root of the equation
using the secant method.
"""
n=1
while n<=NMAX:
x2 = x1 - f(x1)*((x1-x0)/(f(x0)-f(x1)... |
def _dataset_record_label(scanjob):
""" Return label to be used in dataset record
Args:
scanjob (dict): Scanjob that is used to generate the record label
Returns
String with record label
"""
default_label = scanjob.get('scantype', 'default')
return scanjob.get('dataset_label', d... |
def score_accuracy(predictions, actuals):
"""Calculate accuracy score of a trained model on a test set.
predictions : iterable<bool>
True for predicted positive class, False otherwise.
actuals : iterable<bool>
True for actual positive class, False otherwise.
"""
t = [pr for pr, act ... |
def loader_encode_pcr8(cmdline):
"""
Encode kernel command line the same way systemd-stub does it before measuring.
"""
return (cmdline + "\0").encode("utf-16le") |
def add_counters(dic, arr):
"""
Keep track of how many times a type of layer has appeard and
append _counter to their name to maintain module name uniqueness.
"""
ret = []
for el in arr:
name = el[1:-1]
num = dic.get(name, None)
if num is not None:
ret.append(... |
def sentencize(s):
"""Extract first sentence
"""
s = s.replace('\n', ' ').strip().split('.')
s = s[0] if len(s) else s
try:
return " ".join(s.split())
except AttributeError:
return s |
def create_test_edges(count):
"""Produce some test edges."""
def doc(i):
return '{"_from": "test_vertex/%s", "_to": "test_vertex/%s"}' % (i, i)
return '\n'.join(doc(i) for i in range(0, count)) |
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for ea... |
def generalized_golden_ratio(dim):
"""
Using nested radical formula to calculate generalized golden ratio.
Args:
dim (int):
The number of dimension the ratio is to be used in.
Returns:
(float):
The generalize golden ratio for dimension `dim`.
Examples:
... |
def getParentNames(person, population):
"""
retrieves a persons parent names from the population dictionary if they exist
returns either None or a new dictionary
"""
parents = {}
for name, data in population.items():
if(name == person):
motherName = data["mother"]
... |
def input_data(side1: float, side2: float, side3: float, accuracy: float):
""" Input data from user
>>> input_data(10, 10, 12, 2)
(10, 10, 12, 2)
"""
return side1, side2, side3, accuracy |
def recursive_attach_unit_strings(smirnoff_data, units_to_attach):
"""
Recursively traverse a SMIRNOFF data structure, appending "* {unit}" to values in key:value pairs
where "key_unit":"unit_string" is present at a higher level in the hierarchy.
This function expects all items in smirnoff_data to be fo... |
def get_variable(variables, variable_key):
"""Returns variable from given variables list.
Args:
variables (list): List of variables, whether in campaigns or
inside variation
variable_key (string): Variable identifier
Returns:
dict: Variable corresponding to variable_key in ... |
def success_dict(key_name: str, data: object):
"""Return a success dictionary containing response data"""
data_dict = {key_name: data}
return {"status": "success", "data": data_dict} |
def get_username_from_summary(summary):
"""
If the summary string ends with `@someone`, return `someone`
"""
lastword = summary.rsplit(None, 1)[-1]
if lastword[0] == '@':
return summary[:-len(lastword)-1], lastword[1:]
return summary, None |
def insertion_sort(my_list):
"""
Sort a list out
:param my_list: a list of integers
:return: crescent sorted list
"""
n = len(my_list)
for i in range(1, n):
value = my_list[i]
j = i
while j > 0 and my_list[j - 1] > value:
my_list[j] = my_list[j - 1]
... |
def F(m):
"""
Write a function that compute Fibbo number at index m.
"""
large, small = 1, 0
# dynamically update the two variables
for i in range(m):
large, small = large + small, large
return small |
def link_format(name, url):
"""make markdown link format string
"""
return "[" + name + "]" + "(" + url + ")" |
def letter_prob(c):
""" if c is the space character (' ') or an alphabetic character,
returns c's monogram probability (for English);
returns 1.0 for any other character.
adapted from:
http://www.cs.chalmers.se/Cs/Grundutb/Kurser/krypto/en_stat.html
"""
# check to ensure that... |
def slashescape(err):
""" codecs error handler. err is UnicodeDecode instance. return
a tuple with a replacement for the unencodable part of the input
and a position where encoding should continue"""
#print err, dir(err), err.start, err.end, err.object[:err.start]
thebyte = err.object[err.start:err.... |
def do_boost(p,boost):
"""
do_boost: function for a fake gaussian distribution
to create a smeared (bigger) footprint
input:
p : value to boost
boost: # to chose width of boost
output:
P: list() with boosted p values
"""
P = list()
if int(b... |
def nolast(l):
"""
Returns a collection without its last element.
Examples
--------
>>> nolast([0, 1, 2])
[0, 1]
>>> nolast([])
[]
"""
return l[:-1] |
def collatz(n):
"""Cuenta las veces que se itera hasta llegar a 1.
Pre: n debe ser un numero entero.
Post: Devuelve un numero natural de las repeticiones.
"""
res = 1
while n!=1:
if n % 2 == 0:
n = n//2
else:
n = 3 * n + 1
res += 1
return res |
def getLOL(objects, objects_per_row=3):
"""Returns a list of list of the passed objects with passed objects per
row.
"""
result = []
row = []
for i, object in enumerate(objects):
row.append(object)
if (i + 1) % objects_per_row == 0:
result.append(row)
row ... |
def align_tokens(tokens, sentence):
"""
This module attempt to find the offsets of the tokens in *s*, as a sequence
of ``(start, end)`` tuples, given the tokens and also the source string.
>>> from nltk.tokenize import TreebankWordTokenizer
>>> from nltk.tokenize.util import align_tokens
... |
def get_marital_status(x):
""" returns the int value for the nominal value marital-status
"""
if x == 'Never-married':
return 1
elif x == 'Married-civ-spouse':
return 2
elif x == 'Divorced':
return 3
elif x == 'Married-spouse-absent':
return 4
elif x == 'Widow... |
def _suffix_from_bnum(band_number):
"""Get file suffix from band number."""
if band_number in (61, 62):
return 'B' + str(band_number)[0] + '_VCID_' + str(band_number)[1]
return 'B' + str(band_number) |
def combine_copy_options(copy_options):
""" Returns the ``copy_options`` attribute with spaces in between and as
a string.
Parameters
----------
copy_options : list
copy options which is to be converted into a single string with spaces
inbetween.
Returns
-------
str:
... |
def fold(init, op, *args):
"""Apply operator function op on all arguments and return sum result. Very strange and confusing."""
result = init
for arg in args:
result = op(result, arg)
return result |
def list_inventory(inventory):
"""
:param inventory: dict - an inventory dictionary.
:return: list of tuples - list of key, value pairs from the inventory dictionary.
"""
return [(item, quantity) for item, quantity in inventory.items() if quantity] |
def computeDrawingArea(windowWidth, windowHeight, imageWidth, imageHeight):
""" Determine how to draw the image at the center of the window as large as
possible and without cropping. Returns (x, y, width, height) of the
computed area.
"""
if windowWidth * imageHeight > windowHeight * imageWi... |
def RGBtoHEX(R, G, B):
""" convert RGB to HEX color
:param R: red value (0;255)
:param G: green value (0;255)
:param B: blue value (0;255)
:return: HEX color string """
rgb = tuple(int(i) for i in (R, G, B))
return '#%02x%02x%02x' % rgb |
def diff(a: str, b: str, a_name: str, b_name: str) -> str:
"""Return a unified diff string between strings `a` and `b`."""
import difflib
a_lines = [line for line in a.splitlines(keepends=True)]
b_lines = [line for line in b.splitlines(keepends=True)]
diff_lines = []
for line in difflib.unified... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.