content stringlengths 42 6.51k |
|---|
def parse_colon_speparated_lines(lines):
"""
@summary: Helper function for parsing lines which consist of key-value pairs
formatted like "<key>: <value>", where the colon can be surrounded
by 0 or more whitespace characters
@return: A dictionary containing key-value pairs of the ... |
def convertVote(castCode):
"""
Parameters :
castCode : Code for vote type cast by member
Returns :
Real value (0, 0.5, or 1.0) for vote cast
"""
if int(castCode) <= 3:
return 1.0
elif int(castCode) <= 6:
return 0.0
else:
return 0.5 |
def epochBessel2JD(Bepoch):
#----------------------------------------------------------------------
"""
Convert a Besselian epoch to a Julian date
:param Bepoch:
Besselian epoch in format nnnn.nn
:type Bepoch:
Floating point number
:Returns:
Julian date
:Reference:
See: :func:`JD2epochBessel`
:... |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
import re
# your code here
sol = 0
for i in range(len(line)):
sol=max(sol,len(max(re.findall(line[i]+"+",line),key=len)))
return sol |
def clip_filename_with_extension(filename):
""" clips long file names """
clipped = filename[filename.rfind("/") + 1 :]
if len(clipped) > 15:
clipped = clipped[:6] + "..." + clipped[clipped.rfind(".") - 4 :]
return clipped |
def bubble_sort(input_list):
"""Bubble sort."""
if not isinstance(input_list, (list, tuple)):
raise ValueError('input takes list/tuple only')
if isinstance(input_list, (tuple)):
input_list = list(input_list)
if not all(isinstance(val, (int, float)) for val in input_list):
raise... |
def strategy(state):
""" Information provided to you:
state = (board, last_move, playing, board_size)
board = (x_stones, o_stones)
stones is a set contains positions of one player's stones. e.g.
x_stones = {(8,8), (8,9), (8,10), (8,11)}
playing = 0|1, the current player's index
Your str... |
def get_in_dist(p1, p2, or_vec_x, or_vec_y):
"""Calculate the (signed) in-text distance of the points ``p1`` and ``p2`` according to the orientation vector with
x-coordinate ``or_vec_x`` and y-coordinate ``or_vec_y``.
:param p1: first point
:param p2: second point
:param or_vec_x: x-coordinate of ... |
def phy2pix(header, coords):
"""Transform physical coordinates into pixel coordinates.
Arguments
---------
header: dict or pyfits.Header
A header with CRVAL, CDELT and CRPIX keywords.
coords: list of arrays
The coordinates stored in an iterable.
Returns
-------
out... |
def quicksort(x):
"""
Describe how you are sorting `x`
"""
# Quicksort input function to tell initial values of p and r. Initial pivot point is in the middle of the array.
def quicksortinput(x):
quickSortHelper(x,0,len(x)-1)
# Recursive quicksort function, partitions the array and then quicksor... |
def sizeof_fmt(num: int, suffix: str = "o") -> str:
"""
Human readable version of file size.
Supports:
- all currently known binary prefixes (https://en.wikipedia.org/wiki/Binary_prefix)
- negative and positive numbers
- numbers larger than 1,000 Yobibytes
- arbitrary units
... |
def get_sample_transcription_from_header(header: str) -> str:
"""Generate a sample transcription from a header."""
return (
header
+ """
---
Bla bla bla
---
Footer"""
) |
def parse_int_set(nputstr=""):
"""Return list of numbers given a string of ranges
http://thoughtsbyclayg.blogspot.com/2008/10/parsing-list-of-numbers-in-python.html
"""
selection = set()
invalid = set()
# tokens are comma separated values
tokens = [x.strip() for x in nputstr.split(',')]
... |
def read_file(filename, default=None):
"""
Read the contents of a file, returning default if the file cannot be read.
:param filename: name of file to read
:type filename: str
:param default: value to return if file cannot be read
:return: contents of the file or default
"""
contents = ... |
def is_available_bus_sits(capacity, on, wait) -> int:
"""This function test if there is enought sits in bus."""
return 1 if (capacity - on) >= wait else 0 |
def _pattern_as_asterisk(pattern):
"""
Replace recurring %D (D: character) in the datetime pattern to asterisk.
"""
import re
return re.sub("(\\%\D)+", "*", pattern) |
def kernel_sigma(n_kernels):
"""
get sigmas for each guassian kernel.
:param n_kernels: number of kernels(including the exact match)
:return: sigmas, a list of sigma
"""
sigmas = [0.001] # exact match small variance means exact match ?
if n_kernels == 1:
return sigmas
return sig... |
def _get_highest_except(values, excluded_values):
"""
:param values: ([int])
:param excluded_values: (set(int))
:return: (int) highest value in values except the excluded value
"""
return max(set(values).difference(excluded_values)) |
def check_username(name, address):
"""
This will check to see if a username is given or if one needs to be asked for
Args:
name (None|str) : this will be None if no username is given or check to make sure a string otherwise.
address (str) : string of the address getting username for
retu... |
def update_rdataset_contents(data_obj, package, dataset_name, json_file):
"""Update the contents of json script"""
if "archived" in json_file.keys():
json_file.pop("archived")
if ("resources" in json_file.keys()) and (len(json_file["resources"]) != 0) and (
"path" in json_file["resource... |
def mwis(weight):
"""
maximum weighted independent sets
"""
n = len(weight)
d = [0]
d.append(weight[0])
for i in range(2,len(weight)+1):
d.append( max(d[i-1], d[i-2]+weight[i-1]) )
exist = ''
i = n-1
while i >= 0:
if d[i+1] == d[i]:
exist = '0' +... |
def splitName(name):
"""splitName(name)
Split an object name in parts, taking dots and indexing into account.
"""
name = name.replace("[", ".[")
parts = name.split(".")
return [p for p in parts if p] |
def inverse(dictionary):
"""
{a: {b}} -> {b: {a}}
"""
result = {}
for key, values in dictionary.items():
for value in values:
if value not in result:
result[value] = set()
result[value].add(key)
return result |
def zdt2(individual):
"""ZDT2 multiobjective function.
:math:`g(\\mathbf{x}) = 1 + \\frac{9}{n-1}\\sum_{i=2}^n x_i`
:math:`f_{\\text{ZDT2}1}(\\mathbf{x}) = x_1`
:math:`f_{\\text{ZDT2}2}(\\mathbf{x}) = g(\\mathbf{x})\\left[1 - \\left(\\frac{x_1}{g(\\mathbf{x})}\\right)^2\\right]`
... |
def compute_intersection_length(A, B):
"""Compute the intersection length of two tuples.
Args:
A: a (speaker, start, end) tuple of type (string, float, float)
B: a (speaker, start, end) tuple of type (string, float, float)
Returns:
a float number of the intersection between `A` and... |
def str_signature(sig):
""" String representation of type signature
>>> str_signature((int, float))
'int, float'
"""
return ', '.join(cls.__name__ for cls in sig) |
def count_occupied_seats(seat_map):
"""Count all occupied seats at the end of the round."""
occupied = 0
for seat, state in seat_map.items():
if state == "#":
occupied += 1
return occupied |
def nat_to_string(x):
"""Given a natural number, converts it into a binary string Do not modify this function."""
assert(x >= 0)
if x == 0:
return ""
else:
return nat_to_string(x//2) + str(x % 2) |
def count_increased(values):
"""
Count how many measurements increased from previous value
:param values: List of values
:returns: Number of measurements that increased from previous value
"""
# how many measurements increased
increased = 0
# first value
previous = values[0]
# r... |
def A_int(freqs,delt):
"""Calculates the Intermediate Amplitude
Parameters
----------
freqs : array
The frequencies in Natural units (Mf, G=c=1) of the waveform
delt : array
Coefficient solutions to match the inspiral to the merger-ringdown portion of the waveform
"""
retur... |
def grades(*arg , status = False):
"""
-> Student's school performance.
:arg: grades of a students.
:status: indicates whether student is approved or not.
"""
dict = {'Amount' : len(arg),
'Highter' : max(arg),
'Lower' : min(arg),
'Average': sum(arg)/len(arg)}
... |
def yes_no_formatter(value, **_):
""" Handle True/False from Django model and 1/0 from raw sql """
if value is None:
return ''
if value == 1: # boolean True is equal to 1
return 'Yes'
if value == 0: # boolean False is equal to 0
return 'No'
assert False, "Unable to convert ... |
def keywords_check(agr_data, value):
"""
check a database reference does have a keyword
:param agr_data:
:param value:
:return:
"""
result = 'Failure'
if 'keywords' in agr_data:
for keyword in agr_data['keywords']:
if keyword == value:
result = 'Succ... |
def insertion_sort(items):
"""
>>> insertion_sort([2, 1, 4, 6, 3])
[1, 2, 3, 4, 6]
"""
sorted_items = []
for i in items:
if not sorted_items:
sorted_items.append(i)
else:
for ind, item in enumerate(sorted_items):
if i < item:
... |
def prep_totals(totals_list, exits=True):
"""Method to prepare list of addition."""
try:
new_list = []
for x, fl in enumerate(totals_list):
if exits:
fll = fl * -1 if x > 1 else fl
else:
# Make this values positives
... |
def check_bucket_valid(bucket):
"""
Check bucket name whether is legal.
:type bucket: string
:param bucket: None
=======================
:return:
**Boolean**
"""
alphabet = "abcdefghijklmnopqrstuvwxyz0123456789-"
if len(bucket) < 3 or len(bucket) > 63:
re... |
def pure_cp(cp):
"""
return chord progression list only contain string expression.
>>> c_p2 = [START,C_Major,'C','Am','F','G','C','Am','F','G',G_Major,'Em','C','D','D7','G',END]
>>> temp = copy.copy(c_p2)
>>> c_p3 = [C_Major,C_Major,START,'C',END,START,START,END,'F',G_Major]
>>> pure = pure_cp(... |
def calcToBreakEvenPrice(initialSharePrice, allotment, buyCommission, sellCommission):
"""Return (Buy Commission + Sell Commission) / Allotment + Initial Share Price."""
return (buyCommission + sellCommission) / allotment + initialSharePrice |
def find_removed_hosts(prev_hosts, host_names_set):
""" Finds host names that have been removed since last iteration of ranking algorithm.
Args:
prev_hosts: (list) Host names from prevous iteration.
host_names_set: (list) Host names from current iteration.
Returns:
diff_strs: (list) List with removed ho... |
def _get_property_column(column_name):
"""
Create a dictionary representing column properties
:param column_name: Name of column
:return: A dictionary representing column properties
"""
column_dict = {'name': column_name, 'description': ""}
return column_dict |
def get_sections_in_range(sections, time_range):
"""get sections in a certain time range (e.g., in the train_ranges)
Args:
sections: list of tuples (<onset>, <offset>) or (<label>, <onset>, <offset>)
time_range: (list of) tuple(s) (<onset>, <offset>)
Returns:
"""
if isinstance(tim... |
def _additional_imports(model_name):
"""
Adds additional imports for experimental models.
"""
if model_name == 'IterativeImputer':
return ["from sklearn.experimental import enable_iterative_imputer # pylint: disable=W0611"]
if model_name in ('HistGradientBoostingClassifier', 'HistGradientBo... |
def detect_simple_decomp(var):
"""
Look for a simple domain decomposition in the blocks of this variable. This is defined
as a situation where each process writes an equal sized block of an array, and one of
the array dimensions is used to separate data written by the ranks. If found, return
a variable descri... |
def set_tags(template: str, analysisname: str, era: str, sample_group: str) -> str:
"""
Function used to set the tags in the template.
Args:
template: The template to be modified.
analysisname: The name of the analysis.
era: The era of the analysis.
sample_group: The sample ... |
def matches_filter(val, op, required_value):
"""
check if table content matches filtered value
Parameters
------------
val : str
value from registry table to be compared
op : str
filtering operation to be performed
required_value : str
value to match from filter_expr... |
def git_repo_kwargs(tmpdir_repoparent, git_dummy_repo_dir):
"""Return kwargs for :func:`create_repo_from_pip_url`."""
repo_name = 'repo_clone'
return {
'url': 'git+file://' + git_dummy_repo_dir,
'parent_dir': str(tmpdir_repoparent),
'name': repo_name,
} |
def jtype( c ):
"""
Return the a string with the data type of a value, for JSON data
"""
ct = c['type']
return ct if ct != 'literal' else '{}, {}'.format(ct,c.get('xml:lang')) |
def cB_to_zipf(cB):
"""
Convert a word frequency from centibels to the Zipf scale
(see `zipf_to_freq`).
The Zipf scale is related to centibels, the logarithmic unit that wordfreq
uses internally, because the Zipf unit is simply the bel, with a different
zero point. To convert centibels to Zipf,... |
def GetLeftBrow(points):
"""
Returns left brow points.
Args:
points: Points
Returns:
Points
"""
eye = []
for i in range(5):
eye.append(points[i + 17])
return eye |
def seti(registers, a, b, c):
"""(set immediate) stores value A into register C. (Input B is ignored.)"""
registers[c] = a
return registers |
def get_universal_bounds(name_to_data_map):
"""
Gets the bounds of all recorded segments
"""
min_lat = float("inf")
max_lat = float("-inf")
min_lon = float("inf")
max_lon = float("-inf")
for name in name_to_data_map:
item = name_to_data_map[name]
min_lat = item["bounds"... |
def _get_ngrams(n, text):
"""Calcualtes n-grams.
Args:
n: which n-grams to calculate
text: An array of tokens
Returns:
A set of n-grams
"""
ngram_set = set()
text_length = len(text)
max_index_ngram_start = text_length - n
for i in range(max_index_ngram_start + 1):
ngram_set.add(tuple(tex... |
def dict_diff(prv, nxt):
"""Return a dict of keys that differ with another config object."""
keys = set(list(prv.keys()) + list(nxt.keys()))
result = {}
for k in keys:
if prv.get(k) != nxt.get(k):
result[k] = (prv.get(k), nxt.get(k))
return result |
def above_threshold(student_scores, threshold):
"""
:param student_scores: list of integer scores
:param threshold : integer
:return: list of integer scores that are at or above the "best" threshold.
"""
total = []
for score in student_scores:
if score >= threshold:
tota... |
def get_column_major(arr):
"""
Internal function for switching nested list from row major to column major
"""
cm_arr = []
for c in range(len(arr[0])):
new_col = []
for row in arr:
new_col.append(row[c])
cm_arr.append(new_col)
return cm_arr |
def dict_with_indexes(words):
"""
The function takes a list of words as its argument.
Returns a dict with the key as the index of the word and value as the word.
For example,
INPUT: ["apple", "ball", "cat", "dog"]
OUTPUT: {0: "apple", 1: "ball", 2: "cat", 3: "dog"}
"""
return {index: w... |
def _is_sunder(name):
"""Returns True if a _sunder_ name, False otherwise."""
return (name[0] == name[-1] == '_' and
name[1:2] != '_' and
name[-2:-1] != '_' and
len(name) > 2) |
def CountsToFloat(counts, bits=9, vmax=2.5, vmin=-2.5):
"""Convert the integer output of ADC to a floating point number by
mulitplying by dv."""
dv = (vmax-vmin)/2**bits
return dv*counts |
def filter_urls(url_to_check) -> bool:
"""
Filters the URLs collected so that only those from base_url domain
are kept. To remove the remaining non useful URLs we assume every valid BBC article has a 8 digit
string in its URI and discard those which do not.
@Returns bool Tru... |
def alpha_beta_max_to_mu_chi_var_chi_max(alpha, beta, amax):
"""
Convert between parameters for beta distribution
"""
mu_chi = alpha / (alpha + beta) * amax
var_chi = alpha * beta / ((alpha + beta)**2 * (alpha + beta + 1)) * amax**2
return mu_chi, var_chi, amax |
def _int(val: int) -> bytes:
"""
Encode and int to a big endian byte array
"""
if val == 0:
return val.to_bytes(1, byteorder='big')
return val.to_bytes((val.bit_length() + 7) // 8, byteorder='big') |
def findgcd(x, y):
"""This function returns the greatest common factor/divisor."""
if x % y == 0: # if statement to identify
return y
else:
return findgcd(y, x % y) |
def get_connected_nodes(current_node, paths):
"""
Get all nodes that are connected to current_node
:param current_node: current node
:param paths: paths of this node
:return: all connected nodes in a list
"""
connectedNodes = list()
for path in paths:
if (current_node.id == path... |
def expected_supervisor_files(plones, supervisor_ext):
""" from a list of plones, learn our expected supervisor/conf.d files.
"""
filenames = set()
for aplone in plones:
filenames.add("{0}_zeo{1}" .format(aplone['plone_instance_name'], supervisor_ext))
return filenames |
def release(request):
"""
This fixture exists to be substituted into the *specfile* fixture
indirectly, or else provide a default of %autorelease.
"""
return getattr(request, "param", "Release: %autorelease") |
def color565(r, g=0, b=0):
"""Convert red, green and blue values (0-255) into a 16-bit 565 encoding. As
a convenience this is also available in the parent adafruit_rgb_display
package namespace."""
try:
r, g, b = r # see if the first var is a tuple/list
except TypeError:
pass
r... |
def remove_options(args: dict) -> dict:
""" Strips options part of doc which gets parsed by docopts
- args: the dictionary of arguments produced by docopts
- returns: a dictionary with just the useful arguments in it
"""
new_args = dict()
for arg in args.keys():
if arg == "Option... |
def collect_money(f_max_value, f_quarters, f_dimes, f_nickels):
"""Collect money into the machine
Params:
f_max_value: float
Returns:
float or str
"""
try:
money_collected = int(f_quarters) * 0.25
money_collected += int(f_dimes) * 0.10
money_collected += int... |
def parse_spread(spread_bet):
"""Parse a spread bet object from Bovada and return, in order, the spread and the home and away spread prices"""
outcomes = spread_bet["outcomes"]
spread = ""
home_spread_price = ""
away_spread_price = ""
if len(outcomes) > 2:
raise Exception("Unexpected obj... |
def get_dict_contributions_formatter_key_to_tuple(dict_contributions_given: dict) -> dict:
"""
Formats given dict by making the key a tuple
:param dict_contributions_given: dict that you want to have it's keys made into a tuple
:return: new formatted dict
"""
dict_result = {}
for key, val... |
def parse_boolean(s):
"""Return True or False, depending on the value of ``s`` as defined by the ConfigParser library."""
boolean_states = {'0': False,
'1': True,
'false': False,
'no': False,
'off': False,
... |
def binary_to_integer(binary):
"""
Convert R or G or B pixel values from binary to integer.
INPUT: A string tuple (e.g. ("00101010"))
OUTPUT: Return an int tuple (e.g. (220))
"""
return int(binary, 2) |
def getLine(p1, p2, eps=1e-30):
"""
p1 is a tuple of the first point
p2 is a tuple of the second point
returns a tuple of the slope and y-intercept of the line going throug both points
"""
if abs(p1[0] - p2[0]) < eps:
slope = 1 / eps
else:
slope = float((p1[1] - p2[1]) / (p1... |
def softmax(li):
"""softmax - Logistic Sigmoid function
"""
from math import exp
sumE = sum([exp(i) for i in li])
return [exp(i)/sumE for i in li] |
def get_scales(count, scale):
"""Returns the item scales required to represent a count of atoms at equal position"""
res = []
i = scale
while count > 0:
if count & 1:
res.append(i)
count >>= 1
i -= 1
return res |
def from_minutes(mins):
"""
converts a minute value into a day-hour-minute tuple
"""
day = mins // 1440
remainder = mins - (day * 1440)
hour = remainder // 60
minute = remainder - (hour * 60)
return day, hour, minute |
def _hex_print_format(value):
"""hex representation of an integer
:param value: an integer to be represented in hex
"""
return "0x{:08x}".format(value) |
def float_to_16(value):
""" convert float value into fixed exponent (8) number
returns 16 bit integer, as value * 256
"""
value = int(round(value*0x100,0))
return value & 0xffff |
def encode_with(string, encoding):
"""Encoding ``string`` with ``encoding`` if necessary.
:param str string: If string is a bytes object, it will not encode it.
Otherwise, this function will encode it with the provided encoding.
:param str encoding: The encoding with which to encode string.
:re... |
def get_terms(raw_lines, term_type):
"""
Takes a list of strings and returns a new list containing only
lines starting with `term_type` and strips line endings.
Term can be either of the "main" (or `!T`) type or additional (or
`!G`) type
Parameters
----------
raw_lines : list of str
... |
def listify(x):
"""
If given a non-list, encapsulate in a single-element list.
@rtype: list
"""
return x if isinstance(x, list) else [x] |
def ramp(x: float) -> float:
"""A ramp function.
Simha 2014's Delta-function in eqn 6
"""
return x if x >= 0 else 0 |
def de2bi(obj):
"""
Converts a decimal number into its binary representation
Parameters
----------
obj : int or str
A number in decimal format
Returns
-------
int
The binary representation of the input number
"""
return int(bin(int(obj))[2:]) |
def raw_to_regular(exitcode):
"""
This function decodes the raw exitcode into a plain format:
For a regular exitcode, it returns a value between 0 and 127;
For signals, it returns the negative signal number (-1 through -127)
For failures (when exitcode < 0), it returns the special value -128
"""... |
def ots(inp):
""" Output to string: Convert array output to a backspace-seperated string """
out_string = ""
for element in inp:
out_string += str(element) + "\n"
return out_string |
def mat44_to_pos(mat):
"""
Get position from matrix.
:param mat: 4x4 matrix
:return: list, position
"""
return [mat[i][3] for i in range(3)] |
def polignac(num,p):
"""
input: num can be any positive integer and p and prime number.
output: Gives the total number of factors of p in num! (num factorial).
Stated another way, this function returns the total number of factors
of p of all numbers between 1 and num; de Polignac's formula is prett... |
def plane_to_sphere_car(az0, el0, x, y):
"""Deproject plane to sphere using plate carree (CAR) projection.
The input (x, y) coordinates are unrestricted. The target point can likewise
be anywhere on the sphere.
Please read the module documentation for the interpretation of the input
parameters and... |
def get_english_score(input_bytes):
"""Returns a score which is the sum of the probabilities in how each letter of the input data
appears in the English language. Uses the above probabilities.
Thanks to: https://github.com/ricpacca
"""
CHARACTER_FREQ = {
'a': 0.0651738, 'b': 0.0124248, 'c': ... |
def natNetwork(ctx, mach, nicnum, nat, args):
"""This command shows/alters NAT network settings
usage: nat <vm> <nicnum> network [<network>]
"""
if len(args) == 1:
if nat.network is not None and len(str(nat.network)) != 0:
msg = '\'%s\'' % (nat.network)
else:
msg ... |
def count_factors(n):
"""Return the number of positive factors that n has.
>>> count_factors(6) # 1, 2, 3, 6
4
>>> count_factors(4) # 1, 2, 4
3
"""
i, count = 1, 0
while i <= n:
if n % i == 0:
count += 1
i += 1
return count |
def _linelen(line, tabsize=8):
""" Calculate the length of aline, considering tabsize """
tab_cnt = line.count('\t')
if not tab_cnt:
return len(line)
count = 0
for char in line:
if char == '\t':
count += tabsize - count % tabsize
else:
count += 1
... |
def transfer_driver_cookies_to_request(cookies):
"""
Extract the cookies to a format that the request library understands
:param cookies: This should be a driver cookie. Obtained with the command my_driver.get_cookies()
:type cookies: dict
:return: Cookies dictionary suitable for a requests lib obj... |
def limit_llbbox(bbox):
"""
Limit the long/lat bounding box to +-180/89.99999999 degrees.
Some clients can't handle +-90 north/south, so we subtract a tiny bit.
>>> ', '.join('%.6f' % x for x in limit_llbbox((-200,-90.0, 180, 90)))
'-180.000000, -89.999999, 180.000000, 89.999999'
>>> ', '.join... |
def fid_path(fid, fsname_rootpath):
"""
Get the fid path of a file
"""
return "%s/.lustre/fid/%s" % (fsname_rootpath, fid) |
def sorted_srs_list(srs):
"""
"sort" list of SRS. Moves EPSG:3857, EPSG:900913 and EPSG:4326 to the
front, keeps order of other projections.
"""
result = list(srs)
if 'EPSG:4326' in result:
result.pop(result.index('EPSG:4326'))
result.insert(0, 'EPSG:4326')
if 'EPSG:900913' i... |
def make_zigzag(points, num_cols):
""" Changes linearly ordered list of points into a zig-zag shape.
This function is designed to create input for the visualization software. It orders the points to draw a zig-zag
shape which enables generating properly connected lines without any scanlines. Please see the... |
def for_name(fq_name, recursive=False):
"""Find class/function/method specified by its fully qualified name.
Fully qualified can be specified as:
* <module_name>.<class_name>
* <module_name>.<function_name>
* <module_name>.<class_name>.<method_name> (an unbound method will be
returned in this cas... |
def Str(X):
"""wandelt eine Zahl in einen String in Zehnerpotenzdarstellung um"""
return "{:.2e}".format(X) |
def parse_formdata_params(data):
"""
Takes a formdata request body and parses it into key/value pairs.
Parameters:
data(str): Input string of multipart form data to parse.
Returns:
list: List of dictionaries in {key:value} pairs.
"""
results = []
diced = data.split("\r\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.