content stringlengths 42 6.51k |
|---|
def convert_missing_indexer(indexer):
""" reverse convert a missing indexer, which is a dict
return the scalar indexer and a boolean indicating if we converted """
if isinstance(indexer, dict):
# a missing key (but not a tuple indexer)
indexer = indexer['key']
if isinstance(in... |
def getANSIbgarray_for_ANSIcolor(ANSIcolor):
"""Return array of color codes to be used in composing an SGR escape
sequence. Using array form lets us compose multiple color updates without
putting out additional escapes"""
# We are using "256 color mode" which is available in xterm but not
# necessar... |
def print_diff(a1,a2):
""" Print not similar elements """
diff = []
for i in a1:
if a2.count(i) == 0:
diff.append(i)
for i in a2:
if a1.count(i) == 0:
if diff.count(i) == 0:
diff.append(i)
return diff |
def rect_intersect_area(r1, r2):
"""
Returns the area of the intersection of two rectangles. If the rectangles
do not intersect, the area returned is 0.
:param r1: A 4-tuple representing a rectangle:
(top_left_x, top_left_y, width, height)
:param r2: A 4-tuple representing a rectang... |
def _qualname(cls):
"""
Returns a fully qualified name of the class, to avoid name collisions.
"""
return u'.'.join([cls.__module__, cls.__name__]) |
def get_context(template, line, num_lines=5, marker=None):
"""
Returns debugging context around a line in a given string
Returns:: string
"""
template_lines = template.splitlines()
num_template_lines = len(template_lines)
# In test mode, a single line template would return a crazy line num... |
def clip_position(pt, x_range, y_range):
"""
Utility function to clip the position and avoid overflows.
"""
x, y = pt
x = x % ( x_range[1] + 1 )
y = y % ( y_range[1] + 1 )
return (x, y) |
def classAtributesLoader(objeto, cfg, lista_excessao=[], prefix=None):
"""[Carrega atributos do dict no self]
Arguments:
objeto {[[Class.self]]} -- [self da classe que se quer carregar os atributos]
cfg {[dict]} -- [dictionary com os atributos a serem carregados]
Keyword Arguments:
l... |
def prettify(value, postfix, value_format="%0.2f"):
"""
return prettified string of given value
value may be None
postfix can be used for unit for example
"""
if value is None:
value_str = "--"
else:
value_str = value_format % value
return "%s %s" % (value_str, postfix) |
def remove_from_definition(definition, node):
"""Return quorum slice definition with the given node removed and the threshold reduced by 1"""
threshold = definition['threshold']
nodes = definition['nodes']
if node in nodes:
nodes = nodes.copy()
nodes.remove(node)
threshold = max(... |
def fib_recursive(n):
"""[summary]
Computes the n-th fibonacci number recursive.
Problem: This implementation is very slow.
approximate O(2^n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a posit... |
def parse_move(move):
""" pulls the column and row out of the move """
if not (len(move) == 2):
return None, None
try:
row = ord(move[0].upper()) - 65
col = int(move[1])
except:
return None, None
return row, col |
def ordered_sequential_search(ordered_list, item):
"""Ordered Sequential search
Complexity:
item is present: best case=1, worst case=n, avg=n/2
item not present: best case=1, worst case=n, avg=n/2
Args:
ordered_list (list): An ordered list.
item (int): The item to search.
... |
def _build_poolq_shell_executable(
poolq_shell_path,
barcode_file,
condition_file,
barcode_reads,
reads,
row_barcode_policy="PREFIX:CACCG@12",
col_barcode_policy="FIXED:0",
verbose=False,
):
"""
Parameters:
------------
poolq_shell_path
path to poolq3.sh
bar... |
def listsplit(liststr=u''):
"""Return a split and stripped list."""
ret = []
for e in liststr.split(u','):
ret.append(e.strip())
return ret |
def photoUrl(prefix, suffix):
"""Construct the GET request for a foursquare photo."""
return prefix+"original"+suffix |
def reverse_region (region):
""" Reverse a given region
"""
return [region[1][::-1], region[0][::-1]] |
def filterForXml(value):
""" Replaces control characters with replace characters
@param value: The value to filter
@type value: C{unicode}
@return: The filtered value
@rtype: C{unicode}
"""
try:
regex = filterForXml._regex
except AttributeError:
import r... |
def descriptor(data):
"""Parameter list as string
data: binary data a string"""
from struct import unpack
descriptor = ""
i = 0
while i < len(data):
type,version,length = unpack(">BBH",data[i:i+4])
if type == 3:
payload = data[i+4:i+length]
descriptor = pa... |
def text_block(text, margin=0):
"""
Pad block of text with whitespace to form a regular block, optionally
adding a margin.
"""
# add vertical margin
vertical_margin = margin // 2
text = "{}{}{}".format(
"\n" * vertical_margin,
text,
"\n" * vertical_margin
)
... |
def varint_bytes(int_value):
"""Serialize `int_value` into varint bytes and return them as a byetarray."""
buf = bytearray(9)
if int_value < 0:
raise TypeError('Negative values cannot be encoded as varint.')
count = 0
while True:
next = int_value & 0x7f
int_value >>= 7
... |
def is_guarded(point, queens, n):
"""Check if a given point is guarded by any queens in a given list.
A point is guarded iff there are any queens in `queens` that are on the
same row or column, or are on the same sum or difference diagonals.
:queens: A list of (row, col) points where queens are on th... |
def trial_name_cmp_func(x,y):
"""
Comparison function for sorting trial names
"""
num_x = int(x.split('_')[1])
num_y = int(y.split('_')[1])
if num_x > num_y:
value = 1
elif num_y > num_x:
value = -1
else:
value = 0
return value |
def parse_model_config(path):
"""
Parses the configuration file.
:param path: YOLOv3 configuration file path.
:return: Module definitions as an ordered list.
"""
with open(path, 'r') as fp:
lines = fp.read().split('\n')
lines = [x.rstrip().lstrip() for x in lines if x and not x.s... |
def nthstr(n):
"""
Formats an ordinal.
Doesn't handle negative numbers.
>>> nthstr(1)
'1st'
>>> nthstr(0)
'0th'
>>> [nthstr(x) for x in [2, 3, 4, 5, 10, 11, 12, 13, 14, 15]]
['2nd', '3rd', '4th', '5th', '10th', '11th', '12th', '13th', '14th', '15th']
... |
def fix_latex_command_regex(pattern, application='match'):
"""
Given a pattern for a regular expression match or substitution,
the function checks for problematic patterns commonly
encountered when working with LaTeX texts, namely commands
starting with a backslash.
For a pattern to be matched ... |
def anonymize_number(number):
""" Anonymize 3 last digits of a number, provided as string. """
if number.isdigit() and len(number) >= 3:
return number[:-3] + "xxx"
else:
# Not a number or e.g. "unknown" if caller uses CLIR
return number |
def detokenize_enzymatic_reaction_smiles(rxn: str) -> str:
"""Detokenize an enzymatic reaction SMILES in the form precursors|EC>>products.
Args:
rxn: a tokenized enzymatic reaction SMILES.
Returns:
the detokenized enzymatic reaction SMILES.
"""
rxn = rxn.replace(" ", "")
if "[... |
def _find_channel_index(data_format):
"""Returns the index of the channel dimension.
Args:
data_format: A string of characters corresponding to Tensor dimensionality.
Returns:
channel_index: An integer indicating the channel dimension.
Raises:
ValueError: If no channel dimension was found.
"""
... |
def profile(point, context, user, owner, viewer):
"""
"""
return {'is_owner': owner == viewer } |
def get_user(app_configs):
"""
Looks for either 'api_key_id' or 'email'
in the provided dict and returns its value.
Returns None if neither are found or set to
a valid value
:param app_configs: a dictionary of all the values in the app.config file
:type app_configs: dict
:rtype: [str/N... |
def _strip_nul(text):
"""Remove NUL values from the text, so that it can be treated as text
There should likely be no NUL values in human-readable logs anyway.
"""
return text.replace('\x00', '<NUL>') |
def _get_full_attr_name(attr_name_stack, short_attr_name=None):
"""Join the attr_name_stack to get a full attribute name.
:param attr_name_stack: List of attribute names sitting on our
processing stack while building MQL queries.
:param short_attr_name: The trailing attr_name to be appended to the
... |
def number_else_string(text):
"""
Converts number to an integer if possible.
:param text: Text to be converted
:return: Integer representation of text if a number. Otherwise, it returns the text as is
"""
return int(text) if text.isdigit() else text |
def IsUserHeader(decorated_name):
"""Returns true if decoraed_name looks like a user header."""
return decorated_name[0] == '"' and decorated_name[-1] == '"' |
def proc_to_seconds(val, entry):
"""Process a value in minutes to seconds"""
return 60 * int(val) |
def format(dict):
"""
itype: Dict
rtype: String, formatted dict
"""
res = ['\t\t<object>']
for (key, val) in dict.items():
line = '\t\t\t<{}>"{}"</{}>'.format(key, val, key)
res.append(line)
res.append('\t\t</object>\n')
return '\n'.join(res) |
def _is_subpath(path, ancestors):
"""Determines if path is a subdirectory of one of the ancestors"""
for ancestor in ancestors:
if not ancestor.endswith('/'):
ancestor += '/'
if path.startswith(ancestor):
return True
return False |
def length_of(l):
"""Get number of elements in list or None for singletons."""
return len(l) if isinstance(l, list) else None |
def _is_password_valid(pw):
"""Returns `true` if password is strong enough for Firebase Auth."""
return len(pw) >= 6 |
def do_date(dt, format='%Y-%m-%d - %A'):
"""Jinja template filter to format a datetime object with date only."""
if dt is None:
return ''
# Only difference with do_datetime is the default format, but that is
# convenient enough to warrant its own template filter.
return dt.strftime(format) |
def to_list(obj):
""" Return a list containing obj if obj is not already an iterable"""
try:
iter(obj)
return obj
except TypeError:
return [obj] |
def in_range(in_num, minimum, maximum):
"""
Sees if the entered value is within the given range
:param in_num: The number to check
:type in_num: float
:param minimum: The minimum value of the range (inclusive)
:type minimum: float
:param maximum: The maximum value of... |
def solution(n: int, a: list) -> list:
"""
>>> solution(5, [3, 4, 4, 6, 1, 4, 4])
[3, 2, 2, 4, 2]
"""
counters = [0] * n
max_counter = n + 1
cur_max = 0
for num in a:
if num == max_counter:
counters = [cur_max] * n
else:
counters[num - 1] += 1
... |
def dequote(s):
""" If a string has single or double quotes around it, remove them """
if (s[0] == s[-1]) and s.startswith(("'", '"')):
return s[1:-1]
return s |
def format(formatter, payload):
"""Returns a list of formatted strings
Example:
>>> formatter = "{} is {}"
>>> data = {"name":"donnees", "age":1}
>>> result = format(formatter, data)
>>> print(result[0])
name is donnees
>>> print(result[1])
age is 1
Or
>>> formatter = lamdb... |
def get_headers(environ):
"""
Returns headers from the environ
"""
headers = {}
for name in environ:
if name[0:5] == "HTTP_":
headers[name[5:]] = environ[name]
return headers |
def orthonormal_exp(variables: list) -> list:
"""
orthonormal expansion of a list of distinct variables
>>> orthonormal_exp([1,2,3])
[(1,), (-1, 2), (-1, -2, 3), (-1, -2, -3)]
"""
result = []
last = []
for var in variables:
if last:
last[-1]*=-1
last.appe... |
def difference(num1, num2):
"""
Find the difference between 2 numbers.
:type num1: number
:param num1: The first number to use.
:type num2: number
:param num2: The second number to use.
>>> difference(1, 4)
3
"""
# Return the calculated value
return abs(num1 - num2) |
def determine_interp_factor(value, before, after):
"""Determine interpolation factor for removal of division in follow-on
code
For the formula:
v = v0 + (v1 - v0) * ((t - t0) / (t1 - t0))
I'm defining the interpolation factor as this component of the formula:
((t - t0) / (t1 - t0))... |
def shrink_path(full_path: str, max_len: int = 70) -> str:
"""
Shrinks the path name to fit into a fixed number of characters.
Parameters
-----------
full_path: String containing the full path that is to be printed. \n
max_len: Integer containing the maximum length for the f... |
def meta_name(obj):
"""
Returns meta type name of the given object.
"""
return obj.__class__.__name__ |
def is_digit(value: str) -> bool:
"""Return if ``value`` is number (decimal or whole)"""
if value.count('.') == 1 and value.replace('.', '').isdigit() or value.isdigit():
return True
return False |
def box_to_rect(box, width, height):
"""
:param box: center_x, center_y, bbox_w, bbox_h
:param width: image width
:param height: image height
:return: x1, y1, x2, y2(in pixel)
"""
x, y, w, h = box
x1 = (x - w * 0.5) * width
y1 = (y - h * 0.5) * height
x2 = (x + w * 0.5) * width... |
def flatten_dict_vals(dict_):
"""
Flattens only values in a heirarchical dictionary, keys are nested.
"""
if isinstance(dict_, dict):
return dict([
((key, augkey), augval)
for key, val in dict_.items()
for augkey, augval in flatten_dict_vals(val).items()
... |
def isEqual(lhs, rhs):
"""types should be a either a list, tuple, etc"""
print(lhs)
print(rhs)
for x,y in zip(lhs, rhs):
if x == y:
continue
else:
return False
return True |
def is_image_file(filename):
"""Check if it is an valid image file by extension."""
return any(
filename.endswith(extension)
for extension in ['jpeg', 'JPEG', 'jpg', 'png', 'JPG', 'PNG', 'gif']) |
def is_sequence(arg):
"""Returns True only if input acts like a sequence, but does
not act like a string.
"""
return (not hasattr(arg, "strip") and
hasattr(arg, "__getitem__") or
hasattr(arg, "__iter__")) |
def build_user_agent(octavia_version: str, workspace_id: str) -> str:
"""Build user-agent for the API client according to octavia version and workspace id.
Args:
octavia_version (str): Current octavia version.
workspace_id (str): Current workspace id.
Returns:
str: the user-agent s... |
def arithmetic_series(n):
"""Arithmetic series by Gauss sum formula.
Time complexity: O(1).
Space complexity: O(1)
"""
return (1 + n) * n / 2 |
def exists(field):
"""
Only return docs which have 'field'
"""
return {"exists": {"field": field}} |
def parser_NVOD_reference_Descriptor(data,i,length,end):
"""\
parser_NVOD_reference_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "NVOD_reference", "contents" : unparsed_descriptor_contents }
... |
def daily_severity_rating(fwi):
"""Daily severity rating.
Parameters
----------
fwi : array
Fire weather index
Returns
-------
array
Daily severity rating.
"""
return 0.0272 * fwi ** 1.77 |
def _get_plot_style(i, selected_case_idx, num_cases):
"""
Return plot attributes based on the index of the selected case and the number of cases.
Parameters
----------
i : int
Index of the current case.
selected_case_idx : int
Index of the selected case.
num_cases : int
... |
def flatten(array):
"""
Returns a list of flattened elements of every inner lists (or tuples)
****RECURSIVE****
"""
import numpy
res = []
for el in array:
if isinstance(el, (list, tuple, numpy.ndarray)):
res.extend(flatten(el))
continue
res.append(el)
... |
def dotmm(A, B, check=True):
"""
Matrix-matrix dot product, optimized for small number of components
containing large arrays. For large numbers of components use numpy.dot
instead. Unlike numpy.dot, broadcasting rules only apply component-wise, so
components may be a mix of scalars and numpy arrays ... |
def ComputeAngleDifference(angle1, angle2):
"""
This function computes the difference between two angles.
:rtype : float
:param angle1: float with the first angle
:param angle2: float with the second angle
:return:
"""
if angle1 < 0:
inicial = angle1 + 360
else:
inic... |
def compose_username(nick, email, provider):
"""
@brief Compose the username
The username policy via openid is as follow:
* Try to use the nick name
* If not available fall back to email
* Append the the openid provider as domain. Delimiter is % in order to
diferentiate from @ (if email ... |
def converttodiamondmatrix(m):
"""
Convert to a diamond shaped matrix.
a
a b c d b
d e f -> g e c
g h i h f
i
"""
d = [ [ "" for _ in range(len(m)*2-1) ] for _ in range(2*len(m)-1) ]
for y in range(1, 2*len(m)):
for x in... |
def dsv_of_list(d, sep=","):
"""
Converting a list of strings to a dsv (delimiter-separated values) string.
Note that unlike most key mappers, there is no schema imposing size here. If you wish to impose a size
validation, do so externally (we suggest using a decorator for that).
Args:
d: ... |
def analyze_discriminant(lookup, word1, word2):
"""Find patterns that include word1 but not word2."""
ret = []
for pattern, words in lookup.items():
# XOR presence of these words
if (word1 in words) != (word2 in words):
ret.append(pattern)
return ret |
def generate_resource_link(pid, resource_path, static=False, title=None):
"""
Returns a valid html link to a public resource within an autogenerated instance.
Args:
pid: the problem id
resource_path: the resource path
static: boolean whether or not it is a static resource
ti... |
def intcode_parse(code):
"""Accepts intcode. Parses intcode and returns individual parameters. """
actual_code = code % 100
parameter_piece = code - actual_code
parameter_piece = parameter_piece // 100
parameter_code_list = []
while parameter_piece > 0:
parameter_code_list.append(param... |
def calc_system_multiplier(grow_system):
"""
System Multiplier
Notes
-----
Standard yield isn't 100% accurate and doesn't consider high density vertical farming systems. The estimated yield
from ZipGrow Ziprack_8 is 66,825 kg/year for 235m2 plant area. Adjusted yield without multiplier i... |
def move_zeros(array):
"""Algorithm to move zeros to end of array while preserving positions of other elements"""
count = abs(array.count(0) - sum(x is False for x in array))
nozeros = [elem for elem in array if elem != 0 or elem is False]
return nozeros+[0 for i in range(count)] |
def get_bin_linesep(encoding, linesep):
"""
Simply doing `linesep.encode(encoding)` does not always give you
*just* the linesep bytes, for some encodings this prefix's the
linesep bytes with the BOM. This function ensures we just get the
linesep bytes.
"""
if encoding == 'utf-16':
re... |
def float_to_rational(value: float):
"""Casts a float to a DcRationalNumberType.
:param value: The value to cast.
:return: DcRationalNumberType -- the cast result.
"""
if value == 0:
return 0, 0
string = format(value, ".2e")
if abs(value) < 1:
string = string.split("e") # K... |
def get_mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/float(n) |
def convert_int_minutes_to_militar_time_format(list):
"""
Convert the list of minutes ranges to a list of hour ranges.
>>> convert_int_minutes_to_militar_time_format([[540, 600], [720, 780]])
[['9:00', '10:00'], ['12:00', '13:00']]
"""
result = []
for i in list:
hours = int... |
def esc_seq(n, s):
"""Escape sequence. Call sys.stdout.write() to apply."""
return f'\033]{n};{s}\007' |
def _context_license_spdx(context, value):
"""convert a given known spdx license to another one"""
# more values can be taken from from https://github.com/hughsie/\
# appstream-glib/blob/master/libappstream-builder/asb-package-rpm.c#L76
mapping = {
"Apache-1.1": "ASL 1.1",
"Apache-2.0... |
def decode(search_input: str, post: str) -> int:
""" Binary space partitioning.
"""
elem_length = 2 ** len(search_input)
elem = 0
for char in search_input:
elem_length //= 2
if char == post:
elem += elem_length
return elem |
def _twos_complement(value: int, bits: int) -> int:
""" This does twos complement so we can convert hex strings to signed integers.
Why is this not built-in to python int?
"""
if value & (1 << (bits - 1)):
value -= 1 << bits
return value |
def find_seq(template, query):
"""find sequence in another.
Input string template and tuple of queries.
Output list of matches. """
matches = []
for seq in query:
if seq in template:
matches.append(seq)
# print('find_seq', matches)
return matches |
def f2suff(forfile, opath, suff):
"""
Construct outputfile in opath with new suffix.
Definition
----------
def f2suff(forfile, opath, suff):
Input
-----
forfile Fortran90 file name
opath relative output path
Script assumes output path: dirname(forfile)/opath
... |
def white(message):
"""
white color
:return: str
"""
return f"\x1b[37;1m{message}\x1b[0m" |
def readattr(_obj, _name, _default=None, _error_on_none=None):
"""
Reads an attribute value from an object
:param _obj: The object
:param _name: The name of the attribute
:param _default: If set, the value to return if the attribute is missing or the value is None
:param _error_on_none: If set, ... |
def check_output(*popenargs, **kwargs):
"""
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
... |
def check_status(checksite):
"""Return true only if wiki is public and open"""
return ((checksite.get('closed') is None)
and (checksite.get('private') is None)
and (checksite.get('fishbowl') is None)) |
def make_safe_star_id(star_id):
""" Make a star id that is safe to include in a URL.
:param star_id: star id that may contain spaces or plus signs [string].
:return: star_id safe to include in a URL [string].
"""
return star_id.replace("+", "%2B").replace(" ", "+") |
def _round_point_no_nearest(point, epsilon):
"""
:param point: list of coordinates
"""
return [round(x / epsilon) * epsilon for x in point] |
def formatnumber(n):
"""Format a number with beautiful commas."""
parts = list(str(n))
for i in range((len(parts) - 3), 0, -3):
parts.insert(i, ',')
return ''.join(parts) |
def generate_hostname(ip_address):
"""
:param IPv4Address ip_address:
:rtype: unicode
:return:
"""
numeric_ip = int(ip_address)
return "x{:02x}{:02x}{:02x}{:02x}".format((numeric_ip >> 0x18) & 0xFF,
(numeric_ip >> 0x10) & 0xFF,
... |
def distance_from_speed_and_time(movement_speed, movement_time):
"""Returns distance from speed and time"""
return movement_time * movement_speed * 1000 / 3600 |
def get_masters(ppgraph):
"""From a protein-peptide graph dictionary (keys proteins,
values peptides), return master proteins aka those which
have no proteins whose peptides are supersets of them.
If shared master proteins are found, report only the first,
we will sort the whole proteingroup later a... |
def get_r_squared(t, dof):
"""
Get the r-squared value for effective size measure.
Parameters
----------
> t: the t-statistic for the distribution
> dof: the degrees of freedom of the sample
Returns
-------
The r_squared value for effective size measure
"""
t_squared = t * t
return t_squar... |
def _ns_join(name, ns):
"""Dumb version of name resolution to mimic ROS behaviour."""
if name.startswith("~") or name.startswith("/"):
return name
if ns == "~":
return "~" + name
if not ns:
return name
if ns[-1] == "/":
return ns + name
return ns + "/" + name |
def QuickSort(A, l, r):
"""
Arguments:
A -- total number list
l -- left index of input list
r -- right index of input list
Returns:
ASorted -- sorted list
cpNum -- Number of comparisons
"""
# Number of comparisons
cpNum = r - l
# Base case
if cpNum == 0:
return [A[l]], 0
elif cpNum ... |
def _parse_licenses(output):
"""Parse the licenses information.
It will return a dictionary of products and their
license status.
"""
licenses = {}
# We are starting from 2, since the first line is the
# list of fields and the second one is a separator.
# We can't use csv to parse this... |
def tof2ev(d, t0, E0, t):
"""
d/(t-t0) expression of the time-of-flight to electron volt
conversion formula.
**Parameters**\n
d: float
Drift distance
t0: float
time offset
E0: float
Energy offset.
t: numeric array
Drift time of electron.
**Return**\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.