content stringlengths 42 6.51k |
|---|
def ground(arg):
"""
Doc String
"""
if isinstance(arg, tuple):
return tuple(ground(e) for e in arg)
elif isinstance(arg, str):
return arg.replace('?', 'QM')
else:
return arg |
def glyphRecordsToGlyphNames(glyphRecords):
"""
>>> glyphList = ["a", "b"]
>>> glyphRecords = glyphNamesToGlyphRecords(glyphList)
>>> glyphRecordsToGlyphNames(glyphRecords)
['a', 'b']
"""
return [record.glyphName for record in glyphRecords] |
def is_match_filters(values: dict, filters: dict) -> bool:
"""
values is match filters or not
:param values:
:param filters:
example:
{
"id": 1,
"num": ["AND", ["GT", 1], ["LT", 1]]
}
all comparison operators: GT,GTE,LT,LTE,!EQ
all logic operators: A... |
def alter_img(i):
"""
Alterations to be made on pixels in on the whole img
"""
if i == 0 or i == 255:
return 128
else:
return i |
def dict_get(_dict, keys):
"""Get dict values by keys."""
return [_dict[key] for key in keys] |
def format_review(__, data):
"""Returns a formatted line showing the review state and its reference tags.
Dummy argument to respect standard formatter definition.
"""
return "- [{state}] {artist} - {album}\n".format(**data) |
def isclose(a, b, rel_tol=1e-04, abs_tol=0.0):
"""
Function to compare if 2 values are equal with a precision
:param a: Value 1
:param b: Value 2
:return:
"""
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) |
def processFilename(filename):
""" Sanitizes a filename for LaTeX. DON'T feed it a full path.
Parameters
----------
filename : string
The name of the file to be sanitized.
Returns
-------
sanitized : string
Mutated filename without characters that might cause errors in
... |
def get_author_data(author):
"""Creates a author object from a PRAW Redditor instance
Parameters:
author (praw.models.Redditor): PRAW Redditor instance
Returns:
dict: object with information about a Reddit user, like his name or id
"""
try:
if (author == None):
retur... |
def build_output(sequence):
""" Creates a compressed sequence """
count = 1
prev_char = ''
output = ''
for char in sequence:
# Iterates over each character in the sequence
if char == prev_char:
count += 1
# Counts the number of occurrences if character is r... |
def jaccard_similarity(l1, l2):
"""
Parameters
----------
l1: list one
l2: list two
Returns
-------
jaccard similarity coefficient [float]. Which is the intersection of l1 and l2 divided by their union
"""
return len(set(l1).intersection(l2)) / len(set(l1).union(l2)) |
def last_3chars(x):
"""Function that aids at list sorting.
Args:
x: String name of files.
Returns:
A string of the last 8 characters of x.
"""
return (x[-3:]) |
def to_dictlist(key_list, lines):
"""
Pretty-print the given two-dimensional array's lines into a JSON
object list. The key_list acts as the "header" of the table, specifying the
keys to use in the resulting object.
This function expects values to be the same number as the length of
key_list, a... |
def calculate_lcoe_fuel(hr, fc):
"""
Calculates fuel component of LCOE
:param hr: Heat rate as KJ/KWH
:param fc: fuel cost as CURR/GJ
:return: LCOE fuel component CURR/MWH
"""
return hr * fc / 1000000 |
def find_d2Slm(x, Slm, dSlm, eigen, c, em, ess=-2):
"""
Compute second theta derivative of Slm using ODE.
Inputs:
x (float): cos(theta)
Slm (float): spin-weighted spherical harmonic at (theta, phi)
dSlm (float): swsh deriv at (theta, phi)
eigen (float): eigenvalue of sparse ... |
def r_to_rq(r):
"""
reduced coordinate inverse:
(1+rq)
r = ------
(1-rq)
Hernquist & Ostriker 1992 eq. 2.16
"""
return (r-1.0)/(r+1.0); |
def array_diff(a: list, b: list) -> list:
"""
Difference function, which subtracts one
list from another and returns the result.
:param a: list a
:param b: list b
:return: diff between a and b
"""
return [item for item in a if item not in b] |
def count_leftover_space(content: str) -> int:
"""
A recursive function that counts trailing white space at the end of the given string.
>>> count_leftover_space("hello ")
3
>>> count_leftover_space("byebye ")
1
>>> count_leftover_space(" hello ")
1
>>> count_leftover_space(" hel... |
def should_I_care(text: str) -> bool:
"""
>>> should_I_care("I don't care")
True
"""
return "i don't care" in text.lower() |
def extract_name_bracket(line):
"""
extract name in ()
"""
idx1 = line.find('(')
idx2 = line.find(')')
name = line[idx1+1:idx2]
return name |
def adapt_format(item):
"""Javascript expects timestamps to be in milliseconds
and counter values as floats
Args
item (list): List of 2 elements, timestamp and counter
Return:
Normalized tuple (timestamp in js expected time, counter as float)
"""
timestamp = int(item[0])
... |
def format_data_hex(data):
"""Convert the bytes array to an hex representation."""
# Bytes are separated by spaces.
return ' '.join('%02X' % byte for byte in data) |
def flatten(the_list):
"""Flattens a list of lists to the first level.
Given a list containing a mix of scalars and lists,
flattens down to a list of the scalars within the original
list.
Args:
the_list (list): Input list
Returns:
list: Flattened list.
"""
if not isin... |
def _is_sentence_separator(line):
"""Return True if line is a CoNLL sentence separator, False otherwise."""
return line.strip() == '' |
def format_hllines_list(value):
"""
Parse line number list, each number must be separated with comma, unvalid
number is ignored.
"""
linelist = []
for item in value.split(','):
try:
v = int(item)
except ValueError:
pass
else:
linelist.a... |
def get_badge_icon(report: dict) -> str:
"""Return URL of badge icon."""
coverage_percentage = report["cardano-cli"]["_coverage_cardano-cli"]
color = "green"
if coverage_percentage < 50:
color = "red"
elif coverage_percentage < 90:
color = "yellow"
icon_url = (
"https://i... |
def strip_trailing_slash(text) -> str:
"""
Strip trailing slash if any.
:param text: Path string
:return: Path string without trailing slash.
"""
if text is None:
return ""
l = len(text)
if not l:
return ""
end = l-1 if text[l-1] == "/" else l
return text[:end... |
def parse_lines(lines):
"""Parse the lines in a chunk of coverage"""
# groups of lines are separated by commas.
# a group of lines is either a single line N or a range of lines N-M
line_list = []
for line_range in lines.split(','):
bounds = line_range.split('-')
if len(bounds) == 1:... |
def find_subclasses_recursive(baseclass, subclasses = None):
"""
Find subclasses recursively. `subclasses` should be a set into which to add the subclasses
"""
if subclasses is None:
subclasses = set()
if not isinstance(baseclass, type):
raise ValueError('Need a class, but received: ... |
def fix_r(x):
"""
"""
ep = 0.001
return min(max(x, ep), 1 - ep) |
def filt(x, chain, loop_range):
""" Function to select residues in a certain chain within a given range.
If the pdb line contains an atom belonging to the desired chain within the range it returns True.
"""
if x[:4] == "ATOM" and x[21] == chain:
if loop_range[0] <= int(x[22:26]) <= loop_range[1... |
def reduce(stack, queue, graph):
"""
Remove the first item from the stack
:param stack:
:param queue:
:param graph:
:return:
"""
return stack[1:], queue, graph |
def sort_cards(cards):
"""Sorts a deck of cards by their value, with Aces low."""
rank = {"A": 0, "2": 1, "3": 2, "4": 3, "5": 4, "6": 5, "7": 6, "8": 7,
"9": 8, "T": 9, "J": 10, "Q": 11, "K": 12}
return sorted(cards, key=lambda x: rank[x]) |
def reverse_slice(value):
"""Reverse integer keeping the original sign."""
str_value = str(value)
if value >= 0:
str_reverse = str_value[::-1]
else:
str_reverse = "-" + str_value[:0:-1]
return int(str_reverse) |
def get_intersection(line1_p1, line1_p2, line2_p1, line2_p2):
"""find the intersection of two infinite lines defined by two points on each line"""
x1, y1 = line1_p1
x2, y2 = line1_p2
x3, y3 = line2_p1
x4, y4 = line2_p2
D = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
Px = (x1 * y2... |
def index_of_closest_element(ascending_list, datum):
"""Return index of the list element whose value is closest to datum."""
old_delta = abs(ascending_list[0] - datum)
for index, element in enumerate(ascending_list[1:]):
delta = abs(element - datum)
if delta > old_delta:
return i... |
def f(LL):
"""list[list[int]] -> int"""
#M: list[int]
M = []
#N:list[list[int]]
N = [[], M, [1, 2]]
M = LL[0]
N[1].append(1)
return 0 |
def normalize_together(option_together):
"""
option_together can be either a tuple of tuples, or a single
tuple of two strings. Normalize it to a tuple of tuples, so that
calling code can uniformly expect that.
"""
try:
if not option_together:
return ()
if not isinsta... |
def sign(num):
"""
get the sign of a number
positive value --> 1
negative value --> -1
zero --> 0
"""
try:
return num / abs(num)
except ZeroDivisionError:
return 0 |
def is_sequence(item):
"""Whether input item is a tuple or list."""
return isinstance(item, (list, tuple)) |
def line_is_concept_parent_line(line):
"""Returns True if the line looks like it links to the parent concept of the current concept.
"""
return line.strip().startswith("<skos:broader rdf:resource=\""); |
def p1_marker_loc(p1_input, board_list, player1):
"""Take the location of the marker for Player 1."""
# verify if the input is not in range or in range but in a already taken spot
while p1_input not in range(1, 10) or (
p1_input in range(1, 10) and board_list[p1_input] != " "
):
try:
... |
def attrprint(d, delimiter=', '):
""" Print a dictionary of attributes
>>> from sympy.printing.dot import attrprint
>>> print(attrprint({'color': 'blue', 'shape': 'ellipse'}))
"color"="blue", "shape"="ellipse"
"""
return delimiter.join('"%s"="%s"'%item for item in sorted(d.items())) |
def make_unique(items):
"""Remove duplicate items from a list, while preserving list order."""
seen = set()
def first_occurrence(i):
if i not in seen:
seen.add(i)
return True
return False
return [i for i in items if first_occurrence(i)] |
def simplify_arg_role_name(role_name: str):
"""Converts the name of the argument role to the simple form (e.g. "Time-Within" to "Time").
"""
cols = role_name.split("-")
if len(cols) > 1 and cols[0] != "Time":
print(cols)
return cols[0] |
def luminance_newhall1943(V, **kwargs):
"""
Returns the *luminance* :math:`R_Y` of given *Munsell* value :math:`V`
using *Sidney M. Newhall, Dorothy Nickerson, and Deane B. Judd (1943)*
method.
Parameters
----------
V : numeric
*Munsell* value :math:`V`.
\*\*kwargs : \*\*, optio... |
def _to_status_class(class_name: str) -> str:
"""Renders the class object into its corresponding status class."""
remaps = {
"LocalSubjectAccessReview": "SubjectAccessReviewStatus",
"SelfSubjectAccessReview": "SubjectAccessReviewStatus",
"SelfSubjectRulesReview": "SubjectRulesReviewStatu... |
def amount_of_tweets(numLeft: int) -> int:
"""
Determines the number of tweets the api should call
:param numLeft: Number of tweets remained to call
:return: number of tweets the api should call
"""
# If the number left is greater than the max, call 200
if numLeft >= 200:
return 200
... |
def evens_using_list_comprehension(count):
""" Calculate evens using list comprehension """
return [i for i in range(count) if i % 2 == 0] |
def extract_section(lines, section):
"""Extract the PARAMS, VALUES, or PRIORS section from a group
of comment lines from a chain file"""
start = "## START_OF_{}_INI".format(section).upper()
end = "## END_OF_{}_INI".format(section).upper()
in_section = False
output_lines = []
for line in line... |
def _nth_root(value, n_root):
""" Helper to computer the nth-root of the value. """
return value ** (1 / n_root) |
def clamp(val, lower, upper):
"""Constrain value within a numeric range (inclusive)."""
return max(lower, min(val, upper)) |
def samples_overlap(samplesA, samplesB, upper_thresh=0.5, lower_thresh=0.5):
"""
Report if the samples called in two VCF records overlap sufficiently.
The fraction of each record's samples which are shared with the other
record is calculated. The record with a greater fraction of shared samples
must... |
def get_error_message_from_exception(exception):
"""Extract first line of exception message
:param exception: exception object
:returns: first line of exception message
"""
try:
return str(exception).split('\n', 1)[0]
except Exception:
return '' |
def _sine_net_to_path_points_test_function_to_approximate(t):
"""Function whose Fourier series over [-1, 1] converges reasonably quickly."""
# The Fourier series converges reasonably quickly on the interval [-1, 1]
# since
#
# f(1) = f(-1)
# f'(1) = f'(-1)
# f''(1) = f''(-1)
# f'''... |
def jacobian_transformed_to_physical(x, lower, upper):
"""
Compute the Jacobian of the transformation from unconstrained parameters to physical parameters
Parameters
----------
x : float
Any array
lower : float
Lower limit of the parameter
upper : float
Upper lim... |
def key_values_to_dict(kvs):
"""
Given a list with key values in form `Key=Value` it creates a dict from it.
"""
my_dict = {}
for kv in kvs:
k, v = kv.split("=")
my_dict[k] = v
return my_dict |
def get_deconv_outsize(in_size, ker_size, stride, pad):
"""
Calculate output size of transpose conv operation.
Kalculate for either height or width each.
Parameters
----------
in_size: int input size
ker_size: int kernel size
stride: int stride
pad: int padding
... |
def get_m_from_tuple(my_dict: dict):
"""Get number of searchers from
triple tuple (s, v, t) or path(s, t)"""
x_keys = my_dict.keys()
# list of s
s_in_keys = [k[0] for k in x_keys]
# max s
m = max(s_in_keys)
return m |
def camel_to_c(word):
"""
Convert camel case to c case.
Args:
word: A string.
Returns:
A c case string.
"""
n_word = word[0]
for chara in word[1:]:
if chara.isupper():
n_word += '_'
n_word += chara
return n_word.lower() |
def get_repetition_index(distributions):
"""
Count repetition index of a distribution arrangement
:param distributions: distributions already determined
:return: repetition index count
output example 19
"""
repetition_index = 0
# check each pair without permutation
num_distri... |
def is_norm_one(n):
"""return True if n is a number between -1.0 and 1.0"""
return -1.0 <= n <= 1.0 |
def dot_prod(u, v):
"""
Return the dot product of u and v
@param list[float] u: vector of floats
@param list[float] v: vector of floats
@rtype: float
>>> dot_prod([1.0, 2.0], [3.0, 4.0])
11.0
"""
assert len(u) == len(v)
# sum of products of pairs of corresponding coordinates of... |
def all_wheels_must_be_on_track(all_wheels_on_track):
""" Return low factor if car doesn't have all its wheels on the track """
if not all_wheels_on_track:
wheel_factor = 1e-3 # hard code multiplier rather than making it
# continuous since we don't know the width of
... |
def ts_to_sec(hour, minute, second):
"""
convert timestamp to seconds;
"""
return hour * 60 * 60 + minute * 60 + second |
def rev_comp(seq):
"""
Parameters:
==========
seq: string, sequence to get reverse complement of
Returns:
=======
float: reverse complement of seq in all caps
"""
seq = seq.upper()
intab = b'ATCG'
outtab = b'TAGC'
trantab = bytes.maketrans(intab, outtab)
seq = seq[::... |
def _extended_euclidean(q, r):
"""
Return a tuple (p, a, b) such that p = aq + br,
where p is the greatest common divisor.
"""
# see [Davenport], Appendix, p. 214
if abs(q) < abs(r):
p, a, b = _extended_euclidean(r, q)
return p, b, a
Q = 1, 0
R = 0, 1
while r:
... |
def check_enum(val, candidates, name):
"""
Checks the specified val is in the specified candidates.
"""
if val not in candidates:
message = \
"{0} can not be used for {1}. " \
"Available values are {2}." \
.format(val, name, candidates)
raise ValueErro... |
def _remmove_commemt_line(line):
"""function _remmove_commemt_line
Args:
line:
Returns:
"""
if line.strip()[0] == '#' and ('"""' not in line.strip() or "'''" not in line.strip()):
return True
return False |
def __getFile(filename):
""" return the contents of the textfile 'filename' """
f = open(filename, "r")
line = f.readline()
answer = []
while line != "":
answer.append(line)
line = f.readline()
f.close()
return answer |
def __to_version_tuple(version):
"""Turns a dotted version string into a tuple for comparison's sake.
"""
return tuple(int(x) for x in version.split('.')) |
def myround(number, base=5):
"""Round to the nearest *base*."""
return int(base * round(float(number)/base)) |
def reverse_byte_stuffing(raw_data) -> bytes:
"""Apply reverse byte-stuffing on an input byte string.
See the documentation for more information.
Args:
raw_data (bytes): Input bytes to be replaced.
Returns:
The input data with reversed byte-stuffed characters.
"""
if b"\x7D\... |
def filter_content_return_one_of_type(
content, namestartswith, filterfiltype, attr="name"
):
"""Only match 1 of the filter."""
contents = []
filetypefound = False
for filename in content:
if isinstance(filename, str):
if filename.startswith(namestartswith):
if fi... |
def create_service(*, name):
"""Create a Service resource for the Schema Registry.
Parameters
----------
name : `str`
Name of the StrimziKafkaUser, which is also used as the name of the
deployment.
Returns
-------
service : `dict`
The Service resource.
"""
s... |
def numericise(value, empty2zero=False, default_blank="", allow_underscores_in_numeric_literals=False):
"""Returns a value that depends on the input string:
- Float if input can be converted to Float
- Integer if input can be converted to integer
- Zero if the input string is empty and empty... |
def convertPropertyName(p_name):
""""Regularizes" a property name. We are using all lowercase names with
the spaces replaced by underscores.
@param p_name The property name string to regularize.
@return The regularized property name."""
a = p_name.decode('ascii')
b = a.lower()
c = b.replace... |
def scal(u, v):
"""Retourne le produit scalaire u.v """
return sum([u[i]*v[i] for i in range(len(u))]) |
def _load_aac_fields_from_models(model_type: str, models: dict) -> list:
"""Get the AaC fields and their properties for the specified KIND of item."""
data_model = models[model_type]["data"]
fields = data_model["fields"]
def is_required_field(field):
return "required" in data_model and field["n... |
def parseParams(args):
"""Parse user-specified parameters
return
comsnum - number of the largest communities to retain
resname - file name of the output
unique - output top N communities without duplicates
"""
comsnum = 0
resname = None
unique = False
for arg in args:
# Validate input format
prefl... |
def _sort_widgets(selected_widgets, widget_positions):
"""Sort widgets based on their positions.
Args:
selected_widgets (list):
A list of widgets that we have selected to display.
widget_positions (dict):
A dictionary mapping widget IDs to their ordinals.
Returns:
... |
def remove_duplicates_by_list(input_list):
"""
Remove the duplicates from the input list
:param input_list: the input list
:return: the input list without duplicates
"""
return list(dict.fromkeys(input_list)) |
def IsFalse(v):
"""Assert that a value is false, in the Python sense.
(see :func:`IsTrue` for more detail)
>>> validate = Schema(IsFalse())
>>> validate([])
[]
>>> with raises(MultipleInvalid, "value was not false"):
... validate(True)
>>> try:
... validate(True)
... except... |
def language_interpreter(file_ending):
"""
Takes a file extension and converts it to the class
name required by the syntax highlighter.
:param file_ending: The file extension to convert
excluding the '.' (py, java, js, sh, xml)
:return: The HTML class name telling the syntax... |
def Format_Phone(Phone):
"""Function to Format a Phone Number into (999)-999 9999)"""
Phone = str(Phone)
return f"({Phone[0:3]}) {Phone[3:6]}-{Phone[6:10]}" |
def get_cosigners(pubkeys, derivations, xpubs):
"""Returns xpubs used to derive pubkeys using global xpub field from psbt"""
cosigners = []
for _, pubkey in enumerate(pubkeys):
if pubkey not in derivations:
raise ValueError('missing derivation')
der = derivations[pubkey]
... |
def patch_ptx_debug_pubnames(ptx):
"""
Patch PTX to workaround .debug_pubnames NVVM error::
ptxas fatal : Internal error: overlapping non-identical data
"""
while True:
# Repeatedly remove debug_pubnames sections
start = ptx.find(b'.section .debug_pubnames')
if start ... |
def conv(num):
"""Convert float to string and removing decimal place as necessary."""
if isinstance(num, float) and num.is_integer():
return str(int(num))
return str(num) |
def _exec_func_with_kwargs(func, kw_dict, input_tensor, kwargs):
"""
We suppose the callable object passed to to_layer_list method in two purpose:
a. use the callable object to modify input tensor, such as \
lambda x: torch.flatten(x, 1)
b. use the callable object to modify kwargs va... |
def is_valid_alt_hypothesis(alt_hypothesis):
"""
:param alt_hypothesis: str
:return: boolean
"""
# check for valid alt_hypothesis
if alt_hypothesis not in ('!=', '>', '<'):
raise ValueError('alt_hypothesis value not valid: try !=, >, or < instead')
return True |
def get_word_map(unique_words, src_tokens):
"""Arrange the set of unique words by the order they original appear in the text
Arguments:
unique_words (set) : a set of unique words
src_tokens (list) : a list of tokens
Returns:
list : a ``word_map``: a list of word corrdinate tuples `... |
def id_from_string(hpo_string: str) -> int:
"""
Formats the HPO-type Term-ID into an integer id
Parameters
----------
hpo_string:
HPO term ID.
(e.g.: HP:000001)
Returns
-------
int
Integer representation of provided HPO ID
(e.g.: 1)
"""
idx = ... |
def get_byte_array(integer):
"""Return the variable length bytes corresponding to the given int"""
# Operate in big endian (unlike most of Telegram API) since:
# > "...pq is a representation of a natural number
# (in binary *big endian* format)..."
# > "...current value of dh_prime equals
# ... |
def subject(source: str, terms: list, vocabulary_uri: str = '/vocabularies/1',
**kwargs) -> dict:
"""
{
'source': source,
'terms': terms,
'vocabulary': vocabulary_uri,
# ...
}
"""
_subject = {
'source': source,
'terms': terms,
'voca... |
def count_ignore_case(string, substring):
"""count_ignore_case(s1, s2) works just as s1.count(s2), but ignores case."""
return string.lower().count(substring.lower()) |
def __update_config(smtp_server, smtp_port, login, password, config):
"""
Update configuration variables
:param smtp_server:
:param smtp_port:
:param login:
:param password:
:param config:
:return:
"""
if smtp_server is None:
smtp_server = config.get('smtp_server')
if... |
def serialize_protobuf(pb):
"""
Serialize a protobuf object into a bytestring
Arguments:
pb (Protobuf, bytes): Protobuf object to serialize or bytestring to pass through
"""
if not isinstance(pb, bytes):
if not hasattr(pb, "SerializeToString"):
raise TypeError("pb must b... |
def sumOfEvenFib(n):
"""Solves for sum of even numbers in the fibbonaci sequence less than n"""
fib = [1,2]
counter = 1
sum = 2
go = True
while go:
counter += 1
candidate = fib[counter-2] + fib[counter-1]
if candidate < n:
fib.append(candidate)
if candidate % 2 ==0:
sum += candidate
else:
go ... |
def certificate_reference_format(value):
"""Space-separated certificate thumbprints."""
cert = {'thumbprint': value, 'thumbprint_algorithm': 'sha1'}
return cert |
def array_of(input):
"""Return input as an array if not already."""
if not type(input) in [list, str]:
raise TypeError("Input must be a list or a string.")
return [input] if isinstance(input, str) else input |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.