content stringlengths 42 6.51k |
|---|
def toJadenCase(string):
"""
Convert strings to how they would
be written by Jaden Smith. The strings
are actual quotes from Jaden Smith,
but they are not capitalized in the
same way he originally typed them.
Example:
Not Jaden-Cased:
"How can mirrors be real if
our eyes aren't real"
Jaden-Cased:
... |
def strMakeComma(categories):
"""
Make comma seperate string i.e: a, b, c
"""
result = ""
for catg in categories:
result += catg["name"] + ", "
if len(result) > 0:
result = result[:len(result) - 2]
return result |
def difference(actual, expected):
"""
Returns strings describing the differences between actual and expected sets.
Example::
>>> difference({1, 2, 3}, {3, 4, 5})
('; added {1, 2}', '; removed {4, 5}')
>>> difference({1}, {1})
('', '')
:param set actual: the actual set... |
def compile_target_uri(url: str, query_string: bytes) -> str:
"""Append GET query string to the page path, to get full URI."""
if query_string:
return f"{url}?{query_string.decode('utf-8')}"
else:
return url |
def apply_weather_correction(
enduse,
fuel_y,
cooling_factor_y,
heating_factor_y,
enduse_space_heating,
enduse_space_cooling
):
"""Change fuel demand for heat and cooling service
depending on changes in HDD and CDD within a region
(e.g. climate change indu... |
def get_title(title_raw):
"""
Extracts title from raw string
"""
return title_raw.replace('\xa0', ' ').split('\n')[0].split('## ')[1] |
def wordgen(iters, base_cases, rule, return_all=False):
"""generate arbitrary recursive words
Args:
iters (int): number of iterations to run on top of base cases
base_cases (list of strings): strings which your rule can refer to
rule (method): A function that takes in previous strings a... |
def hmap_hash(str):
"""hash(str) -> int
Apply the "well-known" headermap hash function.
"""
return sum((ord(c.lower()) * 13
for c in str), 0) |
def fmt_dft(val):
"""Generate default argument description
This secondary utility function is supporting formatting of command line argument help string
"""
return "" if val is None else " (default: {0})".format(val) |
def list2pairlist(input_list: list, start=None) -> list:
"""
Example:
input_list = [1,2,3,4,5], start=None -> [(1, 2), (2, 3), (3, 4), (4, 5)]
input_list = [1,2,3,4,5], start=10 -> [(10, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
"""
if start is not None:
return [(start, input_list[0])] + list(... |
def random_hex_code(number_of_digits):
"""
Creates a random string of hex characters.
Parameters
----------
number_of_digits : int
Returns
-------
str
"""
import random
digits = []
for i_digit in range(number_of_digits):
i = random.randrange(16)
digits.append("0123456789abcdef"[i])
r... |
def get_tests(test_trie):
"""Gets all tests in this test trie.
It detects if an entry is a test by looking for the 'expected' and 'actual'
keys in the dictionary.
The keys of the dictionary are tuples of the keys. A test trie like
"foo": {
"bar": {
"baz": {
"actual": "PASS",
"expec... |
def has_keyword(list_post, fields, keywords):
"""Return list
Search list childs for a dict containing a specific keyword.
"""
results = []
for field in fields:
if field in list_post:
for keyword in keywords:
if keyword.upper() in list_post[field].upper():
... |
def gtype( n ):
"""
Return the a string with the data type of a value, for Graph data
"""
t = type(n).__name__
return str(t) if t != 'Literal' else 'Literal, {}'.format(n.language) |
def _get_log_formatter(verbosity_level):
"""
Get a log formatter string based on the supplied numeric verbosity level.
:param int verbosity_level: the verbosity level
:return: the log formatter string
:rtype: str
"""
formatter = "%(levelname)s: %(message)s"
if verbosity_level >= 3:
... |
def cmd_valid(cmd):
"""Checks to see if a given string command to be sent is valid in structure.
Used in talk() prior to sending a command to the Arduino.
Parameters
----------
cmd : str
The command string to be sent. Command is structured as
"<mode, motorID, arg_m1, arg_m2, arg... |
def assign_relative_positions(abs_start, abs_end, overall_start):
"""Return relative positions given the absolute interval positions.
Bases the relative positions from an overall starting position.
Args:
abs_start (int): global start of the interval, 1-based
abs_end (int): global end of the interval, 1-... |
def solution(M, A):
"""
3 steps -
1. count the value of distinct in current window
2. check for duplicates
3. count distinct
method-
0,0
tail ------ head
for tail - 0 -------head 0,1,2,3...length
:param M:
:param A:
:return:
"""
in_current_slice = [False] * (M + ... |
def getEndAddress(fileSize, startAddress):
"""
:param fileSize: size of the FreeRTOS image used to add OTA descriptor in bytes
:param startAddress: start address in decimal integer
:return: end address in decimal integer
"""
endAddress = startAddress # initialize it as start address
endAdd... |
def safe_get_value(maybe_dict, key: str):
"""
Get the value for `key` if `maybe_dict` is a `dict` and has that
key. If `key` isn't there return `None`. Otherwise, `maybe_dict`
isn't a `dict`, so return `maybe_dict` as is.
"""
if isinstance(maybe_dict, dict):
return maybe_dict.get(key, No... |
def sub_dir_algo(d):
""" build out the algorithm portion of the directory structure.
:param dict d: A dictionary holding BIDS terms for path-building
"""
return "_".join([
'-'.join(['tgt', d['tgt'], ]),
'-'.join(['algo', d['algo'], ]),
'-'.join(['shuf', d['shuf'], ]),
]) |
def remove_special_characters(value):
""" Remove special characters from argument
:param value - a string containing special characters to remove
:returns a string with special characters removed
"""
# If not a string then just return as is
if not isinstance(value, str):
return value
... |
def mean_squared_error(x1, x2):
"""Calculates the mean squared error between x1 and x2
[description]
Arguments:
x1 {list-like} -- the calculated values
x2 {list-like} -- the actual values
Returns:
[type] -- [description]
Raises:
RuntimeError -- [... |
def _uid2unixperms(perms, has_owner):
""" Convert the uidperms and the owner flag to full unix bits
"""
res = 0
if has_owner:
res |= (perms & 0x07) << 6
res |= (perms & 0x05) << 3
elif perms & 0x02:
res |= (perms & 0x07) << 6
res |= (perms & 0x07) << 3
else:
... |
def check_present(wanted, item_list):
"""
check if item is present in the list
"""
for item in item_list:
if item.get('description') == wanted:
return True
return False |
def projection_type_validator(x):
"""
Property: Projection.ProjectionType
"""
valid_types = ["KEYS_ONLY", "INCLUDE", "ALL"]
if x not in valid_types:
raise ValueError("ProjectionType must be one of: %s" % ", ".join(valid_types))
return x |
def group_keys_by_attributes(adict, names, tol='3f'):
""" Make group keys by shared values of attributes.
Parameters
----------
adict : dic
Attribute dictionary.
name : str
Attributes of interest.
tol : float
Float tolerance.
Returns
-------
... |
def get_recursively(in_dict, search_pattern):
"""
Takes a dict with nested lists and dicts,
and searches all dicts for a key of the field
provided.
"""
fields_found = []
for key, value in in_dict.items():
if key == search_pattern:
fields_found.append(value)
elif ... |
def is_symmetrical(num: int) -> bool:
"""Determine if num is symmetrical."""
num_str = str(num)
return num_str[::-1] == num_str |
def get_models_weight(models_info):
"""Parses the information about model ids and weights in the `models`
key of the fusion dictionary. The contents of this key can be either
list of the model IDs or a list of dictionaries with one entry per
model.
"""
model_ids = []
weights = []
try:
... |
def is_product_bookable(
product_code: str,
availability: bool,
durability: int,
) -> bool: # noqa E125
"""Checks if a product is available for booking
"""
# Quick and dirty check
if availability and durability ... |
def page_start(weekday, day, month):
"""
Print the initialisation of the page
"""
lines = list()
lines.append("<html>")
lines.append("<head>")
date = weekday.capitalize() + " " + str(day) + " " + str(month)
lines.append("<title>Dagens mat - {}</title>".format(date))
lines.append('<li... |
def dec2hex(n, uni=1):
"""Convert decimal number to hex string with 4 digits, and more digits if
the number is larger.
>>> dec2hex(12)
'000C'
>>> dec2hex(100)
'0064'
>>> dec2hex(65535)
'FFFF'
>>> dec2hex(100000)
'186A0'
"""
hexadec = "%X" % n
if uni == 1:
wh... |
def is_out_of_bounds(board, row, col):
"""checks if the indexes are within the boundary of the board"""
return not (0 <= row < len(board) and 0 <= col < len(board[0])) |
def animals(chickens: int, cows: int, pigs: int) -> int:
"""Return the total number of legs on your farm."""
return sum([(chickens * 2), (cows * 4), (pigs * 4), ]) |
def _get_request_args(args):
"""
Build a tuple of the maximum age an event can be plus the maximum amount
of records to return in the SQL query.
If no argument is provided, or the value is uncastable to an int the
respective default value or 360 and 1000 will be returned.
"""
... |
def build_cflags_y(cflags_list):
"""
Build cflags-y additions from the @cflags_list.
Note: the input sources should have their file extensions.
"""
return '\n'.join(['cflags-y += {0}'.format(cflag) for cflag in cflags_list]) |
def Cluster(sequence, partition_point):
"""Return a tuple (left, right) where partition_point is part of right."""
return (sequence[:partition_point], sequence[partition_point:]) |
def get_offer_type_enum(offer_type):
"""
"""
if offer_type == "bogo":
return 0
elif offer_type == "informational":
return 1
elif offer_type == "discount":
return 2
else:
return 3 |
def distance(x0, y0, x1, y1):
"""distance between points"""
dx = x1 - x0
dy = y1 - y0
dist = ((dx ** 2) + (dy ** 2)) ** 0.5
return dist |
def check_history(model, history):
"""Check if model was trained with different history to avoid key errors."""
if not model.get('~'*history):
history = len([c for c in model if c.startswith('~') and c.endswith('~')][0])
print('#'* 57)
print("# WARNING: the model was trained with history... |
def parse_str(s: str):
"""
Parse entry of info file
Parameters
----------
s : str
Value
Returns
-------
obj
Corresponding python type
"""
if s.isnumeric():
return int(s)
elif set(s) - set('-.0123456789E') == set():
# Try is a workaround for th... |
def ultimate_answer(question):
"""Provides an answer to the ultimate question.
Returns '42' if the question is 'What is the meaning of Life, The Universe,
Everything?' otherwise returns 'That is not much of a question'
args:
question (str): The question to be answered.
returns... |
def max_integer(my_list=[]):
"""
finds the largest integer of a list
"""
if len(my_list) == 0:
return (None)
my_list.sort()
return (my_list[-1]) |
def clean_onnx_name(name: str) -> str:
"""Modifies a onnx name that is potentially invalid in dace
to make it valid"""
return "ONNX_" + name.replace(".", "DOT").replace(":", "COLON").replace(
"/", "SLASH").replace("-", "DASH") |
def pool_output_length(input_length, pool_size, stride, pad, ignore_border):
"""
Compute the output length of a pooling operator
along a single dimension.
Parameters
----------
input_length : integer
The length of the input in the pooling dimension
pool_size : integer
The le... |
def is_standard_key(key):
"""
Function to determine whether the supplied key is one of the common/standard keys.\n
:param key: key to check
:return: True if standard key otherwise False
"""
if key.find("concept") != -1 or key.find("lifecycle") != -1 or key.find("org") != -1 or key.find(
... |
def docstring_to_tooltip(docstring):
"""
Returns tooltip friendly version of the docstring
:param docstring: a docstring
:return: the docstring content
"""
docstring = docstring or ''
if not docstring.strip().splitlines():
return ''
return docstring.strip().splitlines()[0] |
def int_to_binary(d, length=8):
"""
Binarize an integer d to a list of 0 and 1. Length of list is fixed by `length`
"""
d_bin = '{0:b}'.format(d)
d_bin = (length - len(d_bin)) * '0' + d_bin # Fill in with 0
return [int(i) for i in d_bin] |
def diff_dict(old, new):
"""
>>> diff_dict({'del': '0', 'change': '0', 'stay': '0'}, {'change': '1', 'stay': '0', 'add': '0'})
{'added': ['add'], 'removed': ['del'], 'changed': ['change']}
"""
all_keys = set(old) | set(new)
diff = {'added': [], 'removed': [], 'changed': []}
for k in all_keys... |
def rollout_rewards_combinator(rollout_rewards, new_rewards):
"""
Combine rewards used in deploy_workers in rl_oracle.py.
"""
new_rollout_rewards = []
for i, j in zip(rollout_rewards, new_rewards):
new_rollout_rewards.append(i + j)
return new_rollout_rewards |
def match(first_list, second_list, attribute_name):
"""Compares two lists and returns true if in both there is at least one element which
has the same value for the attribute 'attribute_name' """
for i in first_list:
for j in second_list:
if i[attribute_name] == j[attribute_name]:
... |
def create_initial_state(dihedrals, grid_spacing, elements, init_coords, dihedral_ranges=None, energy_decrease_thresh=None, energy_upper_limit=None):
"""Create the initial input dictionary for torsiondrive API
Parameters
----------
dihedrals : List of tuples
A list of the dihedrals to scan over... |
def generate_traefik_path_labels(url_path, segment=None, priority=2,
redirect=True):
"""Generates a traefik path url with necessary redirects
:url_path: path that should be used for the site
:segment: Optional traefik segment when using multiple rules
:priority: Priorit... |
def feature_selection(all_features):
"""
Description: Function defining which features to use
Input: all_features -> boolean telling us if we use all the features or only the important ones
Return: A list of the features we keep
"""
if all_features:
features = ['Age', 'HoursPerWeek', 'To... |
def parse_cooler_uri(s):
"""
Parse a Cooler URI string
e.g. /path/to/mycoolers.cool::/path/to/cooler
"""
parts = s.split("::")
if len(parts) == 1:
file_path, group_path = parts[0], "/"
elif len(parts) == 2:
file_path, group_path = parts
if not group_path.startswith(... |
def all_neighbors(x,y,arr):
"""Returns all neighbors including diagonals"""
neighbors = []
for i in [-1,0,1]:
for j in [-1,0,1]:
neighbors.append((x+i,y+j))
neighbors = [i for i in neighbors if i != (x,y)]
return neighbors |
def _dict_has_value(dct):
"""helper to check if the dict contains at least one valid value"""
for val in dct.values():
if isinstance(val, str):
if val.strip() != '':
return True
elif isinstance(val, list):
if val:
return True
elif t... |
def decode(chromosome):
"""
Takes each individual from the population and decodes their value.
"""
first_value = chromosome & 0xff
second_value = (chromosome & 0xFF00) >> 8
third_value = (chromosome & 0xFF0000) >> 16
fourth_value = (chromosome & 0xFF000000) >> 24
decoded_value = first_... |
def good_request(status: str):
"""
Check if request from NYT API was good
"""
return ('OK' == status) |
def filter_file(single_file):
""" Method used to filter out unwanted files """
if(single_file.endswith(".txt")
or single_file.endswith(".py")
or single_file.endswith(".java")
or single_file.endswith(".s")):
return single_file |
def parse_text(data: list):
"""Remove newlines, HTML characters, and join lines that do not include headers
"""
data = [i.strip() for i in data] # Strip
data = list(filter(None, data)) # Remove empty lines
# Skip blank files
if not data:
return data
# Add first header if none
... |
def diff_pf_potential(phi):
""" Derivative of the phase field potential. """
return phi**3-phi |
def _resolve_repository_template(
template,
abi = None,
arch = None,
system = None,
tool = None,
triple = None,
vendor = None,
version = None):
"""Render values into a repository template string
Args:
template (str): The template to use fo... |
def hex2rgb(hexstring, digits=2):
"""Converts a hexstring color to a rgb tuple.
Example: #ff0000 -> (1.0, 0.0, 0.0)
digits is an integer number telling how many characters should be
interpreted for each component in the hexstring.
"""
if isinstance(hexstring, (tuple, list)):
return hex... |
def MakeLong(high, low):
"""Pack high into the high word of a long and low into the low word"""
# we need to AND each value with 0xFFFF to account for numbers
# greater then normal WORD (short) size
return ((high & 0xFFFF) << 16) | (low & 0xFFFF) |
def getPointRange(iFace, dims):
"""Return the correct point range for face iFace on a block with
dimensions given in dims"""
il = dims[0]
jl = dims[1]
kl = dims[2]
if iFace == 0:
return [[1, il], [1, jl], [1, 1]]
elif iFace == 1:
return [[1, il], [1, jl], [kl, kl]]
elif i... |
def process_hierarchy(field, data):
"""Process dictionary hierarchy."""
field_arr = field.split(".")
data_set = data
for field in field_arr:
data_set = data_set[field]
return str(data_set) |
def test_limit_points(sequence, max_number_of_lp):
"""
Return the number (color coded) of limit points in a sequence.
Points within a distance epsilon are indistinguishable.
"""
if len(sequence) == 1:
return 0 # undefined
epsilon = 1e-10
try:
for i in range(2, max_n... |
def AND(A, B):
"""Returns events that are in A AND B."""
return A.intersection(B) |
def murnaghan(V, E0, B0, B1, V0):
"""
From PRB 28,5480 (1983)
"""
return E0 + B0 * V / B1 * (((V0/V)**B1)/(B1-1)+1) - V0 * B0 / (B1-1) |
def hex_to_rgb(hex):
"""
Convert hex color code to RGB
"""
code = hex.lstrip("#")
return [int(code[i : i + 2], 16) for i in (0, 2, 4)] |
def prunecomments(blocks):
"""Remove comments."""
i = 0
while i < len(blocks):
b = blocks[i]
if b[b'type'] == b'paragraph' and (
b[b'lines'][0].startswith(b'.. ') or b[b'lines'] == [b'..']
):
del blocks[i]
if i < len(blocks) and blocks[i][b'type'] ... |
def rc_to_xy(row, col, rows):
"""
Convert from (row, col) coordinates (eg: numpy array) to (x, y) coordinates (bottom left = 0,0)
(x, y) convention
* (0,0) in bottom left
* x +ve to the right
* y +ve up
(row,col) convention:
* (0,0) in top left
* row +ve down
* col +ve to the... |
def lsb(x, n):
"""Return the n least significant bits of x.
>>> lsb(13, 3)
5
"""
return x & ((2 ** n) - 1) |
def get_individual_positions(individuals):
"""Return a dictionary with individual positions
Args:
individuals(list): A list with vcf individuals in correct order
Returns:
ind_pos(dict): Map from ind_id -> index position
"""
ind_pos = {}
if individuals:
for i, ind in enu... |
def yp_processed_reviews(yelp_username):
"""
Raw form of reviews that contains ony status and reviews.
File Type: CSV
"""
return '../data/processed/{}.csv'.format(yelp_username) |
def isclassattr(a, cls):
""" Test if an attribute is a class attribute. """
for c in cls.__mro__:
if a in c.__dict__:
return True
return False |
def calcular_costo_envio(kilometros):
"""
num -> float
opera dos numeros para dar como resultado el costo de envio
:param kilometros: se ingresan la cantidad de kilometros recorridos
:return: el costo del envio
>>> calcular_costo_envio(1)
115.0
>>> calcular_costo_envio(0)
0.0
"""... |
def italicize(s):
"""Given a string return the same string italicized (in wikitext)."""
return "''{}''".format(s) |
def double(_printer, ast):
"""Prints a double value."""
return f'{ast["val"]}.0' if isinstance(ast["val"], int) else f'{ast["val"]}' |
def candidateKey(candidate):
"""Generates a comparison key for a candidate.
Candidates are sorted by the number of dimensions (the highest, the better),
then by average execution time of the biggest dimension (the lower the better)"""
if candidate is None:
return (float('inf'), float('inf'))
numDimensions = l... |
def _num_lines(label: str) -> int:
"""Return number of lines of text in label."""
return label.count("\n") + 1 |
def non_deleting_interleaving(o):
""" no empty tuple element (ie. utilize commas maximally)
PRO TIP: When running, listen to 'Charlemagne Palestine - Strumming Music'
"""
return all([len(x) > 0 for x in o]) |
def _mkx(i, steps, n):
"""
Generate list according to pattern of g0 and b0.
"""
x = []
for step in steps:
x.extend(list(range(i, step + n, n)))
i = step + (n - 1)
return x |
def is_empirical(var_type):
"""
Checks whether the variable type for the
variable of interest is to be taken
as a constant value or as numerical values.
"""
return var_type == "empirical" |
def counting_sort_in_place(a):
"""
in-place counting sort
http://p-nand-q.com/python/algorithms/sorting/countingsort.html
"""
counter = [0] * (max(a) + 1)
for i in a:
counter[i] += 1
pos = 0
for i, count in enumerate(counter):
for _ in range(count):
a[pos] =... |
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text |
def surface_zeta_format_to_texture_format(fmt, swizzled, is_float):
"""Convert nv2a zeta format to the equivalent Texture format."""
if fmt == 0x1: # Z16
if is_float:
return 0x2D if swizzled else 0x31
return 0x2C if swizzled else 0x30
if fmt == 0x2: # Z24S8
if is_float... |
def merge_dict_sum(dict1, dict2):
"""
Merge two dictionaries and add values of common keys.
Values of the input dicts can be any addable objects, like numeric, str, list.
"""
dict3 = {**dict1, **dict2}
for key, value in dict3.items():
if key in dict1 and key in dict2:
dict3[k... |
def translate(text, conversion_dict, before=None):
"""
Fix wrong words
"""
if not text:
return text
before = before or str
tmp = before(text)
for key, value in conversion_dict.items():
tmp = tmp.replace(key, value)
return tmp |
def strip_ascii(content_data):
"""
Strips out non-printable ASCII chars from strings, leaves CR/LF/Tab.
Args:
content_data: b"\x01He\x05\xFFllo"
Returns:
stripped_message: "Hello"
"""
stripped_message = str()
if type(content_data) == bytes:
for entry... |
def lcmt_check(grade_v, grade_i, grade_j):
"""
A check used in lcmt table generation
"""
return grade_v == (grade_j - grade_i) |
def container_code_path(spec):
""" Returns the path inside the docker container that a spec (for an app or lib) says it wants
to live at """
return spec['mount'] |
def skip_waiting(scopeURL: str) -> dict:
"""
Parameters
----------
scopeURL: str
"""
return {"method": "ServiceWorker.skipWaiting", "params": {"scopeURL": scopeURL}} |
def a_second_has_elapsed(current_time: float, start_time: float) -> bool:
"""
Given two timestamps (unix epochs), a starting time and a current time,
checks if the current time is at least a second later than the starting
time
"""
return current_time - start_time >= 1 |
def gen_all_holds(hand):
"""
Generate all possible choices of dice from hand to hold.
hand: full yahtzee hand
Returns a set of tuples, where each tuple is dice to hold
"""
if (len(hand) == 0):
return set([()])
holds = set([()])
for die in hand:
f... |
def decode_domain_def(domains, merge=True, return_string=False):
"""Return a tuple of tuples of strings, preserving letter numbering (e.g. 10B)."""
if not domains:
return None, None
if domains[-1] == ",":
domains = domains[:-1]
x = domains
if return_string:
domain_fragments ... |
def match_cond(target, cond_key, cond_value, force=True, opposite=False):
"""
params:
- target: the source data want to check.
- cond_key: the attr key of condition.
- cond_value: the value of condition.
if the cond_value is a list, any item matched will make output matched.
- opposite: re... |
def detect_anagrams(word, candidates):
"""
Return all correct anagrams of a given word from a list of words.
Anagrams are case insensitive, and differ from the original word.
"""
anagrams = []
for candidate in candidates:
c = candidate.lower()
w = word.lower()
if sort... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.