content stringlengths 42 6.51k |
|---|
def listGetArithmeticMean(listofnumbers):
""" Return the arithmetic mean of a list of numbers
"""
arithmeticmean = sum(listofnumbers)
arithmeticmean /= max(len(listofnumbers), 1) * 1.0
return arithmeticmean |
def php_substr(_string, _start, _length=None):
"""
>>> php_substr("abcdef", -1)
'f'
>>> php_substr("abcdef", -2)
'ef'
>>> php_substr("abcdef", -3, 1)
'd'
>>> php_substr("abcdef", 0, -1)
'abcde'
>>> php_substr("abcdef", 2, -1);
'cde'
>>> php_substr("abcdef", 4, -4);
Fa... |
def two_fer (name = 'you'):
"""
:param name: str - optional
:return: str - two for one
"""
return f'One for {name}, one for me.' |
def parabolic(x, a=0.0, b=0.0, c=0.0):
"""Return a parabolic function.
x -> a * x**2 + b * x + c
"""
return a * x**2 + b * x + c |
def line(loc, strg):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR + 1:nextCR]
else:
return strg[lastCR + 1:] |
def camelcase(value: str) -> str:
"""capitalizes the first letter of each _-separated component except the first one.
This method preserves already camelcased strings."""
components = value.split("_")
if len(components) == 1:
return value[0].lower() + value[1:]
else:
components[0] ... |
def connected_component(_n, _v, _edges):
"""
# https://www.geeksforgeeks.org/connected-components-in-an-undirected-graph/
:param _n: number of vertices
:param _v: vertex contained by target component
:type _edges: set of edges, e.g. {(0, 1), (1, 2)}
"""
def dfs_util(temp, _v, _visited):
... |
def _split3_ ( xlims , ylims , zlims ) :
"""Split 3D-region into eight smaller pieces
Example
-------
>>> region = (-1,1),( -2,5) , ( -3,3)
>>> newregions = _split3_( region )
>>> for nr in newregions : print nr
"""
xc = 0.5 * ( xlims[1] + xlims[0] )
dx = 0.5 * ( xli... |
def _is_new_tree(trees, this_tree):
"""
True if it's a new tree.
Parameters
----------
trees:
"""
# check for length
if trees == []:
return True
ll = [len(i) for i in trees]
# print(len(this_tree))
l_this = len(this_tree)
same_length=[]
... |
def depth2intensity(depth, interval=300):
"""
Function for convertion rainfall depth (in mm) to
rainfall intensity (mm/h)
Args:
depth: float
float or array of float
rainfall depth (mm)
interval : number
time interval (in sec) which is correspondend to depth valu... |
def format_legacy_response(response, skills, category):
"""Format responses appropriately for legacy API. # noqa: E501
Examples:
>>> skills = ["Strength", "Hitpoints", "Ranged", "Magic", "Slayer", "Farming"]
>>> category = "xp"
>>> response = [
... {
... 'skills': {
... ... |
def sort_by_length(words):
"""Sort a list of words in reverse order by length.
This is the version in the book; it is stable in the sense that
words with the same length appear in the same order
words: list of strings
Returns: list of strings
"""
t = []
for word in words:
t.ap... |
def all_possible_state_helper( equipment ):
"""
create a list of tuples to represent all possible equipment combinations
equipment is a list of dictionary that contain at least a key called number
"""
result = []
for i, e in enumerate( equipment ):
if i == 0:
for j in range(e... |
def recursive_bases_from_class(klass):
"""Extract all bases from entered class."""
result = []
bases = klass.__bases__
result.extend(bases)
for base in bases:
result.extend(recursive_bases_from_class(base))
return result |
def setPath(day, month, year, repoAddress="\\\\jilafile.colorado.edu\\scratch\\regal\\common\\LabData\\NewRb\\CryoData"):
"""
This function sets the location of where all of the data files are stored. It is occasionally called more
than once in a notebook if the user needs to work past midnight.
:param... |
def _join_lines(lines):
"""
Simple join, except we want empty lines to still provide a newline.
"""
result = []
for line in lines:
if not line:
if result and result[-1] != '\n':
result.append('\n')
else:
result.append(line + '\n')
return ''.join(result).strip() |
def name_test(item):
""" used for pytest verbose output """
return f"{item['params']['mlag']}:{item['expected']['state']}" |
def enum(word_sentences, tag_sentences):
"""
enumerate words, chars and tags for
constructing vocabularies
:param word_sentences:
"""
words = sorted(list(set(sum(word_sentences, []))))
chars = sorted(list(set(sum([list(word) for word in words], []))))
tags = sorted(list(set(sum(tag_sen... |
def test_reassign(obj):
"""
>>> test_reassign(object())
'hello'
>>> sig, syms = infer(test_reassign.py_func, functype(None, [object_]))
>>> sig
const char * (*)(object_)
>>> syms['obj'].type
const char *
"""
obj = 1
obj = 1.0
obj = 1 + 4j
obj = 2
obj = "hello"
... |
def getResNumb(line):
"""
reads the resNumb from the pdbline
"""
if line == None:
return 0
else:
return int( line[22:26].strip() ) |
def identity_matrix(dim):
"""Construct an identity matrix.
Parameters
----------
dim : int
The number of rows and/or columns of the matrix.
Returns
-------
list of list
A list of `dim` lists, with each list containing `dim` elements.
The items on the "diagonal" are ... |
def normalizeGlyphWidth(value):
"""
Normalizes glyph width.
* **value** must be a :ref:`type-int-float`.
* Returned value is the same type as the input value.
"""
if not isinstance(value, (int, float)):
raise TypeError("Glyph width must be an :ref:`type-int-float`, not %s."
... |
def _get_printable_columns(columns, row):
"""Return only the part of the row which should be printed.
"""
if not columns:
return row
# Extract the column values, in the order specified.
return tuple(row[c] for c in columns) |
def cast(current, new):
"""Tries to force a new value into the same type as the current."""
typ = type(current)
if typ == bool:
try:
return bool(int(new))
except (ValueError, TypeError):
pass
try:
new = new.lower()
except:
pass
... |
def standard_dict_group(data):
"""Group with standard dict.
"""
d = {}
for key, value in data:
d.setdefault(key, []).append(value)
return d |
def sublist_at(list, index, length):
"""
Return the sublist that starts at the given index and has the given
length. If the index is out of bounds, return an empty list. If
the length is too long, return only as many item as exist starting
at `index`.
For example:
get_sublist([1, 2, ... |
def generate_ride_headers(token):
"""Generate the header object that is used to make api requests."""
return {
'Authorization': 'bearer %s' % token,
'Content-Type': 'application/json',
} |
def size_convert(size: float = 0) -> str:
"""Convert a size in bytes to human readable format.
Args:
size: The length of a file in bytes
Returns:
A human readable string for judging size of a file
Notes:
Uses the IEC prefix, not SI
"""
size_name = ("B", "KiB", "MiB", ... |
def is_side(s):
"""Return whether s is a side."""
return type(s) == list and len(s) == 3 and s[0] == 'side' |
def decoded_to_json(decoded_message):
"""
wrap the decoded data in json format
"""
response_list = []
for msg in decoded_message:
response = {}
response["text"] = msg.data
coordinates = msg.rect
coord_list = []
coord_list.append(coordinates.left)
coo... |
def find_base_url_path(url):
"""
Finds the base path of a URL.
"""
url = url.strip("/").replace("http://", "https://").split("?")[0].lower()
return url |
def format_ruleset(ruleset):
"""
>>> format_ruleset(11100)
[0, 0, 0, 1, 1, 1, 0, 0]
>>> format_ruleset(0)
[0, 0, 0, 0, 0, 0, 0, 0]
>>> format_ruleset(11111111)
[1, 1, 1, 1, 1, 1, 1, 1]
"""
return [int(c) for c in f"{ruleset:08}"[:8]] |
def getMatchingIndices(func, seq):
"""Returns indices of a sequence where `func` evaluated to True."""
return [i for i, v in enumerate(seq) if func(v)] |
def voltageDivision(v_in, r_list_ordered, showWork=False):
"""
Voltage is divided among the resistors in direct proportion to their resistances;
the larger the resistance, the larger the voltage drop.
"""
r_total = sum(r_list_ordered)
voltages = [r/r_total*v_in for r in r_list_ordered]
if s... |
def import_prov_es(info):
"""
Create job json for importing of PROV-ES JSON.
Example:
job = {
'type': 'import_prov_es',
'name': 'action-import_prov_es',
'tag': 'v0.3_import',
'username': 'ops',
'params': {
'prod_url': '<datase... |
def _is_single_type(data):
""" check whether elements in data has same data-type or not
Arguments:
data {list} -- data you want to check elements' data-type
Returns:
{data-type or bool} -- if all elements has same data-type, return the data-type
if not, return ... |
def uniqify(some_list):
"""
Filter out duplicates from a given list.
:Example:
>>> uniqify([1, 2, 2, 3])
[1, 2, 3]
"""
return list(set(some_list)) |
def get_len(text):
"""
Obtains the length of the input text, in number of characters
Args:
text: string containing text to find the length of
Returns:
The length of the input text represented as an int
"""
text_formatted = text.split(" ")
length_of_text = len(text_formatted... |
def check_dir_slash(path):
"""Appends trailing slash to path if necessary.
Args:
path(str): path to be checked for slash
Returns:
(str) path with slash at the end
"""
if path.endswith('/'):
return path
else:
return path+'/' |
def set_output_path(folder, fprefix, particip, output_file, sess):
""" Define pathway of output files """
output_path = folder + '/' + fprefix + '-' + \
'%02d' % particip + '/' + output_file + '_' + fprefix + \
'-' + '%02d' % particip + '_' + 'run' + \
str(sess) + '.tsv'
return outpu... |
def get_arguments(omit=None):
"""Get a calling function's arguments.
Returns:
args : dict
The calling function's arguments.
"""
from inspect import getargvalues, stack
if omit is None:
omit = []
_args, _, _, _vars = getargvalues(stack()[1][0])
args = {}
for name ... |
def parseDockerAppliance(appliance):
"""
Takes string describing a docker image and returns the parsed
registry, image reference, and tag for that image.
Example: "quay.io/ucsc_cgl/toil:latest"
Should return: "quay.io", "ucsc_cgl/toil", "latest"
If a registry is not defined, the default is: "d... |
def crt(pairs):
"""
After 8 hours of pointless optimizing, I searched for a good solution
and finally found this from "sophiebits". She made a nice and lightning fast
implementation of the Chinese Remainder Theorem. Please, follow the link
to her original solution devoutly:
https://github.com/so... |
def parse_plugins_option(plugins_option):
"""
Return parsed -p command line option or "".
"""
return (plugins_option or "").split(",") |
def user_has_verified_email(user) -> bool:
"""A check to see if the user has an verified email with the organization
Args:
user ([type]): Is the user to check
Returns:
bool: True if the user has verified their email with the organisation
"""
if user["organizationVerifiedDomainEmail... |
def to_hass_level(level):
"""Convert the given Vantage (0.0-100.0) light level to HASS (0-255)."""
return int((level * 255) / 100) |
def erd_encode_signed_byte(value: int) -> str:
"""
Convert a hex byte to a signed int. Copied from GE's hextodec method.
"""
value = int(value)
if value < 0:
value = value + 256
return value.to_bytes(1, "big").hex() |
def _versiontuple(v):
"""
Converts a version string to a tuple.
Parameters
----------
v : :obj:`str`
Version number as a string. For example: '1.1.1'
Returns
-------
tuple
Three element tuple with the version number. For example: (1, 1, 1)
"""
return tuple(map... |
def list_hosts(ip, end):
"""
Creates IP lists for different threads.
:return: list of hosts
"""
address = ip.split(".")
hosts = []
for addr in range(int(address[3]), end):
hosts.append(".".join([octet for octet in address[:3]]) + "." + str(addr))
return hosts |
def file_size(num, suffix='B'):
"""
Output human readable file size
:param num: Integer in bytes
:param suffix: Appended to type of file size
:return: String
"""
for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, su... |
def tensor_transpose(g):
"""
:param g: tensor
:return: tranpose of the tensor
"""
import numpy as np
g = np.array(g)
tg = np.array(g)
for i in range(g.shape[0]):
for j in range(g.shape[0]):
tg[i][j] = g[j][i]
# tg is the transposed tensor
return tg |
def sum_of_odd_nums_upto_n(i):
"""Function for sum of odd nums upto n"""
num = 1
ans = 0
while num <= i:
if num % 2 == 1:
ans = ans + num
num = num + 1
return ans |
def get_coordinate_text(x, y):
"""
extension:
Get the x-coordinate and y-coordinate of mouse and return string coordinate.
:param x: The x-coordinate of the mouse.
:param y: The y-coordinate of the mouse.
:return str, the string of coordinate.
"""
return "(" + str(x) + "," + str(... |
def get_tool_name(url: str) -> str:
"""Get the tool name from the specified URL."""
if url.endswith(".json"):
url = url[:-len(".json")]
if url.endswith(".php"):
url = url[:-len(".php")]
parts = url.split("_")
for i, fragment in enumerate(parts):
if fragment[0].isupper():
... |
def count_user(data_list):
"""
Function count the users.
Args:
data_list: The data list that is doing to be iterable.
Returns:
A list with the count value of each user type.
"""
customer = 0
subscriber = 0
for i in range(len(data_list)):
if data_list[i][5] ... |
def _generate_fortran_bool(pybool):
"""Generates a fortran bool as a string for the namelist generator
"""
if pybool:
fbool = '.true.'
else:
fbool = '.false.'
return fbool |
def ordinal(num):
"""Returns ordinal number string from int,
e.g. 1, 2, 3 becomes 1st, 2nd, 3rd, etc. """
SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'}
# 10-20 don't follow the normal counting scheme.
if 10 <= num % 100 <= 20:
suffix = 'th'
else:
# the second parameter is a default... |
def get_select_indexes(selects, attributes):
""" Gets the indexes for all select statements.
Args:
selects: select values
attributes: attributes in the tables
Returns:
indexes: look up indexes for select values
"""
if selects[0] != '*':
indexes = []
split_se... |
def round_float_str(s, precision=6):
"""
Given a string containing floats delimited by whitespace
round each float in the string and return the rounded string.
Parameters
----------
s : str
String containing floats
precision : int
Number of decimals to round each float to
... |
def count_and_say(n):
"""
Count and say
:param n: number
:type n: int
:return: said string
:rtype: str
"""
# basic case
if n == 0:
return ''
elif n == 1:
return '1'
prev_seq = count_and_say(n - 1)
curr_seq = ''
cnt = 1
for i in range(len(prev_seq... |
def conv_ext_to_proj(P):
"""
Extended coordinates to projective
:param P:
:return:
"""
return P[0], P[1], P[2] |
def google_drive_useable(link):
"""Changes a google drive link into something usable"""
return link.replace('/open?', '/uc?') |
def _common_shape(sshape, ashape):
"""Return broadcast shape common to both sshape and ashape."""
# Just return both if they have the same shape
if sshape == ashape:
return sshape
srank, arank = len(sshape), len(ashape)
# do a special comparison of all dims with size>1
if srank > arank:
... |
def get_price_as_int(n):
"""Utility function."""
return int(('{:.8f}'.format(n)).replace('0.', '')) |
def is_py_script(item: str):
"""check to see if item(file or folder) is a python script, by checking it's extension
Args:
item (str): the name of the file or folder
Returns:
bool: wether or not the item is a python script
"""
is_it_py_script : bool = False
ext : str = ".py"
... |
def make_object(obj, kwargs):
"""
Applies the kwargs to the object, returns obj(kwargs)
"""
return obj(**kwargs) |
def context_to_airflow_vars(context):
"""
Given a context, this function provides a dictionary of values that can be used to
externally reconstruct relations between dags, dag_runs, tasks and task_instances.
:param context: The context for the task_instance of interest
:type context: dict
"""
... |
def clean_value(value):
"""Clean spreadsheet values of issues that will affect validation """
if value == 'n/a':
return 'N/A'
elif value == 'Design was registered before field was added':
return ''
return value |
def get_keys(dict_info):
"""return key info"""
key_list = []
for k in dict_info.keys():
print(k)
key_list.append(k)
return key_list |
def show_variable_description_pca(click_data):
"""
gives a description to each of the variables when their point is clicked in the Graph
:param click_data:
:return:
"""
if not click_data:
return "Click on a data point to get a short description of the variable"
my_dot = click_data[... |
def hhmmss(t: float, dec=0):
"""Format time in seconds to form hh:mm:ss
Arguments
---------
t : float
Timestamp in seconds
dec : int (default 0)
number of decimal places to show for the seconds
"""
h = int(t / 3600)
t -= h * 3600
m = int(t / 60)
t -= m * 60
s... |
def make_edge(v1, v2):
"""
We store edges as tuple where the vertex indices are sorted (so
the edge going from v1 to v2 and v2 to v1 is the same)
"""
return tuple(sorted((v1, v2))) |
def get_x_prime(tau, z):
"""
Equation [2](2.2)
:param tau: time constant
"""
return (1.0 / tau) * z |
def offset_5p(cov, offsets_5p):
"""
Return appropriate offset for 5' transcript ends based on average transcript coverage.
"""
return offsets_5p[0] * cov + offsets_5p[1] |
def pretty_duration(seconds):
""" Returns a user-friendly representation of the provided duration in seconds.
For example: 62.8 => "1m2.8s", or 129837.8 => "2d12h4m57.8s"
"""
if seconds is None:
return ''
ret = ''
if seconds >= 86400:
ret += '{:.0f}d'.format(int(seconds / 86400))... |
def repr_args(args, kwargs):
"""Stringify a set of arguments.
Arguments:
args: tuple of arguments as a function would see it.
kwargs: dictionary of keyword arguments as a function would see it.
Returns:
String as you would write it in a script.
"""
args_s = (("%s, " if kwarg... |
def wsorted(ws):
"""Sort the letters of a word"""
w = list(ws.rstrip())
w.sort()
return ''.join(w) |
def convert_bytes_to(bytes: int, convert_to: str) -> int:
"""
Function convert bytes to kb, mb, gb and tb
>>> convert_bytes_to(1024, convert_to="kb")
1
>>> convert_bytes_to(123456789, convert_to="mb")
118
>>> convert_bytes_to(1073741824, convert_to="gb")
1
"""
data = {"kb": 1, ... |
def edges2nodes(edges):
"""gather the nodes from the edges"""
nodes = []
for e1, e2 in edges:
nodes.append(e1)
nodes.append(e2)
nodedict = dict([(n, None) for n in nodes])
justnodes = list(nodedict.keys())
# justnodes.sort()
justnodes = sorted(justnodes, key=lambda x: str(x[0... |
def query_result_to_dict(result):
"""
SQLAlchemy returns tuples, they need to be converted to dict so we can jsonify
:return:
"""
return dict(zip(result.keys(), result)) |
def is_integer(value, cast=False):
"""Indicates whether the given value is an integer. Saves a little typing.
:param value: The value to be checked.
:param cast: Indicates whether the value (when given as a string) should be cast to an integer.
:type cast: bool
:rtype: bool
.. code-block:: p... |
def decode_line(s,l,func = float):
"""
split a string and convert each token with <func>
and append the result to list <l>
"""
x = s.split()
for v in x:
l.append(func(v))
return(l) |
def parse_word(guess, response):
"""
Given a word and the games response, generate a tuple of rules
Parameters:
guess: str The guess
response: str the response from the game. Must be one of G, Y or B
Y - represents yellow
B - represents black
G - represents green
... |
def _is_import_valid(documents):
"""
Validates the JSON file to be imported for schema correctness
:param documents: object loaded from JSON file
:return: True if schema seems valid, False otherwise
"""
return isinstance(documents, list) and \
all(isinstance(d, dict) for d in documents) and \
all(al... |
def is_valid_matrix(mtx):
"""
>>> is_valid_matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
True
>>> is_valid_matrix([[1, 2, 3], [4, 5], [7, 8, 9]])
False
"""
if mtx == []:
return False
cols = len(mtx[0])
for col in mtx:
if len(col) != cols:
return False
r... |
def get_target(module, array):
"""Return Volume or None"""
try:
return array.get_volume(module.params['target'])
except Exception:
return None |
def exists_in(x, a):
"""True if x is a member of the listoid a, False if not."""
from numpy import size, where
if size(where(a == x)) == 0:
return False
else:
return True |
def smallest_diff_key(A, B):
"""return the smallest key adiff in A such that A[adiff] != B[bdiff]"""
diff_keys = [k for k in A if k not in B or A.get(k) != B.get(k)]
if (len(diff_keys)) != 0:
return min(diff_keys)
else:
return None |
def is_callable(attribute, instance=None):
"""Check if value or attribute of instance are callable."""
try:
if instance:
return callable(getattr(instance, attribute))
else:
return callable(attribute)
except AttributeError:
return False |
def build_path(package_name: str) -> str:
"""Build path from java package name."""
return package_name.replace(".", "/") |
def ra2deg(h, m, s):
"""
Convert RA (hour, minute, second) to degree.
"""
return h * 15.0 + m * 15.0/60.0 + s * 15.0/3600.0 |
def in_region(region, point):
"""
Detect if a point exists in a region.
Region: (x, y, width, height)
Point: (x, y)
Returns True or False depending on if the point exists in the region.
"""
rx, ry, rw, rh = region
x, y = point
return (
x > rx and x < rx + rw a... |
def count_loc(lines):
"""
Taken from:
https://app.assembla.com/spaces/tahar/subversion/source/HEAD/tahar.py
linked to from:
http://stackoverflow.com/questions/9076672/how-to-count-lines-of-code-in-python-excluding-comments-and-docstrings
"""
nb_lines = 0
docstring = False
for line i... |
def _decoded_str_len(l):
"""
Compute how long an encoded string of length *l* becomes.
"""
rem = l % 4
if rem == 3:
last_group_len = 2
elif rem == 2:
last_group_len = 1
else:
last_group_len = 0
return l // 4 * 3 + last_group_len |
def oct2bin(octvalue, init_length):
"""Convert octal value to binary"""
value = str(bin(int(octvalue, 8))[2:])
return value.zfill(init_length) |
def split_path(path, all_paths):
"""Split path into parent and current folder."""
idx = path.rfind('/', 0, -1)
if idx == -1:
return '', path
parent, label = path[0:idx + 1], path[idx+1:-1]
if parent not in all_paths:
return '', path
return parent, label |
def _validate_workflow_var_format(value: str) -> str:
"""Validate workflow vars
Arguments:
value {str} -- A '.' seperated string to be checked for workflow variable
formatting.
Returns:
str -- A string with validation error messages
"""
add_info = ''
parts = value.s... |
def set_bit(target, bit):
"""
Returns target but with the given bit set to 1
"""
return target | (1 << bit) |
def user(default=None, request=None, **kwargs):
"""Returns the current logged in user"""
return request and request.context.get("user", None) or default |
def page_not_found(e):
"""
Handling on page not found
Args:
e (): None
Returns:
HTML Page
"""
# handling 404 ERROR
return "<h1>404</h1>" \
"<p>The resource could not be found</p>", 404 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.