content stringlengths 42 6.51k |
|---|
def makemarkers(nb):
""" Give a list of cycling markers. See http://matplotlib.org/api/markers_api.html
.. note:: This what I consider the *optimal* sequence of markers, they are clearly differentiable one from another and all are pretty.
Examples:
>>> makemarkers(7)
['o', 'D', 'v', 'p', '<', 's'... |
def is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and K... |
def calculate(x: int, y: int = 1, *, subtract: bool = False) -> int:
"""Calculate sum (or difference) of two numbers.
Parameters:
`x` : int, required
The first number
`y` : int, optional
The second number (default is 1)
`subtraction`: bool, optional
Whether to perform subtra... |
def paths_that_contain(paths, nodes, bool_and=False):
"""Return paths that contain at least one or all of the nodes.
Parameters
----------
paths : list.
list of paths where each path is a tuple of integers. Example : [(1,2,3), (1,3,4)]
nodes : list.
List of nodes that the paths are... |
def make_scp_safe(string: str) -> str:
"""
Helper function to make a string safe for saving in Kaldi scp files. They use space as a delimiter, so
any spaces in the string will be converted to "_MFASPACE_" to preserve them
Parameters
----------
string: str
Text to escape
Returns
... |
def make_img(file, width, height):
"""
:param file:
:param width:
:param height:
:return:
"""
return {
'type': 'image',
'file': file,
'width': width,
'height': height
} |
def bbox(coords1, coords2):
"""
Create BBox between two coordinates
:param coords1: coords1 Point coordinate
:param coords2: coords2 Point coordinate
:return: Bounding Box as [west, south, east, north]
"""
x1 = coords1[0]
y1 = coords1[1]
x2 = coords2[0]
y2 = coords2[1]
if x1 ... |
def regionFromResize(curr_width, curr_height, bounds_width, bounds_height):
"""Region from Resize
Returns a new set of region points based on a current width and height and
the bounding box
Args:
curr_width (uint): The current width
curr_height (uint): The current height
bounds_width (uint): The boundary wi... |
def np_within(x, target, bounds):
"""Is x within within bounds (positive or negative) of expected"""
return (x - target) ** 2 < bounds ** 2 |
def build_json_response(status, value):
"""
Generate json format from input params
:param status: string
:param value: string
:return: json array
"""
return {
'status': status,
'message': value
} |
def bezier(t, x1, y1, x2, y2):
"""The famous Bezier curve."""
m = 1 - t
p = 3 * m * t
b, c, d = p * m, p * t, t * t * t
return (b * x1 + c * x2 + d,
b * y1 + c * y2 + d) |
def final_strategy(score, opponent_score):
"""Write a brief description of your final strategy.
*** YOUR DESCRIPTION HERE ***
"""
# BEGIN PROBLEM 12
"*** REPLACE THIS LINE ***"
""
return 4
# END PROBLEM 12 |
def seq3(seq):
"""Turn a one letter code protein sequence into one with three letter codes.
The single input argument 'seq' should be a protein sequence using single
letter codes, either as a python string or as a Seq or MutableSeq object.
This function returns the amino acid sequence as a string usin... |
def extract_type(tag: str, sep: str = "-") -> str:
"""Extract the span type from a tag.
Tags are made of two parts. The second part is the type of the span which
is specific to the downstream task. This function extracts that value from
the tag.
Args:
tag: The tag to extract the type from.... |
def intersect(box1, box2):
"""Calculate the intersection of two boxes."""
b1_x0, b1_y0, b1_x1, b1_y1 = box1
b2_x0, b2_y0, b2_x1, b2_y1 = box2
x0 = max(b1_x0, b2_x0)
y0 = max(b1_y0, b2_y0)
x1 = min(b1_x1, b2_x1)
y1 = min(b1_y1, b2_y1)
if x0 > x1 or y0 > y1: # No intersection, return No... |
def depth(obj):
"""
"""
if obj == []:
return 1
elif isinstance(obj, list):
return 1 + max([depth(x) for x in obj])
else:
return 0 |
def compare_matches(matches, target) -> bool:
"""
Make sure the matches and target matches are the same.
"""
for match in target:
if match not in matches and tuple(reversed(match)) not in matches:
return False
return True |
def predictor_fail(body):
"""
Callback function which work when properties prediction failed
:param body: MassTransit message
"""
global PREDICTOR_FAIL_FLAG
PREDICTOR_FAIL_FLAG = True
return None |
def _BackendPremultiplication(color):
"""Apply premultiplication and unpremultiplication to match production.
Args:
color: color tuple as returned by _ArgbToRgbaTuple.
Returns:
RGBA tuple.
"""
alpha = color[3]
rgb = color[0:3]
multiplied = [(x * (alpha + 1)) >> 8 for x in ... |
def normal_mapping(time, tex_coords, viewer_dir, unit_normal, tangent_t, tangent_b, *args, **kw):
"""
dummy
"""
normal_map = kw.get('normal_map', 'none')
unit_new_normal = unit_normal
return (unit_new_normal, tex_coords) |
def parse_resume_step_from_filename(filename):
"""
Parse filenames of the form path/to/modelNNNNNN.pt, where NNNNNN is the
checkpoint's number of steps.
"""
split = filename.split("model")
if len(split) < 2:
return 0
split1 = split[-1].split(".")[0]
try:
return int(split1... |
def myreadlines(self):
"""Read and return the list of all logical lines using readline."""
lines = []
while True:
line = self.readline()
if not line:
return lines
else:
lines.append(line) |
def s_to_x (s, chars):
"""Convert a string to a list of integers.
s_to_x(s, chars) -> x
s: string to convert.
chars: a list of characters that s may contain, without repetitions.
x: a list of integers corresponding to the characters of s by taking the index
of the character in chars.
"""
char_to_digit = ... |
def compute_jaccard_similarity(query, document):
""" function taken explicitly from:
http://billchambers.me/tutorials/2014/12/21/tf-idf-explained-in-python.html
calculates the intersection over union of a query
in a given document.
"""
intersection = set(query).intersection(set(document))
un... |
def find_duplicates(boreField, disp=False):
"""
The distance method :func:`Borehole.distance` is utilized to find all
duplicate boreholes in a boreField.
This function considers a duplicate to be any pair of points that fall
within each others radius. The lower index (i) is always stored in the
... |
def rotate(matrix):
"""
:contrarotate matrix.
"""
return list(map(list,zip(*matrix[::])))[::-1] |
def get_title(html):
"""Finds a title in a HTML document."""
title_tag = '<title>'
start = html.find(title_tag)
if start < 0:
return None
end = html.find('</title>', start)
if end < 0:
return None
return html[start + len(title_tag): end] |
def or_field_filters(field_name, field_values):
"""OR filter returns documents that contain a field matching any of the values.
Returns a list containing a single Elasticsearch "terms" filter.
"terms" filter matches the given field with any of the values.
"bool" execution generates a term filter (whic... |
def fib(num):
"""
Check if a number is in the Fibonacci sequence.
:type num: integer
:param num: The number to check.
>>> fib(8)
True
>>> fib(4)
False
"""
num1 = 1
num2 = 1
while True:
if num2 < num:
tempnum = num2
num2 += n... |
def clip_point(p,size):
"""
Ensure 0 <= p < size.
Parameters
----------
p : int
Point to clip.
size : int
Size of the image the point sits in.
Returns
-------
p : int
Clipped point.
"""
return min(max(0,p),size); |
def create_numeric_suffix(base, count, zeros):
"""Create a string based on count and number of zeros decided by zeros
:param base: the basename for new map
:param count: a number
:param zeros: a string containing the expected number, coming from suffix option like "%05"
"""
spli = zero... |
def predict(row, weights):
"""
Super simple one layer perceptron based on this example:
https://machinelearningmastery.com/
implement-perceptron-algorithm-scratch-python/
"""
activation = weights[0]
for i in range(len(row)-1):
activation += weights[i + 1] * row[i]
if ... |
def calc_overlap_extensible(agent_traits, neighbor_traits):
"""
Given sets, the overlap and probabilities are just Jaccard distances or coefficients, which
are easy in python given symmetric differences and unions between set objects. This also accounts
for sets of different length, which is crucial in... |
def _get_summary_name(tensor, name=None, prefix=None, postfix=None):
"""Produces the summary name given.
Args:
tensor: A variable or op `Tensor`.
name: The optional name for the summary.
prefix: An optional prefix for the summary name.
postfix: An optional postfix for the summary name.
... |
def critical_events_in_outputs(healthcheck_outputs):
"""Given a list of HealthCheckResults return those which are unhealthy.
"""
return [healthcheck for healthcheck in healthcheck_outputs if healthcheck.healthy is False] |
def kind(n, ranks):
"""
Return the first rank that this hand has exactly n of.
Return None if there is no n-of-a-kind in the hand.
Args:
n: number of equal ranks to be checked. Valid values: 1 to 4.
ranks: list of ranks of cards in descending order.
"""
for r in ranks:
i... |
def unique(l):
"""
Create a new list from l with duplicate entries removed,
while preserving the original order.
"""
new_list = []
for el in l:
if el not in new_list:
new_list.append(el)
return new_list |
def calculate(start_a):
"""
>>> calculate(0)
1848
>>> calculate(1)
22157688
"""
a = 0
b = 10551260 if start_a == 1 else 860
for d in range(1, b + 1):
if b % d == 0:
a += d
return a |
def transform_in_list(list_in, list_type=None):
"""Transform a 'String or List' in List"""
if list_in is None:
list_in = ''
if not list_in == list(list_in):
list_in = list_in.split()
if list_type:
print(list_type, list_in)
return list_in |
def behzad(x,y):
"""this is just a DocString"""
z=x**2+y**2
return z |
def duplicate_encode(word):
"""This function is the solution to the Codewars Duplicate Encoder Kata that
can be found at:
https://www.codewars.com/kata/54b42f9314d9229fd6000d9c/train/python."""
word_lowercase = word.lower()
occurrences = {}
for character in list(word_lowercase):
number_... |
def extract_code(number):
"""extract area code from number.
Args:
number: number to analyze
Returns:
area code
"""
if number[0] == '(':
first_bracket = number.find('(') + 1
second_bracket = number.find(')')
return number[first_bracket:second_bracket]
elif... |
def sizeof_fmt(num, suffix='B'):
"""Format bytes into human friendly units."""
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 get_tag_options(label_matches):
"""Returns a list of the unique tags present in label_matches."""
tag_options = []
for key in label_matches.keys():
if key[1] not in tag_options:
tag_options.append(key[1])
return tag_options |
def version(val):
"""Calculate a string version from an integer value."""
ver = val / 100. if val > 2. * 100. else val / 10.
return f'{ver:.1f}' |
def pairwise_disjoint(c):
"""Return whether elements in `c` are pairwise disjoint."""
union = set().union(*c)
n = sum(len(u) for u in c)
return n == len(union) |
def calc_k_neg1(T_K):
"""
Calculates k1- kinetic constant from Table 1 of Kaufmann and Dreybrodt (2007).
Parameters
----------
T_K : float
temperature Kelvin
Returns
-------
k_neg1 : float
kinetic constant k1-
Notes
-----
Related to the rate of CO2 conversion... |
def normalize(x: int) -> int:
"""Normalize an integer between -1 and 1."""
if x > 0:
return 1
elif x < 0:
return -1
return 0 |
def parse_results(results):
"""Break up multiline output from ls into a list of (name, size) tuples."""
return [(line.split()[8], int(line.split()[4])) for line in results.splitlines() if line.strip()]
#return [(line.split()[1], int(line.split()[0])) for line in results.splitlines() if line.strip()] |
def apply_iam_bindings_patch(current_policy, bindings_patch, action):
"""
Patches the current policy with the supplied patch.
action can be add or remove.
"""
for item in bindings_patch['bindings']:
members = item['members']
roles = item['roles']
for role in roles:
if role not in current_pol... |
def get_module_url(module_items_url):
"""
Extracts the module direct url from the items_url.
Example:
items_url https://canvas.instance.com/api/v1/courses/course_id/modules/module_id/items'
becomes https://canvas.instance.com/courses/course_id/modules/module_id
"""
return module_items_url.re... |
def add_splitter(splits, splitter):
"""
Adds a spliter back to the splits
eg: if splitted on space ' '
['this', 'is', 'me']
becomes
['this', ' ', 'is', ' ', 'me']
"""
restruct = []
no = -1
for x in splits:
no += 1
if no == len(splits) - 1:
restruct.a... |
def dfs_iter(graph: dict, target, start=None) -> bool:
"""Iterative DFS.
Args:
graph: keys are vertices, values are lists of adjacent vertices
target: node value to search for
start: node to start search from
Examples:
>>> dfs_iter(graph, 7)
True... |
def relative_error(value, value_ref):
"""Return the relative error
:param value: [int,float]
Value to compare
:param value: [int,float]
Reference value
:return err: float
Relative error.
"""
return (value-value_ref)/value_ref |
def var_char(_x=0):
"""Creats a string version of VARCHAR function
Arguments:
x {integer} -- [description]
Returns:
string -- [description]
"""
return "VARCHAR(" + str(_x) + ")" |
def small_caps(text: str) -> str:
"""
Return the *text* surrounded by the CSS style to use small capitals.
Small-caps glyphs typically use the form of uppercase letters but are reduced
to the size of lowercase letters.
>>> small_caps("Dupont")
"<span style='font-variant:small-caps'>Dup... |
def calculate_building_intersection_matrix(bn, nf):
"""
:param bn: number of buildings (including both sides of the road)
:param nf: number of floors in each building
:return: number of buildings that lies between any two nodes
"""
total_nodes = bn * nf
node_eachside = int(total_nod... |
def play_or_pass(card_values, pegging_total):
"""
Determine if the next player has cards to play or should pass.
"""
action = 'pass'
remainder = 31 - pegging_total
if any(int(value) <= remainder for value in card_values):
action = 'play'
return action |
def inverse_square(array):
"""return the inverse square of array, for all elements"""
return 1/(array**2) |
def is_row_has_tokens_to_remove(tokens, tokens_to_remove: set):
"""Check if given tokens has no intersection with unnecessary tokens."""
if tokens_to_remove.intersection(set(tokens)):
return True
return False |
def start_vowel(word):
"""Checks if word starts with a vowel. Returns True if so"""
return word[0].lower() in ['a', 'e', 'i', 'o', 'u'] |
def time_calc(ttime):
"""Calculate time elapsed in (hours, mins, secs)
:param float ttime: Amount of time elapsed
:return: int, int, float
"""
# create local copy
tt = ttime
# if not divisible by 60 (minutes), check for hours, mins, secs
if divmod(tt, 60)[0] >= 1:
h_t = divmo... |
def stereo_to_mono(data_in):
"""
byte[] output = new byte[input.Length / 2];
int outputIndex = 0;
for (int n = 0; n < input.Length; n+=4)
{
// copy in the first 16 bit sample
output[outputIndex++] = input[n];
output[outputIndex++] = input[n+1];
... |
def build_composite_expr(query_values, entity_name, year):
"""Builds a composite expression with ANDs in OR to be used as MAG query.
Args:
query_values (:obj:`list` of str): Phrases to query MAG with.
entity_name (str): MAG attribute that will be used in query.
year (int): We collect d... |
def almul(x, y):
"""
Function to multiply 2 operands
"""
return(x * y) |
def nice_size(size):
"""
Returns a readably formatted string with the size
>>> nice_size(100)
'100 bytes'
>>> nice_size(10000)
'9.8 KB'
>>> nice_size(1000000)
'976.6 KB'
>>> nice_size(100000000)
'95.4 MB'
"""
words = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB']
pref... |
def russian_peas(num1, num2):
""" We're trying to implement AES polynomial using bit strings. There are two
params, and one return value.
The AES Irreducible is: P(x) = x8 + x4 + x3 + x + 1
Which should be 0x11A in Hex
So if the number multiplied together is larger than 0xFF we need to mod by
0... |
def generate_linear_peptides(pdb_seq):
"""
Assembling all the linear Pepscan peptides into the protein sequence.
parameter: The PDB sequence.
Returns: A list containing all the looped peptides.
"""
step = 5
peptide_mer = 20
linear_list = []
for i in range(0, len(pdb_seq), step):
... |
def extract_section(soup, attrs={}, name='div', all=False):
"""
gets the bs4.element.Tag (or list thereof) of a section specified by the attrs (dict or list of dicts)
and extracts (rips out of the tree (soup)) the found tags as well (to save memory)
"""
if soup: # soup is non-None
if all==Fa... |
def minimum(listy):
"""
Input: A list of numbers
Output: The lowest number in the list, iteration.
"""
mini = 1000000000000
for i in listy:
if i < mini:
mini = i
if len(listy) == 0:
return "None"
else:
return mini |
def create_api_part_search(_id, _qty):
"""
Creates the map containing the pertinent part search parameters.
@param _id: Digi-Key part ID.
@param _qty: Part quantity. Should probably be more than zero.
@return: A map of the parameters.
"""
ret = {}
ret["Keywords"] = _id
ret["RecordCount"] = _qty
return ret |
def startswith_token(s, prefix, separators=None):
"""Tests if a string is either equal to a given prefix or prefixed by it
followed by a separator.
"""
if separators is None:
return s == prefix
prefix_len = len(prefix)
if s.startswith(prefix):
if len(s) == prefix_len:
return True
if isinstance(separa... |
def get_script_tag(source):
""" Get HTML script tag with the specified source.
"""
return '<script type="text/javascript" src="{}"></script>'.format(source) |
def strnbytes(nbytes):
"""
Return number of bytes in a human readable unit of KiB, MiB or GiB.
Parameter
---------
nbytes: int
Number of bytes, to be displayed in a human readable way.
Example
-------
>>> a = np.empty((100,100))
>>> print(strnbytes(a.nbytes))
78.125 KiB... |
def contains_nonascii_characters(string):
""" check if the body contain nonascii characters"""
for c in string:
if not ord(c) < 128:
return True
return False |
def straight_line(x, m, b):
"""
`line
<https://en.wikipedia.org/wiki/Line_(geometry)#On_the_Cartesian_plane>`_
.. math::
f(x) = mx+b
"""
return m * x + b |
def construct_workflow_name(example, workflow_engine):
"""Construct suitable workflow name for given REANA example.
:param example: REANA example (e.g. reana-demo-root6-roofit)
:param workflow_engine: workflow engine to use (cwl, serial, yadage)
:type example: str
:type workflow_engine: str
"""... |
def make_kd_tree(points, dim, i=0):
"""
Build a KD-Tree for fast lookup.
Based on a recipe from code.activestate.com
"""
if len(points) > 1:
points.sort(key=lambda x: x[i])
i = (i + 1) % dim
half = len(points) >> 1
return (
make_kd_tree(points[: half], dim... |
def pobox(to_parse=None):
"""
Returns the mailing address for the PO box
:param to_parse:
:return:
"""
output = "You can send stuff to me at the following address: \n" \
"7241 185th Ave NE \n" \
"# 2243 \n" \
"Redmond, WA 98073"
return output |
def solution(A):
"""
https://app.codility.com/demo/results/trainingBY9CAY-RBU/
:param A:
:return:
"""
len_ar = len(A) + 1
sum_length = int(len_ar * (len_ar + 1) / 2)
return sum_length - sum(A) |
def get(db, key):
"""
Get value by given key
"""
value = db.get(key)
if value is None:
return None
return value |
def coords_to_xyz(labels, coords):
"""
Displays coordinates
"""
s = ""
for i in range(len(coords)):
s += labels[i] + " " + str(coords[i][0]) + " " + \
str(coords[i][1]) + " " + str(coords[i][2]) + "\n"
return s |
def copy_dict_or_new(original: dict) -> dict:
"""Makes a copy of the original dict if not None;
otherwise returns an empty dict.
"""
if original is None:
return dict()
return dict(original) |
def _isSubsequenceContained(subSequence, sequence):# pragma: no cover
"""
Checks if the subSequence is into the sequence and returns a tuple that
informs if the subsequence is into and where. Return examples: (True, 7),
(False, -1).
"""
n = len(sequence)
m = len(subSequence)
for i in ra... |
def count_rectangles(m: int, n: int) -> int:
"""Returns the number of rectangles in an m by n rectangular grid."""
return m * (m + 1) * n * (n + 1) // 4 |
def initialise_costs_to_zero(tree_types):
"""
This method returns a dictionary cost, where each key is an element in the list tree_types and each value is 0
:param tree_types: A list of tree types that represent the keys of the dictionary
:return: The dictionary cost where each value is set to 0
""... |
def get_path_from_finish(current):
"""Traces back the path thourgh parent-nodes"""
backwards = []
while current:
backwards.append(current.location)
current = current.parent
backwards.reverse()
return backwards |
def filter_imgs(bbox, min_size=None, format='xywh'):
"""Filter image acoording to box size.
Args:
min_size (int | float, optional): The minimum size of bounding
boxes in the images. If the size of a bounding box is less than
``min_size``, it would be add to ignored field. Defaul... |
def _StringSetConverter(s):
"""Option value converter for a comma-separated set of strings."""
if len(s) > 2 and s[0] in '"\'':
s = s[1:-1]
return set(part.strip() for part in s.split(',')) |
def __has_number(word):
"""Check numbers"""
return any(char.isdigit() for char in word) |
def sum_even_fib_numbers(n):
"""Sum even terms of Fib sequence up to n"""
assert n >= 0
total = 0
current_term = 1
last_term = 1
while current_term <= n:
if not current_term%2:
total += current_term
current_term, last_term = current_term + last_term, current_term
... |
def get_size(size):
"""Get size in readable format"""
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
size = float(size)
i = 0
while size >= 1024.0 and i < len(units):
i += 1
size /= 1024.0
return "%.2f %s" % (size, units[i]) |
def create_token_content_id(iteration):
"""
:param iteration:
:return:
"""
return 'tokenContent' + iteration |
def GetDeleteResultsPathInGCS(artifacts_path):
"""Gets a full Cloud Storage path to a destroy-results file.
Args:
artifacts_path: string, the full Cloud Storage path to the folder containing
deletion artifacts, e.g. 'gs://my-bucket/artifacts'.
Returns:
A string representing the full Cloud Storage ... |
def parse_sequence(directions):
"""Parse textual representation of sequence of directions
into a list."""
return [direction.upper() for direction in directions.split(',')] |
def assignment_one_param(arg):
"""Expected assignment_one_param __doc__"""
return "assignment_one_param - Expected result: %s" % arg |
def every_n(sequence, n=1):
"""
Iterate every n items in sequence.
:param sequence: iterable sequence
:param n: n items to iterate
"""
i_sequence = iter(sequence)
return list(zip(*[i_sequence for i in range(n)])) |
def count_words(tokenized_sentences):
"""
Count the number of word appearence in the tokenized sentences
Args:
tokenized_sentences: List of lists of strings
Returns:
dict that maps word (str) to the frequency (int)
"""
word_counts = {}
# Loop through e... |
def window_historical_load(historical_load, window_begin, window_end):
"""Filter historical_load down to just the datapoints lying between times window_begin and window_end, inclusive."""
filtered = []
for timestamp, value in historical_load:
if timestamp >= window_begin and timestamp <= window_end:... |
def month_int_to_str(month_idx: int) -> str:
"""Converts an integer [1-12] into a string of equivalent month."""
switcher = {
1: "January",
2: "February",
3: "March",
4: "April",
5: "May",
6: "June",
7: "July",
8: "August",
9: "September",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.