content stringlengths 42 6.51k |
|---|
def get_facets_values(facet, header):
"""extracts facets values from the contents attribute"""
values = {}
if type(facet) is str:
values.update({header[0]: facet})
elif type(facet) is list:
values.update({k:v for k,v in zip(header, facet)})
return values |
def _prepare_response_data(message, data=None):
"""Prepare response output.
Returns a simple dict containing a key `message` and optionally a key `data`.
"""
output = {"message": message}
if data is not None:
output["data"] = data
return output |
def LCS(value: str) -> bytes:
"""
pack a string into a LCS
"""
return b'\x84' + str.encode(value) + b'\x00' |
def reverse_complement(seq):
"""
Returns reverse complement of seq, with
any non-ACTG characters replaced with Ns
"""
transform = {'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
'N': 'N'}
try:
comp = [transform[e] for e in seq... |
def params_schedule_fn_constant_09_01(outside_information):
"""
In this preliminary version, the outside information is ignored
"""
mdp_default_gen_params = {
"inner_shape": (7, 5),
"prop_empty": 0.9,
"prop_feats": 0.1,
"start_all_orders": [
{"ingredients": ["... |
def initialize_tensor_board(dimensions, value):
"""
Initializes board with 0s.
Parameters:
dimensions (tuple): dimensions of the board
Returns: an nD board
"""
# Base case
if len(dimensions) == 1:
return [value for i in range(dimensions[0])]
# Iterative c... |
def create_callback_data(*args):
"""Crea una stringa a partire dai vlaori (arbitrari) in entrata, che verranno separati da ;"""
return ";".join(str(i) for i in args) |
def fun1(n):
"""
sum up to n using recursion
:param n:
:return:
"""
if n == 0:
return 0
else:
return n + fun1(n - 1) |
def readable_timedelta(days):
"""
Return a string of the number of weeks and days included in days.
Arguments:
days {int} -- number of days to convert
Returns:
{str} -- "{} week(s) and {} day(s)"
"""
# insert your docstring here
weeks = days // 7
remainder = days % 7
... |
def dereference_dict(name:str):
"""
Function to get dictionary to dereference
output labels as numbers (from the model)
to output labels as names.
Need name of dataset of which to dereference
"""
if name == "kauto5cls":
kauto_dict = {
0 : "woosan-song",
1 ... |
def encode_proto_bytes(val: str) -> bytes:
""" Encodes a proto string into latin1 bytes """
return val.encode('latin1') |
def sea_sick(sea):
"""getin sick."""
sick = 0
for i in range(len(sea) - 1):
if sea[i] != sea[i + 1]:
sick += 1
if sick > len(sea) * .2:
return "Throw Up"
return "No Problem" |
def bdd_vars(bdd_vars, variables, skin, data_base_path):
""" Inject bdd_vars so they becomes available in play
fixture """
bdd_vars['data_base_path'] = data_base_path
return bdd_vars |
def list_of_words(text):
"""Convert paragraph of " " and "\n" delimited words into a list of words"""
lines = text.strip().split("\n")
single_line = " ".join(lines)
words = single_line.split(" ")
return words |
def subtract(a, b):
""" Subtracts b from a. """
return [a[0] - b[0], a[1] - b[1]] |
def remove_extra_zeroes(number: str) -> str:
"""
Remove all zeroes from the end of the string
:param number:
:return:
"""
index = None
for i in range(-1, len(number) * -1, -1):
if number[i] == '0':
index = i
else:
break
if index is not None:
... |
def is_reserved_name(name):
"""Tests if name is reserved
Names beginning with 'xml' are reserved for future standardization"""
if name:
return name[:3].lower() == 'xml'
else:
return False |
def gen_harmonies(n_streams, base_freq=200, ratio=[1,4,5,6]):
"""Generate harmonies for as many streams as needed. Obviously limited by range of reasonable frequencies.
Used during weights sonification.
Args:
base_freq: Basic frequency to build on.
ratio: List with ratios for frequencies. S... |
def _extract_problem_info(source):
"""Split the logpath to identify test problem, data set, etc.
Args:
source (Cockpit or str): ``Cockpit`` instance, or string containing the
path to a .json log produced with ``Cockpit.write``, where
information will be fetched from.
... |
def selection_sort(arr):
""" Selection Sort
Complexity: O(n^2)
"""
for i in range(len(arr)):
minimum = i
for j in range(i+1, len(arr)):
# "Select" the correct value
if arr[j] < arr[minimum]:
minimum = j
# Using a pythonic swap
a... |
def TransformIf(r, expr):
"""Disables the projection key if the flag name filter expr is false.
Args:
r: A JSON-serializable object.
expr: A command flag filter name expression. See `gcloud topic filters` for
details on filter expressions. The expression variables are flag names
without the lea... |
def spaced_str(input_list):
"""takes a list containing floats and creates a string of its entries such that each float value is separated
by a space. such a string is often used in urdfs - helper function for urdf creation
"""
# todo: nicer doc and comment
assert isinstance(input_list, list), "input... |
def count_keys(n):
"""Generate outcome bitstrings for n-qubits.
Args:
n (int): the number of qubits.
Returns:
list: A list of bitstrings ordered as follows:
Example: n=2 returns ['00', '01', '10', '11'].
"""
return [bin(j)[2:].zfill(n) for j in range(2**n)] |
def checkIfErrorJSONResponse(retval):
"""
Checks if the JSON returned is of the calss ErrorJSONReponse
"""
return retval.__class__.__name__ == "ErrorJSONResponse" |
def get_patterns_per_repository(repo):
"""
Get all unique patterns in the repository.
Keyword arguments:
repo -- object containing properties of the repo
"""
dynamic_count = 0
if 'DYNAMIC-PATTERN' in repo['uniquePatterns']:
dynamic_count += repo['uniquePatterns']['DYNAMIC-PATTERN']... |
def rev_seq(nuc, nuc_type='dna'):
"""Return the complement of each nucleotide"""
if nuc == 'A':
if nuc_type == 'rna':
return 'U'
elif nuc_type == 'dna':
return 'T'
else:
return 'T'
elif nuc == 'T':
return 'A'
elif nuc == 'C':
r... |
def set_cover(universe, subsets):
"""Find a family of subsets that covers the universal set"""
elements = set(e for s in subsets for e in s)
# Check the subsets cover the universe
if elements != universe:
return None
covered = set()
cover = []
# Greedily add the subsets with the most... |
def process_hits(page, args, dbname):
""" Processes each hit in a scroll search and proposes changes
in the array returned """
changes = []
if 'hits' in page and 'hits' in page['hits']:
for hit in page['hits']['hits']:
doc = hit['_id']
body = {}
if args.ob... |
def _gen_parabola(phase: float, start: float, mid: float, end: float) -> float:
"""Gets a point on a parabola y = a x^2 + b x + c.
The Parabola is determined by three points (0, start), (0.5, mid), (1, end) in
the plane.
Args:
phase: Normalized to [0, 1]. A point on the x-axis of the parabola.
start... |
def dec_hex(getal):
"""
convert dec characters to their hex representative
"""
return bytes([int(getal)]) |
def split_line(line, parsers, sep=" "):
"""Split a line into pieces and parse the strings."""
parts = [part for part in line.split(sep) if part]
values = [parser(part) for parser, part in zip(parsers, parts)]
return values if len(values) > 1 else values[0] |
def deep_copy(to_copy, rows, cols):
"""Need i say?
"""
clean_mtx = []
for i in range(rows):
row = []
for j in range(cols):
row.append(to_copy[i][j])
clean_mtx.append(row)
return clean_mtx |
def binary_search_return_first_invariant(arr, low, high, key):
"""
maintain invariant of arr[low] < key <= arr[high]
"""
if arr[low] >= key:
return low
if arr[high] < key:
return high + 1
while low + 1 < high:
mid = (low + high) // 2
if arr[mid] < key:
... |
def is_img_shape(shape):
"""Whether a shape is from an image."""
try:
return len(shape) == 3 and (shape[-3] in [1, 3])
except TypeError:
return False |
def disabling_button(n_clicks):
"""
Disabling the button after its being clicked once
"""
if n_clicks >= 1:
return {'display':"none"} |
def isascii(w):
"""Is all characters in w are ascii characters"""
try:
w.encode('ascii')
return True
except UnicodeError:
return False |
def to_list(*args):
"""
Input:
args - variable number of integers represented as strings, e.g. to_list("15353", "025")
Output:
lst - a Python array of lists of strings, e.g. [[1,5,3,5,3],[0,2,5]]
"""
lst = []
for string in args:
lst.append([int(digit) for digit in string... |
def get_min_remaining_length(traces):
"""
Minimum remaining length (for sequential, parallel cut detection)
Parameters
--------------
traces
Traces
"""
min_len_traces = []
min_rem_length = []
for x in traces:
if len(x) == 0:
min_len_traces.append(0)
... |
def targets_to_labels(targets):
"""Returns a set of label strings for the given targets."""
return set([str(target.label) for target in targets]) |
def map_getattr(classInstance, classFunc, *args):
"""
Take an instance of a class and a function name as a string.
Execute class.function and return result
"""
return getattr(classInstance, classFunc)(*args) |
def count_common_prefix(str_seq, prefix):
""" Take any sequence of strings, str_seq, and return the count of
element strings that start with the given prefix.
>>> count_common_prefix(('ab', 'ac', 'ad'), 'a')
3
>>> count_common_prefix(['able', 'baker', 'adam', 'ability'], 'ab')
... |
def Dedup(seq):
"""Return a sequence in the same order, but with duplicates removed."""
seen = set()
result = []
for s in seq:
if s not in seen:
result.append(s)
seen.add(s)
return result |
def n_palavras_diferentes(lista_palavras):
"""
Essa funcao recebe uma lista de palavras e devolve o numero de palavras
diferentes utilizadas.
"""
freq = dict()
for palavra in lista_palavras:
p = palavra.lower()
if p in freq:
freq[p] += 1
else:
freq... |
def scale_simulation_fit(simulated_value, actual_value, number_individuals, total_individuals):
"""
Calculates goodness of fit for the provided values, and scales based on the total number of individuals that exist.
The calculation is 1 - (abs(x - y)/max(x, y)) * n/n_tot for x, y simulated and actual values... |
def config_section_data():
"""Produce the default configuration section for app.config,
when called by `resilient-circuits config [-c|-u]`
"""
config_data = u"""[fn_ip_void]
ipvoid_base_url=https://endpoint.apivoid.com
ipvoid_api_key=<your-api-key>
"""
return config_data |
def bounce_out(t):
"""Bounce out. Amplitude of bounce decreases."""
if t < 0.36363636363636365:
return 7.5625 * t * t
elif t < 0.7272727272727273:
return 7.5625 * (t - 0.5454545454545454) ** 2 + 0.75
elif t < 0.9090909090909091:
return 7.5625 * (t - 0.8181818181818182) ** 2 + 0.9... |
def _sort_key_max_confidence(sample):
"""Samples sort key by the max. confidence."""
max_confidence = float("-inf")
for inference in sample["inferences"]:
if inference["confidence"] > max_confidence:
max_confidence = inference["confidence"]
return max_confidence |
def is_same_len(*args):
"""
>>> is_same_len(1, 'aaa')
Traceback (most recent call last):
...
TypeError: object of type 'int' has no len()
>>> is_same_len([1], ['aaa'])
True
>>> is_same_len([1, 'b'], ['aaa', 222])
True
>>> is_same_len([1, 'b', 3], ['aaa', 222, 'ccc... |
def zscore_den(observed, expected, N, denom):
"""
Computes zscore with precomputed denominator.
:param observed:
:param expected:
:param N:
:param denom:
:return:
"""
x = float(observed - expected) / float(N)
return x / denom |
def config_get(from_,what_):
""" Returns value what_ from_ """
from_=from_.replace(' ','')
d = from_[from_.index(what_+'=')+1+len(what_):].split('\n')[0]
return d |
def check_for_winner(board):
"""
Searches through the boards and returns the id of the board if anyone has a full row or a full column.
If no winner were found, it returns -1.
"""
# First check if someone has a full row
count = 5
for j, row in enumerate(board):
for k, n in ... |
def is_wind(text: str) -> bool:
"""Returns True if the text is likely a normal wind element"""
# Ignore wind shear
if text.startswith("WS"):
return False
# 09010KT, 09010G15KT
if len(text) > 4:
for ending in ("KT", "KTS", "MPS", "KMH"):
if text.endswith(ending):
... |
def flatten(l):
"""
Flattens the list l.
:param l: list
:return: flattened list.
"""
return [item for sublist in l for item in sublist] |
def boolean_type(text):
"""Custom Parse Type to parse a boolean value.
The same values are parsed as YAML does:
http://yaml.org/type/bool.html
Plus 0 and 1
"""
text = text.lower()
return text == "1" or text.startswith("y") or text == "true" or text == "on" |
def check_required_modules(required_modules, verbose=True):
""" Function checks for Python modules which should be "importable"
before test suite can be used.
@return returns True if all modules are installed already
"""
import imp
not_installed_modules = []
for module_name in requir... |
def int_of_string_opt(s, base=10):
"""
Convert string to integer without raising exceptions
:param s: integer string
:param base: numbering base
:return: integer value or None on failure
"""
try: return int(s, base)
except: return None |
def stringifyRequestArgs(args):
"""Turn the given HTTP request arguments from bytes to str.
:param dict args: A dictionary of request arguments.
:rtype: dict
:returns: A dictionary of request arguments.
"""
# Convert all key/value pairs from bytes to str.
str_args = {}
for arg, values ... |
def _text(x: float, y: float, text: str, fontsize: int = 14):
"""Draw SVG <text> text."""
return f'<text x="{x}" y="{y}" dominant-baseline="middle" ' \
f'text-anchor="middle" font-size="{fontsize}px">{text}</text>' |
def century(year):
"""
Given a year, return the century it is in
:param year:
:return:
"""
if year % 100 == 0:
return year // 100
return (year // 100) + 1 |
def get_figshare_project_data(initial_data, headers, resources):
"""
Get all top level figshare projects.
Parameters
----------
initial_data: list
List of all top level projects
headers: dict
The authorization header that Figshare expects
resources: list
A list of re... |
def good_str(x):
"""Returns a safe (escaped) version of the string.
str -- The string"""
return repr(str(x))[1:-1] |
def to_minutes(s):
"""
Convert a time specification on the form hh:mm to minutes.
>>> to_minutes('8:05')
485
"""
h, m = s.split(':')
return int(h) * 60 + int(m) |
def strip_illegal_characters(name):
"""
Strip characters that the APIC deems are illegal
:param name: String to remove the illegal characters
:return: String with the illegal characters removed
"""
chars_all_good = True
for character in name:
if character.isalnum() or character in (... |
def col_labels(matrix_dim):
"""
Return the column-stacked-matrix-basis labels based on a matrix dimension.
Parameters
----------
matrix_dim : int
The matrix dimension of the basis to generate labels for (the
number of rows or columns in a matrix).
Returns
-------
list o... |
def _tuple_slice(tup, start, end):
"""get sliced tuple from start and end."""
return tup[start:end] |
def flatten_nested_lists(L):
""" Each element of L could be a list or any object other than a list. This function
returns a list of non-list objects, where the internal lists or lists_of_lists
have been 'flattened'.
"""
ret = []
for elem in L:
if isinstance(elem, list):
ret.extend(flatten_... |
def selection_collision(selections, poolsize):
"""
Calculate the probability that two random values selected from an arbitrary
sized pool of unique values will be equal. This is commonly known as the
"Birthday Problem".
:param int selections: The number of random selections.
:param int poolsize: The number of un... |
def get_values_multicol(columns_to_query_lst, columns_to_update_lst, query_values_dict_lst ):
"""
makes flat list for update values.
:param columns_to_query_lst:
:param columns_to_update_lst:
:param query_values_dict_lst:
:return values: list of user-given values for multirow... |
def generic_layer_dict_maker() -> dict:
"""Just a function that puts all of the standard layer definitions and
their corresponding allowed amino acids into a convenient dictionary.
As of versions > 0.7.0, made layers more restrictive. Old definitions
for helices were:
"core AND helix": 'AFILVWYNQ... |
def versionString(version):
"""Create version string."""
ver = [str(v) for v in version]
numbers, rest = ver[:2 if ver[2] == '0' else 3], ver[3:]
return '.'.join(numbers) + '-'.join(rest) |
def adaptive_name(template, host, index):
"""
A helper function for interface/bridge name calculation.
Since the name of interface must be less than 15 bytes. This util is to adjust the template automatically
according to the length of vmhost name and port index. The leading characters (inje, muxy, mbr)... |
def num_to_one(x: int) -> int:
"""Returns +1 or -1, depending on whether parm is +ve or -ve."""
if x < 0:
return -1
else:
return 1 |
def chop_at_now(ttlist):
"""Chop the list of ttvalues at now.
"""
ttlist = list(ttlist)
if not ttlist:
return []
first = ttlist[0]
now = first.__class__()
return [ttval for ttval in ttlist if ttval <= now] |
def convert_types(input_dict):
"""Convert types of values from specified JSON file."""
# Eval `type` and `element_type` first:
for key in input_dict.keys():
if input_dict[key]['type'] == 'tuple':
input_dict[key]['type'] = 'list'
for el_key in ['type', 'element_type']:
... |
def join_name(*parts):
"""Joins a name. This is the inverse of split_name, but x == join_name(split_name(x)) does not necessarily hold.
Joining a name may also be subject to different schemes, but the most basic implementation is just joining all parts
with a space.
"""
return " ".join(parts) |
def fetch_extra_data(resource):
"""Return a dict with extra data retrieved from CERN OAuth."""
person_id = resource.get("cern_person_id")
return dict(person_id=person_id) |
def welcome():
"""List all available api routes"""
return(
f"Available Routes:<br/>"
f"Precipitation: /api/v1.0/precipitation<br/>"
f"Stations: /api/v1.0/stations<br/>"
f"Temperatures: /api/v1.0/tobs<br/>"
f"Temperature stat start date (yyyy-mm-dd): /api/v1.0/yyyy-mm-dd<b... |
def unify_quotes(token_string, preferred_quote):
"""Return string with quotes changed to preferred_quote if possible."""
bad_quote = {'"': "'", "'": '"'}[preferred_quote]
allowed_starts = {
'': bad_quote,
'f': 'f' + bad_quote,
'r': 'r' + bad_quote,
'u': 'u' + bad_quote,
... |
def h2_style():
"""
h2 style
"""
return {
"border-color" : "#99A1AA",
"background-color" : "#CCEECC"
} |
def problem9(solution):
"""Problem 9 - Special Pythagorean triplet"""
# Find a^2 + b^2 = c^2 for a < b < c
a = 1
while a <= solution/3:
b = a + 1
while b <= solution/2:
c = solution - (a+b)
if c <= b:
break
if (a * a) + (b * b) == (c *... |
def flatten_twdict(twlist: list):
"""
create flat list of tweet text from list of dict or list of list
:param twlist: list of dict
:return:
"""
templst: list = []
for twthis in twlist:
if isinstance(twthis, dict):
templst.append(twthis['text'])
elif isinstance(twt... |
def edgesToVerts(s):
""" Turn a list of edges into a list of verticies """
o = set()
for e in s:
o.add(e[0])
o.add(e[1])
return o |
def _is_ethernet(port_data):
"""Return whether ifIndex port_data belongs to an Ethernet port.
Args:
port_data: Data dict related to the port
Returns:
valid: True if valid ethernet port
"""
# Initialize key variables
valid = False
# Process ifType
if 'ifType' in port_d... |
def maybe_int(string):
"""
Returns the integer value of a string if possible,
else None
"""
try:
return int(string)
except ValueError:
return None |
def update_params(original_return, add_params):
"""Insert additional params to dicts."""
if isinstance(original_return, list):
original_return = [{**i, **add_params} for i in original_return]
elif isinstance(original_return, dict):
original_return.update(add_params)
return original_retur... |
def find_all_simulations(flist, sim):
"""
Finds all simulations in the list given.
:param flist:
:param sim:
:return: [list]
"""
if not flist:
return None
else:
matches = []
for fs in flist:
if fs.startswith(sim):
matches.append(fs)
... |
def get_ref(name, prop='selfLink'):
""" Creates reference to a property of a given resource. """
return '$(ref.{}.{})'.format(name, prop) |
def bytify(n=0, size=1, reverse=False, strict=False):
"""
Returns bytearray of at least size bytes equivalent of integer n that is
left zero padded to size bytes. For n positive, if the bytearray
equivalent of n is longer than size and strict is False the bytearray
is extended to the length needed ... |
def derive_config_dict(config_obj):
"""Get the config dict from the obj
:param config_obj: The config object
:type config_obj:
:return:
:rtype:
"""
if config_obj:
config_dict = dict(config_obj.__dict__)
config_dict.pop("_sa_instance_state")
return config_dict
els... |
def parse_number(value):
"""
Try converting the value to a number
"""
try:
return float(value)
except ValueError:
return None |
def remove_nondigits(string_arg):
"""
Removes all non-digits (letters, symbols, punctuation, etc.)
:param str:
:return: string consisting only of digits
:rtype: str
"""
return ''.join(filter(lambda x: x.isdigit() or x == '.', string_arg)) |
def tamper(payload, **kwargs):
"""
Replaces (MySQL) instances like 'CONCAT(A, B)' with 'CONCAT_WS(MID(CHAR(0), 0, 0), A, B)' counterpart
Requirement:
* MySQL
Tested against:
* MySQL 5.0
Notes:
* Useful to bypass very weak and bespoke web application firewalls
tha... |
def as_list(x, length=1):
"""Return x if it is a list, else return x wrapped in a list."""
if not isinstance(x, list):
x = length*[x]
return x |
def parse_none_results(result_dict):
"""
Replace `None` value in the `result_dict` to a string '-'
"""
for key, value_list in result_dict.items():
for i in range(len(value_list)):
if value_list[i] is None:
result_dict[key][i] = '-'
return result_dict |
def attr_populated(obj, attr):
"""Return True if attr was populated in obj from source JSON."""
return not not getattr(obj, '_populated_' + attr, False) |
def autodoc_skip_member(app, what, name, obj, skip, options):
"""Skips undesirable members.
"""
# N.B. This should be registerd before `napoleon`s event.
# N.B. For some reason, `:exclude-members` via `autodoc_default_options`
# did not work. Revisit this at some point.
if "__del__" in name:
... |
def _union_lists(lists):
"""
Return a list that contains of all the elements of lists without
duplicates and maintaining the order.
"""
seen = {}
return [seen.setdefault(x, x)
for l in lists for x in l
if x not in seen] |
def local_ports(servers_list) -> "list[int]":
"""Maps given JSON servers array into a server ports list using "port" property."""
return [game_server["port"] for game_server in servers_list] |
def selection_sort(integers):
"""Search through a list of Integers using the selection sorting method.
Search elements 0 through n - 1 and select smallest, swap with element at
index 0, iteratively search through elements n - 1 and swap with smallest.
"""
integers_clone = list(integers)
for ind... |
def sanitize_html(text):
"""Prevent parsing errors by converting <, >, & to their HTML codes."""
return text\
.replace('<', '<')\
.replace('>', '>')\
.replace('&', '&') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.