content stringlengths 42 6.51k |
|---|
def convertYawToDegrees(yaw):
"""
Converts a yaw which is -180 to 180 to a compass heading between 0 and 360
Useful in particular for the yaw value that the NavX supplies
:param yaw: Initial yaw between -180 and 180
:return: Degrees 0 to 360
"""
if yaw == 0.0:
return 0.0
if yaw >... |
def get_instance_region(instance, region):
"""
Get the region attribute stored in instance if one is not provided.
"""
if region is None:
if not hasattr(instance, "region_"):
raise ValueError("No default region found. Argument must be supplied.")
region = instance.region_
... |
def makeslices(n):
""" Return a list of `n` slice objects.
Each slice object corresponds to [:] without arguments.
"""
slices = [slice(None)] * n
return slices |
def make_url(api_key, url, args=None):
"""
Adds the API Key to the URL if it's not already there.
"""
if args is None:
args = []
argsep = '&'
if '?' not in url:
argsep = '?'
if '?apiKey=' not in url and '&apiKey=' not in url:
args.insert(0, ('apiKey', api_key))
re... |
def create_empty_assignment(mjpeg_info_dict):
"""
Creates an empty camera assignment dictionary
"""
camera_assignment = {}
for k in mjpeg_info_dict:
camera_assignment[k] = '--'
return camera_assignment |
def window(region, start_index, end_index):
"""
Returns the list of words starting from `start_index`, going to `end_index`
taken from region. If `start_index` is a negative number, or if `end_index`
is greater than the index of the last word in region, this function will pad
its return value with `... |
def fibonacci_memory(nth_nmb: int) -> int:
"""An recursive approach to find Fibonacci sequence value, storing those already calculated."""
memory: dict = {0: 0, 1: 1} # Cache to store calculated fib values in
def fib(_n):
if _n <= 1:
return _n # Return input nr
elif _n not in ... |
def compute_Pn_t(S, n, N):
""" """
n.sort()
n.reverse()
m = n[:S]
m.reverse()
M = max(m)
Pm = [1] #P>(n), vale 1 per n=1
#attenzione agli indici, 0 deve corrispondere a n = 1
for i in range(1,M):
Q = m.count(i)
p = Q/S
P = Pm[i-1] - p
Pm.append(P) #ele... |
def b(n):
""" Simple function to approximate b(n) when evaluating a Sersic profile
following Capaccioli (1989). Valid for 0.5 < n < 10
Parameters
----------
n: float or array
Sersic index
Returns
-------
b(n): float or array
Approximation to Gamma(2n) = 2 ga... |
def scrub(text, chars, new):
"""Replace chars.
"""
for char in chars:
if char in text:
text = text.replace(char, new)
return text.strip() |
def is_unmapped_read(flag):
"""
Interpret bitwise flag from SAM field.
Returns True if the read is unmapped.
"""
IS_UNMAPPED = 0x4
return (int(flag) & IS_UNMAPPED) != 0 |
def _deriv_log1p(x):
"""The derivative of log1p(x)"""
return 1.0 / (1.0 + x) |
def build_readable_attribute_key(key: str, attribute_name: str):
"""
Formatting nested attribute name to be more readable, and convenient to display in fetch incident command.
For the input of "srcIpAddr", "incidentSrc" the formatted key will be: "source_ipAddr".
Args:
key: (str): The that was ... |
def safe_unicode(obj):
"""Safe conversion to the Unicode string version of the object."""
try:
return str(obj)
except UnicodeDecodeError:
return obj.decode("utf-8") |
def is_number(s):
"""Check if a varible is a number. Return True if it is. False if not"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
... |
def accuracy(predictions, targets):
"""Computes raw accuracy (True Predictions) / (All Predictions)
Args:
predictions (list): a list of predicted labels
targets (list): a list of gold labels
Returns:
float: the raw accuracy between the predictions and the gold labels
""... |
def host_local_machine(local_hosts=None):
""" Returns True if its a recognized local host
Keyword Arguments:
local_hosts {list str} -- List of namaes of local hosts (default: {None})
Returns:
[bool] -- True if its a recognized local host False otherwise.
"""
from socket imp... |
def build_ddb_projection_expression(return_attributes):
"""
converts list of attribute names to token substitutes to avoid conflicts with DynamoDB reserved words
:param attributes: list of attribute string names
:return: projection expression string, dict map of expression attribute tokens to attribute... |
def rowtrace(cursor, row):
"""Called with each row of results before they are handed off. You can return None to
cause the row to be skipped or a different set of values to return"""
print ("Row:", row)
return row |
def _is_arraylike(x):
""" Returns whether the input is array-like """
return (hasattr(x, '__len__') or
hasattr(x, 'shape') or
hasattr(x, '__array__')) |
def quadratic_vertex_integrate(x, a, b, c):
"""The integrate for vertex form of quadratic function
:param x: independent variable
:param a: coefficient {a} of quadratic function
:param b: the x coordinates of the vertex
:param c: the y coordinates of the vertex
:return:a * (b ** 2) * x + c * x -... |
def add_scale(s1,s2):
"""
Parameters
----------
s1,s2: Input scaling parameters
Returns
-------
The output scaling of a two input scaled added
"""
return max(s1,s2)*2 |
def ror(a, b):
"""Rotate right
Returns (result, carry)
"""
b &= 31
if b:
return ( (a >> b) | ((a << (32 - b)) & 0xffffffff), 1 & (a >> (b-1)) )
else:
return (a, 0) |
def new_level(number):
"""
returns true if number is the sum of all powers of 2
less than some arbitrary number
ie following a breadth first traversal
this node is the first of a new level
:param number: int
:return: Bool
"""
return (number != 0) and (number & (number + 1) == 0) |
def get_subplots_dimensions(n_plots):
"""
For given number of plots returns the 'optimal' rows x columns distribution
of subplots and figure size.
Args:
n_plots [int] - number of subplots to be includeed in the plot
Returns:
nrows [int] - suggested number of rows ncols [int] - sugges... |
def add_dicts(d1, d2):
"""Merge two dicts of addable values"""
if d1 is None:
return d2
if d2 is None:
return d1
keys = set(d1)
keys.update(set(d2))
ret = {}
for key in keys:
v1 = d1.get(key)
v2 = d2.get(key)
if v1 is None:
ret[key] = v2
... |
def fuzz_up(v, epsilon):
"""
Adjust v upwards, by a proportion controlled by self.epsilon.
This is typically used for fuzzy maximum constraints.
By default, positive values of v are increased by 1% so that
slightly larger values can pass the fuzzy maximum constraint.
Similarly, negative values... |
def compute_left_time(lecture_time, progress):
"""
:param lecture_time:
:param progress:
:return:
"""
time_left = lecture_time * (100 - progress) * 6 // 10
return time_left |
def trimExonAndFlip(exStart, exEnd, exStrand, seqLen, seqStrand):
""" Put the exon into the current sequence window:
- trim exon to the window (0, seqLen), return None if completely outside the view.
- reverse the exon coordinates if seqStrand=="-"
"""
if exStart < 0:
if exEnd < 0:
... |
def ucs2tostring(ucs2):
"""
@param ucs2: the bytes array in ucs2 as provided by the SIM module
@return: the decoded string
"""
return bytes.fromhex(ucs2.decode('ascii')).decode('utf_16_be') |
def change(d,n,m):
""" Recursively modify dictionary entries """
if isinstance(d,dict):
for k,v in d.items():
d[k] = change(v,n,m) # recursively recall
if d[k] == None: d.pop(k,None) # remove key if none referenced
return d
else:
hits = len([i for i in d])
... |
def map_offset(ori_offset, offset_mapping):
"""
map ori offset to token offset
"""
for index, span in enumerate(offset_mapping):
if span[0] <= ori_offset < span[1]:
return index
return -1 |
def prepare_io(datum):
"""Convert dictionary into input-output tuple for Keras."""
src = datum["src"]
tgt = datum["tgt"]
return src, tgt |
def _rename_par(name: str, atoms: list) -> str:
"""Rename of the name of a parameter by replacing the index of the atom in the name by the label of
the atom and revert the order of coordinates and atom name.
Used for the space group constrained parameters. For example, "x_0" where atom index 0 is Ni will b... |
def get_activated_doi(doi):
"""
Get activated DOI with flags removed. The following two flags are appended
to the DOI string to indicate publication status for internal use:
'pending' flag indicates the metadata deposition with CrossRef succeeds, but
pending activation with CrossRef for DOI to take... |
def rreplace(s, old, new, occurrence, only_if_not_followed_by=None):
"""replaces occurences of character, counted from last to first, with new
character.
Arguments:
s - string
old - character/string to be replaced
new - character/string to replace old with
occurence - nth occurence up to w... |
def get_cell(grid, y: int, x: int) -> str:
"""Returns the value of a cell"""
return grid[y - 1][x - 1] |
def strip_instance(name):
"""Strip #.+ suffix if exists."""
if name.find('#') != -1:
return name[:name.rfind('#')]
return name |
def rotations(s):
"""Get all the rotations of a string
E.g.
'abc' => ['abc', 'bca', 'cba']
"""
all_rotations = []
for i in range(len(s)):
rotation = s[i:] + s[:i]
all_rotations.append(rotation)
return all_rotations |
def make_iterable(value):
"""
Transform into an iterable.
Transforms a given `value` into an iterable if it is not.
Else, return the value itself.
Example
-------
>>> make_iterable(1)
[1]
>>> make_iterable([1])
[1]
"""
try:
iter(value)
except TypeError:
... |
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, lis... |
def _look_up_name_and_summary(registration_tid, summaries):
"""Some common code used in all objects to map RegistrationName and Summary"""
registration_name = None
summary = None
for s in summaries:
if s['RegistrationTID'] == registration_tid:
registration_name = s['RegistrationNam... |
def estimate_sheet_type(sheet):
"""Estimate sheet type based on sheet name."""
sheet = sheet.lower()
if "coord" in sheet:
return "Coordinates"
if "loc" in sheet:
return "Locations"
if "item" in sheet:
return "Items"
if "inv" in sheet:
return "Inventory"
if "or... |
def toint(x):
"""Try to convert x to an integer number without rasing an exception."""
try: return int(x)
except: return x |
def Efw(cf, cw, swi, p, pi):
"""
Calculate formation expansion factor
"""
Efw = ((cf + cw * swi) / (1 - swi)) * (pi - p)
return (Efw) |
def fsescape(s):
"""Escape string to be safely used in path names
@param s: some string
@type s: basestring
@returns: escaped string
@rtype: str
"""
res = []
for x in s:
c = ord(x)
if c > 127 or c == 47 or c == 92: # 47==slash, 92==backslash
res.append("~%... |
def read_query_notes(query_str, first_line=False):
"""
Returns the Comments from a query string that are in the header
"""
lines = query_str.split("\n")
started = False
parts = []
for line in lines:
line = line.strip()
if line.startswith("#"):
parts.append(line)
... |
def check_object_not_in_prod_cons(object_to_check, consumer_list, producer_list):
"""Check if object/data_name not in producer or consumer lists"""
check = False
if not any(object_to_check in o for o in consumer_list + producer_list):
check = True
return check |
def sumevenfib(N):
"""
N is a positive number
This function will add up all even fibonacci numbers that do not exceed N
We use the convention that F_0 = 0, F_1 = 1,...,F_3 = 2
Note that F_3k is the subsequence of even Fibonacci numbers
"""
F1 = 1
F0 = 0
S = 0
while F0 <= N:
S += F0
F3 = 2*F1 + F0
F1 =... |
def int_to_hex(i, prec):
"""
Return the two's complement hexadecimal representation of an
integer.
"""
if i > 2 ** (prec - 1) - 1 or i < -(2 ** (prec - 1)):
raise ValueError("""Value must be in the range given by @prec.""")
if i < 0:
i = 2 ** prec + i
hex_str = format(i, "x"... |
def text_to_line_numbered_text(text):
"""Adds line numbers to the provided text."""
lines = text.split('\n')
results = []
i = 1
for line in lines:
results.append(str(i) + ': ' + line)
i += 1
return '\n '.join(results) |
def uncurry_nested_dictionary(curried_dict):
"""
Transform dictionary from (key_a -> key_b -> float) to
(key_a, key_b) -> float
"""
result = {}
for a, a_dict in curried_dict.items():
for b, value in a_dict.items():
result[(a, b)] = value
return result |
def _ints(data):
"""Remove spaces, convert to list of ints"""
return list(map(int, data.replace(" ", ""))) |
def have_html_extension(l):
"""Check if .html extension is present"""
if ".html" in str(l):
return 1
else:
return 0 |
def int_or_none(value):
"""Return integer equivalent or None for a given value.
:param value: value to be parsed
:returns: None if value=None else int(value)
"""
if value is None:
return None
if value == "":
return None
return int(value) |
def get_ceph_rook_cfg(k8s_conf):
"""
Returns ceph rook enablement choice
:return true/false
"""
if k8s_conf.get('enable_ceph_rook') :
return k8s_conf['enable_ceph_rook'] |
def list_to_csv(x):
"""Converts a list of str to a comma-separated string."""
return ','.join(x) |
def is_file_input(im: str) -> bool:
""" Determine user's input mode.
Determine whether the user should provide the input using a file or a shell.
Raises a ValueError if input_mode format is not expected.
Params:
im: A one-character string. 'f' for file input, 's' for shell.
Returns:
A boolean which is Tru... |
def x_y_to_name(x, y) -> str:
"""
Make name form x, y coords
Args:
x: x coordinate
y: y cooridante
Returns: name made from x and y
"""
return f"{x},{y}" |
def read_file(filename):
"""
opens and read a file from file system
returns file content as data if ok
returns None is error while reading file
"""
try:
fhnd = open(filename)
data = fhnd.read()
fhnd.close()
return data
except:
return None |
def cgetattr(obj, attr: str):
""" Case-insensitive getattr """
for a in dir(obj):
if a.lower() == attr.lower():
return getattr(obj, a) |
def fibonacci(n):
"""
Fibonacci number
https://en.wikipedia.org/wiki/Fibonacci_number
:param n:
:return:
"""
if n == 0:
return 0
if n == 1:
return 1
return fibonacci(n-1) + fibonacci(n-2) |
def console_output(access_key_id, secret_access_key, session_token, verbose):
""" Outputs STS credentials to console """
if verbose:
print("Use these to set your environment variables:")
exports = "\n".join([
"export AWS_ACCESS_KEY_ID=%s" % access_key_id,
"export AWS_SECRET_ACCESS_KE... |
def find_rotation_point(words):
"""
Time: O(log N) or O(l * log N)
Space: O(1)
N: number of words
l: length of longest string (it could be considered as O(1) and omitted)
"""
def search(start, end):
if start == end:
return words[start]
mid = (start + end) // 2
... |
def validate4(s,a):
"""validate4(s, a): for loop with generator and (l in a)"""
for x in ((l in a) for l in s):
if not x:
return False
return True |
def convert_with_dict(lst, dct):
""" convert lst to another lst
with dct table if possible """
lst2 = []
for i in lst:
try:
ii = dct[i]
except:
ii = "-"
else:
pass
lst2.append(ii)
return(lst2) |
def clean_blocks(blocks):
"""
The message that comes from the action button from Slack has added
additional information for the context blocks which does not conform with
the API documentation. To be able to post the message back to Slack we must
clean all fields that's not allowed.
"""
for ... |
def html_encode(txt):
"""HTML encode."""
txt = txt.replace('&', '&')
txt = txt.replace('<', '<')
txt = txt.replace('>', '>')
return txt |
def out_of_china(lng, lat):
"""
No offset when coordinates are out of China
:param lng:
:param lat:
:return:
"""
if lng < 72.004 or lng > 137.8347:
return True
if lat < 0.8293 or lat > 55.8271:
return True
return False |
def sum_squares(numbers):
"""Sums the squares of an iterable collection of numbers."""
sum = 0
for i in numbers:
sum += i**2
return sum |
def format_text(text, max_length = 50, suffix = "..."):
""" Replaces tabulations and ends of line.
"""
text = text if len(text) <= max_length else f"{text[:max_length]}{suffix}"
return text.replace('\t', "\\t").replace('\n', "\\n") |
def checker_trailing_whitespace(physical_line):
"""Trailing whitespace is superfluous.
Okay: echo Test#
W201: echo Test #
Okay: #
W202: #
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
ph... |
def call(func, *args, **kwargs):
"""
Call `func` with positional arguments `args` and keyword arguments `kwargs`.
Parameters
----------
func : callable
Function to call when the node is executed.
args : list
Sequence of positional arguments passed to `func`.
kwargs : dict
... |
def step(edge, x):
"""Return 0.0 if x < edge; otherwise result is 1.0, with x a float scalar or vector."""
return 0.0 if x < edge else 1.0 |
def remove_even_integers(_array: list) -> list:
"""
Remove Even Integers from Array
"""
new_arrays = [number for number in _array if number % 2]
return new_arrays |
def kw_pop(*args,**kwargs):
"""
Treatment of kwargs. Eliminate from kwargs the tuple in args.
"""
arg=kwargs.copy()
key,default=args
if key in arg:
return arg,arg.pop(key)
else:
return arg,default |
def is_tag_p(elm):
"""
Tries to check if the element is a tag
It checks by verifying that the element has a not None name that is not the string '[doc]'.
* **elm**: the element to be checked
* **return**: True if the element looks like a tag
"""
if elm is not None and elm.name is not None ... |
def bytes_from_int(v, pad_to):
"""Creates little-endian bytes from integer."""
assert v >= 0
return int.to_bytes(v, pad_to, byteorder="little") |
def to_alternating_case(string: str) -> str:
"""
each lowercase letter becomes uppercase and
each uppercase letter becomes lowercase
:param string:
:return:
"""
return ''.join((char.upper() if char.islower() else char.lower()) for char in string) |
def get_new_size_zoom(current_size, target_size):
"""
Returns size (width, height) to scale image so
smallest dimension fits target size.
"""
scale_w = target_size[0] / current_size[0]
scale_h = target_size[1] / current_size[1]
scale_by = max(scale_w, scale_h)
return (int(current_size[0]... |
def is_valid(chosenHand):
"""Check if hand is valid"""
if chosenHand == "Rock" or chosenHand == "Paper" or chosenHand == "Scissors":
return True
print("Invalid hand! Please Choose from one of the following:\n" +
"'Rock', 'Paper', or 'Scissors'")
return False |
def flip_date_format(date: str) -> str:
"""Goes from YYYY/MM/DD to DD/MM/YYYY and vice-versa"""
a, m, b = date.replace("-", "/").split("/")
return f"{b}/{m}/{a}" |
def sum_range(nums, start=0, end=None):
"""Return sum of numbers from start...end.
- start: where to start (if not provided, start at list start)
- end: where to stop (include this index) (if not provided, go through end)
>>> nums = [1, 2, 3, 4]
>>> sum_range(nums)
10
>>>... |
def _ensure_cr(text):
""" Remove trailing whitespace and add carriage return
Ensures that `text` always ends with a carriage return
"""
return text.rstrip() + '\n' |
def Propagate(goidlist,GOparentsDict):
"""
Input list of GO identifiers
Return list inclusing all GO parents
"""
parents={}
stack=[]
for goid in goidlist: stack.append(goid)
while len(stack)>0:
goid=stack.pop()
parents[goid]=1
if not goid in GOparentsDict: continu... |
def first_bad_pair(sequence):
"""Return the first index of a pair of elements where the earlier
element is not less than the later elements. If no such pair
exists, return -1."""
for i in range(len(sequence) - 1):
if sequence[i] >= sequence[i + 1]:
return i
return -1 |
def minimize_document(document):
"""
Takes a document obtained directly from its json from the portal and strips
it down to a subset of desired fields. The document @id is prepended to the
attachment href
"""
minimized_document = {}
for field in ('document_type', 'urls', 'references'):
... |
def truncate(text, max_len, fill="..."):
"""
Truncate given text to a given maximum length.
Parameters
----------
text : str
The text to truncate.
max_len : int
The maximum allowed length for `text`. If `text` is longer than
`max_len` it will be shortened, otherwise it w... |
def checkload(input):
"""
Check if the load input is integer or not. If int return int, if not return string
"""
try:
return int(input)
except ValueError:
return input |
def in_circle(x, y, x0, y0, r):
"""
Check if a point (x, y) is in the circle centered at (x0, y0) with
redius r
"""
dr = (x-x0)**2 + (y-y0)**2 - r**2
if dr <= 0:
check = True
else:
check = False
return check |
def optimize_solution(solution):
"""
Eliminate moves which have a full rotation (N % 4 = 0)
since full rotations don't have any effects in the cube
also if two consecutive moves are made in the same direction
this moves are mixed in one move
"""
i = 0
while i < len(soluti... |
def _find_element_section(config, name):
"""
Search config for the given element name and return the section.
"""
section_list = ['optics', 'sources', 'filters']
out_list = []
for section in section_list:
if name in config[section]:
out_list.append(section)
if len(out_li... |
def most_repeated_word(string):
"""
Function that returns that most repeated word in a string
In: String
out: String
"""
word_list = string.lower().split(' ')
dictionary = {}
most_repeated_value = 0
most_repeated_key = ''
for word in range(len(word_list)):
if word_list[... |
def rolling_xor(shellcode: bytes, decode: bool=False) -> bytes:
""" Perform a rolling xor encoding scheme on `shellcode`.
:param shellcode: bytes object; data to be [en,de]coded
:param decode: boolean, decrypt previously xor'd data
:return: bytes object
"""
shellcode = bytearray(shellcode)
... |
def Mobius(z):
"""Distort the resulting image by a Mobius transformation."""
return (z - 20) / (3 * z + 1j) |
def huffman_initial_count(message_count, digits):
"""
Return the number of messages that must be grouped in the first layer for
Huffman Code generation.
:message_count: Positive integral message count.
:digits: Integer >= 2 representing how many digits are to be used in codes.
:returns: The num... |
def isstr(obj):
"""Return True if the obj is a string of some sort."""
return isinstance(obj, str) |
def spin(program_list, amount):
"""Rotate program list by amount from the end of the list
e.g. abcde amount 3 gives cdeab."""
return program_list[-amount:] + \
program_list[:len(program_list) - amount] |
def int_to_roman(val):
"""Helper function to convert integer to roman number."""
if not 0 < val < 4000:
val = 3999
ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
nums = ('M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV',
'I')
result = ''
... |
def arithmetic_simplify_06(x):
""" arithmetic_simplify_06 """
return x * 2 * 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.