content stringlengths 42 6.51k |
|---|
def get_car_info_api(car_name: str, car_year: str) -> str:
"""Return the car info as gotten by an API"""
return f"The {car_name} was manufactured in {car_year}" |
def shout(word):
"""Return a string with three exclamation marks"""
# Concatenate the strings: shout_word
shout_word = word + '!!!'
# Replace print with return
return(shout_word) |
def CSVformat(str_in):
"""
removes certain characters from fields returned by Jira requests, in order to facilitate insertion into SQL tables
would need to be written differently for a production application, to handle escape characters etc. more intelligently
parameters:
str_in (string): the string from Jira tha... |
def to_padded_string(number, padding=None, decimals=None):
"""
Given a number object, converts that to a string. For non-natural numbers,
we can optionally set the number of decimals to round to and print out.
If a padding value is given, prefixes with enough spaces to make the final
string at least... |
def indent_string(string, indent=' ', include_first=True, include_last=False):
"""
Indent a string by adding indent after each newline.
:param string: The string to indent
:param indent: The string to use as indentation
:param include_first: Also indent the first line of the string (before the firs... |
def symbols(el):
"""Map words of operators to symbols of operators.
Arguments:
el {str} -- word of operator
Returns:
str -- symbol of operator
"""
el_lower = el.lower()
if el_lower == "and":
return "&"
elif el_lower == "or":
return "|"
elif el_lower == "... |
def myfuncPrimeFactors(n):
"""
This function finds and returns the prime factorization
of a whole number (excluding zero) via the reiterative division
method.
Example of usage:
getPrimeFactors = myfuncPrimeFactors( 716 )
print(getPrimeFactors)
"""
i = 2
factors = []
w... |
def instancesNaked(unit,values):
"""Find all the instances of naked twins in a unit
Args:
unit: a unit defining a set of boxes in the model
values(dict): a dictionary of the form {'box_name': '123456789', ...}
Returns:
an array of tuples with all the naked twin instances in the unit... |
def extract(string: str, start: int, len_: int) -> str:
"""Extract a section of a certain length from a string.
Args:
string (str): The string to extract from.
start (int): How many chars to move forward.
len_ (int): The amount of chars to extract.
Returns:
str: The extract... |
def factorial(n, show=False):
"""
-> Executa um calculo de fatorial
:param n: Recebe o numero do fatorial a ser calculado.
:param show=False: Por padrao false mas se for True mostra o processo de calculo.
:param return: Retorna o valor calculado
"""
print(30 * '-')
f = 1
f... |
def full_frame(flag=True):
"""When this flag is True, the related constraint should be applied if
is_full_frame(SUBARRAY) is True. Returns "F" or False.
>>> full_frame(True)
'F'
>>> full_frame(False)
False
"""
return "F" if flag else False |
def debom(string):
"""Strip BOM from strings."""
return string.encode("utf-8").decode("utf-8-sig") |
def codons(rna):
"""
Splits rna into codons.
Args:
rna (str): RNA string.
Returns:
list: codons.
"""
return [rna[index:index+3] for index in range(0, len(rna), 3) if len(rna[index:index+3]) == 3] |
def to_list(x):
"""
Return x if it is already a list, or return a list containing x if x is a scalar.
"""
if isinstance(x, (list, tuple)):
return x # Already a list, so just return it.
return [x] |
def check_agents_are_known(configuration):
"""
Checks if all keys of the configuration "structure" are defined in the "agents" section
:param configuration: the object group to look at
:return: if all agents are well defined
"""
known_agents = configuration["agents"]
known_agents_id = [agent... |
def string_mappings(mapping_list):
"""Make a string out of the mapping list"""
details = ''
if mapping_list:
details = '"' + str(mapping_list) + '"'
return details |
def genericTypeValidator(value, typ):
"""
Generic. (Added at version 2.)
"""
return isinstance(value, typ) |
def _convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = _convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "fro... |
def _write_categories(categories_list):
"""
Parameters
----------
categories_list : list of str
the list of category's names
Returns
-------
the categories' dictionary
"""
# create an empty categories' dictionary
categories_dict = {"categori... |
def selection_sort(lst):
"""Perform an in-place selection sort on a list.
params:
lst: list to sort
returns:
lst: passed in sequence in sorted order
"""
if not isinstance(lst, list):
raise TypeError('Sequence to be sorted must be list type.')
for i in range(len(lst) - 1)... |
def get_iname_tag(image_name):
"""
return tuple with image name and tag
"""
if ":" in image_name:
iname, tag = image_name.split(":")
else:
iname, tag = image_name, "latest"
return iname, tag |
def label_blockstructures(blockstructures):
"""Conversion between long-hand and short-hand
for MTL block structures.
"""
conversion = {
'trueshare' : 'I',
'mhushare' : 'Y',
'split' : 'V',
'attenshare' : 'W',
}
labels = []
for blockstructure in blockstructures... |
def as_list(list_data):
"""Prints a list as html.
"""
return {
'list': list_data,
} |
def bind_question_text_alternatives(question):
"""Bind question text with each alternative in one single string variable.
:param question:
:return [string] merged_question_text:
"""
s = question["question_text"]
for alternative in question["options"]:
s = s + " " + alternative["text"]
... |
def returnMaxAcreage(fire_data):
"""
return maximum acreage
"""
fire_max = 0
for fire in fire_data:
if fire["properties"]["ACRES"] >= fire_max:
fire_max = fire["properties"]["ACRES"]
return fire_max |
def color_contrast_ratio(fore_color, back_color):
"""Calculated the contrast ratio between a foreground color (with optional
alpha) and a background color.
Args:
fore_color: Color in the form of rgb [r,g,b] or rgba [r,g,b,a]
back_color: Color in the form of rgb [r,g,b] or rgba [r,g,b,a]
... |
def bisect(f, lo=0, hi=None, eps=1e-9):
"""
Returns a value x such that f(x) is true.
Based on the values of f at lo and hi.
Assert that f(lo) != f(hi).
"""
lo_bool = f(lo)
if hi is None:
offset = 1
while f(lo+offset) == lo_bool:
offset *= 2
hi = lo + offs... |
def ss_label(ss_code):
"""
Get the frequency based subsystem code.
:param ss_code: Subsystem code.
:return: Frequency
"""
if ss_code == "2": # 1200 khz
return "1200 kHz"
elif ss_code == "3": # 600 khz
return "600 kHz"
elif ss_code == "4": ... |
def _jupyter_nbextension_paths():
"""
Set up the notebook extension for displaying metrics
"""
return [{
"section": "notebook",
"dest": "nbclearafter",
"src": "static",
"require": "nbclearafter/main"
}] |
def helm_sequences():
"""Returns prefixes of files with raw HELM sequences"""
return ['example_', 'for_alignment1_', 'for_alignment2_', 'for_alignment3_', 'for_alignment_without_nh2_',
'helmtest_', 'input_data_', 'multi_chain_peps_', 'multi_chem_pep_', "test_data_"] |
def invert_atomlist_coordinates(atomst):
"""
Inverts atom coordinates
:param atoms: list of atom list
>>> c1 = [['c1', '1', '1', '-2', '3'], ['c1', 2, 1, -2, 3]]
>>> invert_atomlist_coordinates(c1)
[['c1', '1', -1.0, 2.0, -3.0], ['c1', 2, -1.0, 2.0, -3.0]]
"""
atoms = []
for line in atomst:
line =... |
def get_header_dict(value):
"""function to convert string header to dictionary"""
values = value.rstrip("\n").split("\n")
header_dict = {}
for value in values:
key, value = value.split(":", 1)
header_dict[key.rstrip().lstrip()] = value.lstrip().rstrip()
return header_dict |
def is_iterable(obj):
""" Check for the `__iter__` attribute so that this can cover types that
don't have to be known by this module, such as NumPy arrays. """
return hasattr(obj, '__iter__') and not isinstance(obj, str) |
def json_int_key_encode(rename_dict):
"""
Recursively rename integer value keys if they are casted to strings
via JSON encoding
returns: dict with new keys
"""
if isinstance(rename_dict, dict):
for k in list(rename_dict.keys()):
if hasattr(k, 'isdigit') and k.isdigit():
... |
def bisect_left(arr, x):
"""
x = 5
L R
1 3 4 10 10
arr[i] <5 | 5 <= arr[i]
x = 2
L R
1 3 4 10 10
arr[0..L] < 2 | 2 <= arr[R..N]
"""
N = len(arr)
l = -1 # arr[l] < x
r = N # arr[r] >= x
while r > l + 1:
... |
def mutated_schema(schema, mutator):
"""Apply a change to all levels of a schema.
Returns a new schema rather than modifying the original.
"""
schema = mutator(schema.copy())
if 'items' in schema:
schema['items'] = mutated_schema(schema['items'], mutator)
if 'properties' in schema:
... |
def prefix_suffix_prep(string1, string2):
"""Calculates starting position and lengths of two strings such that
common prefix and suffix substrings are excluded.
Expects len(string1) <= len(string2)
"""
# this is also the minimun length of the two strings
len1 = len(string1)
len2 = len(string... |
def percentage_string(val):
""" Returns a percentage-formatted string for a value, e.g. 0.9234 becomes 92.34% """
return '{:,.2%}'.format(val) |
def map_labels(label):
"""
Purpose: a function used for the pandas library's ".apply()" method
to convert all the specific labels in the dataframe into general labels
Params: label(string) -> the label from every single row of the dataframe column
Returns: a general label (string)
"""
... |
def require(obj, key, required_type=None):
"""Return the value with the specified key in obj if it exists, otherwise raise a KeyError.
If required_type is not None, a TypeError will be raised if the corresponding value
is not an instance of required_type.
"""
if key not in obj:
raise KeyErr... |
def set_architecture(architecture_id):
"""Set architecture-specific parameters. Supported architectures:
* 'default'/'intel': a conventional multi-core CPU, such as an Intel Haswell
"""
# All sizes are in Bytes
# The /cache_size/ is the size of the private memory closest to a core
if arch... |
def binary_search(list: list, target: str):
"""binary search
Args:
list (list): sorted list
target (str): search target
"""
low = 0
high = len(list) - 1
while low <= high:
mid = (low + high) // 2
pick = list[mid]
if pick == target:
return ... |
def remove_last_slash(path):
""" Remove the last slash in the given path [if any] """
if path.endswith('/'):
path = path[:-1]
return path |
def fair_split(i, n, p):
"""
Split n requests amongst p proxies
Returns how many requests go to the i-th proxy
"""
n1 = int(n)
i1 = int(i)
p1 = int(p)
return int((n1 * i1) / p1) - int((n1 * (i1 - 1)) / p1) |
def remove_whitespace(string):
"""
This function remove space
Parameters :
string: the string
Returns :
return string witout space
"""
return string.replace(' ','') |
def oauth_generator(function, *args, **kwargs):
"""Set the _use_oauth keyword argument to True when appropriate.
This is needed because generator functions may be called at anytime, and
PRAW relies on the Reddit._use_oauth value at original call time to know
when to make OAuth requests.
Ret... |
def get_status_string(record):
"""Get the status label given a record of either data format or component"""
if "when_revoked" not in record or "when_published" not in record or \
"when_added" not in record:
return None
if record["when_revoked"] is not None:
return "revoked"
elif... |
def h1(text: str):
"""
:param h1: string with text for HTML header
:return: string containing HTML header 1
"""
if not isinstance(text, str):
raise TypeError("input must be a string")
local_text = ("""<h1>""" + text + """</h1>
""")
return local_text |
def inventory_alias_to_official_habitica_name(inventory_name: str):
"""Take an inventory_name argument and return the canonical Habitica item name"""
# pylint: disable=too-many-return-statements
if inventory_name in ["hatchingpotions", "hatchingPotion"]:
return "hatchingPotions"
if inventory_nam... |
def reverse_and_add(x):
"""
Returns the sum of x and y, where y is formed by reversing the digits of x
"""
return(x + int(str(x)[::-1])) |
def indent_all_but_first(string, indent):
"""Indent all but the first line of a string."""
return "\n".join(" " * indent * (i > 0) + l for i, l in enumerate(string.split("\n"))) |
def iter_algorithm(d, n, p, corpus, pr):
"""
PR(p) = ( (1-d) / n ) + ( d * sum( PR(i) / NumLinks(i) ) )
i
d = dampening number; n = # of possible pages; p = page; i = incoming pages
"""
page_sum = 0
# This for loop will calcula... |
def subjfn(prop):
""" Function to retrieve the subject of prop (obtained from the
intensional representation produced by SpatialParser).
E.g. prop[1] = ['[]'], prop[1][0] = '[] """
return prop[1][0] |
def dictadd(dict_a, dict_b):
"""
Returns a dictionary consisting of the keys in `a` and `b`.
If they share a key, the value from b is used.
>>> dictadd({1: 0, 2: 0}, {2: 1, 3: 1})
{1: 0, 2: 1, 3: 1}
"""
result = dict(dict_a)
result.update(dict_b)
return result |
def find_c(side1, side2, side3):
"""
Takes three side lengths an returns the largest
:param side1: int or float
:param side2: int or float
:param side3: int or float
:return: int or float
"""
if side1 > side2 and side1 > side3:
return side1
elif side2 > side1 and side2 > sid... |
def maybe_fix_unary_chain(tgt_toks):
"""Fix unary chain IN:GET_LOCATION-SL:LOCATION_MODIFIER-IN:GET_LOCATION."""
if (not "[SL:LOCATION_MODIFIER" in tgt_toks or
not "[IN:GET_LOCATION" in tgt_toks):
return tgt_toks
for i in range(len(tgt_toks) - 3):
if (tgt_toks[i:i + 3] == [
"[IN:GET_LOCATION... |
def captcha_halfway(numbers):
"""Sum the digits that match the one half way around a cyclic string."""
total = 0
for i in range(int(len(numbers) / 2)):
if numbers[i] == numbers[i + int(len(numbers) / 2)]:
total += int(numbers[i])
return total * 2 |
def stringToByteArray(string: str) -> list:
"""
A port of javascript string to Bytearray function
:param string: a string
"""
result = []
i = 0
print(len(string))
while i < len(string):
a = ord(string[i])
result.append((65280 & a) >> 8)
result.append(255 & a)
... |
def make_args(args_dict, required, options):
""" Make command line argument list, for testing argument parsers
Args:
args_dict (:obj:`dict`): argument names and their values
required (:obj:`list`): required command line arguments
options (:obj:`list`): optional command line arguments
... |
def is_palindrome(value):
"""Check if a string is a palindrome."""
return value == value[::-1] |
def levenshteinDistance(s1: str, s2: str) -> int:
"""
https://stackoverflow.com/questions/2460177/edit-distance-in-python
"""
if len(s1) > len(s2):
s1, s2 = s2, s1
distances = range(len(s1) + 1)
for i2, c2 in enumerate(s2):
distances_ = [i2+1]
for i1, c1 in enumerate(s1)... |
def point_check(point,start,end):
""" This function checks if the coordinates of a point lies at the edge of a grid. It returns a list of
boolean values. """
check=0
for i in point:
if i == start or i == end:
check+=1
return check |
def is_hit(x, y):
"""Return wheter given coords hit a circular target of r=1."""
return x*x + y*y <= 1 |
def screen_position(tam_win, tam_scr):
"""
Windows Position
"""
dato_scr = (tam_scr-tam_win) / 2
return dato_scr |
def __calculate_coefficient_of_variation(profile_jsons, feature_name):
"""
Calculates coefficient of variation for single feature
Parameters
----------
profile_jsons: Profile summary serialized json
feature_name: Name of feature
Returns
-------
coefficient_of_variation : Calculated... |
def trangle_area(a, b, c):
"""triangle_area"""
return ((a[0] - c[0]) * (b[1] - c[1]) - (a[1] - c[1]) * (b[0] - c[0])) / 2.0 |
def is_genetic_effect(effect):
"""
Is this effect a genetic effect?
:rtype: bool
"""
return effect in set(['additive', 'dominance', 'mitochondrial']) |
def xgcd(a: int, b: int) -> tuple:
"""
Extended Euclidean algorithm.
Returns (g, x, y) such that a*x + b*y = g = gcd(a, b).
"""
x0, x1, y0, y1 = 0, 1, 1, 0
while a != 0:
(q, a), b = divmod(b, a), a
y0, y1 = y1, y0 - q * y1
x0, x1 = x1, x0 - q * x1
return b, x0, y0 |
def break_chocolate(n, m):
"""
Split the chocolate bar of given dimension n x m into small squares.
:param n: integer value.
:param m: integer value.
:return: number of splits for n x m square.
"""
return n * m - 1 if n * m > 0 else 0 |
def replace_ref(tokens):
""" syntax
"""
size = len(tokens)
new_list = []
i = 0
while i < size:
if i < size - 2 and tokens[i + 2] == b'R':
new_list.append({'_REF': tokens[i]})
i += 3
else:
new_list.append(tokens[i])
i += 1
retur... |
def process_response_code(info):
"""Check the VirusTotal response code to ensure hash exists in its database
Args:
info: the full VirusTotal report in json format.
Returns:
True if the hash was found in the VirusTotal database. False if not.
"""
if info["response_code"] == 1: #retu... |
def dailyLow (lowTemps, date):
"""Finds the low temperature for date in question.
.. warning:
Assumes date has been validated using dateValidation and that data
exists for date in question using dataAvailable.
:param list lowTemps: Low temperatures for given month
:param date: Date (Mo... |
def convertString(x):
"""
Converts textual description of number of likes to integer
i.e. - '16.5k' -> 16,500
"""
string = str(x)
if 'k' in string:
number = float( ''.join(string.split('k')[0].split(',')) ) * 1000
elif 'm' in string:
number = float( ''.join(string.split... |
def find_total_denials(overall_paths):
"""return total denial of paths"""
cnt = 0
for path in overall_paths:
if not path:
cnt+=1
return cnt |
def list_get(l, index, default):
"""
>>> list_get([], 0, None)
>>> list_get([], -1, 7)
7
>>> list_get(None, 0, None)
Traceback (most recent call last):
...
TypeError: 'NoneType' object is not subscriptable
>>> list_get([1], 1, 9)
9
>>> list_get([1, 2, 3, 4], 2, 8)
3
... |
def trans_nums_to_strs(nums):
"""
:param nums: number
:return: number of translations
"""
nums = str(nums)
cache = [1, 1] # sol(n-2), sol(n-1)
for i in range(1, len(nums)):
if 9 < int(nums[i-1:i+1]) < 26:
cache[1], cache[0] = cache[0] + cache[1], cache[1]
else:
... |
def limit_to_safe_range(value: float) -> float:
"""
Controls like throttle, steer, pitch, yaw, and roll need to be in the range of -1 to 1.
This will ensure your number is in that range. Something like 0.45 will stay as it is,
but a value of -5.6 would be changed to -1.
"""
if value < -1:
... |
def listToTensorString(array):
"""turn python list into java tensor string representation"""
assert isinstance(array, list)
a = [listToTensorString(element) if isinstance(element, list) else element for element in array]
return '{%s}' % ', '.join(list(map(str, a))) |
def compute_cumulants(moments):
"""
Compute the cumulants from the moments up to order 4
"""
assert len(moments) >= 4, "You must have moments at least up to order 4."
kappas = [0] * 4
kappas[0] = moments[0]
kappas[1] = moments[1] - moments[0] ** 2
kappas[2] = moments[2] - 3 * moments[1]... |
def bolt_min_dist(d_0):
"""
Minimum bolt spacing.
:param d_0:
:return:
"""
e_1 = 1.2 * d_0
e_2 = 1.2 * d_0
e_3 = 1.5 * d_0
p_1 = 2.2 * d_0
p_2 = 2.4 * d_0
return e_1, e_2, e_3, p_1, p_2 |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except (AttributeError, TypeError):
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
excep... |
def single(collection):
""":yaql:single
Checks that collection has only one element and returns it. If the
collection is empty or has more than one element, raises StopIteration.
:signature: collection.single()
:receiverArg collection: input collection
:argType collection: iterable
:return... |
def is_hex_str(value, chars=40):
# type: (str, int) -> bool
"""Check if a string is a hex-only string of exactly :param:`chars` characters length.
This is useful to verify that a string contains a valid SHA, MD5 or UUID-like value.
>>> is_hex_str('0f1128046248f83dc9b9ab187e16fad0ff596128f1524d05a9a77c... |
def flatten_json(json_dict, delim):
"""Flattens a JSON dictionary so it can be stored in a single table row
Parameters:
json_dict (dict): Holds the json data
delim (string): The delimiter to be used to create flattened keys
Returns:
flattened_dict (dict)... |
def _pack_uvarint(n: int) -> bytes:
"""Pack an unsigned variable-length integer into bytes. """
result = b""
while True:
chunk = n & 0x7F
n >>= 7
if n:
result += bytes((chunk | 0x80,))
else:
result += bytes((chunk,))
break
return result |
def get_fx(x, linear):
""" Return the y value of function x """
a,b,offset = linear
y = ((a * x) + b)//offset
return y |
def toggle_active_links(pathname):
"""Toggles active menu links based on url pathname
Args:
pathname (str): Url pathname
Returns:
bool: Active state for each page
"""
if pathname in ["/datyy/", "/datyy/summary"]:
return True, False, False, False, False
if pathname == "... |
def _get_wikiconv_year_info(year: str) -> str:
"""completes the download link for wikiconv"""
# base directory of wikicon corpuses
wikiconv_base = "http://zissou.infosci.cornell.edu/convokit/datasets/wikiconv-corpus/"
data_dir = wikiconv_base + "corpus-zipped/"
return data_dir + year + "/full.corp... |
def int_32_lsb(x: int):
"""
Get the 32 least significant bits.
:param x: A number.
:return: The 32 LSBits of x.
"""
return int(0xFFFFFFFF & x) |
def csv_to_list(x):
"""Converts a comma separated string to a list of strings."""
return x.split(',') |
def gens_by_bus(buses, gens):
"""
Return a dictionary of the generators attached to each bus
"""
gens_by_bus = {k: list() for k in buses.keys()}
for gen_name, gen in gens.items():
gens_by_bus[gen['bus']].append(gen_name)
return gens_by_bus |
def check_required_data(dati: tuple) -> bool:
"""
Ritorna True se tutti i dati passati non sono None o stringa vuota
"""
result = True
for elem in dati:
if elem is None:
result = False
break
tmp = elem.strip(' \n\r')
if tmp == '':
result ... |
def is_commit(s):
"""Return true if `s` looks like a git commit.
>>> is_commit("a3bcD445")
True
>>> is_commit("xyzzy123")
False
"""
if len(s) >= 6:
try:
int(s, 16)
return True
except ValueError:
pass
return False |
def texsafe(value):
""" Returns a string with LaTeX special characters stripped/escaped out """
special = [
[ "\\xc5", 'A'], #'\\AA'
[ "\\xf6", 'o'],
[ "&", 'and'], #'\\"{o}'
]
for char in ['\\', '^', '~', '%', "'", '"']: # these mess up things
value = value.replace(char... |
def tag_and(*tag_ands):
"""Select a (list of) tag_and(s)."""
vtag_and = [t for t in tag_ands]
return {"tag_and": vtag_and} |
def convertValueToOSCRange(midiValue, oscRange, midiRange):
"""
value : OSC value
OscRange:
midiRange
"""
minOSC = oscRange[0]
maxOSC = oscRange[1]
minMidi = midiRange[0]
maxMidi = midiRange[1]
percent = (midiValue - minMidi ) / (maxMidi-minMidi) * 100.0
oscVal = (maxOSC -... |
def check_if_factor(guess, value):
"""Check if the guess is a factor of the value"""
if value % guess == 0:
return True
else:
return False |
def rstrip_str(user, str):
"""
Replace strings with spaces (tabs, etc..) only with newlines
Remove blank line at the end
"""
return '\n'.join([s.rstrip() for s in str.splitlines()]) |
def make_new(data, name):
"""Make a copy of a dictionary with defaults."""
if name not in data:
return None
out = data['_defaults'].copy()
out.update(data[name])
return out |
def _zerofix(x, string, precision=6):
"""
Try to fix non-zero tick labels formatted as ``'0'``.
"""
if string.rstrip('0').rstrip('.') == '0' and x != 0:
string = ('{:.%df}' % precision).format(x)
return string |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.