content stringlengths 42 6.51k |
|---|
def _escape(s: str) -> str:
"""Escapes special chracters in inputrc strings"""
return s.replace("\\", "\\\\").replace('"', '\\"') |
def aXbXa(v1, v2):
"""
Performs v1 X v2 X v1 where X is the cross product. The
input vectors are (x, y) and the cross products are
performed in 3D with z=0. The output is the (x, y)
component of the 3D cross product.
"""
x0 = v1[0]
x1 = v1[1]
x1y0 = x1 * v2[0]
x0y1 = x0 * v2[1]
... |
def fetch_online(ticker='MSFT', days=1):
"""
:param ticker: name of the stock to fetch the data for
:param days: how many most recent data to fetch. days = 1 fetches for today only.
:return: list of quotes for the most recent 'days'
"""
data = []
for day in range(days):
pass
retu... |
def get_check_name(geojson):
"""
Returns the checkName from a FeatureCollection
:param geojson:
:return string:
"""
return geojson.get("properties").get("generator") |
def get_common_count(list1, list2):
"""
Get count of common between two lists
:param list1: list
:param list2: list
:return: number
"""
return len(list(set(list1).intersection(list2))) |
def _pad_key(key: str):
"""pads key with / if it does not have it"""
if key.startswith("/"):
return key
return "/" + key |
def convert_kg_to_target_units(data_kg, target_units, kg_to_kgC):
"""
Converts a data array from kg to one of several types of target units.
Args:
data_kg: numpy ndarray
Input data array, in units of kg.
target_units: str
String containing the name of the units ... |
def weight_of(vertex1, vertex2, edges):
""" Gives the distance between two vertices. It reads it from the tuple array "edges" """
if vertex1 == vertex2:
return None
for _tuple in edges:
if vertex1 in _tuple and vertex2 in _tuple:
return _tuple[2]
return None |
def remove_OOV(text, vocab):
"""
Remove OOV words in a text.
"""
tokens = str(text).split()
tokens = [word for word in tokens if word in vocab]
new_text = " ".join(tokens)
return new_text |
def inv_depths_normalize(inv_depths):
"""
Inverse depth normalization
Parameters
----------
inv_depths : list of torch.Tensor [B,1,H,W]
Inverse depth maps
Returns
-------
norm_inv_depths : list of torch.Tensor [B,1,H,W]
Normalized inverse depth maps
"""
mean_inv... |
def _getbuf(data):
"""Converts data into ascii,
returns bytes of data.
:param str bytes bytearray data: Data to convert.
"""
if isinstance(data, str):
return data.encode("ascii")
return bytes(data) |
def insert_file_paths(command, file_paths, start_delim='<FILE:', end_delim='>'):
"""
Insert file paths into the command line at locations indicated by
the starting and ending delimiters.
"""
tokens = command.split()
final_tokens = []
for token in tokens:
if token.startswith(start_del... |
def mix(x, y, a):
"""glsl `mix` function.
"""
return x * (1 - a) + y * a |
def get_city_by_id(item_id):
"""Get City by Item ID.
Given the item ID of a luxury good, return which city it needs to be brought to.
Args:
item_id (str): Item ID
Returns:
str: City name the item should be brought to.
"""
ids_to_city = {
"RITUAL": "Caerleon",
... |
def passes_language_test(t008, t041s):
"""
Checks if data in 008 and 041$a fulfills Recap language test
args:
t008: str, value of 008 MARC tag
t041s: list, list of language codes found in 041 $a
returns:
Boolean: True if applicable for Recap, False if not
"""
if t041s is ... |
def trimBytes(bs):
""" Trims trailing zeros in a byte string """
n = bs.find(b'\0')
if n != -1:
return bs[:n]
return bs |
def is_numeric(x):
"""Tests to see if a character is numeric"""
try:
float(x)
return True
except (ValueError, TypeError):
return False |
def applyF_filterG(L, f, g):
"""
Assumes L is a list of integers
Assume functions f and g are defined for you.
f takes in an integer, applies a function, returns another integer
g takes in an integer, applies a Boolean function,
returns either True or False
Mutates L such that, for each ... |
def _build_index_definition(index):
"""
Creates request object to Index to be deployed
:param index:
:return:
"""
index_def = {
"IndexName": index["name"],
"KeySchema": [
{
"AttributeName": index["index_key_name"],
"KeyType": "HASH"
... |
def test_case(panel):
"""Return a simple case"""
case_info = {
"case_id": "1",
"genome_build": 37,
"owner": "cust000",
"individuals": [
{"analysis_type": "wgs", "sex": 1, "phenotype": 2, "individual_id": "ind1"}
],
"status": "inactive",
"panels... |
def strip_leading_output_cell(lyx_string):
"""Return `string` with any leading output cell stripped off."""
lyx_string_lines = lyx_string.splitlines()
saved_lines = []
max_search_lines = 3
found_cell = False
inside_cell = False
for count, line in enumerate(lyx_string_lines):
if not f... |
def _positive_int(integer_string, strict=False, cutoff=None):
"""
Cast a string to a strictly positive integer.
"""
if integer_string:
ret = int(integer_string)
else:
return integer_string
if ret < 0 or (ret == 0 and strict):
raise ValueError()
if cutoff:
retu... |
def star_sub_sections(body:str):
"""
Change
\subsection
\subsubsection
To:
\subsection*
\subsubsection*
"""
body = body.replace(r'\subsection',r'\subsection*')
body = body.replace(r'\subsubsection',r'\subsubsection*')
return body |
def sort_dict_items_by_key(_dict):
"""Sort dict items by key."""
return sorted(
_dict.items(),
key=lambda item: item[0],
) |
def reform_uid(uid):
"""
Convert a uid with underscores to the original format
"""
return uid[:3]+"://" + "/".join(uid[6:].split("_")) |
def get_default_nncf_compression_config(h, w):
"""
This function returns the default NNCF config for this repository.
The config makes NNCF int8 quantization.
"""
nncf_config_data = {
'input_info': {
'sample_size': [1, 3, h, w]
},
'compression': [
{
... |
def stations_by_river(stations):
"""Given list of MonitoringStation objects; returns dictionary mapping river
names to a list of MonitoringStation objects, which lie on that river."""
output = {}
for station in stations:
if station.river not in output:
output[station.river] = [stati... |
def binary(i, width):
"""
>>> binary(0, 5)
[0, 0, 0, 0, 0]
>>> binary(15, 4)
[1, 1, 1, 1]
>>> binary(14, 4)
[1, 1, 1, 0]
"""
bs = bin(i)[2:]
bs = ("0" * width + bs)[-width:]
b = [int(c) for c in bs]
return b |
def merge_strings(*args, **kwds):
"""Returns non empty string joined by sep
The default separator is an empty string.
"""
sep = kwds.get('sep', '')
return sep.join([s for s in args if s]) |
def get_powers_of_2(_sum):
"""Get powers of 2 that sum up to the given number.
This function transforms given integer to a binary string.
A reversed value limited to digits of binary number is extracted
from it, and each of its characters is enumerated.
Each digit is tested for not being 0. If the... |
def hash_generator(token_to_id, tokens):
"""Generate hash for tokens in 'tokens' using 'token_to_id'.
Args:
token_to_id: dict. A dictionary which maps each token to a unique ID.
tokens: list(str). A list of tokens.
Returns:
int. Hash value generated for tokens in 'tokens' using 'to... |
def getvalue(row, name, mapping={}):
"""If name in mapping, return row[mapping[name]], else return row[name]."""
if name in mapping:
return row[mapping[name]]
else:
return row[name] |
def inject_post_param(request, injectionstring):
"""
Generates a list of new requests with replaced/modified post parameters
:param request: request instance
:param injection_string: list of strings to inject into the request
:return: list of requests
"""
r... |
def _client_row_class(client: dict) -> str:
"""
Set the row class depending on what's in the client record.
"""
required_cols = ['trust_balance', 'refresh_trigger']
for col in required_cols:
if col not in client:
return 'dark'
try:
if client['trust_balance'] > clien... |
def populate_src_and_dst_dicts_with_single_offense(offense, src_ids, dst_ids):
"""
helper function: Populates source and destination id dictionaries with the id key/values
:return:
"""
if "source_address_ids" in offense and isinstance(
offense["source_address_ids"], list
):
for s... |
def greatest_common_divisor(number1: int, number2: int) -> int:
"""Return greatest common divisor of number1 and number2."""
if number1 < number2:
divisor = number1
else:
divisor = number2
while divisor > 0:
if number1 % divisor == 0 and number2 % divisor == 0:
break
... |
def get_class_source_from_source(source: str) -> str:
"""Gets class source from source, i.e. module.path@version, returns version.
Args:
source: source pointing to potentially pinned sha.
"""
# source need not even be pinned
return source.split("@")[0] |
def name_class(classname):
"""Change AMQP class name to Python class name"""
return classname.capitalize() |
def get_next_moves(board):
"""Return a list of allowed moves for the given board state."""
return [i for i, p in enumerate(board) if p == 0] |
def wer(h, r):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time ans space complexity.
Parameters
----------
r : list
h : list
Returns
-------
int
Examples
--------
>>> wer("who is there".split(),... |
def not_equal(quant1, quant2):
"""Binary function to call the operator"""
return quant1 != quant2 and quant2 != quant1 |
def remove_prefix(text, prefix):
""" Remove prefix from text if present. """
if text.startswith(prefix):
return text[len(prefix):]
return text |
def clean_filename(filename):
"""
Heuristically replaces known extensions to create sensible output file name
:param filename: the input file name to strip extensions from
"""
if filename.endswith(".conll10") or filename.endswith(".conllu") and not filename.startswith("."):
return filename.replace(".conll10", "... |
def as_text(bytes_or_text, encoding="utf-8"):
"""Returns the given argument as a unicode string.
Args:
bytes_or_text: A `bytes`, `str`, or `unicode` object.
encoding: A string indicating the charset for decoding unicode.
Returns:
A `str` (Python 3) object.
Raises:
TypeError: If `bytes... |
def combin(n, r):
"""A fast way to calculate binomial coefficients by Andrew Dalke (contrib)."""
if 0 <= r <= n:
ntok = 1
rtok = 1
for t in range(1, min(r, n - r) + 1):
ntok *= n
rtok *= t
n -= 1
return ntok // rtok # bit-wise operation
el... |
def simplified_collection(constants):
"""Dummy collection for tests"""
return {
"@context": f"/{constants['api_name']}/contexts/DroneCollection.jsonld",
"@id": f"/{constants['api_name']}/DroneCollection/1",
"@type": "DroneCollection",
"members": [{"@id": f"/{constants['api_name']... |
def format_patch(patch_parts):
"""Format the patch parts back into a patch string."""
return '{patch}.{prerel}{prerelversion}'.format(**patch_parts) |
def degrees_to_meters(degrees):
"""
111195 = (Earth mean radius)*PI/180
(supposedly 'maximum error using this method is ~ 0.1%')
:see: https://stackoverflow.com/questions/12204834/get-distance-in-meters-instead-of-degrees-in-spatialite
"""
ret_val = 111195 * degrees
return ret_val |
def has_repeating_pair(string):
"""Check if string has repeating pair of letters."""
return any(
string.count(string[index:index+2]) > 1
for index, _ in enumerate(string[:-1])
) |
def _get_cpus(metrics):
"""Get a list of strings representing the CPUs available in ``metrics``.
:param list metrics: The metrics used to look for CPUs.
:rtype: :py:class:`list`
The returned strings will begin with the CPU metric name. The list is sorted in ascending order.
"""
cpus = list({m... |
def isprime(potential_prime_number):
"""Basically takes a number and
checks if it is prime or not.
"""
n = abs(int(potential_prime_number)) # This is to make sure it is a positive integer
if n < 2:
return False
if n % 2 == 0:
return n == 2 # since 2 is prime will return true t... |
def trim_comments(val):
"""
Remove in-line comments that begin with "#", and whitespace.
"""
return val.split("#")[0].strip() |
def url_join(*parts):
"""Join parts of URL and handle missing/duplicate slashes."""
return "/".join(str(part).strip("/") for part in parts) |
def plus_percent_str(x):
"""Format percent string with sign and apt number of decimal places."""
if x < 10:
return '{:+.1f}%'.format(x)
else:
return '{:+.0f}%'.format(x) |
def filter_by_channel(archives, allowed_channels):
"""
Filters out archive groups which are not in allowed_channels.
"""
# Collections compare function
import collections
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
lens = [] # Get all unique allowed channels len... |
def cal_func(step, n, N, per):
"""
Parameters
----------
L : int
the length of the segment that will be got.
n : int
the number of the segment type that will be balanced.
N : int
the most type in the five types.
per : int(less than 1)
the percentage of the mo... |
def get_alignment_character(alignment: str) -> str:
""" Returns an alignment character for string formatting """
# Determine left alignment character
if alignment in ["left", "l"]:
return ""
# Determine right alignment character
elif alignment in ["right", "r"]:
return ">"
# D... |
def powerset(L):
"""
Constructs the power set, 'potenz Menge' of a given list.
return list: of all possible subsets
"""
import itertools
pset = []
for n in range(len(L) + 1):
for sset in itertools.combinations(L, n):
pset.append(sset)
return pset |
def wrap(width, text):
"""
Split strings into width for
wrapping
"""
lines = []
arr = text.split()
lengthSum = 0
line = []
for var in arr:
lengthSum += len(var) + 1
if lengthSum <= width:
line.append(var)
else:
lines.append(" ".join(l... |
def _tuple_to_str(value: tuple) -> str:
""" returns a tuple as a string without parentheses """
return ','.join(map(str, value)) |
def optical_spectra(header_dict):
"""
access DR12 detail page for spectra
:param header_dict:
:return:
"""
url = "https://dr12.sdss.org/spectrumDetail?mjd={}&fiber={}&plateid={}".format(
header_dict['MJD'],
header_dict['FIBERID'],
header_dict['PLATEID']
)
prin... |
def get_url(js):
""" @todo """
if 'homepage' in js:
return js['homepage']
if 'checkver' in js:
if 'url' in js['checkver']:
return js['checkver']['url']
if 'github' in js['checkver']:
return js['checkver']['github']
return '' |
def b(s, encoding="utf-8"):
""" str/int/float to bytes """
if isinstance(s, bytes):
return s
if isinstance(s, (str, int ,float)):
return str(s).encode(encoding)
raise TypeError("unsupported type %s of %r" % (s.__class__.__name__, s)) |
def invoke_lambda_demo(*args):
"""Demo of a stand-alone way of using lambda
Examples:
>>> invoke_lambda_demo(10, 25, 'blah')\n
Here is what is happening:
(lambda x: x + x)(item)
[20, 50, 'blahblah']
Returns:
object: Returns double of the given argument.
"""
... |
def tsub(tup1, tup2):
""" Subtracts tup1 elements from tup2 elements. """
return (tup1[0]-tup2[0], tup1[1]-tup2[1]) |
def remove_nones(dictionary: dict) -> dict:
"""remove_nones"""
return {
dictionary_key: key_value
for dictionary_key, key_value in dictionary.items()
if key_value is not None
} |
def prepare_input_parameters(input_layer_size, hidden_layer_size, number_of_labels,
lambda_value):
"""Prepare input parameters as a dictionary"""
input_parameters = {}
input_parameters['input_layer_size'] = input_layer_size
input_parameters['hidden_layer_size'] = hidden_laye... |
def get_nbits_to_copy(i: int, j: int, n: int) -> int:
"""Returns the number of bits to copy during a single byte process.
:param i: the number of the total bits processed.
:param j: the number of bits processed on current base type.
:param n: the number of bits current base type occupy.
"""
retu... |
def _validate_severity(parser, arg):
"""Check that the severity level provided is correct."""
valid_severities = {"info": 0, "warning": 1, "error": 2}
if arg.strip().lower() not in valid_severities:
parser.error("Invalid severity. Options are error, warning, or info")
else:
return valid_severities[arg.... |
def adjust_data(code_list, noun=12, verb=2):
"""Set the computer to a desired state by adjusting the noun and verb
parameters.
Parameters
----------
code_list : list
opcode as provided by advent of code
noun : int, optional
the first parameter (in position 1), by default 12
... |
def norm_random(random_number):
"""Turn a random number to a number between 0 and max_value """
precision = 20
res = 0.
for i in range(precision):
bit = random_number & (1 << i)
res += bit
res %= precision
res /= precision
return res |
def obs_preprocessor_tm_act_in_obs(obs):
"""
This takes the output of gym as input
Therefore the output of the memory must be the same as gym
"""
obs = (obs[0], obs[1], obs[2], obs[3], *obs[4:]) # >= 1 action
# logging.debug(f" (not same as old): preprocessed obs:{obs}")
return obs |
def convertSnake(j):
""" this is convert FROM snake to json(camel) """
out = {}
for k in j:
new_k = k.split('_')
out[new_k[0] + ''.join(x.title() for x in new_k[1:])] = j[k]
return out |
def label_case(snake_case):
"""Specialized helper function to replace underscore with spaces and capitalize first letter of string, but keep WMR and WMQ capitalized
Args:
snake_case (str): String written in snake case to be reformatted.
Returns:
str: The reformatted string.
... |
def get_data(data_config, name):
"""
for backwards compatibility of old configs
:param data_config:
:param name:
:return:
"""
if "all" in data_config:
return data_config["all"]
elif name in data_config:
return data_config[name]
else:
return data_config |
def compare(M, A):
"""
:param M: Matrix with Names and DNA sequences
:param A: Array with DNA values
:return: String representing a person's name
"""
for line in M[1:]:
match = True
for j in range(1, len(line)):
if A[j-1] == line[j]:
continue
... |
def is_desired_workflow(run_json):
"""
Checks if this run is for the "Presubmit Checks" workflow.
"""
# Each workflow has a fixed ID.
# For the "Persubmit Checks" workflow, it is:
# https://api.github.com/repos/taichi-dev/taichi/actions/workflows/1291024
DESIRED_ID = 1291024
return run_j... |
def simpleDijkstra(adjacencyList, source, target):
"""
This method performs the Dijkstra algorithm on simple graphs, given as an
adjacency list.
:param list[list[int] adjacencyList: A list where the indexes of elements in the outer list are
equal to the index of the graph node. The integers in the i... |
def customsplit(s):
"""
Need to implement our own split, because for exponents of three digits
the 'E' marking the exponent is dropped, which is not supported by python.
:param s: The string to split.
:return: An array containing the mantissa and the exponent, or the value, when no split was possibl... |
def utf8decode(value):
"""
Returns UTF-8 representation of the supplied 8-bit string representation
>>> utf8decode('foobar')
u'foobar'
"""
return value.decode("utf-8") |
def get_last_n_path_elements_as_str(fpath: str, n: int) -> str:
"""
Args:
- fpath: string representing file path
- n: integer representing last number of filepath elements to keep
Returns:
-
"""
elements = fpath.split("/")[-n:]
return "/".join(elements) |
def render_bandwidth_speed(speed):
"""
Renders speeds given in Mbps.
"""
if not speed:
return ""
if speed >= 1000000 and speed % 1000000 == 0:
return f"{int(speed / 1000000)} Tbps"
elif speed >= 1000 and speed % 1000 == 0:
return f"{int(speed / 1000)} Gbps"
elif speed... |
def _is_decoy_prefix(pg, prefix='DECOY_'):
"""Determine if a protein group should be considered decoy.
This function checks that all protein names in a group start with `prefix`.
You may need to provide your own function for correct filtering and FDR estimation.
Parameters
----------
pg : dic... |
def unique_colname(suggested, existing):
"""Given a suggested column name and a list of existing names, returns
a name that is not present at existing by prepending _ characters."""
while suggested in existing:
suggested = '_{0}'.format(suggested)
return suggested |
def generateExpoSystem(d, k):
""" int x int -> list[int]
returns a system of <k> capacities generated
by <d>
"""
# V: list[int]
V = [1]
# val, i: int
val = 1
for i in range(k-1):
val *= d
V.append(val)
return V |
def convert(hours, minutes):
"""convert_hours = hours * 60 * 60
convert_minutes = minutes * 60"""
convert_to_seconds = hours * 60 * 60 + minutes * 60 #cleaner
print (convert_to_seconds)
return convert_to_seconds |
def DetermineMinAndMax(MeetingPoints):
"""This function determines the minimal and maximal position where the wave function will be set to 0 depending on the points where the potential meets the guess energy and on
the minimum and maximum that are initially set for the potential.
Parameter:
----------
... |
def fatorial(numero, mostrar=False):
"""
Teste
Feito por -Lndr-
"""
from math import factorial
if mostrar:
contador = numero
while contador > 0:
print(contador, end=" ")
if contador != 1:
print("x", end=" ")
contador... |
def name_equality_check(setup_deps, pipfile_deps):
"""
Checks that all names present in either dependency file are present
in both dependency files
Args:
setup_deps (dict<str, list<tuple<str, str>>>):
Dictionary from setup.py dependency name keys to a list of
tuples as a... |
def sbool(mixed, default=None):
"""Safe boolean cast."""
try:
return bool(mixed)
except:
return default |
def RK4(f, x, t1, t2, pf, stim=None):
"""
Fourth-order, 4-step RK routine.
Returns the step, i.e. approximation to the integral.
If x is defined at time t_1, then stim should be an array of
stimulus values at times t_1, (t_1+t_2)/2, and t_2 (i.e. at t1 and t2, as
well as at the midpoint).
A... |
def list2tuple(list_to_convert):
"""
Converts a list of lists of lists ... into a tuple of tuples of tuples
[1, 2, ['A', 'B', ['alpha', 'beta', 'gamma'], 'C'], 3] -->
--> (1, 2, ('A', 'B', ('alpha', 'beta', 'gamma'), 'C'), 3)
https://stackoverflow.com/questions/1014352/how-do-i-convert-... |
def set_fba_name(source, year):
"""
Generate name of FBA used when saving parquet
:param source: str, source
:param year: str, year
:return: str, name of parquet
"""
return source if year is None else f'{source}_{year}' |
def truncate(input_str, length):
"""Truncate string to specified length
Args:
input_str: String to truncate
length: Maximum length of output string
"""
if len(input_str) < (length - 3):
return input_str
return input_str[:(length - 3)] + '...' |
def get_bit_label(drawer, register, index, qubit=True, layout=None, cregbundle=True):
"""Get the bit labels to display to the left of the wires.
Args:
drawer (str): which drawer is calling ("text", "mpl", or "latex")
register (QuantumRegister or ClassicalRegister): get bit_label for this regist... |
def find_where_wires_cross(coords1, coords2):
"""Find and return intesections of the wires
based on their coordinates
"""
matches = []
coords1 = set(coords1)
coords2 = set(coords2)
for coord in coords1:
if coord in coords2:
matches.append(coord)
return matches |
def _is_ipv4_like(s):
"""Find if a string superficially looks like an IPv4 address.
AWS documentation plays it fast and loose with this; in other
regions, it seems like even non-valid IPv4 addresses (in
particular, ones that possess decimal numbers out of range for
IPv4) are rejected.
"""
p... |
def maybe_hparams_to_dict(hparams):
"""If :attr:`hparams` is an instance of :class:`~texar.hyperparams.HParams`,
converts it to a `dict` and returns. If :attr:`hparams` is a `dict`,
returns as is.
"""
if hparams is None:
return None
if isinstance(hparams, dict):
return hparams
... |
def json_set_hook(dct):
"""
Return an encoded set to it's python representation.
"""
if not isinstance(dct, dict):
return dct
if '__set__' not in dct:
return dct
return set((tuple(item) if isinstance(item, list) else item) for item in dct['__set__']) |
def isbn_10_check_digit(nine_digits):
"""Function to get the check digit for a 10-digit ISBN"""
if len(nine_digits) != 9: return None
try: int(nine_digits)
except: return None
remainder = int(sum((i + 2) * int(x) for i, x in enumerate(reversed(nine_digits))) % 11)
if remainder == 0: tenth_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.