content stringlengths 42 6.51k |
|---|
def mults_of_ns(mults=[1], limit=1000):
"""
returns the sum of all the values that are multiples of ns up to limit
"""
return sum(set([val for val in range(limit) for arg in mults if val%arg==0])) |
def date_extend(month, year):
"""
A function to help me not write the same thing many times.
If the month is December the month switches to January next year
@type month: integer
@param month: a month of the year
@type day: integer
@param day: a day of the given month
@rtype: tup... |
def half_even_round(value, scale):
"""
Round values using the "half even" logic
See more: https://docs.python.org/3/library/decimal.html#rounding-modes
>>> half_even_round(7.5, 0)
8.0
>>> half_even_round(6.5, 0)
6.0
>>> half_even_round(-7.5, 0)
-8.0
>>> half_even_round(-6.5, 0)... |
def checkAnswers(answers):
"""
checkAnswers(answers): Check our answers. This is an array that is returned (even if empty) in the same order as the actual answers.
"""
retval = []
for answer in answers:
sanity = answer["sanity"]
headers = answer["headers"]
#headers["class"] = 0 # Debugging
if headers[... |
def print_reverse(head_node):
"""Prints the elements of the given Linked List in reverse order"""
# If reached end of the List
if head_node is None:
return None
else:
# Recurse
print_reverse(head_node.next)
print(head_node.data) |
def _get_in_response_to(params):
"""Insert InResponseTo if we have a RequestID."""
request_id = params.get('REQUEST_ID', None)
if request_id:
return {
'IN_RESPONSE_TO': request_id,
**params,
}
else:
return params |
def _py_list_append(list_, x):
"""Overload of list_append that executes a Python list append."""
# Revert to the original call.
list_.append(x)
return list_ |
def get_nested_obj_attr_value(obj, lookup_str, seperator="__"):
"""
return the value of an inner attribute of an object
e.g. `user__organization__member__organization__slug` would return the organization slug related to the user
:object obj: an object. could be model obj
:string lookup_str: str to ... |
def make_url(path):
""" This is a terrible function. Don't take it as a reference in your own code.
It just happens to be good enough for our purposes here. """
return "http://localhost:5000/{path}".format(path=path) |
def get_branch(version: str) -> str:
""" Get the branch of an update """
return 'stable' if version.startswith('V') else 'weekly' |
def print_port(filter_port, packet_port):
"""
Confirm if filter_port is packet_port or any
"""
if filter_port in [packet_port, 'Any', 'any', 'ANY']:
return True
return False |
def rootsearch(f, a: float, b: float, dx: float):
"""Seacrh one root in range [a, b]."""
x1 = a
f1 = f(a)
x2 = a + dx
f2 = f(x2)
if x2 > b:
x2 = b
f2 = f(x2)
while f1*f2 > 0.0:
if x1 >= b:
return None, None
x1 = x2
f1 = f2
x2 = x1 +... |
def parse_params(params):
"""
Take Tor-formatted parameters, then returns a keyword-based dictionary
of integers.
For example, we use it to parse "params" fields:
https://github.com/plcp/tor-scripts/blob/master/torspec/dir-spec-4d0d42f.txt#L1820
:param str params: input... |
def get_fields(json):
"""
Retrieve arguments from JSON request
:param json: JSON request sent in payload
:return: Parsed arguments
"""
record_name = json.get('record_name')
ip4_address = json.get('address')
parent_zone = json.get('parent_zone')
return record_name, ip4_address, paren... |
def pluralize(num: int, thing: str) -> str:
"""Return the string f"1 {thing}" or f"{num} {thing}s", depending on `num`."""
return f"1 {thing}" if num == 1 else f"{num} {thing}s" |
def convert_dms_from_float(value, loc):
"""
convert floats coordinates into degrees, munutes and seconds + ref tuple
return: tuple like (25, 13, 48.343 ,'N')
"""
if value < 0:
loc_value = loc[0]
elif value > 0:
loc_value = loc[1]
else:
loc_value = ""
abs_value = ... |
def merge(source, destination):
"""Update destination dict with source recursively.
see: https://stackoverflow.com/questions/20656135 (also: 7204805)
"""
for key, value in source.items():
if isinstance(value, dict):
node = destination.setdefault(key, {}) # get node or create one
... |
def handle_problematic_characters(errors, filename, start, end, message):
"""Trivial helper routine in case something goes wrong in `decode`.
:Parameters:
- `errors`: the ``errors`` parameter known from standard ``str.encode``
methods. It is just passed by `decode`.
- `filename`: the input... |
def _compare(idx, text):
"""
compare function for sorted
"""
txt = text[idx]
if isinstance(txt, tuple):
txt = txt[1]
try:
decimal_string = txt
decimal_value = float(decimal_string)
txt = u""
except ValueError:
decimal_value = float('Infinity')
... |
def pre_process(board, turn="x"):
""" Takes the board with x and o and turns in into vectors with numbers. 1 is AI, -1 is human, and 0 is empty """
result = []
opposite = "o" if turn == "x" else "x"
result = [1 if x == turn else x for x in board]
result = [-1 if x == opposite else x for x in result... |
def abort_message(message):
"""Generic abort message"""
return {'message': message} |
def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
... |
def element(atomic_number):
"""
Return the element of a given atomic number.
:param atomic_number:
The atomic number for the element in question (e.g., 26).
:type atomic_number:
int-like
:returns:
The short-hand element for a given atomic number.
:rtype:
str
... |
def zipstar(L, lazy=False):
"""
A much faster A, B, C = zip(*[(a, b, c), (a, b, c), ...])
May return lists or tuples.
"""
if len(L) == 0:
return L
width = len(L[0])
if width < 100:
return [[elem[idx] for elem in L] for idx in range(width)]
L = zip(*L)
return L if... |
def parse_compute_version(compute_version):
"""Parse compute capability string to divide major and minor version
Parameters
----------
compute_version : str
compute capability of a GPU (e.g. "6.0")
Returns
-------
major : int
major version number
minor : int
min... |
def LinearSearch(array, value):
"""
Function to implement linear search where each
element of array is consecutively checked to
find the key element
"""
# Traversing through each element of the array
for i in range(len(array)):
# Comparing current array element with the
# el... |
def isint(o):
"""Determine if object is int-like (is convertible using `int()`)."""
try:
int(o)
return True
except ValueError:
return False |
def get_vector(value):
"""Convert an integer into a byte-vector string."""
if value == 0: return ''
vector = []
sign = 1
if value < 1:
sign = -1
value *= -1
while value:
vector.insert(0, value % 256)
value //= 256
if vector[0] & 0x80:
vector.inser... |
def cross_product(a, b):
""" Return the angles in (x, y, z) between two vectors, a & b. """
a1, a2, a3 = a
b1, b2, b3 = b
return (a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1) |
def expsum(x, coefficient, powers):
"""
:param x: Input variable
:param coefficient: List of coefficients [ a0, a1, a2, a3, a4, ... an]
:param powers: List of expoents [ c0, c1, c2, c3, c4, ... cn]
:return: a0.x^c0 + a1.x^c1 + a2.x^c2 + a3.x^c3 + ...
"""
S = 0
... |
def get_min_maf(mafStr):
"""Choose minimum MAF from MAF scores concatenated by :"""
maf_min = 1.0
for maf in mafStr.split(':'):
if float(maf)<maf_min:
maf_min =float(maf)
return maf_min |
def transform(record):
"""
Transforms (maps) a record.
Parameters
----------
record : dict
The record to transform.
Returns
-------
dict
The transformed record.
"""
return {
record["stakeholder_approach"]: {
record["stakeholder_id"]: {
... |
def cigar_to_lens(cigar):
"""Extract lengths from a CIGAR string.
Parameters
----------
cigar : str
CIGAR string.
Returns
-------
int
Alignment length.
int
Offset in subject sequence.
"""
align, offset = 0, 0
n = '' # current step size
for c in ... |
def transform_groups(response_objects):
""" Strips list of API response objects to return list of group objects only
:param response_objects:
:return: list of dictionary objects as defined in /docs/schema/gsuite.md
"""
groups = []
for response_object in response_objects:
for group in r... |
def get_cycle_length(n):
"""
takes an integer 0 < n < 10000
returns the number of steps it
will take to get to 1
by performing n // 2 if n is even
and n * 3 + 1 if n is odd
"""
steps = 1
while ( n != 1 ):
if n % 2 == 0:
n = n / 2
steps = steps + 1
... |
def raoult_liquido(fraccion_vapor, presion_vapor, presion):
"""Calcula la fraccion molar de liquido mediante la ec de Raoult"""
return fraccion_vapor * presion / presion_vapor |
def is_markdown(view):
"""Determine if the given view location is Markdown."""
if view is None:
return False
else:
try:
location = view.sel()[0].begin()
except IndexError:
return False
pass
pass
matcher = 'text.html.markdown'
retur... |
def bad_argument(*args: tuple, **kwargs: dict) -> dict:
"""
Bad Option exception response
:return: OpenC2 response message - dict
"""
return dict(
status=501,
status_text="Option not supported"
) |
def stem(word):
""" Stem word to primitive form
This example taken from toolz: https://github.com/pytoolz/toolz
There are several different ways to split a string, stem the words,
and calculate their frequency.
"""
return word.lower().rstrip(",.!:;'-\"").lstrip("'\"") |
def bed_complete(pack_idx, x_max):
"""Check to see if bed is complete based on model params."""
# similarly, if np.count_nonzero(bed_space) == x_max
if pack_idx >= x_max:
return 1
else: return 0 |
def _mat_mat_dot_fp(x, y):
"""Matrix (list of lists) times matrix (list of lists)."""
zip_y = list(zip(*y))
return [[sum(a * b for a, b in zip(row_x, col_y))
for col_y in zip_y] for row_x in x] |
def hello(friend_name):
"""
Return a string
- param[0] = a String. Ignore for now.
- @return = a String containing a message
"""
if not isinstance(friend_name, str):
return "Try again"
response = "Hello, " + friend_name + "!"
return response |
def partition(condition, iterable, output_class=tuple):
"""
split an iterable into two according to a function evaluating to either
true or false on each element
:param condition: boolean function
:param iterable: iterable to split
:param output_class: type of the returned iterables
:retur... |
def status_sorter(a):
"""
Helper function to sort string elements, which can be None, too.
:param a: element, which gets sorted
:return:
"""
if not a["status"]:
return ""
return a["status"] |
def removecomment(astr, cphrase):
"""
the comment is similar to that in python.
any charachter after the # is treated as a comment
until the end of the line
astr is the string to be de-commented
cphrase is the comment phrase"""
# linesep = mylib3.getlinesep(astr)
alist = astr.splitlines(... |
def parse_keyids(key):
"""Return parsed keyid string(s) or tuple of."""
if isinstance(key, str):
return key
elif isinstance(key, (tuple, list)):
return tuple(parse_keyids(keyid) for keyid in key)
return getattr(key, "keyid") |
def is_sublist(list_, sublist):
"""A sublist is part of a given list"""
return any(list_[i:i+len(sublist)] == sublist
for i in range(len(list_)-len(sublist)+1)) |
def split_task_parameters(line):
""" Split a string of comma separated words."""
if line is None:
result = []
else:
result = [parameter.strip() for parameter in line.split(",")]
return result |
def _convert_to_metrics_list(metrics):
"""Convert a dict of metrics names and weights as keys and values, into a list
of dicts with the two keys "name" and "weight" as keys and the metrics name and
metric weight as their corresponding values.
Examples:
metrics {"name1": 1.0, "name2": 2.0} res... |
def iana_interface_type(
num # type: int
):
"""Parse IANA-defined interface types"""
if num == 1:
return "Other"
elif num == 2:
return "BBN 1822"
elif num == 3:
return "HDH 1822"
elif num == 4:
return "DDN X.25"
elif num == 5:
return "RFC-877 X.25"
# For all Ethernet-like CSMA-CD interfaces per IAN... |
def _parse_ctab_atom_block(contents):
"""
"""
atom_block = []
for row in contents:
atom_block.append(row.rstrip('\n'))
return atom_block |
def non_english_lang(lp):
"""Returns the non-English language from the supplied language pair.
Args:
lp: a string representing a language pair, e.g. "en-te"
Returns:
A string representing the non-English language in the language-pair, e.g.
"te".
Raises:
ValueError if `lp` does not have two pa... |
def get_int_from_string(string):
"""
Turn a string into integers.
"""
conv = []
maxpool = []
for k,v in string.items():
if k == 'conv':
for i in v:
String = i.split('(')
String = String[1][:-1]
String = String.split('... |
def transform_chw(transform, lst):
"""Convert each array in lst from CHW to HWC"""
return transform([x.transpose((1, 2, 0)) for x in lst]) |
def array_diff(a, b):
"""."""
return [x for x in a if x not in b] |
def maybe_snowflake(value):
"""
Converts the given `value` to `snowflake` if applicable. If not returns `None`.
Parameters
----------
value : `str`, `int` or `Any`
A value what might be snowflake.
Returns
-------
value : `int` or `None`
Raises
------
As... |
def islands(array):
"""
Identify islands In a given array, identify groups ("islands") of identical elements. A group must consist of 2 or more contiguous identical elements.
Given: An array like: "proogrrrammminggg"
Output: o, r, m, g
Challenge output: o:2, r:5, m:9, g:14 (positions of first occurr... |
def parse_file_list(data):
"""
Parse the file list contained in the torrent dict from the Gazelle API.
:param: data The string to parse
:return: A dict. The keys are the relative paths of the files and the
values are the size of the file in bytes.
"""
files = {}
for x in data.... |
def list_operations(list1, list2):
"""Sa se scrie o functie care primeste ca parametri doua liste a si b.
Returneaza un tuplu de seturi care sa contina: (a intersectat cu b, a reunit cu b, a - b, b - a).
Se foloseste de operatiile pe seturi.
"""
l1set = set(list1)
l2set = set(list2)
aminusb... |
def unzip_files(zip_filename_list):
"""
Unzipping the datasets
parameters
----------
zip_filename_list : the list of file names to unzip under the data folder
"""
from zipfile import ZipFile
import os
folder_names = []
for file in zip_filename_list:
# p... |
def joinPath(parentPath, name):
"""
Join a *canonical* `parentPath` with a *non-empty* `name`.
>>> joinPath('/', 'foo')
'/foo'
>>> joinPath('/foo', 'bar')
'/foo/bar'
>>> joinPath('/foo', '/foo2/bar')
'/foo/foo2/bar'
>>> joinPath('/foo', '/')
'/foo'
"""
if name.startswit... |
def stringToTupleOfFloats(s):
"""
Converts s to a tuple
@param s: string
@return: tuple represented by s
"""
ans = []
for i in s.strip("()").split(","):
if i.strip() != "":
if i == "null":
ans.append(None)
else:
ans.append(float... |
def post_args_from_form(form):
"""
Take a table of form data or other sort of dictionary and turn it into a
regular 1D list to be passed as args
"""
res = list()
for item in form:
res.append(item)
res.append(form[item].value)
return res |
def factorial(n: int) -> int:
"""
Calculate the factorial of an integer greater than zero.
:param n: Must be an integer greater than zero.
:return: The integer value of N!
"""
if n < 0:
print("n must be a positive number. {} is an invalid response.".format(n))
exit(code=1)
if... |
def get_desktop_data_path(language: str, word_type: str):
"""
Returns the path to the data json of the desktop app given a language and word type.
Parameters
----------
language : str
The language the path should be returned for.
word_type : str
The type of word... |
def phylsowingdatecorrection(sowingDay=1,
latitude=0.0,
sDsa_sh=1,
rp=0.0,
sDws=1,
sDsa_nh=1,
p=120.0):
"""
PhylSowingDateCorrection Mod... |
def _fortran_to_val(val):
"""
Transform a Fortran value to a Python one.
Args:
val (str): The value to translate.
Returns:
A Python representation.
"""
if val[0] == val[-1] == '"': # A string
return val[1:-1]
if val == ".true.":
return True
if val == ... |
def is_empty(items):
"""
Iterate over a list to check if its element contains values or not.
'' or None are regarded as non-values.
Args:
``items`` (list): A list of items.
Returns:
``bool``. Returns ``True`` if the list only contains empty
values, else returns ``False``.
... |
def merge_intervals(data):
"""
data = [(10,20), (15,30), (100, 200)]
out = [(10,30), (100,200)]
"""
if len(data)==0:
return data
result = []
saved = list(data[0])
for st, en in sorted([sorted(t) for t in data]):
if st <= saved[1]:
saved[1] = max(saved[1], en)
... |
def utilization_threshold_abstract(f, limit, utilization):
""" The abstract utilization threshold algorithm.
:param f: A function to calculate the utilization threshold.
:type f: function
:param limit: The minimum allowed length of the utilization history.
:type limit: int
:param utilizatio... |
def name_contains(test_name, vals):
"""Determines if any string in vals is a substring of test_name.
Args:
test_name: (string) String to determine if contains substrings.
vals: (list of strings) List of substrings to test for.
Returns:
True if a substring in vals is in test_name, e... |
def generate_options_for_mode(server=None, control_value=None, **kwargs):
"""
Define a list of tuples that will be returned to generate the field options
for the mode Action Input, depending on the value from monitoring_tool
passed in as the control_value argument.
each tuple follows this order: (v... |
def find_pivot_index(nums):
"""
Suppose a sorted array A is rotated at some pivot unknown to you
beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element. NOTE: The array will not contain duplicates.
"""
min_num = nums[0]
pivot_index = 0
left = 0
right =... |
def _replace_esc(s: str, chars: str) -> str:
"""replace the given escape sequences of `chars` with \\uffff"""
for c in chars:
if f'\\{c}' in s:
break
else:
return s
b = []
i = 0
length = len(s)
while i < length:
try:
sbi = s.index('\\', i)
... |
def translate_name(name):
"""Translate feature name."""
return name.translate(str.maketrans('', '', " '")) |
def _count_dot_semicolumn(value):
"""Count the number of `.` and `:` in the given string."""
return sum([1 for c in value if c in [".", ":"]]) |
def cleanup_code(content):
"""Automatically removes code blocks from the code."""
# remove ```py\n```
if content.startswith('```') and content.endswith('```'):
return '\n'.join(content.split('\n')[1:-1])
# remove `foo`
return content.strip('` \n') |
def dashcase(var): # some-variable
"""
Dash case convention. Include '-' between each element.
:param var: Variable to transform
:type var: :py:class:`list`
:returns: **transformed**: (:py:class:`str`) - Transformed input in ``dash-case`` convention.
"""
return "-".join(var) |
def chunk(keywords, lines):
"""
Divide a file into chunks between
key words in the list
"""
chunks = dict()
chunk = []
# Create an empty dictionary using all the keywords
for keyword in keywords:
chunks[keyword] = []
# Populate dictionary with lists of chunks asso... |
def correct_protein_residue_numbers(ligand_interaction_data, protein_first_residue_number):
"""
Correct the protein residue numbers in interaction data.
Parameters
----------
ligand_interaction_data : dict
One of sub-dicts (corresponding to a single ligand)
created by the functi... |
def print_leaf(counts):
"""A nicer way to print the predictions at a leaf."""
total = sum(counts.values()) * 1.0
probs = {}
for lbl in counts.keys():
probs[lbl] = str(int(counts[lbl] / total * 100)) + "%"
return probs |
def remove_close_values_on_log_scale(values, tolerance=0.1):
"""
Params
------
values -- array-like of floats
tolerance (float) -- for a given x remove all y:
x - tolerance*x < y < x + tolerance*x
Example
-------
tolerance = 0.1
[1, 1.01, 15, 14, 1.11] -> [... |
def _includes_base_class(iter_classes, base_class):
"""
Returns whether any class in iter_class is a subclass of the given base_class.
"""
return any(
issubclass(current_class, base_class) for current_class in iter_classes
) |
def freq_label_to_human_readable_label(freq_label: str) -> str:
"""Translate pandas frequency labels to human-readable labels."""
f2h_map = {
"5T": "5 minutes",
"15T": "15 minutes",
"1h": "1 hour",
"24h": "1 day",
"168h": "1 week",
}
return f2h_map.get(freq_label,... |
def _is_code_chunk(chunk_lang):
"""determine from ```<chunk_lang>... if the chunk is executable code
or documentation code (markdown) """
return chunk_lang.startswith('{') and chunk_lang.endswith('}') |
def siwsi(b8a, b11):
"""
Shortwave Infrared Water Stress Index \
(Fensholt and Sandholt, 2003).
.. math:: SIWSI = (b8a - b11)/(b8a + b11)
:param b8a: NIR narrow.
:type b8a: numpy.ndarray or float
:param b11: SWIR 1.
:type b11: numpy.ndarray or float
:returns SIWSI: Index value
... |
def find_next_empty(puzzle):
""" Return row, col tuple (or None, None) if there is no empty square"""
for r in range(9):
for c in range(9):
if puzzle[r][c] == 0:
return r,c
return None, None |
def add_namespace_to_cmd(cmd, namespace=None):
"""Add an optional namespace to the command."""
return ['ip', 'netns', 'exec', namespace] + cmd if namespace else cmd |
def add_backslash(url: str) -> str:
"""
:param url: url
:return: add backslash to url
:rtype: str
"""
return url if "/" in url[-1] else f"{url}/" |
def getColor(cnvtype=None):
"""Return the shade of the item according to it's variant type."""
if cnvtype == "copy_number_variation":
return "128,128,128"
elif cnvtype == "deletion":
return "255,0,0"
elif cnvtype == "delins":
return "255,0,0"
elif cnvtype == "insertion":
... |
def _check_int_input(var, input_name: str) -> int:
"""
_check_int_input
Convenience function to check if an input is an int (or a float coercable into an int without
rounding). If the input is not of the expected types it will raise a helpful value error.
Parameters
----------
var
... |
def arclength( lat1, lon1, lat2, lon2, radius=None ):
"""Arc-length distance in km
Assumes angles in degrees ( not radians ).
Todd Mitchell, April 2019"""
if radius is None:
radius = 6.37e3 # in km
import numpy as np
meanlat = np.mean( ( lat1, lat2 ) )
rcosine = radius * np.c... |
def phred_to_prob(q):
"""Convert a phred score (Sanger or modern Illumina) in probabilty
Given a phred score q, return the probabilty p
of the call being right
Args:
q (int): phred score
Returns:
float: probabilty of basecall being right
"""
p = 10 ** (-q / 10)
return ... |
def parse_copy_startup_config_running_config(raw_result):
"""
Parse the 'copy startup-config running-config' command raw output.
:param str raw_result: copy startup-config running-config
raw result string.
:rtype: dict
:return: The parsed result of the copy startup-config running-config:
... |
def get_kwargs(names, defaults, kwargs):
"""Return wanted parameters, check remaining.
1. Extracts parameters `names` from `kwargs`, filling them with the
`defaults`-value if it is not in `kwargs`.
2. Check remaining kwargs;
- Raise an error if it is an unknown keyword;
- Print warnin... |
def get_data_from_dict(source_dict, keys):
""" Get dict with keys witch specify and with values from specified dict by that keys from source_dict
:param source_dict: dictionary
:param keys: keys for creation new dict, that keys should be exists in a source_dict
:return: dict with keys witch specify and... |
def get(attribute_name, json_response, default=None):
"""
Retrieve attribute from a JSON response.
:param attribute_name: Attribute name to get.
:param json_response: JSON response.
:param default: Value to return if the attribute is not found.
:return: Attribute value.
"""
return defaul... |
def element_to_list(element):
"""Converts an element to a list of True blocks"""
return [True] * element |
def filter_with_prefixes(value, prefixes):
"""
Returns true if at least one of the prefixes exists in the value.
Arguments:
value -- string to validate
prefixes -- list of string prefixes to validate at the beginning of the value
"""
for prefix in prefixes:
if value.startswith(prefi... |
def cDekel(c2, alpha):
"""
Compute the Dekel+ concentration, c, using the conventional
concentration, c_-2, and the Dekel+ innermost slope, alpha.
Syntax:
cDekel(c2,alpha)
where
c2: concentration, c_-2 = R_vir / r_-2 (float or array)
alpha: Dekel+ innermost slope (float o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.