content stringlengths 42 6.51k |
|---|
def closest_color(rgb, colors):
"""
Determine the closest color in `colors` to `rgb`.
WARNING: this function is *destructive*. It removes the result from the input
`colors` list. This is to prevent overlapping colors in the color assignment below
(starting line 263). It is recommended to pass a copied list to this function if you
wish to protect the original list.
Parameters
----------
rgb : tuple[int]
An RGB color.
colors : list[tuple[int]]
Returns
-------
tuple[int]
An RGB color.
"""
r, g, b = rgb
color_diffs = []
for color in colors:
cr, cg, cb = color
color_diff = (abs(r - cr) ** 2 + abs(g - cg) ** 2 + abs(b - cb) ** 2) ** (1 / 2)
color_diffs.append((color_diff, color))
result = min(color_diffs)[1]
colors.remove(result)
return result |
def get_bit(z, i):
"""
gets the i'th bit of the integer z (0 labels least significant bit)
"""
return (z >> i) & 0x1 |
def table_subset_eq(table1, table2):
"""check whether table1 is subsumed by table2 """
if len(table1) == 0: return True
if len(table2) == 0: return False
schema1 = tuple(sorted(table1[0].keys()))
schema2 = tuple(sorted(table2[0].keys()))
if schema1 != schema2: return False
frozen_table1 = [tuple([t[key] for key in schema1]) for t in table1]
frozen_table2 = [tuple([t[key] for key in schema1]) for t in table2]
for t in frozen_table1:
cnt1 = len([r for r in frozen_table1 if r == t])
cnt2 = len([r for r in frozen_table2 if r == t])
if cnt2 < cnt1:
return False
return True |
def checker(expression):
"""If the expression is true, return the string "checked".
This is useful for checkbox inputs.
"""
if expression:
return "checked"
else:
return None |
def count_bits_set_kernighan(n: int) -> int:
"""
https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan
>>> count_bits_set_kernighan(0b101010101)
5
>>> count_bits_set_kernighan(2 << 63)
1
>>> count_bits_set_kernighan((2 << 63) - 1)
64
"""
c = 0
while n:
n &= n - 1
c += 1
return c |
def theta(T, p, p0=1000.):
"""Calculate (virtual) potential temperature [K], theta, from (virtual)
temperature T [K] and pressure p [mbar] using Poisson's equation.
Standard pressure p0 at sea level is 1000 mbar or hPa.
Typical assumptions for dry air give:
R/cp = (287 J/kg-K) / (1004 J/kg-K) = 0.286
"""
return T * (p0/p)**0.286 |
def adapt_state_dict(to_load, to_receive):
"""
Adapt distributed state dictionaries to non-distributed
"""
iterator = zip(list(to_load.keys()),
list(to_receive.keys()))
for kl, kr in iterator:
if kl != kr:
kl_new = kl.replace('.module', '')
assert kl_new == kr
to_load[kl_new] = to_load.pop(kl)
return to_load |
def areAllStrings(container):
"""Return ``True`` if all items in *container* are instances of
:func:`str`."""
for item in container:
if not isinstance(item, str):
return False
return True |
def validate_comma_seperated_list(input):
"""Split the input string into an array. """
return input.split(',') |
def make_linear_colorscale(colors):
"""
Makes a list of colors into a colorscale-acceptable form
For documentation regarding to the form of the output, see
https://plot.ly/python/reference/#mesh3d-colorscale
"""
scale = 1.0 / (len(colors) - 1)
return [[i * scale, color] for i, color in enumerate(colors)] |
def get_time_integer(time):
"""Return time as integer value."""
hours, minutes, seconds = time.split(":")
return int(hours) * 3600 + int(minutes) * 60 + int(seconds) |
def bulk_data(json_string, bulk):
"""
Check if json has bulk data/control messages. The string to check are in
format: ``{key : [strings]}``.
If the key/value is found return True else False
:param dict json_string:
:param dict bulk:
:returns: True if found a control message and False if not.
:rtype: bool
"""
for key, value in bulk.items():
if key in json_string.keys():
for line in value:
if json_string.get(key) == line:
return True
return False |
def test_pgm(h, f):
"""PGM (portable graymap)"""
if len(h) >= 3 and \
h[0] == 'P' and h[1] in '25' and h[2] in ' \t\n\r':
return 'pgm' |
def _padboth(width, s):
"""Center string.
>>> _padboth(6, u'\u044f\u0439\u0446\u0430') == u' \u044f\u0439\u0446\u0430 '
True
"""
fmt = u"{0:^%ds}" % width
return fmt.format(s) |
def bitlen(x):
"""returns the length of the binary representation of an integer x >= 0"""
assert x >= 0, "bitlen(x) requires nonegative integer x"
try:
return (int(x)).bit_length()
except: # for python versions < 2.7 or 3.1:
l, m, sh = 0, 0x10000, 16
while x >= m:
#x, l = x>>sh, l+sh
m, sh = m << sh, sh << 1
#assert m == 1 << sh
while sh:
if x >= m: x, l = x>>sh, l+sh
sh >>= 1
m = m >> sh
while x: x, l = x>>1, l+1
return l |
def contains(a, b):
"""
contains
:param a:
:param b:
:return:
"""
return a[0] <= b[0] and \
a[1] <= b[1] and \
b[2] <= a[2] and \
b[3] <= a[3] |
def accuracy(true_y, predicted_y):
"""
This function is used to calculate the accuracy
:param true_y: These are the given values of class variable
:param predicted_y: These are the predicted values of the class variable
:return: the accuracy
"""
accuracy_count = 0
for each in range(len(true_y)):
if true_y[each] == predicted_y[each]:
accuracy_count = accuracy_count + 1
return accuracy_count / float(len(true_y)) |
def to_do(information:dict) -> str:
"""
input: item:dict = {"checked":bool, "test":str}
"""
return f"- {'[x]' if information['checked'] else '[ ]'} {information['text']}" |
def should_minimize(name):
"""
should we minimize or optimize?
:param name:
:return:
"""
return name != 'accuracy' |
def excel_column_number(raw_column_name, index=1):
"""Given a column name, give me the column number
A=1
Z=26
AA=27
AZ=52
BA=53 etc"""
def char_value(c):
return ord(c)-64
value = 0
for char in raw_column_name.upper():
value = value * 26
value = value + char_value(char)
return value - 1 + index |
def split_text_in_three(text, start_line, start_chr, end_line, end_chr):
"""Split the text in three using 2 (line, column) control points."""
lines = text.split("\n")
before = "\n".join(lines[:start_line] + [lines[start_line][:start_chr]])
if start_line == end_line:
excerpt = lines[start_line][start_chr:end_chr]
else:
excerpt = "\n".join(
[lines[start_line][start_chr:]]
+ ["\n".join(lines[start_line + 1 : end_line])]
+ [lines[end_line][:end_chr]]
)
after = "\n".join([lines[end_line][end_chr:]] + lines[end_line + 1 :])
return before, excerpt, after |
def convert_f_to_c(temperature_f):
"""Convert Fahrenheit to Celsius."""
temperature_c = (temperature_f - 32) * (5/9)
return temperature_c |
def is_close(a0, a1, tol=1.0e-4):
"""
Check if two elements are almost equal with a tolerance.
:param a0: number to compare
:param a1: number to compare
:param tol: The absolute tolerance
:return: Returns boolean value if the values are almost equal
"""
return abs(a0 - a1) < tol |
def url_fix_common_typos(url):
"""Fix common typos in given URL like forgotten colon."""
if url.startswith("http//"):
url = "http://" + url[6:]
elif url.startswith("https//"):
url = "https://" + url[7:]
return url |
def is_single_index(slc):
"""Is the slice equivalent to a single index?
"""
if slc.step is None:
step = 1
else:
step = slc.step
return slc.stop is not None and \
slc.start + step >= slc.stop |
def falling_factorial(x: int, n: int) -> int:
"""
Returns the falling factorial of the given number to the given depth.
x(x-1)...(x-(n-1))
:param x: The number to take the falling factorial of
:param n: The depth to which to take the falling factorial
:return: The falling factorial of the given number to the given depth
"""
result = 1
for i in range(n):
result *= x - i
return result |
def is_url(path):
"""
Whether path is URL.
Args:
path (string): URL string or not.
"""
return path.startswith('http://') \
or path.startswith('https://') \
or path.startswith('ppdet://') |
def get_app_url(config):
"""
Returns the application's URL, based on the given config.
"""
return "%s://%s" % (config["PREFERRED_URL_SCHEME"], config["SERVER_HOSTNAME"]) |
def denormalize(coordinate: float, length: int) -> int:
"""Convert a normalized float coordinate between 0 and 1 to a pixel coordinate"""
if not (0 <= coordinate <= 1):
raise ValueError('Coordinate exceeds bounds')
return int(coordinate * length) |
def cutoff(s, length=120):
"""Cuts a given string if it is longer than a given length."""
if length < 5:
raise ValueError('length must be >= 5')
if len(s) <= length:
return s
else:
i = (length - 2) / 2
j = (length - 3) / 2
return s[:i] + '...' + s[-j:] |
def binary_array_to_number(binArr):
"""Given an array of ones and zeroes, convert the equivalent binary value to an integer."""
numArr = "".join(map(str,binArr))
return int(numArr,2) |
def is_year(value: str) -> float:
"""Asserts that a value is plausibly a year."""
try:
year = int(value)
if year > 1600 and year < 2100:
return 1.0
except ValueError as e:
return 0.0
return 0.0 |
def upperstring(input):
"""Custom filter"""
return input.upper() |
def sort_set(set_a):
"""
Sorts set_a
"""
# convert to a list and sort the list.
sort_a = [b for b in set_a]
sort_a.sort()
# Reverse the sort so that most recent (time) is first
sort_a.reverse()
return sort_a |
def _dict_swap_kv(dict_obj):
"""
Swap given dict's key-value pairs.
:param dict_obj: Dict.
:return: New dict with key-value pairs swapped.
"""
# Swap given dict's keys and values
return dict((x[1], x[0]) for x in dict_obj.items()) |
def read_bytes(conn, size):
"""
Read x bytes
:param size: number of bytes to read.
"""
data = bytes()
while len(data) < size:
tmp = conn.recv(size - len(data))
data += tmp
if tmp == '':
raise RuntimeError("socket connection broken")
return data |
def mappings_coincide(map1: dict, map2: dict) -> bool:
"""Returns True if the image of the intersection of the two mappings is
the same, False otherwise. In other words, True if the mappings coincide on
the intersection of their keys."""
intersection = set(map1.keys()) & set(map2.keys())
if any(map1[key] != map2[key] for key in intersection):
return False
return True |
def mod(x, y):
"""Returns the positive remainder of x divided by y"""
# In Python, this function is identical to the remainder operator.
# However, many other languages define remainders differently
assert y > 0
return x % y |
def _ComponentFromDirmd(json_data, subpath):
"""Returns the component for a subpath based on dirmd output.
Returns an empty string if no component can be extracted
Args:
json_data: json object output from dirmd.
subpath: The subpath for the directory being queried, e.g. src/storage'.
"""
# If no component exists for the directory, or if METADATA migration is
# incomplete there will be no component information.
return json_data.get('dirs', {}).get(subpath,
{}).get('monorail',
{}).get('component', '') |
def channel_bytes_to_str(id_bytes):
"""
Args:
id_bytes: bytes representation of channel id
Returns:
string representation of channel id
"""
assert type(id_bytes) in [str, bytes]
if isinstance(id_bytes, str):
return id_bytes
return bytes.hex(id_bytes) |
def mask_bits(n: int, bits: int) -> int:
"""mask out (set to zero) the lower bits from n"""
assert n > 0
return (n >> bits) << bits |
def get_suser(user):
""" str user"""
suser = ''.join(['@{}:{}'.format(*item) for item in user.items()])
return suser |
def rational(x):
""" Returns a decay factor based on the rational function
.. math::
f(x) = 1 / (x+1)
:param x: The function argument.
"""
return 1 / (x + 1) |
def geo_to_str(latitude, longitude, distance):
"""
Return geolocation data as string of comma-separated values.
"""
has_valid_unit = distance.endswith("km") or distance.endswith("mi")
assert has_valid_unit, "Must include units as 'km' or 'mi'."
return ",".join((latitude, longitude, distance)) |
def unit_round_off(t=23):
"""
:param t:
number significand bits
:return:
unit round off based on nearest interpolation, for reference see [1]
"""
return 0.5 * 2. ** (1. - t) |
def is_valid_vlan_id(vlan_id):
"""
check whether vlan_id is in the range of [1,4094]
:param vlan_id: vlan id to validate
:returns: True or False
"""
return True if vlan_id and (vlan_id > 0 and vlan_id < 4095) else False |
def to_csv(s):
"""Split the specified string with respect to a number of delimiter"""
# Remove strange carriage returns (Windows)
s = s.replace('\r', '')
# Replace newline with comma
s = s.replace('\n', ',')
# Replace multiple spaces with a single one
s = ' '.join(s.split())
# Split with respect to comma, semicolon, space, and tab
#s_list = re.split(r'[,;\t ]', s)
return s |
def numerical_sort(string_int_list):
"""Sort list of strings (VLAN IDs) that are digits in numerical order.
"""
as_int_list = []
as_str_list = []
for vlan in string_int_list:
as_int_list.append(int(vlan))
as_int_list.sort()
for vlan in as_int_list:
as_str_list.append(str(vlan))
return as_str_list |
def escape_text(text: str) -> str:
"""The Inception doc is wrong about what it is really escaped
"""
text = text.replace('\\', '\\\\')
text = text.replace('\r', '\\r')
text = text.replace('\t', '\\t')
return text |
def intersectionArea(a, b):
"""
intersect area
:param a:
:param b:
:return:
"""
minX, minY, maxX, maxY = max(a[0], b[0]), max(a[1], b[1]), \
min(a[2], b[2]), min(a[3], b[3])
return max(0, maxX - minX) * max(0, maxY - minY) |
def _infer_numeric_or_str(value: str):
"""Convert value to an int, float or leave it as a string.
:param value: The cli value to parse
:returns: The value converted to int or float if possible
"""
for func in (int, float):
try:
return func(value)
except ValueError:
continue
return value |
def is_sec_compressed(sec):
"""Return a boolean indicating if the sec represents a compressed public key."""
return sec[:1] in (b'\2', b'\3') |
def b(a: float, e: float) -> float:
"""
b = a * a * (1 - e * e)
:param a: semi-major axis
:type a: float
:param e: eccentricity
:return: semi-minor axis
:rtype: float
"""
return a * a * (1 - e * e) |
def upstream_version(version):
"""Extracts upstream version from a version string.
Upstream reference: https://salsa.debian.org/apt-team/apt/blob/master/
apt-pkg/deb/debversion.cc#L259
:param version: Version string
:type version: str
:returns: Upstream version
:rtype: str
"""
if version:
version = version.split(':')[-1]
version = version.split('-')[0]
return version |
def lr_schedule(epoch):
"""
Learning Rate Schedule
"""
# Learning rate is scheduled to be reduced after 80, 120, 160, 180 epochs. Called automatically every
# epoch as part of callbacks during training.
lr = 1e-3
if epoch > 180:
lr *= 1e-4
elif epoch > 160:
lr *= 1e-3
elif epoch > 120:
lr *= 1e-2
elif epoch > 80:
lr *= 1e-1
print('Learning rate: ', lr)
return lr |
def is_number(string):
"""
Test if string is a float.
"""
try:
float(string)
return True
except ValueError:
return False |
def get_hostgroup_flag(code):
"""Get hostgroup flag from code."""
hostgroup_flag = {0: "Plain", 4: "Discover"}
if code in hostgroup_flag:
return hostgroup_flag[code] + " (" + str(code) + ")"
return "Unknown ({})".format(str(code)) |
def _rearrange_result(input_result, length):
"""Turn ``input_result`` from an integer into a bit-string.
Args:
input_result (int): An integer representation of qubit states.
length (int): The total number of bits (for padding, if needed).
Returns:
str: A bit-string representation of ``input_result``.
"""
bin_input = list(bin(input_result)[2:].rjust(length, '0'))
return ''.join(bin_input)[::-1] |
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide) |
def add_url_parameters(url, **parameters):
""" Add url parameters to the base url.
:param url: base url.
:type url: str
:kwargs: key-value pairs of the url parameters to add. If the value is None, the pair is not added.
:return: url string.
:rtype: str
"""
parameters = {k: v for k, v in parameters.items() if v is not None}
if len(parameters) == 0:
return url
parameters = "&".join([f"{k}={v}" for k, v in parameters.items()])
return f"{url}?{parameters}" |
def asbool(value):
"""Convert the given String to a boolean object. Accepted
values are `True` and `1`."""
if value is None:
return False
if isinstance(value, bool):
return value
return value.lower() in ("true", "1") |
def sequence_difference(nth,first_term,term_number):
"""Usage: Find the difference in a sequence"""
return (nth-first_term)/(term_number-1) |
def validar_entrada(string):
"""Recebe uma string e retorna True se ela tiver 1 caractere."""
return len(string) == 1 |
def parse_aws_tags(tags):
"""
When you get the tags on an AWS resource from the API, they are in the form
[{"key": "KEY1", "value": "VALUE1"},
{"key": "KEY2", "value": "VALUE2"},
...]
This function converts them into a Python-style dict().
"""
result = {}
for aws_tag in tags:
assert isinstance(aws_tag, dict)
assert aws_tag.keys() == {"key", "value"}
assert aws_tag["key"] not in result, f"Duplicate key in tags: {aws_tag['key']}"
result[aws_tag["key"]] = aws_tag["value"]
return result |
def even(number):
""" Returns True if number is even """
return number % 2 == 0 |
def _parse_pid(s: bytes) -> int:
"""
123(ab) -> 123
"""
try:
return int(s[:s.index(b'(')])
except ValueError: # '(' not found
try:
return int(s)
except ValueError:
print(s)
assert False |
def is_alpha(char:str)->bool:
"""
Check whether a character is an English alphabet or not
Args:
word (str): [description]
Returns:
Boolean: [description]
"""
try:
return char.encode('ascii').isalpha()
except:
return False |
def digital_prod(n,B=10):
"""Product of the digits of n in base B"""
s = 1
while True:
n,r = divmod(n,B)
s *= r
if n == 0:
return s |
def esc(code: int) -> str:
"""
Converts the integer code to an ANSI escape sequence
:param code: code
:return: escape sequence
"""
return f"\033[{code}m" |
def str2bool(string):
"""Converts a string to a boolean
Parameters:
-----------
string : string
"""
return string.lower() in ("yes", "y", "true", "t", "1") |
def toggle_player(player):
"""
Toggle the player between "X" to "O"
returns player ("X" or "O")
args: toggled player ("X" or "O")
"""
if player == 'X': return 'O'
else: return 'X' |
def getLeastNumbers(nums, k):
"""
https://leetcode-cn.com/problems/zui-xiao-de-kge-shu-lcof/
:param nums:
:param k:
:return:
"""
res = []
for i in nums:
if len(res) == k and res[k - 1] <= i:
continue
index = 0
for ri in res:
if ri >= i:
break
index += 1
if len(res) == k:
res.pop()
res.insert(index, i)
return res |
def accept_path(path, ref_path):
"""
:param path: a logic tree path (list or tuple of strings)
:param ref_path: reference logic tree path
:returns: True if `path` is consistent with `ref_path`, False otherwise
>>> accept_path(['SM2'], ('SM2', 'a3b1'))
False
>>> accept_path(['SM2', '@'], ('SM2', 'a3b1'))
True
>>> accept_path(['@', 'a3b1'], ('SM2', 'a3b1'))
True
>>> accept_path('@@', ('SM2', 'a3b1'))
True
"""
if len(path) != len(ref_path):
return False
for a, b in zip(path, ref_path):
if a != '@' and a != b:
return False
return True |
def _is_positive(integer_string):
"""
Check if a string is a strictly positive integer.
"""
return int(integer_string) > 0 |
def get_var_mode(prefix):
"""Returns False if { in prefix.
``prefix`` -- Prefix for the completion
Variable completion can be done in two ways and completion
depends on which way variable is written. Possible variable
complations are: $ and ${}. In last cursor is between
curly braces.
"""
return False if '{' in prefix else True |
def xor_bytes(a, b):
""" Returns a new byte array with the elements xor'ed. """
return bytes(i^j for i, j in zip(a, b)) |
def score_to_rating_string(score):
"""Take average score and compare to different ratings"""
if 0 <= score < 1:
return "Terrible"
elif 1 <= score < 2:
return "Bad"
elif 2 <= score < 3:
return "OK"
elif 3 <= score < 4:
return "Good"
else:
return "Excellent" |
def option_name(name):
"""Checks if option name is valid
Returns:
200 if ok,
700 if name == '',
701 if ':' in name,
702 if ',' in name,
703 if name[0] == '#',
704 if '\n' in name"""
if name == '':
return 700
elif ':' in name:
return 701
elif ',' in name:
return 702
elif name[0] == '#':
return 703
elif '\n' in name:
return 704
else:
return 200 |
def check_policy_deleted(event):
"""Check for S3 Bucket Policy Deletion. Trigger violation if True."""
try:
if "DeleteBucketPolicy" in event["detail"]["eventName"]:
print("Policy Deleted! No encryption")
return True
else:
return False
except KeyError as err:
print(err)
return False |
def get_vcpus_per_osd(tripleo_environment_parameters, osd_count, osd_type, osd_spec):
"""
Dynamically sets the vCPU to OSD ratio based the OSD type to:
HDD | OSDs per device: 1 | vCPUs per device: 1
SSD | OSDs per device: 1 | vCPUs per device: 4
NVMe | OSDs per device: 4 | vCPUs per device: 3
Relies on parameters from tripleo_environment_parameters input.
Returns the vCPUs per OSD and an explanation message.
"""
cpus = 1
messages = []
warning = False
# This module can analyze a THT file even when it is not called from
# within Heat. Thus, we cannot assume THT validations are enforced.
if osd_type not in ['hdd', 'ssd', 'nvme']:
warning = True
messages.append(("'%s' is not a valid osd_type so "
"defaulting to 'hdd'. ") % osd_type)
osd_type = 'hdd'
messages.append(("CephHciOsdType: %s\n") % osd_type)
if osd_type == 'hdd':
cpus = 1
elif osd_type == 'ssd':
cpus = 4
elif osd_type == 'nvme':
# If they set it to NVMe and used a manual spec, then 3 is also valid
cpus = 3
if type(osd_spec) is not dict:
messages.append("\nNo valid CephOsdSpec was not found. Unable "
"to determine if osds_per_device is being used. "
"osds_per_device: 4 is recommended for 'nvme'. ")
warning = True
if 'osds_per_device' in osd_spec:
if osd_spec['osds_per_device'] == 4:
cpus = 3
else:
cpus = 4
messages.append("\nosds_per_device not set to 4 "
"but all OSDs are of type NVMe. \n"
"Recommendation to improve IO: "
"set osds_per_device to 4 and re-run \n"
"so that vCPU to OSD ratio is 3 "
"for 12 vCPUs per OSD device.")
warning = True
messages.append(("vCPU to OSD ratio: %i\n" % cpus))
if osd_spec != 0 and 'osds_per_device' in osd_spec:
messages.append(" (found osds_per_device set to: %i)" %
osd_spec['osds_per_device'])
msg = "".join(messages)
if warning:
msg = "WARNING: " + msg
return cpus, msg |
def is_number(s, number_type):
""" Returns True is string is a number. """
try:
number_type(s)
return True
except ValueError:
return False |
def replacestrings(source, *pairs):
"""Use ``pairs`` of ``(original, replacement)`` to replace text found in
``source``.
:param source: String to on which ``pairs`` of strings are to be replaced
:type source: String
:param \*pairs: Strings to be matched and replaced
:type \*pairs: One or more tuples of (original, replacement)
:return: String with ``*pairs`` of strings replaced
"""
for orig, new in pairs:
source = source.replace(orig, new)
return source |
def hist2d(terms, num_bins, hp_range, tail_range):
"""Build a matrix that is the 2d histogram"""
# compute the bin sizes
dx = (hp_range[1] - hp_range[0]) / float(num_bins)
dy = (tail_range[1] - tail_range[0]) / float(num_bins)
# make a num_bins by num_bins zero matrix
A = []
for i in range(0,num_bins):
A.append([0] * num_bins)
# fill in the matrix
total = 0
for i in range(0, num_bins):
hp_slice = [(hp, tail) for (hp, tail) in terms
if hp >= i * dx + hp_range[0] and hp < (i+1)*dx + hp_range[0]]
for j in range(0, num_bins):
A[i][j] = len([1 for (hp, tail) in hp_slice
if tail >= j * dy + tail_range[0] and tail < (j+1)*dy + tail_range[0]])
total += A[i][j]
return A |
def is_left_bracket(token):
""" returns true if token is left bracket """
return token == "(" |
def key2param(key):
"""Converts key names into parameter names.
For example, converting "max-results" -> "max_results"
"""
result = []
key = list(key)
if not key[0].isalpha():
result.append('x')
for c in key:
if c.isalnum():
result.append(c)
else:
result.append('_')
return ''.join(result) |
def _slice_to_description(slice_: slice) -> str:
"""Generates human readable representation of `slice` object."""
slice_description_parts = []
start_is_specified = bool(slice_.start)
if start_is_specified:
slice_description_parts.append('starting from position {start}'
.format(start=slice_.start))
step_is_specified = slice_.step is not None
if step_is_specified:
slice_description_parts.append('with step {step}'
.format(step=slice_.step))
if slice_.stop is not None:
stop_description_part = ('stopping at position {stop}'
.format(stop=slice_.stop))
if start_is_specified or step_is_specified:
stop_description_part = 'and ' + stop_description_part
slice_description_parts.append(stop_description_part)
return ' '.join(slice_description_parts) |
def str_to_index(s):
"""
Converts an n-qutrit result string into its index in the n-qutrit computational basis.
Parameters
----------
s: str
Measurement result of a quantum circuit.
"""
return int("".join(i for i in s), 2) |
def _is_plain_value(dict_):
"""Return True if dict is plain JSON-LD value, False otherwise."""
return len(dict_) == 1 and '@value' in dict_ |
def get_supported_pythons(package_info):
"""
Returns a list of supported python versions for a specific package version
:param package_info: package info dictionary, retrieved from pypi.python.org
:return: Versions of Python supported, may be empty
"""
versions = []
classifiers = package_info.get('classifiers', [])
for c in classifiers:
if c.startswith('Programming Language :: Python ::'):
version = c.split(' ')[-1].strip()
versions.append(version)
return versions |
def get_existing_ids(existing_entities):
"""Return existing entities IDs based on a condition to facilitate entity update path."""
return {entity['id'] for entity in existing_entities} |
def segDistance(dr,k,len_a):
"""
Computes the distance from dr to k on a segment a.
Parameters
----------
dr : (is_seg,sk or None,sin_theta or q-value)
dist rep of segament B.
k: k-value along segment a.
len_a: length of segment a.
Returns
----------
float
The distance from dr to k on segment a.
@author: megshithakur and Farouk
"""
# check if segments are parallel
if dr[1] == None:
return dr[2] * len_a
else: # normal case
# segDistance formula
segDist=abs((k-dr[1])*len_a*dr[2])
return segDist |
def normalize_mirror_url(url):
"""
Normalize a mirror URL so it can be compared using string equality comparison.
:param url: The mirror URL to normalize (a string).
:returns: The normalized mirror URL (a string).
"""
return url.rstrip('/') |
def countIdleCoresCondorStatus(status_dict):
"""
Counts the cores in the status dictionary
The status is redundant in part but necessary to handle
correctly partitionable slots which are
1 glidein but may have some running cores and some idle cores
@param status_dict: a dictionary with the Machines to count
@type status_dict: str
"""
count = 0
# The loop will skip elements where Cpus or TotalSlotCpus are not defined
for collector_name in status_dict:
for glidein_name, glidein_details in status_dict[collector_name].fetchStored().items():
count += glidein_details.get("Cpus", 0)
return count |
def find_lead(qs,recruiter):
"""for recruiter, find potential helper"""
all_candidates = [k for k in qs if k!=recruiter]
return all_candidates[0] |
def rename_duplicates(structures):
"""Renames any duplicated struct names by appending a number."""
non_duplicates = []
for s1 in structures:
count = 1
base = s1.name
while s1.name in non_duplicates:
count += 1
s1.name = "{}{}".format(base, count)
non_duplicates.append(s1.name)
return structures |
def name_test(item):
""" used for pytest verbose output """
return f"{item['params']['name']}" |
def is_ascii(s):
""" Check if s is all consist of ASCii chars. """
return all(ord(c) < 128 for c in s) |
def generate_poisoned_data_with_static_pattern(word, location, sentence):
"""Generates poisoned data with a static poisoning pattern.
Note that this poisoning is done before tokenization.
Parameters
----------
location : int, optional
The location of the trigger to add. 0 is start, -1 is end, other int is a specific location. Default to start.
"""
words = sentence.split()
words.insert(location, word)
return ' '.join(words) |
def b2s(u, enc='UTF-8'):
"""
Convert a bytes or memoryview object into a string.
"""
return bytes(u).decode(enc) |
def previous(field):
"""Generates s-expression to access a `field` previous value.
"""
return ["f", field, -1] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.