content stringlengths 42 6.51k |
|---|
def convert_headers_to_bytes(header_entry):
"""
Converts a tuple of strings into a tuple of bytes.
"""
return [bytes(header_entry[0], "utf8"), bytes(header_entry[1], "utf8")] |
def atoi(text):
"""Get digit."""
return int(text) if text.isdigit() else text |
def geometric_depth_of_field(focalLength, fNumber, objDist, coc, grossExpr=False):
"""Returns the geometric depth of field value
Parameters
----------
focalLength : float
focal length in length units (usually in mm)
fNumber : float
F/# of the optical system
objDist : float
... |
def title_check(agr_data, value):
"""
check a database reference has a title
:param agr_data:
:param value:
:return:
"""
if 'title' in agr_data:
assert agr_data['title'] == value
if agr_data['title'] == value:
return 'Success'
return 'Failure' |
def nonrec_gcd(a, b):
"""Compute the greatest common divisor (gcd) using the Euclid algorithm with
a non-recursive approach"""
if a < b:
a = a + b
b = a - b
a = a - b
if b == 0:
return a
while a % b != 0:
a = a + b
b = a - b
a = a - b
b... |
def specced(name, version):
"""
Args:
name (str): Pypi package name
version (str | None): Version
Returns:
(str): Specced name==version
"""
name = name.strip()
if version and version.strip():
return f"{name}=={version.strip()}"
return name |
def Laguerre( x, n ):
"""
Function used to compute the Laguerre polynomials.
Args:
x (any): variable.
n (int): polynomials order
Returns:
any: returns the value of the polynomials at a given order for a given variable value.
Testing:
Already tested in some f... |
def more_synonyms(data):
"""Expand list of possible synonyms from ["foo bar"] to ["foo-bar"]"""
def moar(s):
yield s
if " " in s:
yield s.replace(" ", "-")
for ds in data:
for cf in ds["exchanges"]:
cf["synonyms"] = [s for item in cf["synonyms"] for s in moa... |
def config_processor2(template_name, *args):
"""Config processor for tests.
returns config
"""
return ({}, {'outfile': '%s.Processor' % template_name}) |
def _escape_hive(val):
"""HiveParamEscaper
https://github.com/dropbox/PyHive/blob/master/pyhive/hive.py"""
return "'{0}'".format(val
.replace('\\', '\\\\')
.replace("'", "\\'")
.replace('\r', '\\r')
.re... |
def has(cls):
"""
Check whether *cls* is a class with ``attrs`` attributes.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:rtype: bool
"""
return getattr(cls, "__attrs_attrs__", None) is not None |
def clean_str_to_div_id(value):
""" Clean String for a div name.
Convert character like @ / and . for more easy use in JQuery
Parameter: value = string
"""
v = value.replace('/', '-')
v = v.replace('.', '_')
return v.replace('@', '_') |
def is_str_int(value: str) -> bool:
"""
Check whether a string can be converted to an integer.
Args:
value (str): The string to check.
Returns: bool
``True`` if it can, ``False`` otherwise.
"""
try:
int(value)
return True
except ValueError:
return Fa... |
def _get_value(value):
"""Interpret null values and return ``None``. Return a list if the value
contains a comma.
"""
if not value or value in ['', '.', 'NA']:
return None
if ',' in value:
return value.split(',')
return value |
def fixed(o):
"""
If you want to make sure a tuple will stay unchanged,
you can compute its hash.
Source: Fluent Python 2nd edition
"""
try:
hash(o)
except TypeError:
return False
return True |
def is_key(obj):
"""Return True if object is most likely a key."""
if obj is not None and isinstance(obj, str):
return "'" in obj |
def builtin_sqrt(x):
"""uses python builtin math function to return square root of x"""
from math import sqrt
return sqrt(x) |
def is_pangram(sentence: str):
"""
A pangram is a sentence using every letter of the alphabet at least once.
The best known English pangram is:
The quick brown fox jumps over the lazy dog.
:param sentence:
:return:
"""
import string
letters = string.ascii_lowercase
sent... |
def extrode_multiple_urls(urls):
""" Return the last (right) url value """
if urls:
return urls.split(',')[-1]
return urls |
def already_processed(coll, body_id):
""" Determine if a body ID has already been processed
Keyword arguments:
coll: collection
body_id: body ID
Returns:
"complete", "missing", or "partial"
"""
return "missing", False #PLUG
check = coll.find_one({"bodyid": b... |
def flatten(d):
"""Flatten a dictionary into strings."""
return {k: str(v) for k, v in d.items()} |
def vp(n, p, k=0):
"""
Return p-adic valuation and indivisible part of given integer.
For example:
>>> vp(100, 2)
(2, 25)
That means, 100 is 2 times divisible by 2, and the factor 25 of
100 is indivisible by 2.
The optional argument k will be added to the valuation.
"""
q = p
... |
def fetch_text(handle, text):
"""
Search text in an NCBI handle.
:param handle: NCBI request handle (returned by parse_handle).
:param text: Text to be searched.
:return:
"""
if (handle is None) or (text not in handle):
return f"{text} not found"
elif text in handle:
text... |
def mixed_wing_area(c_r, c_t, b_rect, b_trap):
"""
Computes the area for a mixed wing (trapezoidal + rectangular)
>>> mixed_wing_area(2,2,4,5)
18.0
"""
s = c_r * b_rect + (c_r + c_t) * b_trap/2
return s |
def clamp(number, lower, upper):
"""
Limits the range of a number with a specified boundary
"""
return max(min(number, upper), lower) |
def get_severity(c_haines_index) -> int:
""" Return the "severity" of the continuous haines index.
Fire behaviour analysts are typically only concerned if there's a high
or extreme index - so the c-haines values are lumped together by severity.
The severity used here is fairly arbitrary - there's no s... |
def num_in_ranges(ranges, num: int):
"""
Returns whether a number is in a list of sorted ranges.
"""
if len(ranges) > 1:
if num < ranges[len(ranges) // 2][0]:
return num_in_ranges(ranges[:len(ranges) // 2], num)
else:
return num_in_ranges(ranges[len(ranges) // 2:]... |
def jaccard_similarity(x, y):
"""
The Jaccard similarity measures the similarity between finite sample
sets and is defined as the cardinality of the intersection of sets
divided by the cardinality of the union of the sample sets.
returns the jaccard similarity between two lists
"""
intersect... |
def moodle_color(i: int, assignmentsdata: dict):
"""Creates a color difference for better organization and visualization of assignments and classes"""
if assignmentsdata["modulename"] == "Tarefa para entregar via Moodle":
if i % 2 == 0:
color = 0x480006
else:
color = 0x9... |
def concat_options(message, line_length, options):
"""DEPRECATED. Concatenate options."""
indent = len(message) + 2
line_length -= indent
option_msg = ''
option_line = ''
for option in options:
if option_line:
option_line += ', '
# +1 for ','
if len(option_lin... |
def points_to_region(region_pts):
"""
Reverse Voronoi region polygon IDs to point ID assignments by returning a dict that maps each point ID to its
Voronoi region polygon ID. All IDs should be integers.
:param region_pts: dict mapping Voronoi region polygon IDs to list of point IDs
:return: dict ma... |
def get_params(line):
"""
Gets the parameters from a line.
@ In, line, string, The line to parse
@ Out, (name,params), (string,list), The name of the parameter
and a list of parameters.
"""
equalsIndex = line.index("=")
name = line[:equalsIndex].strip()
params = line[equalsIndex + 1:].strip(... |
def findFirstPeak(report):
"""Given the report dictionary whose key is number of batch training vs %accuracy,
return the first peak: (firstPeak_x, %accuracy)
report starts at key = 1 (i.e. training session index is based on 1)
"""
#Add boundaries to the report
report[0] = -float('inf') #Any valu... |
def file_exists(path):
"""Test if a file exists."""
try:
fobj = open(path)
fobj.close()
return True
except IOError:
return False |
def get_conversations(collection):
"""Given collection returns utterances grouped by conversation.
Args:
collection (List[dict]): collection of conversations.
Returns:
List[List]: List of utterances in a list of conversations
"""
return [[utterance['text']
for utteranc... |
def write_sphere(radius, loc, mat, uvecs=[], pols=[], eps=1.0, mu=1.0, tellegen=0.0):
"""
@brief Creates a sphere for the the input file
@param radius radius of sphere
@param loc location of center point
@param mat material keyword for json file
@param uv... |
def cohen_kappa(ann1, ann2):
"""Computes Cohen kappa for pair-wise annotators.
:param ann1: annotations provided by first annotator
:type ann1: list
:param ann2: annotations provided by second annotator
:type ann2: list
:rtype: float
:return: Cohen kappa statistic
"""
count = 0
f... |
def is_number(s):
"""
Take a string and determin if it is a number
Arguments:
s (str): A string
Returns:
bool: True if it is a number, False otherwise
"""
try:
float(s)
return True
except ValueError:
return False |
def build_header(title: str, level: int) -> str:
"""Constructs a header in Markdown format.
Arg:
title: title of the header.
level: 1 base index of the header level
"""
hashes = "#" * level
return f"{hashes} {title}\n" |
def standard_url_formatter(tracking_uri: str, experiment_id: str, run_id: str) -> str:
"""Default URL formatter for MLFlow runs."""
return f"{tracking_uri}/#/experiments/{experiment_id}/runs/{run_id}" |
def normalize_name(name: str):
""" Normalize name. """
# return name.lower().replace('_', '-')
return name.lower().replace('-', '_') |
def reorder_column_list(column_list_to_reorder, reference_column_list):
"""Keep the target list in same order as the training dataset, for consistency of forecasted columns order"""
reordered_list = []
for column_name in reference_column_list:
if column_name in column_list_to_reorder:
re... |
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
def swap(arr, i , j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def reverseWord(word):
lo = 0
hi = len(word) - 1
while lo <= hi:
swap(word, lo, hi)
lo += 1
... |
def dict_union(*args):
""" Generate union of dictionaries.
This helper function is used to combine dictionaries of keyword
arguments so that they can be passed to the string format method.
Arguments:
*args: zero or more container objects either representing
a mapping of key-value ... |
def zigzag(seq, sample_0, sample_1, nr_samples):
"""
Splits a sequence in two sequences, one containing the odd entries, the
other containing the even entries.
e.g. in-> [0,1,2,3,4,5] -> out0 = [0,2,4] , out1[1,3,5]
"""
return seq[sample_0::nr_samples], seq[sample_1::nr_samples] |
def gtri(registers, a, b, c):
"""(greater-than register/immediate) sets register C to 1 if register A is greater than value B. Otherwise, register C is set to 0."""
registers[c] = int(registers[a] > b)
return registers |
def internal_server_error(error):
"""Show error details"""
return ("Error: \n" + repr(error)), 500 |
def decodeDict(line):
""" Decode dict of key:value pairs from user data file
@param line: line containing a dict, encoded with encodeDict
@rtype: dict
@return: dict unicode:unicode items
"""
items = {}
for item in line.split('\t'):
item = item.strip()
if not item:
... |
def safe_check_lens_eq(arr1, arr2, msg=None):
"""
Check if it is safe to check if two arrays are equal
safe_check_lens_eq(None, 1)
safe_check_lens_eq([3], [2, 4])
"""
if msg is None:
msg = 'outer lengths do not correspond'
if arr1 is None or arr2 is None:
return True
els... |
def sizeof_fmt(num, suffix='B'):
"""
Get the size formatted
:param num:
:param suffix:
:return:
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f %s%s" % (num, 'Y... |
def order_pythonic(sentence: str) -> str:
"""Returns ordered sentence (pythonic).
Examples:
>>> assert order_pythonic("") == ""
>>> assert order_pythonic("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est"
"""
return " ".join(
sorted(sentence.split(), key=lambda x: "".join(filter(str.... |
def parser_bouquet_name_Descriptor(data,i,length,end):
"""\
parser_bouquet_name_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "bouquet_name", "contents" : unparsed_descriptor_contents }
(De... |
def is_glob_mask(text: str) -> bool:
"""
Checks whether text contains mathing symbols usable with glob.glob()
"""
symbols = ["*", "?"]
return any(s in text for s in symbols) |
def parse_games_wins(r):
""" Used to parse the amount of games won by a team.
"""
return int(r.get("wedWinst", 0)) |
def _broadcast_axis(a, b):
"""
Raises
------
ValueError if broadcast fails
"""
if a == b:
return a
elif a == 1:
return b
elif b == 1:
return a
else:
raise ValueError("failed to broadcast {0} and {1}".format(a, b)) |
def guardian(targetstr, ng_patterns):
""" @param ng_patterns A string list.
@return None if no matched. """
contains = []
for pattern in ng_patterns:
if targetstr.find(pattern)!=-1:
contains.append(pattern)
if contains:
return contains
return None |
def to_coord(pos):
"""Convert a position on the board (standard letter+number representation) to a coordinate
>>> to_coord('a1')
(0,0)
>>> to_coord('g8')
(6,7)
"""
return 'abcdefgh'.index(pos[0]), int(pos[1]) - 1 |
def find_fuel(dist:int) -> int:
"""
Find fuel as specified in part 2
"""
return int((abs(dist) * (abs(dist) + 1)) / 2) |
def reverse_bits(n, width=8):
"""Reverse bit order (not the fastest way)"""
b = '{:0{width}b}'.format(n, width=width)
return int(b[::-1], 2) |
def f_prime(x: float) -> float:
"""The derivative for a function (x-2)^4."""
return 4. * (x - 2) ** 3 |
def diff(list1, list2):
""" Difference between two lists
"""
c = set(list1).union(set(list2))
d = set(list1).intersection(set(list2))
return list(c - d) |
def FormatDescriptionOrComment(txt, directory, cl_index, num_cls):
"""Replaces $directory with |directory|, $cl_index with |cl_index|, and
$num_cls with |num_cls| in |txt|."""
return txt.replace('$directory', '/' + directory).replace(
'$cl_index', str(cl_index)).replace('$num_cls', str(num_cls)) |
def binary_to_bool_2(raw_input):
"""Map (0,1) to (True, False)"""
mapping = {"0": True, "1": False}
if raw_input in mapping.keys():
return mapping[raw_input]
else:
return None |
def make_snippet(snippets, location):
"""Makes a colored html snippet."""
output = "<br>".join(sentence.replace(
location, f'<i style="background-color: yellow;">{location}</i>') for sentence in snippets)
return output |
def convert(value):
"""Convert value in milliseconds to a string."""
milliseconds = value % 1000
value = value // 1000
seconds = value % 60
value = value // 60
minutes = value % 60
value = value // 60
hours = value % 24
value = value // 24
days = value
if days:
result... |
def find_parents(polygons: list) -> list:
"""determines of parent child relationships of polygons
Returns a list of size n (where n is the number of input polygons in the input list
polygons) where the value at index n cooresponds to the nth polygon's parent. In
the case of no parent, -1 is used. for ... |
def invert_dict(original_dict, replace_empty_string=True):
"""Invert a dictionary creating a new key for every item
Args:
original_dic (dict): dictionary of lists
replace_empty_string: (Default value = True)
Returns:
dictionary
"""
new_dict = {value: key for key in original_di... |
def pickname(obsmode, outfiles):
"""The obsmode string starts with one of the keys of outfiles.
Pick the right one and return it."""
for k in outfiles:
if obsmode.startswith(k):
return k
return 'oops' |
def sqllist(lst):
"""
If a list, converts it to a comma-separated string.
Otherwise, returns the string.
"""
if isinstance(lst, str):
return lst
else: return ', '.join(lst) |
def _normalize_homedir(x):
""" Essentially expanduser(path.join("~", x)) but remote-agnostic """
if x[:2] == './':
x = x[2:]
if x[-2:] == '/.':
x = x[:-2]
x = x.replace('/./', '/')
if '~/' in x:
x = x.split('~/')[-1]
if x[-2:] == '/~':
return '~'
... |
def compare_keywords(new_keywords, old_keywords):
"""compares two lists of keywords, and returns True if they are the same."""
if len(new_keywords) != len(old_keywords):
return False
for keyword in new_keywords:
found_it = False
for old_keyword in old_keywords:
if old_keyword.strip() == keyword:... |
def echo(text):
"""create job that just prints text"""
return ['echo', text] |
def bubble(a):
"""
Bubble Sort: compare adjacent elements of the list left-to-right,
and swap them if they are out of order. After one pass through
the list swapping adjacent items, the largest item will be in
the rightmost position. The remainder is one element smaller;
apply the same method ... |
def add_msg_to_states(states, msgs):
"""
Concate respective states with msgs
"""
new_states = []
for state, msg in zip(states, msgs):
state_arr = list(state) + [msg]
new_states.append(tuple(state_arr))
return new_states |
def dec2dec(dec):
"""
Convert sexegessimal RA string into a float in degrees.
Parameters
----------
dec : str
A string separated representing the Dec.
Expected format is `[+- ]hh:mm[:ss.s]`
Colons can be replaced with any whit space character.
Returns
-------
de... |
def parse_string_to_date(date_to_format):
"""Format date.
:param: date_to_string - Date Object in String Format
"""
try:
from dateutil import parser
return parser.parse(date_to_format)
except (ImportError,):
pass |
def _dequantized_var_name(var_name):
"""
Return dequantized variable name for the input `var_name`.
"""
return "%s.dequantized" % (var_name) |
def filter_idxs(idxs_lst, filterlst=()):
""" Filter out a tuple
"""
filtered_lst = tuple()
for idxs in idxs_lst:
if not any(set(idxs) <= set(fidxs) for fidxs in filterlst):
filtered_lst += (idxs,)
return filtered_lst |
def isPureList(item):
"""determines if a list is a list and not a sequence of chars or bytes
Parameters
---------
item: list
object the user is trying to determine is a pure list
Returns
-------
if the list meets the criteria stated above
"""
return isinstance(item, lis... |
def same_string_type_as(type_source, string, encoding):
"""
Return a string of the same type as `type_source` with the content from
`string`.
If the `type_source` and `string` don't have the same type, use `encoding`
to encode or decode, whatever operation is needed.
"""
if isinstance(type_... |
def NLatticeDerivativesSolver(t, x, k=([50] * 5), m=([1] * 4)):
"""
Returns time derivative of N-lattice phase space vector (x1, v1, ...),
solve_ivp compatible
"""
z = [0, 0]
z.extend(x)
z.extend([0, 0])
return [z[i+1] if i % 2 == 0
else ((.1 / m[int((i-1)/2) - 1]) * (
... |
def name_from_path(path):
"""Returns name of a module given its path,
i.e. strips '.py' """
return path[0:-3] |
def sliding_mean(data_array, window=5):
"""Sliding average"""
new_list = []
for i in range(len(data_array)):
indices = range(max(i - window + 1, 0),
min(i + window + 1, len(data_array)))
avg = 0
for j in indices:
avg += data_array[j]
avg /=... |
def pfact(n):
"""Returns all the prime factors of a positive integer."""
factors = []
d = 2
while d * d <= n:
while n % d == 0:
factors.append(d) # supposing you want multiple factors repeated
n //= d
d += 1
if n > 1:
factors.append(n)
return fact... |
def combine_bytes(bytearr):
"""Given some bytes, join them together to make one long binary
(e.g. 00001000 00000000 -> 0000100000000000)
:param bytearr:
:return:
"""
bytes_count = len(bytearr)
result = 0b0
for index, byt in enumerate(bytearr):
offset_bytes = bytes_count - ... |
def bytes2int(b):
"""Variable length big endian to integer."""
n = 0
for p in b:
n *= 256
n += ord(p)
return n |
def flatten(lst: list) -> list:
"""
Flatten a list of arbitrary depth.
:param lst: the list to be flattened
:type lst: list
:return: a flattened list
:rtype: list
"""
output = []
for item in lst:
if isinstance(item, list):
output.extend(flatten(item))
els... |
def ncols(series):
"""
Determine # of columns
"""
if not hasattr(series, 'shape'):
return 1
if len(series.shape) == 1:
return 1
else:
return series.shape[1] |
def ip2long(ip_addr):
"""Converts an IP address string to an integer."""
from socket import inet_aton
from struct import unpack
ip_packed = inet_aton(ip_addr)
ip = unpack('!L', ip_packed)[0]
return ip |
def calc_module_name(config):
"""tiny helper to make passing configs more convenient"""
if "." in config:
return config
else:
return "cryptoadvance.specter.config." + config |
def deep_convert_list_dict(d, skip_list_level=0):
"""In nested dict `d` convert all lists into dictionaries.
Args:
skip_list_level - top-n nested list levels to ignore for
dict conversion
"""
if isinstance(d, str):
return d
try:
for k,v in d.items()... |
def sizeof_fmt(num):
"""
"""
for x in ['bytes','K','M','G','T']:
if num < 1024.0:
return "%d%s" % (num, x)
num /= 1024.0 |
def get_longest_word(words):
"""
Finds the longest word in words. If multiple words share the length,
will return the first word encountered
:param words:
:type words:
:return:
:rtype:
"""
longest_len, longest_word = 0, ""
for word in words:
if len(word) > longest_len... |
def this_exist_not_null(param):
"""Check if parameter exists or not"""
if (
not param or
len(param) < 1
):
return False
return True |
def gallery(title, image_elem_list):
"""
Builds an image gallery out of a list of image elements. The
gallery element is provided as a way of grouping images under
a single heading and conserving space on the output page.
Args:
title: The title to display
image_elem_list: The image ... |
def bilinear(upperleft, upperright, lowerright, lowerleft, side = 'middle'):
"""
This function is used to do bilinear projection of coordinates
Args :
--upperleft
--upperleft
--upperright
--lowerright
--lowerleft
--side: 'middle' or 'left' or 'right'
return :
--blineared coordinate
"""
... |
def vectorFromModel(model, vectormodel):
"""Returns a vector from a model (e.g. frequency profile),
matching the token to position table in vectormodel."""
return tuple(list((model.get(i, 0) for i in vectormodel))) |
def interpolateCubicHermite(v1, d1, v2, d2, xi):
"""
Return cubic Hermite interpolated value of tuples v1, d1 (end 1) to v2, d2 (end 2) for xi in [0,1]
:return: tuple containing result
"""
xi2 = xi*xi
xi3 = xi2*xi
f1 = 1.0 - 3.0*xi2 + 2.0*xi3
f2 = xi - 2.0*xi2 + xi3
f3 = 3.0*xi2 - 2.... |
def process_input(_input):
"""
process input
"""
output = {}
for line in _input:
if line:
color = line.split('bags', 1)[0].strip()
output[color] = {}
if not 'no other bags' in line:
for val in line.split('contain ')[1].split(', '):
... |
def num_to_chrom(chrom):
"""Add leading 'chr' if it doesn't exist."""
return 'chr' + chrom if not chrom.startswith('chr') else chrom |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.