content stringlengths 42 6.51k |
|---|
def get_secret(str_or_list):
"""
Find and returns mail secret.
Mail secret uses following format:
SECRET{ some-secret }
note that there are no spaces between all capitalized keyword
SECRET and immediately following it curly brackets.
However, the text inside curly brackets can be surrounded by white
spaces. In example above ``get_secret``
function returns "some-secret" string.
:str_or_list: argument can be either a string of a list of
strings.
"""
text = str_or_list
if isinstance(str_or_list, list):
text = "\n".join(str_or_list)
try:
message_secret = text.split('SECRET{')[1].split('}')[0]
except IndexError:
message_secret = None
if message_secret:
message_secret = message_secret.strip()
return message_secret |
def has_docstring(func):
"""Check to see if the function
`func` has a docstring.
Args:
func (callable): A function.
Returns:
bool
"""
ok = func.__doc__ is not None
if not ok:
print("{} doesn't have a docstring!".format(func.__name__))
else:
print("{} looks ok".format(func.__name__))
return func.__doc__ is not None |
def is_hidden(var, X, e):
"""Is var a hidden variable when querying P(X|e)?"""
return var != X and var not in e |
def __highlight_function__(feature):
"""
Function to define the layer highlight style
"""
return {"fillColor": "#ffaf00", "color": "green", "weight": 3, "dashArray": "1, 1"} |
def _call_with_frames_removed(func, *args, **kwds):
"""
remove_importlib_frames in import.c will always remove sequences
of importlib frames that end with a call to this function
Use it instead of a normal call in places where including the importlib
frames introduces unwanted noise into the traceback (e.g. when executing
module code)
"""
return func(*args, **kwds) |
def appendUrl(baseUrl, appendedPath):
"""
Concatinates 2 url paths, eliminating the trailing / from the first one, if required.
This function is not compatible with query paramters or anything other than urlpaths.
baseUrl (str): The base url to be appended to.
appendedPath (str): The appended portion of the path.
Returns: A new url with the full path.
"""
if not baseUrl or len(baseUrl) <= 0:
return appendedPath
if not appendedPath or len(appendedPath) <= 0:
return baseUrl
if baseUrl.endswith("/") and appendedPath.startswith("/"):
baseUrl = baseUrl[:len(baseUrl)-1]
return baseUrl + appendedPath |
def infixe(arbre):
"""Fonction qui retourne le parcours prefixe de l'arbre
sous la forme d'une liste
"""
liste = []
if arbre != None:
liste += infixe(arbre.get_ag())
liste.append(arbre.get_val())
liste += infixe(arbre.get_ad())
return liste |
def LowercaseMutator(current, value):
"""Lower the value."""
return current.lower() |
def OffsetPosition(in_ra,in_dec,delta_ra,delta_dec):
"""
Offset a position given in decimal degrees.
Parameters
----------
in_ra: float
Initial RA (decimal degrees).
in_dec: float
Initial DEC (demical degrees).
delta_ra: float
Offset in RA (decimal degrees).
delta_dec: float
Offset in DEC (decimal degrees).
Returns
-------
ra: float
Offset RA.
dec: float
Offset DEC.
"""
ra = in_ra
dec = in_dec + delta_dec
if dec > 90.:
dec = 180 - dec
ra = 180 + ra
if dec < -90.:
dec = -180 - dec
ra = 180 + ra
ra = ra + delta_ra
if ra > 360.:
ra = ra - 360.
if ra < 0.:
ra = ra + 360.
return ra,dec |
def GetRateURL(base, symbols, date="latest"):
"""Create the URL needed to access the API.
For a date and chosen currencies."""
url = "http://api.fixer.io/%s?base=%s&symbols=%s" % (date, base, symbols)
return url |
def is_code_line(line):
"""A code line is a non empty line that don't start with #"""
return line.strip()[:1] not in {'#', '%', ''} |
def clamp(n, range):
"""
Given a number and a range, return the number, or the extreme it is closest to.
:param n: number
:param range: tuple with min and max
:return: number
"""
minn, maxn = range
return max(min(maxn, n), minn) |
def IsWithinTMRegion(pos, posTM):#{{{
"""Check whether a residue position is within TM region
"""
isWithin = False
for (b,e) in posTM:
if pos >= b and pos < e:
return True
return False |
def normalization(value, maxvalue, minvalue):
"""
normalization method
"""
value = (value - minvalue) / (maxvalue - minvalue)
return value |
def parenthesize(digitList):
"""
For each digit x in the digit list, this method adds x
parenthesis before and after the digit. It returns the new list.
"""
parenthesizedList = []
for x in digitList:
parenthesizedList += ['(']*int(x) + [x] + [')']*int(x)
return parenthesizedList |
def find_next_square(sq):
"""
Complete the findNextSquare method that finds the next integral perfect square after
the one passed as a parameter. If the parameter is itself not a perfect square, than -1
should be returned. You may assume the parameter is positive.
:param sq: a positive integer.
:return: the next perfect square after the given one else, not given perfect square return -1.
"""
root = sq ** 0.5
if root.is_integer():
return (root + 1)**2
return -1 |
def split_rpm_filename(rpm_filename):
"""
Parse the components of an rpm filename and return them as a tuple: (name, version, release, epoch, arch)
foo-1.0-1.x86_64.rpm -> foo, 1.0, 1, '', x86_64
1:bar-9-123a.ia64.rpm -> bar, 9, 123a, 1, ia64
:param rpm_filename: a string filename (not path) of an rpm file
:returns: a tuple of the constituent parts compliant with RPM spec.
"""
components = rpm_filename.rsplit('.rpm', 1)[0].rsplit('.', 1)
arch = components.pop()
rel_comp = components[0].rsplit('-', 2)
release = rel_comp.pop()
# Version
version = rel_comp.pop()
# Epoch
epoch_comp = rel_comp[0].split(':', 1) if rel_comp else []
if len(epoch_comp) == 1:
epoch = ''
name = epoch_comp[0]
elif len(epoch_comp) > 1:
epoch = epoch_comp[0]
name = epoch_comp[1]
else:
epoch = None
name = None
return name, version, release, epoch, arch |
def _smallest_size_at_least(height, width, smallest_side):
"""Computes new shape with the smallest side equal to `smallest_side`.
Computes new shape with the smallest side equal to `smallest_side` while
preserving the original aspect ratio.
Args:
height: an int32 scalar indicating the current height.
width: an int32 scalar indicating the current width.
smallest_side: A python integer or scalar indicating the size of
the smallest side after resize.
Returns:
new_height: an int32 scalar indicating the new height.
new_width: and int32 scalar indicating the new width.
"""
height = float(height)
width = float(width)
smallest_side = float(smallest_side)
if height > width:
scale = smallest_side / width
else:
scale = smallest_side / height
new_height = int(height * scale)
new_width = int(width * scale)
return new_height, new_width |
def apply_fn_to_list_items_in_dict(dictionary, fn, **kwargs):
"""
Given a dictionary with items that are lists, applies the given function to each
item in each list and return an updated version of the dictionary.
:param dictionary: the dictionary to update.
:param fn: the function to apply.
:param **kwargs: variable keyworded arguments to run fn with
:returns: an updated version of the dictionary.
"""
updated_dictionary = {}
for key, items in dictionary.items():
updated_items = []
for item in items:
updated_item = fn(item, **kwargs)
updated_items.append(updated_item)
updated_dictionary[key] = updated_items
return updated_dictionary |
def split_reversible_reactions(crn):
"""
Replace every reversible reaction with the two corresponding irreversible
reactions.
"""
new = []
for [r, p, k] in crn:
assert len(k) == 1 or len(k) == 2
new.append([r, p])
if len(k) == 2:
new.append([p, r])
return new |
def celsius_to_fahrenheit(celsius: float) -> float:
"""Convert degrees Celsius to degrees Fahrenheit
:param float celsius: a temperature in Celsius
:return: a temperature in Fahrenheit
:rtype: float
"""
return celsius * 9.0/5.0 + 32.0 |
def calculate_diagnol_periphery_73251a56(i, j, y, diagonol):
"""Looking at 6 directions to the current y[i,j] location
which is not equal to the diagonal element and append it to the list"""
near_diagnol_element = []
if (y[i + 1][j] != 0 and y[i + 1][j] != diagonol):
near_diagnol_element.append(y[i + 1][j])
elif (y[i - 1][j] != 0 and y[i - 1][j] != diagonol):
near_diagnol_element.append(y[i - 1][j])
elif (y[i][j + 1] != 0 and y[i][j + 1] != diagonol):
near_diagnol_element.append(y[i][j + 1])
elif (y[i][j - 1] != 0 and y[i][j - 1] != diagonol):
near_diagnol_element.append(y[i][j - 1])
elif (y[i + 2][j - 1] != 0 and y[i + 2][j - 1] != diagonol):
near_diagnol_element.append(y[i + 2][j - 1])
elif (y[i - 1][j + 2] != 0 and y[i - 1][j + 2] != diagonol):
near_diagnol_element.append(y[i - 1][j + 2])
# Return unique color found
return max(set(near_diagnol_element), key=near_diagnol_element.count) |
def params_to_mongo(query_params):
"""Convert HTTP query params to mongodb query syntax.
Converts the parse query params into a mongodb spec.
:param dict query_params: return of func:`rest.process_params`
"""
if not query_params:
return {}
for key, value in query_params.items():
if isinstance(value, list):
query_params[key] = {'$in': value}
return query_params |
def function_with_types_in_docstring(param1, param2):
"""Compare if param1 is greater than param2.
Example function with types documented in the docstring.
Function tests if param1 is greater than param2 (True) otherwise
returns False.
`PEP 484`_ type annotations are supported. If attribute, parameter, and
return types are annotated according to `PEP 484`_, they do not need to be
included in the docstring:
Parameters
----------
param1 : int
The first parameter.
param2 : str
The second parameter.
Returns
-------
bool
True if successful, False otherwise.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
"""
result = None
try:
converted_param2 = int(param2)
if param1 > converted_param2:
result = True
else:
result = False
except ValueError:
print("Parameter 2 must be a string representing a number using digits [0-10]")
raise ValueError
except TypeError:
print("Parameter 1 must be an integer")
raise TypeError
print(f"Function called with: {param1} and {param2}")
print(f"Function returns: {result}")
return result |
def search_box(display_mode, query_params, user, *args, **kwargs):
""" Template tag to render the search box. """
return {
"display_mode": display_mode,
"GET_params": query_params,
"user": user,
} |
def parse_video_time_format(s, fps=30.):
""" Format MM:SS.f """
m, sf = s.split(":")
m = float(m)
s, f = [float(x) for x in sf.split(".")]
time_interval = m * 60. + s + 1. /fps * f
return time_interval |
def _translate_int(exp, length):
""" Given an integer index, return a 3-tuple
(start, count, step)
for hyperslab selection
"""
if exp < 0:
exp = length+exp
if not 0<=exp<length:
raise ValueError("Index (%s) out of range (0-%s)" % (exp, length-1))
return exp, 1, 1 |
def _partition(env_list, is_before):
"""partition the list in the list items before and after the sel"""
before, after = [], []
iterator = iter(env_list)
while True:
try:
item = next(iterator)
except:
break
if is_before(item):
before.append(item)
else:
after.append(item)
after.extend(iterator)
break
return before, after |
def rivers_with_station(stations):
""" Given a list of station objects, this function returns a set,
with the names of the rivers with a monitoring station.
"""
rivers = set()
for station in stations:
rivers.add(station.river)
return rivers |
def get_labels(filename, logger=None):
"""Returns a dictionary of alternative sequence labels, or None
- filename - path to file containing tab-separated table of labels
Input files should be formatted as <key>\t<label>, one pair per line.
"""
labeldict = {}
if filename is not None:
if logger:
logger.info("Reading labels from %s", filename)
with open(filename, 'rU') as ifh:
count = 0
for line in ifh.readlines():
count += 1
try:
key, label = line.strip().split('\t')
except ValueError:
if logger:
logger.warning("Problem with class file: %s",
filename)
logger.warning("%d: %s", (count, line.strip()))
logger.warning("(skipping line)")
continue
else:
labeldict[key] = label
return labeldict |
def f(x):
""" A function. """
y = x + 10
return y |
def _stringToList(str: str) -> list:
"""Convert a string containing endLine char into
a list.
"""
l = []
s = ''
for c in str:
if c == '\n':
l.append(s)
s = ''
else:
s += c
l.append(s)
return l |
def get_root(region_parent_zip, region_id):
"""
Return the penultimate `parent_id` for any `region_id`.
The penultimate parent is one layer below the root (0).
The set of penultimate parents are the distinct regions contained in the segmentation.
They correspond to putative functional regions.
:param tuple region_parent_zip: a list of 2-tuples of `region_ids` and `parent_ids`
:param int region_id: the `region_id` whose root parent_id is sought
:return int parent_id: the corresponding penultimate `parent_id` (one step below the root - value of `0`)
"""
if region_id == 0:
return 0
# derive a dictionary of region_id-->parent_id
region_parent_dict = dict(region_parent_zip)
# terminate when the ultimate parent is 0
while region_parent_dict[region_id] != 0:
# get the parent of the parent
region_id = region_parent_dict[region_id]
# this is the penultimate region_id
parent_id = region_id
return parent_id |
def get_all_manifests(image_assembly_config_json):
"""Returns the list of all the package manifests mentioned in the specified product configuration.
Args:
image_assembly_config_json: Dictionary, holding manifest per categories.
Returns:
list of path to the manifest files as string.
Raises:
KeyError: if one of the manifest group is missing.
"""
try:
return image_assembly_config_json.get(
"base", []) + image_assembly_config_json.get(
"cache", []) + image_assembly_config_json.get("system", [])
except KeyError as e:
raise KeyError(
f"Product config is missing in the product configuration: {e}") |
def _legacy_client_key_set(clients):
"""
Transform a set of client states into a set of client keys.
"""
return {cs.client_key for cs in clients} |
def new_test(tag, name):
"""Create default, empty sub-test result objects
:param tag: tag for resource being tested
:param name: name of sub-test
:return: sub-test object
"""
# init all status message to 'could not be executed' failures
test = {'tag': tag,
'test': name,
'status': 'UNEXECUTED',
'message': 'Test could not be executed',
'extra': []
}
return test |
def tags_to_spans(tags):
"""Convert tags to spans."""
spans = set()
span_start = 0
span_end = 0
active_conll_tag = None
for index, string_tag in enumerate(tags):
# Actual BIO tag.
bio_tag = string_tag[0]
assert bio_tag in ["B", "I", "O"], "Invalid Tag"
conll_tag = string_tag[2:]
if bio_tag == "O":
# The span has ended.
if active_conll_tag:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = None
# We don't care about tags we are
# told to ignore, so we do nothing.
continue
elif bio_tag == "B":
# We are entering a new span; reset indices and active tag to new span.
if active_conll_tag:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
elif bio_tag == "I" and conll_tag == active_conll_tag:
# We're inside a span.
span_end += 1
else:
# This is the case the bio label is an "I", but either:
# 1) the span hasn't started - i.e. an ill formed span.
# 2) We have IOB1 tagging scheme.
# We'll process the previous span if it exists, but also include this
# span. This is important, because otherwise, a model may get a perfect
# F1 score whilst still including false positive ill-formed spans.
if active_conll_tag:
spans.add((active_conll_tag, (span_start, span_end)))
active_conll_tag = conll_tag
span_start = index
span_end = index
# Last token might have been a part of a valid span.
if active_conll_tag:
spans.add((active_conll_tag, (span_start, span_end)))
# Return sorted list of spans
return sorted(list(spans), key=lambda x: x[1][0]) |
def real(s):
"""Proper function from kata designer."""
head = s.rstrip('0123456789')
tail = s[len(head):]
if tail == "":
return s+"1"
return head + str(int(tail) + 1).zfill(len(tail)) |
def lat_dict_to_list(dct: dict) -> list:
"""Make a dictionary of lattice information to a 6-vector [a, b, c, alpha, beta, gamma]."""
return [
dct[k] for k in ("a", "b", "c", "alpha", "beta", "gamma")
] |
def replace_strings(s, replacers):
"""Performs a sequence of find-replace operations on the given string.
Args:
s: the input string
replacers: a list of (find, replace) strings
Returns:
a copy of the input strings with all of the find-and-replacements made
"""
sout = s
for sfind, srepl in replacers:
sout = sout.replace(sfind, srepl)
return sout |
def extract_num(buf, start, length):
""" extracts a number from a raw byte string. Assumes network byteorder """
# note: purposefully does /not/ use struct.unpack, because that is used by the code we validate
val = 0
for i in range(start, start+length):
val <<= 8
val += ord(buf[i])
return val |
def str_to_seconds(string):
"""Pocesses a string including time units into a float in seconds.
Args:
string (str): Input string, including units.
Returns:
float: The processed time in seconds.
Examples:
>>> int(round(str_to_seconds('1')))
1
>>> int(round(str_to_seconds('1s')))
1
>>> int(round(str_to_seconds('2m')))
120
>>> int(round(str_to_seconds('3h')))
10800
>>> int(round(str_to_seconds('2d')))
172800
"""
if isinstance(string, str):
multipliers = {"s": 1.0, "m": 60.0, "h": 60.0 ** 2.0, "d": 24.0 * 60 ** 2.0}
for key, multiplier in zip(multipliers, list(multipliers.values())):
if key in string:
return float(string.strip(key)) * multiplier
return float(string) |
def to_square(coefficients):
"""
Computes f^2 and returns its coefficients, where f is a polynomial function given as a list of coefficients
:param coefficients: list of coefficients of a polynomial function f
:return result: list of coefficients of polynomial function f^2
"""
result = [0 for number in range(len(coefficients) * 2 - 1)]
for index_1 in range(len(coefficients)):
for index_2 in range(len(coefficients)):
result[index_1 + index_2] += coefficients[index_1] * coefficients[index_2]
return result |
def forward_differences(f, h, x):
"""
Forward Finite Differences.
Approximating the derivative using the Forward
Finite Method.
Parameters:
f : function to be used
h : Step size to be used
x : Given point
Returns: Approximation
"""
return (f(x + h) - f(x)) / h |
def sigmoid_pw(x):
"""A piecewise linear version of sigmoid."""
# Make use of sigmoid(-x) = 1 - sigmoid(x)
positive = True
if x < 0.:
positive = False
x = -x
if x < 1.:
y = 0.23105 * x + 0.50346
elif x < 2.:
y = 0.14973 * x + 0.58714
elif x < 3.:
y = 0.07177 * x + 0.74097
elif x < 4.:
y = 0.02943 * x + 0.86595
elif x < 5.:
y = 0.01129 * x + 0.93751
else:
y = 1.0
return y if positive else 1. - y |
def route_file_paths(fpaths,dir_src,dir_dst):
"""Convert list of files to src:dst maps, replacing src with dst filepath
:param fpaths: list of globbed filepaths
:param dir_src: filepath (str)
:param dir_dst: filepath (str)
:return: list of dicts with src:dst filepaths (str)
"""
return [ {'src': f, 'dst': f.replace(dir_src,dir_dst)} for f in fpaths] |
def complement_angle(angle):
""" 90 minus angle, in degrees"""
return 90 - angle; |
def users_in_same_organization(user_one, user_two):
"""Returns true if the two users passed in belong to the same organization."""
if not hasattr(user_one, 'organization') or not hasattr(user_two, 'organization'):
return False
return user_one.organization == user_two.organization |
def set_bit(current, epaddr, v):
"""
>>> bin(set_bit(0, 0, 1))
'0b1'
>>> bin(set_bit(0, 2, 1))
'0b100'
>>> bin(set_bit(0b1000, 2, 1))
'0b1100'
>>> bin(set_bit(0b1100, 2, 0))
'0b1000'
>>> bin(set_bit(0b1101, 2, 0))
'0b1001'
"""
if v:
return current | 1 << epaddr
else:
return current & ~(1 << epaddr) |
def closed_range(start: int, stop: int, step=1) -> range:
"""
Creates a closed range that allows you to specify a case
from [start, stop] inclusively.
```
with switch(value) as s:
s.case(closed_range(1, 5), lambda: "1-to-5")
s.case(closed_range(6, 7), lambda: "6")
s.default(lambda: 'default')
```
:param start: The inclusive lower bound of the range [start, stop].
:param stop: The inclusive upper bound of the range [start, stop].
:param step: The step size between elements (defaults to 1).
:return: A range() generator that has a closed upper bound.
"""
if start >= stop:
raise ValueError("Start must be less than stop.")
return range(start, stop + step, step) |
def letterMatch(letter, alphalist, letterlist, hanglist):
"""Hangman letter test with logic for no retries of prior submitted letters.
Return True if match, False if no match, or None if invalid letter."""
ch = letter[0] if (str == type(letter)) and (0 < len(letter)) else None
fmatch = None
if (None != ch) and (ch in alphalist):
fmatch = False
alphalist.remove(ch)
for k in range(0, len(letterlist)):
if ch == letterlist[k]:
fmatch = True
hanglist[k] = ch
return fmatch |
def first_or_default(iterable, predicate=None, default=None):
"""First the first value matching a perdicate otherwise a default value.
:param iterable: The items over which to iterate.
:param predicate: A predicate to apply to each item.
:param default: The value to return if no item matches.
:return: The first value matching a predicate otherwise the default value.
"""
for item in iterable:
if not predicate or predicate(item):
return item
return default |
def match_strings(str1, str2):
"""
Returns the largest index i such that str1[:i] == str2[:i]
"""
i = 0
min_len = len(str1) if len(str1) < len(str2) else len(str2)
while i < min_len and str1[i] == str2[i]: i += 1
return i |
def sizeof_fmt(num, suffix='B'):
"""Size to human readable format.
From stack overflow.
"""
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix) |
def invert(n):
"""Return 1 if n is 0, 0 if n is 1, otherwise n."""
if n == 0:
return 1
elif n == 1:
return 0
else: # NaN case
return n |
def create_ant(var_num):
"""
:param var_num: number of variables needed for the obj.function
:return: a combined list of 2 elements. Element 0 is the path as a list. Element 1 is the obj. value.
"""
path = []
#for initial values we believe the ants chose the 0-th discrete value. (count method 0 ...n-1)
for i in range(var_num):
path.append(0)
#for initial value i choose a big one , but it depends on the nature of the obj. function
value = 1000
ant = []
ant.append(path)
ant.append(value)
return ant |
def quantify(iterable, pred=bool):
"""Count the number of items in iterable for which pred is true."""
return sum(1 for item in iterable if pred(item)) |
def get_boolean(entry):
"""
This function ...
:param entry:
:return:
"""
return entry == "True" |
def reverse_seq(seq):
"""(str) -> str
Return reverse complement of sequence (used for writing rev comp sequences to fastq files).
>>> reverse_seq('TCAGCATAATT')
'AATTATGCTGA'
>>> reverse_seq('ACTGNN')
'NNCAGT'
"""
rev_comp = ''
nuc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'}
for base in seq:
rev_comp = nuc[base] + rev_comp
return rev_comp |
def phred(q):
"""Convert 0...1 to 0...30
No ":".
No "@".
No "+".
"""
n = int(q * 30 + 33)
if n == 43:
n += 1
if n == 58:
n += 1
return chr(n) |
def unique(L):
"""
L is a list
Return unique elements in L
"""
unique = []
for i in L:
if i not in unique:
unique.append(i)
return unique |
def newman_conway(num):
""" Returns a list of the Newman Conway numbers for the given value.
Time Complexity: O(n)
Space Complexity: O(n)
"""
if num ==0:
raise ValueError
if num == 1:
return '1'
p = [0,1,1]
for i in range(3, num+1):
sum = p[p[i - 1]] + p[i - p[i - 1]]
p.append(sum)
return ' '.join(str(elem) for elem in p[1:]) |
def calculate_condensate_params(Rvi, Bgi):
"""
Calculate theoretically the undefined properties of gas-condensate (Bo, Rs)
Input:
Rvi: initial Rv, float
Bgi: initial Bg, float
Output:
Rsi: initial Rs, float
Boi: initial Bo, float
"""
Rsi = 1 / Rvi
Boi = Rsi * Bgi
return(Rsi, Boi) |
def bytes_to_hexstr(value, start='', sep=' '):
"""Return string of hexadecimal numbers separated by spaces from a bytes object."""
return start + sep.join(["{:02X}".format(byte) for byte in bytes(value)]) |
def pow_mod(n, k, mod):
"""
Exponentiation by squaring
:return: n ** k
"""
if k == 0:
return 1
elif k & 1 == 1:
return pow_mod(n, k - 1, mod) * n % mod
else:
tmp = pow_mod(n, k // 2, mod)
return tmp * tmp % mod |
def get_valid_macs(data):
"""Get a list of valid MAC's from the introspection data."""
return [m['mac']
for m in data.get('all_interfaces', {}).values()
if m.get('mac')] |
def integer_bit_length_shift_counting(num):
"""
Number of bits needed to represent a integer excluding any prefix
0 bits.
:param num:
Integer value. If num is 0, returns 0. Only the absolute value of the
number is considered. Therefore, signed integers will be abs(num)
before the number's bit length is determined.
:returns:
Returns the number of bits in the integer.
"""
bits = 0
if num < 0:
num = -num
# Do not change this to `not num` otherwise a TypeError will not
# be raised when `None` is passed in as a value.
if num == 0:
return 0
while num >> bits:
bits += 1
return bits |
def bytes_to_string(_bytes) -> str:
"""Decodes bytes to utf-8 string
Args:
_bytes (bytes): bytes value
Returns:
str
.. todo:: We're not decoding the string here, because it
fails for certain windows commands
"""
value = str(_bytes.replace(b"\x00", b""))[2:-1].replace("\r", "")
value = value.replace("\\r", "").replace("\\n", " ")
return value |
def quit(msg=''):
"""Return a valid QUIT message with an optional reason."""
return 'QUIT :%s' % msg |
def rot2omega(rot,twotheta,ccwrot):
"""
sign dependent determination of omega from rot and twotheta
"""
if ccwrot:
return(rot-twotheta/2.0)
else:
return(-rot-twotheta/2.0) |
def _get_all_authors(commits_info):
""" Returns all authors' information
The information includes name and Email
"""
authors_unduplicated = [{'name': commit_info['author'], 'email': commit_info['authorEmail']}
for commit_info in commits_info]
all_names = []
authors = []
for author in authors_unduplicated:
if author['name'] not in all_names:
authors.append(author)
all_names.append(author['name'])
return authors |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]:
if value.lower().endswith(letter):
return int(value[:-len(letter)], 0) * multiplier
else:
return int(value, 0) |
def number_of_short_term_peaks(n, t, t_st):
"""
Estimate the number of peaks in a specified period.
Parameters
----------
n : int
Number of peaks in analyzed timeseries.
t : float
Length of time of analyzed timeseries.
t_st: float
Short-term period for which to estimate the number of peaks.
Returns
-------
n_st : float
Number of peaks in short term period.
"""
assert isinstance(n, int), 'n must be of type int'
assert isinstance(t, float), 't must be of type float'
assert isinstance(t_st, float), 't_st must be of type float'
return n * t_st / t |
def all_equal(elements):
"""return True if all the elements are equal, otherwise False.
"""
first_element = elements[0]
for other_element in elements[1:]:
if other_element != first_element: return False
return True |
def search_boolean(search_query, forward_index, inverted_index, documents_id):
"""Search the words of search_query in inverted index
:param str search_query: normilized with stemming
:param dict forward_index:
:param dict inverted_index:
:param list of str documents_id:
:return list of Document documents: returns empty list if documents aren't found
"""
docs_id = []
words_in_query = search_query.split(" ")
words = []
for word in words_in_query:
if word in inverted_index.keys():
docs_id.append(set(inverted_index[word]))
words.append(word)
documents = []
if len(docs_id) > 0:
set_of_docs_id = docs_id[0]
for docs_set in docs_id:
set_of_docs_id = set_of_docs_id.intersection(docs_set)
for id in set_of_docs_id:
documents.append(forward_index[str(id)])
return documents |
def slices_overlap(slice_a, slice_b):
"""Test if the ranges covered by a pair of slices overlap."""
assert slice_a.step is None
assert slice_b.step is None
return max(slice_a.start, slice_b.start) \
< min(slice_a.stop, slice_b.stop) |
def flatten(some_list):
"""
Flatten a list of lists.
Usage: flatten([[list a], [list b], ...])
Output: [elements of list a, elements of list b]
"""
new_list = []
for sub_list in some_list:
new_list += sub_list
return new_list |
def _assert_int(num):
"""
Tries to parse an integer num from a given string
:param num: Number in int/string type
:return: Numeric value
"""
if isinstance(num, int):
return num
num_str = str(num)
radix = 16 if num_str.lower().startswith('0x') else 10
res = int(num_str, radix)
# Python converts str to int as a signed integer
if res > 0x7FFFFFFF:
res -= 0x100000000
return res |
def __int_to_binary_char__(char_as_ord):
"""converts ordinal char represenation to binary string, e.g. b'x'.
It is used for parametrized test because the chars are passed as integers.
"""
return chr(char_as_ord).encode() |
def ruby_strip(chars):
"""Strip whitespace and any quotes."""
return chars.strip(' "\'') |
def eh_tabuleiro(tab):
"""
eh_tabuleiro recebe um argumento de qualquer tipo e devolve True
se o argumento corresponder a um tabuleiro (ou seja, um tuplo com 3 tuplos
em que cada um deles contem um inteiro igual a -1, 1 ou 0), caso contrario
devolve False.
"""
if not type(tab)==tuple:
return False
if len(tab)==3:
for linha in tab:
if not type(linha)==tuple:
return False
if len(linha)==3:
for num in linha:
if not (num in [-1,0,1] and type(num)==int):
return False
else:
return False
else:
return False
return True |
def get_prg_ids(prg_num: int, c_addrs: str, curr_text: str, ids_row: list) -> bool:
""" Function that generates indices of points in PRG table matching current text """
# Definiujemy podstawowe parametry
c_start = 0
found_flag = False
empty_idx = ids_row.index('')
for i in range(prg_num):
if '' not in ids_row:
break
str_idx1 = c_addrs.find(curr_text, c_start)
if str_idx1 >= 0:
str_idx2 = c_addrs.find(' [', str_idx1) + 2
str_idx3 = c_addrs.find(']', str_idx2)
ids_row[empty_idx + i] = c_addrs[str_idx2:str_idx3]
c_start = str_idx3
found_flag = True
return found_flag |
def construct_url(uri, bbox, srs, size, image_format, styles, layers):
"""Constructing URL for retrieving image from WMS Server."""
full_uri = uri
full_uri += '&BBOX=%s' % ",".join(map(str, bbox))
full_uri += '&SRS=%s' % srs
full_uri += '&HEIGHT=%d&WIDTH=%d' % size
full_uri += '&TRANSPARENT=true'
full_uri += '&FORMAT=%s' % image_format
full_uri += '&STYLES=%s' % ",".join(map(str, styles))
full_uri += '&LAYERS=%s' % ','.join(layers)
full_uri += '&VERSION=1.1.1'
full_uri += '&REQUEST=GetMap'
full_uri += '&SERVICE=WMS'
return full_uri |
def sums(a,b,c):
"""
:param a: (float) Varaible a sumar.
:param b: (float) Varaible b a sumar.
:param c: (float) Variable c a sumar.
:return d: (float) a+c.
:return e: (float) a+b+c
"""
d = a + c
e = a + b +c
return d, e |
def convert_to_bool(string):
"""
Convert a string passed in the CLI to a valid bool.
:return: the parsed bool value.
:raise ValueError: If the value is not parsable as a bool
"""
upstring = str(string).upper()
if upstring in ['Y', 'YES', 'T', 'TRUE']:
return True
if upstring in ['N', 'NO', 'F', 'FALSE']:
return False
raise ValueError('Invalid boolean value provided') |
def Dic_Remove_By_Subkeylist(indic,keylist):
"""
Return a new dic, with key/value pairs present in keylist removed.
"""
outdic=indic.copy()
for key in outdic.keys():
if key in keylist:
del outdic[key]
return outdic |
def purge(data):
"""
Removes all data entries with a blank game name.
:param data: the data read from titlekeys.json
:type data: list
:returns: the data devoid of entries having blank game names
:rtype: list
"""
return [d for d in data if d.get("name")] |
def mapAddress(name):
"""Given a register name, return the address of that register.
Passes integers through unaffected.
"""
if type(name) == type(''):
return globals()['RCPOD_REG_' + name.upper()]
return name |
def writeConfig(xyTuple):
"""Creates a config file (config.py) and writes 4 values into it
Arguments:
xyTuple: a tuple of structure (xMin, xMax, yMin, yMax)
"""
outfile = open("config.py","w")
outfile.write("X_MIN="+str(xyTuple[0])+"\n")
outfile.write("X_MAX="+str(xyTuple[1])+"\n")
outfile.write("Y_MIN="+str(xyTuple[2])+"\n")
outfile.write("Y_MAX="+str(xyTuple[3]))
outfile.close()
return None |
def get_correlative(vector, index):
"""Get correlative item in vector,
e.g. get_correlative([3, 45, 6], 11) => 6"""
return vector[index % len(vector)] |
def is_table_mask(line: str) -> bool:
"""Decide whether or not a string is a table mask.
A table mask starts with an indentation, then a '!' character, and then a mixture
of ' ' and '-'
"""
return (
line.startswith(" ")
and line.lstrip().startswith("!")
and "-" in line
and all(c in [" ", "!", "-"] for c in line)
) |
def pick_wm_class_0(tissue_class_files):
"""
Returns the csf tissu class file from the list of segmented tissue class files
Parameters
----------
tissue_class_files : list (string)
List of tissue class files
Returns
-------
file : string
Path to segment_seg_0.nii.gz is returned
"""
if isinstance(tissue_class_files, list):
if len(tissue_class_files) == 1:
tissue_class_files = tissue_class_files[0]
for filename in tissue_class_files:
if filename.endswith("seg_0.nii.gz"):
return filename
return None |
def del_none(d):
"""
Delete keys with the value ``None`` in a dictionary, recursively.
So that the schema validation will not fail, for elements that are none
"""
for key, value in list(d.items()):
if value is None:
del d[key]
elif isinstance(value, list):
for item in value:
if isinstance(item, dict):
del_none(item)
elif isinstance(value, dict):
del_none(value)
return d |
def _unpack_idx(idx, nbits, dim):
""" Convert from raster coords to (i_1, i_2,..., i_dim) """
mask = (2**nbits)-1
res = []
for i in range(dim):
res.append((idx>>(nbits*(dim - 1 - i))) & mask)
return tuple(res) |
def sectype(cid):
"""Get the SWC structure type (sid) from section name `cid`"""
if '.dend[' in cid:
stype = 3
elif '.dend_' in cid:
stype = int(cid.split('_')[-1].split('[')[0])
elif 'soma' in cid:
stype = 1
elif 'axon' in cid:
stype = 2
else:
stype = 0
return stype |
def loss_and_metric_and_predictions_fn(provider):
"""Helper function to create loss and metric fns."""
metric_fn = None
loss_fn = None
predictions_fn = None
if getattr(provider, "get_metric_fn", None) is not None:
metric_fn = provider.get_metric_fn()
if getattr(provider, "get_loss_fn", None) is not None:
loss_fn = provider.get_loss_fn()
if getattr(provider, "get_predictions_fn", None) is not None:
predictions_fn = provider.get_predictions_fn()
return (loss_fn, metric_fn, predictions_fn) |
def is_list_like(spec):
"""
:param spec: swagger object specification in dict form
:rtype: boolean
"""
return isinstance(spec, (list, tuple)) |
def loader_from_key(key):
"""Returns the name, loader pair given a key."""
if ":" in key:
return key.split(":")
return key, None |
def find_ori(dna, ori):
"""
Identify start and end index of the origin of replication
in the given circular DNA.
"""
circular_dna = [x for x in dna]
start, end = -1, -1
for i in range(len(ori) - 1):
circular_dna.append(dna[i])
for i in range(len(circular_dna) - len(ori) + 1):
frag = circular_dna[i : i + len(ori)]
frag = "".join(frag)
if frag == ori:
start = i % len(dna)
end = (start + len(ori)) % len(dna)
break
return start, end |
def fold(header):
"""Fold a header line into multiple crlf-separated lines at column 72."""
i = header.rfind("\r\n ")
if i == -1:
pre = ""
else:
i += 3
pre = header[:i]
header = header[i:]
while len(header) > 72:
i = header[:72].rfind(" ")
if i == -1:
j = i
else:
j = i + 1
pre += header[:i] + "\r\n "
header = header[j:]
return pre + header |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.