content stringlengths 42 6.51k |
|---|
def emptyfn(body: str, return_type: str="u1") -> str:
"""Wrap body inside of an empty function"""
return f"fn test() -> {return_type} {{{body}}}" |
def __get_int(section, name):
"""Get the forecasted int from json section."""
try:
return int(section[name])
except (ValueError, TypeError, KeyError):
return 0 |
def format_transaction(timestamp: float, address: str, recipient: str, amount: int, operation: str, openfield: str):
"""
Returns the formatted tuple to use as transaction part and to be signed
This exact formatting is MANDATORY - We sign a char buffer where every char counts.
"""
str_timestamp = '%.... |
def roman_to_int(s):
"""
https://www.tutorialspoint.com/roman-to-integer-in-python
:type s: str
:rtype: int
"""
roman = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
'IV': 4,
'IX': 9,
'XL': 40,
... |
def sortedSquares(nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
l = 0
r = len(nums) - 1
i = len(nums) - 1
result = [0] * len(nums)
while l <= r:
if nums[l]**2 < nums[r]**2:
result[i] = nums[r]**2
i -= 1
r -= 1
else:
... |
def make_project(id):
"""
return a template project
"""
return {
"type": "Project",
"metrics": [],
"tags": [],
"id": id,
"description": "",
"applicant": "",
} |
def evaluate_g3( kappa, nu, sigma, mu, s3 ):
"""
Evaluate the third constraint equation and also return the jacobians
:param float kappa: The value of the modulus kappa
:param float nu: The value of the modulus nu
:param float sigma: The value of the modulus sigma
:param float mu: The value of ... |
def is_true(v) -> bool:
"""
Check if a given bool/str/int value is some form of ``True``:
* **bool**: ``True``
* **str**: ``'true'``, ``'yes'``, ``'y'``, ``'1'``
* **int**: ``1``
(note: strings are automatically .lower()'d)
Usage:
>>> is_true('true')
True
... |
def expand_video_segment(num_frames_video: int, min_frames_seg: int, start_frame_seg: int, stop_frame_seg: int):
"""
Expand a given video segment defined by start and stop frame to have at least a minimum number of frames.
Args:
num_frames_video: Total number of frames in the video.
m... |
def f(x):
"""
A function for testing on.
"""
return -(x + 2.0)**2 + 1.0 |
def app_name(id):
"""Convert a UUID to a valid Heroku app name."""
return "dlgr-" + id[0:8] |
def rename_keys(dist, keys):
"""
Rename all the dictionary keys *in-place* inside a *dist*,
which is a nested structure that could be a dict or a list.
Hence, I named it as dist... which is much better than lict.
>>> test = {"spam": 42, "ham": "spam", "bacon": {"spam": -1}}
>>> rename_keys(test... |
def put_comma(alignment, min_threshold: float = 0.5):
"""
Put comma in alignment from force alignment model.
Parameters
-----------
alignment: List[Dict[text, start, end]]
min_threshold: float, optional (default=0.5)
minimum threshold in term of seconds to assume a comma.
Returns
... |
def parse_geofence(response):
"""Parse the json response for a GEOFENCE and return the data."""
hue_state = response['state']['presence']
if hue_state is True:
state = 'on'
else:
state = 'off'
data = {'name': response['name'],
'model': 'GEO',
'state': state}
... |
def intersect(ch_block, be_block):
"""Return intersection size."""
return min(ch_block[1], be_block[1]) - max(ch_block[0], be_block[0]) |
def complement_color(r, g, b):
"""Get complement color.
https://stackoverflow.com/questions/40233986/python-is-there-a-function-or-formula-to-find-the-complementary-colour-of-a-rgb
:param r: _description_
:type r: _type_
:param g: _description_
:type g: _type_
:param b: _description_
:t... |
def _pnpoly(x, y, coords):
"""
the algorithm to judge whether the point is located in polygon
reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation
"""
vert = [[0, 0]]
for coord in coords:
for node in coord:
vert.append(node)
vert.appe... |
def get_habituation_folder(s):
"""Get the type of maze from folder"""
names_part = ["habituation", "hab", "hab1", "hab2", "hab3", "hab4", "hab5"]
temp = s.split("/")
for name in temp:
for parts in names_part:
if parts in name:
return 1
return 0 |
def good_public_function_name(good_arg_name):
"""This is a perfect public function"""
good_variable_name = 1
return good_variable_name + good_arg_name |
def ComputeLabelY(Array):
"""Compute label y coordinate"""
Y = min(Array)+ (max(Array)-min(Array))/2
return Y |
def indef2def(indefs, a, b):
"""
Use the stored polynomial indefinite integral coefficients to calculate
the definite integral of the polynomial over the interval [a,b].
"""
# Evaluate a, b contributions using Horner's algorithm.
aval = indefs[-1]
for c in indefs[-2::-1]:
aval = c +... |
def ListToText(txtlst,sep=','):
""" Convert list to a string
:param lst txtlst: list (element shoud be string)
:param str sep' character(s)
:return: text(str) - 'elemnet+sep+element...'
"""
text=''
if sep == '': sep=' '
for s in txtlst: text=text+s+sep
n=text.rfind(sep... |
def getPodStatus(pod):
""" get pod status for display """
#logger.debug("getPodStatus()")
if not pod:
return "no pod"
if not pod['status']:
return "no pod status"
return "%s %s" % (pod['metadata']['name'], pod['status']['phase']) |
def penn_to_wn(tag):
""" Convert between a Penn Treebank tag to a simplified Wordnet tag """
if tag.startswith('N'):
return 'n'
if tag.startswith('V'):
return 'v'
if tag.startswith('J'):
return 'a'
if tag.startswith('R'):
return 'r'
return None |
def max_sum_subarray(arr):
"""
:param - arr - input array
return - number - largest sum in contiguous subarry within arr
"""
sumArray = sum(arr)
maxSum = sumArray
while len(arr) > 1:
if arr[0] > arr[len(arr)-1]:
arr = arr[:-1]
else:
arr = arr[1:]
... |
def init(i):
"""
Input: {}
Output: {
return - return code = 0, if successful
> 0, if error
(error) - error text if return > 0
}
"""
return {'return': 0} |
def replaceAdjacent_cells(freePlaceMap, x, y, count):
"""
Checks every Cell surrounded by the current Cell if its free and has no Value.
Then the Current count will be the new Value and this new Cell will be Added to the List to be checked
:param freePlaceMap: The Current FreePlaceMap
:param x: The... |
def find_disagreement(first_term, second_term):
"""Finds the disagreement set of the terms."""
term_pair_queue = [(first_term, second_term)]
while term_pair_queue:
first_term, second_term = term_pair_queue.pop(0)
if isinstance(first_term, tuple) and isinstance(second_term, tuple):
... |
def split_multimac(devices):
"""
Router can group device that uses dynamic mac addresses into a single device.
This function splits them into separate items.
"""
split_devices = []
for device in devices:
if ',' not in device['mac']:
split_devices.append(device)
... |
def check_alphabet(sequence):
"""Function that takes as input a sequence and it will check that there is at least a letter matching the alphabet
in the sequence, returning true."""
code = "ATCG"
for base in sequence:
if base in code:
return(True)
return(False) |
def str2dict(string):
"""Transform a string to a dictionary"""
dictionary = {}
string_list = string.split(',')
for item in string_list:
result = item.split('=')
dictionary.update({result[0]: result[1]})
return dictionary |
def _to_rv_feature(annotation: dict, class_map: dict) -> dict:
"""Convert the geojson from Raster Foundry's API into the minimum dict required by Raster Vision
"""
return {
"geometry": annotation["geometry"],
"properties": {"class_id": class_map[annotation["properties"]["label"]]},
} |
def shortest_mesh_path_length(source, destination):
"""Get the length of a shortest path from source to destination without
using wrap-around links.
Parameters
----------
source : (x, y, z)
destination : (x, y, z)
Returns
-------
int
"""
x, y, z = (d - s for s, d in zip(sou... |
def puzzle_to_list(puzzle):
"""
Converts a two dimensional puzzle to a one dimensional puzzle.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] --> [1, 2, 3, 4, 5, 6, 7, 8, 0]
"""
lst = []
for row in puzzle:
lst.extend(row)
return lst |
def _vec_vec_elem_mul_fp(x, y):
"""Multiply two vectors element wise."""
return [a * b for a, b in zip(x, y)] |
def normalize(reg_string, prefer_spaces=True, ret_string=False):
"""Make sure everything is lowercase and remove _ and -"""
space = " " if prefer_spaces else ""
result = [
x
for x in reg_string.lower()
.replace("_", " ")
.replace("/", " ")
.replace("-", space)
... |
def import_object(name):
"""Imports an object by name.
import_object('x.y.z') is equivalent to 'from x.y import z'.
"""
parts = name.split('.')
m = '.'.join(parts[:-1])
attr = parts[-1]
obj = __import__(m, None, None, [attr], 0)
try:
return getattr(obj, attr)
except Attribu... |
def get_query_param_set(params):
"""
Strip, lowercase, and remove empty params to be used in a query
"""
param_set = params.strip().lower().split(" ")
param_set = [p for p in param_set if len(p) > 0]
return param_set |
def exp_requirement(level):
""" EXP required to level up from level. """
return 1000 * (level + 1) |
def _normalize_module_set(argument):
""" Split up argument via commas and make sure they have a valid value """
return set([module.strip() for module in argument.split(',')
if module.strip()]) |
def print_all(k):
"""Print all arguments of repeated calls.
>>> f = print_all(1)(2)(3)(4)(5)
1
2
3
4
5
"""
print(k)
return print_all |
def _listToPhrase(things, finalDelimiter, delimiter=', '):
"""
Produce a string containing each thing in C{things},
separated by a C{delimiter}, with the last couple being separated
by C{finalDelimiter}
@param things: The elements of the resulting phrase
@type things: L{list} or L{tuple}
@... |
def get_host_context(resp_host):
"""
Prepare host context data as per Demisto's standard.
:param resp_host: response from host command.
:return: Dictionary representing the Demisto standard host context.
"""
return {
'ID': resp_host.get('id', ''),
'Hostname': resp_host.get('host... |
def dataToBit(val, invert):
"""Return string representation of bit value. Converts common text values
to their bit equivalents, inverting them as required by the feed.
Keyword arguments:
val -- string value to convert
invert -- boolean check for whether to invert truthiness of value
"""
... |
def admin_command(sudo, command):
"""
If sudo is needed, make sure the command is prepended
correctly, otherwise return the command as it came.
:param sudo: A boolean representing the intention of having a sudo command
(or not)
:param command: A list of the actual command to execute... |
def compute_checksum(byte_array):
"""Compute FNV-1 checksum.
Args:
byte_array: list (int)
Each element represents a a byte
Returns:
integer Computed checksum
Raises:
Nothing
"""
checksum = 2166136261
for b in byte_array:
checksum = ((checksum ^... |
def parse_awards(movie):
"""
Convert awards information to a dictionnary for dataframe.
Keeping only Oscar, BAFTA, Golden Globe and Palme d'Or awards.
:param movie: movie dictionnary
:return: well-formated dictionnary with awards information
"""
awards_kept = ['Oscar', 'BAFTA Film Award', 'G... |
def pad(text, min_width, tabwidth=4):
"""
Fill the text with tabs at the end until the minimal width is reached.
"""
tab_count = ((min_width / tabwidth) - (len(text) / tabwidth)) + 1
return text + ('\t' * int(tab_count)) |
def mask_x_by_z(x, z):
"""
Given two arrays x and z of equal length, return a list of the
values from x excluding any where the corresponding value of z is
0.
:param x: Output values are taken from this array
:type x: :class:`~numpy.ndarray`
:param z: x[i] is excluded from the output if z[i... |
def list_to_dict(lista):
"""
Argument: list of objects.
Output: Dict where key is the ID, and value the hole object.
"""
ret = {}
try:
for obj in lista:
clave = obj.get('id')
if clave:
ret[clave] = obj
return ret
except Exceptio... |
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
return dna.count(nucleotide) |
def parsimony_informative_or_constant(numOccurences):
"""
Determines if a site is parsimony informative or constant.
A site is parsimony-informative if it contains at least two types of nucleotides
(or amino acids), and at least two of them occur with a minimum frequency of two.
https://www.megasof... |
def to_list(obj, key=None):
""" to_list(obj) returns obj if obj is a list, else [obj, ].
to_list(obj, key) returns to_list(obj[key]) if key is in obj,
else [].
"""
if key is None:
return obj if isinstance(obj, list) else [obj]
else:
return to_list(obj[key]) if key in obj else [] |
def op_has_scalar_output(input_shapes, optype, attr):
"""
TFLite uses [] to denote both scalars and unknown output shapes. Return True if an op can have scalar outputs
despite having non-scalar inputs. Otherwise, we will replace [] with None
"""
if optype in ["TFL_STRIDED_SLICE", "StridedSlice"]:
... |
def bin_to_int(x: str) -> int:
""" Convert from a binary string to a integer.
Parameters
----------
x: str
Binary string to convert.
Returns
-------
int
Corresponding integer.
"""
return int(x, 2) |
def collided_with_level(player_state, previous_position):
"""
Called whenever the player bumps into a wall.
Usually, you just want to set player_state["position"] = previous_position
:param player_state: Our state
:param previous_position: Where were we before be bumped into the wall?
:... |
def collect_like_terms(term_matrix):
"""
input is polynomial in form of term_matrix from poly_parser.py
output is another term_matrix with terms collected
term_matrix = [[" ", variable1, variable2...], [coefficient, exponent1, exponent2...],...]
"""
t = [term[:] for term in term_matrix]
for ... |
def _error_matches_criteria(error, criteria):
"""
Check if an error matches a set of criteria.
Args:
error:
The error to check.
criteria:
A list of key value pairs to check for in the error.
Returns:
A boolean indicating if the provided error matches the... |
def has_phrase(message: str, phrases: list):
""" returns true if the message contains one of the phrases
e.g. phrase = [["hey", "world"], ["hello", "world"]]
"""
result = False
for i in phrases:
# if message contains it
i = " ".join(i)
if i in message:
result = True
return result |
def reverse(sequence, keep_nterm=False):
"""
Create a decoy sequence by reversing the original one.
Parameters
----------
sequence : str
The initial sequence string.
keep_nterm : bool, optional
If :py:const:`True`, then the N-terminal residue will be kept.
Default is :py... |
def area_triangle(base, height):
"""
Calculate the area of a triangle.
param "base": width of the triangle base
param "height": height of the trianble
"""
return base*height/2 |
def _GetTimeDenom(ms):
"""Given a list of times (in milliseconds), find a sane time unit for them.
Returns the unit name, and `ms` normalized to that time unit.
>>> _GetTimeDenom([1, 2, 3])
('ms', [1.0, 2.0, 3.0])
>>> _GetTimeDenom([.1, .2, .3])
('us', [100.0, 200.0, 300.0])
"""
ms_mul = 1000 * 1000
... |
def apply_step_decay(params, t):
"""
Reduces the learning rate by some factor every few epochs.
Args:
params: parameters for the annealing
t: iteration number (or you can use number of epochs)
Returns:
Updated learning rate
"""
lr = params['curr_lr'] # current learning... |
def susceptibility_two_linear_known(freq_list, interaction_strength,
decay_rate):
""" In the linear regime for a two-level system, the suecpetibility is
known analytically. This is here for useful comparison, as good
agreement between a simulated weak field in a two-level system tells us
... |
def is_greetings(text):
"""
Checks if user is saying hi.
Parameters: text (string): user's speech
Returns: (bool)
"""
state = False
keyword = [
"hey",
"hello",
"hi",
"good morning",
"good afternoon",
"greetings"
]
for word in key... |
def month_to_foldername(month):
"""group months for folder structure"""
folder_name = " "
if month in [1,2,3]:
folder_name = "1-3"
if month in [4,5,6]:
folder_name = "4-6"
if month in [7,8,9]:
folder_name = "7-9"
if month in [10,11,12]:
folder_name = "10-12" ... |
def is_pretty_name_line(line):
"""Line from symbol table defines a simple symbol name (a pretty name)."""
return line.startswith('Pretty name') |
def inferGroup(titlebuffer):
"""infers the function prefix"""
if titlebuffer:
if titlebuffer[0] == "*":
return "*var*"
if titlebuffer[0] in ["-", "_"]: #["*", "-", "_"]
#strip first letter
titlebuffer = titlebuffer[1:]
if titlebuffer.startswith("glfw"):
return "glfw:"
idx = titlebuffer.rfind(":... |
def isinstance_namedtuple(obj) -> bool:
"""
Based on https://stackoverflow.com/a/49325922/7127824 and https://github.com/Hydrospheredata/hydro-serving-sdk/pull/51
The main use is to check for namedtuples returned by pandas.DataFrame.itertuples()
:param obj: any object
:return: bool if object is an ... |
def split(path):
"""Parse a full path and return the collection and the resource name
If the path ends by a '/' that's a collection
:param path: a path in the collection
:type path: str
:return: a pair with the collection name and the resource/collection name
:type: tuple
"""
if pa... |
def plural(x):
"""
Returns an 's' if plural
Useful in print statements to avoid something like 'point(s)'
"""
if x > 1:
return 's'
return '' |
def str_to_bool(v):
""" From http://stackoverflow.com/questions/715417/converting-from-a-string-to-boolean-in-python """
return v.lower() in ["yes", "true", "t", "1"] |
def to_num(text):
"""
Convert a string to a number.
Returns an integer if the string represents an integer, a floating
point number if the string is a real number, or the string unchanged
otherwise.
"""
try:
return int(text)
except ValueError:
try:
return floa... |
def _verify_rank_feature(value, low, high):
"""
Rank features must be a positive non-zero float. Our features are scaled
from 0 to 100 for fair comparison.
"""
if value is None or value == 0:
return None
ceiling = min(value, high)
floor = max(low, ceiling)
return floor |
def _shape_repr(shape):
"""Return a platform independent representation of an array shape
Under Python 2, the `long` type introduces an 'L' suffix when using the
default %r format for tuples of integers (typically used to store the shape
of an array).
Under Windows 64 bit (and Python 2), the `long... |
def _get_ending_key(e):
"""
Generate a key to store repeats temporarily
"""
return ('ending',) |
def pv_grow_perpetuity(c,r,q):
"""Objective : estimate present value of a growthing perpetuity
r : discount rate
q : growth rate of perpetuity
c : period payment
formula : c/(r-g)
e.g.,
>>>pv_grow_perpetuity(30000,0.08,0.04)
750000.0
... |
def sort_ascending(p_files):
"""Sort files by file basename instead of file path.
Added March 2021 by P. de Dumast
"""
from operator import itemgetter
import os
path_basename = []
for f in p_files:
path_basename.append((os.path.basename(f), f))
path_basename = sorted(path_basena... |
def commafy(s):
"""
Returns a copy of s, with commas every 3 digits.
Example:
commafy('5341267') = '5,341,267'
Parameter s: string representing an integer
Precondition: s a string with only digits, not starting with 0
"""
if len(s) <= 3:
return s
left = commafy(s[0:-3])... |
def _gettypenames(operands):
""" helper function to obtain type name dict from an input dict of operands """
return dict([(arg, type(operand).__name__) for arg, operand in operands.items()]) |
def underscore_escape(text):
"""
This function mimics the behaviour of underscore js escape function
The html escaped by jinja is not compatible for underscore unescape
function
:param text: input html text
:return: escaped text
"""
html_map = {
'&': "&",
'<': "<",... |
def parse_proc_load_avg(stdout:str, stderr:str, exitcode:int) -> dict:
"""
0.12 0.22 0.25 1/1048 16989
"""
if exitcode != 0:
raise Exception()
ret = stdout.strip().split(" ")
return {
"load1": float(ret[0]),
"load5": float(ret[1]),
"load15": float(ret[2]),
"processes_runnable": int(ret[3].split("/")[... |
def _convert_old_aldb_status(old_status):
"""Convert insteonplm ALDB load status to new ALDB load status.
Old status values:
EMPTY = 0
LOADING = 1
LOADED = 2
FAILED = 3
PARTIAL = 4
New status values:
EMPTY = 0
LOADED = 1
LOADING = 2
F... |
def add_commas(number):
"""
input: 4500
output: "4,500"
"""
number = str(number)
number = number[::-1] # Reverse number se we can add the commas
#ugliness
if len(number) < 4:
#Less than a thousand
return number[::-1]
if len(number) < 7:
#one comma to be adde... |
def format_exception(e):
""" Returns a string which includes both exception-type and its str() """
try:
exception_str = str(e)
except Exception:
try:
exception_str = repr(e)
except Exception:
exception_str = '(error formatting exception)'
return '%s - %s' ... |
def safe_divide(x, y):
"""Compute x / y, but return 0 if y is zero."""
if y == 0:
return 0
else:
return x / y |
def factorial_iter(n):
"""Nth number of factorial series by bottom-up DP w/ optimized space.
- Time complexity: O(n).
- Space complexity: O(1).
"""
f = 1
for k in range(2, n + 1):
f *= k
return f |
def bind(x, f):
"""
A monadic bind operation similar to Haskell's Maybe type. Used to enable function
composition where a function returning None indicates failure.
:param x: The input value passed to callable f is not None.
:param f: A callable which is passed 'x'
:return: If 'x' is None on in... |
def count_by(iterable, iteratee):
"""
Think of it like a harry potter sorting hat, tells you final number of students in every group.
Similar to group_by, instead of returning a list with every grouped_key, returns count of grouped elements only.
params: array, iteratee
iterable-> list, set, ge... |
def Status(state, health, health_rollup=None):
"""
Status based on Resource.Status in Resource.0.9.2 (Redfish)
"""
status = {'State': state, 'Health': health}
if health_rollup is not None:
status['HealthRollup'] = health_rollup
return status |
def get_bit(num: int, index: int) -> bool:
"""
Get the index-th bit of num.
"""
mask = 1 << index
return bool(num & mask) |
def PopulationDynamics(population, fitness):
"""Determines the distribution of species in the next generation."""
n = list(population)
L = len(population)
f = fitness(population)
for i in range(L): n[i] *= f[i]
N = sum(n)
if N == 0.0: return population
for i in range(L): n[i] /= N
... |
def there_are_only_spaces(string):
""" Check string for any character that is not a space. """
slist = list(string)
while len(slist) > 0:
char = slist.pop(0)
if char != ' ':
return False
return True |
def param_nully(value) -> bool:
"""Determine null-like values."""
if isinstance(value, str):
value = value.lower()
return value in [None, '', 'undefined', 'none', 'null', 'false'] |
def fitler_errors_from_input_data(data_to_valid,errors):
""" filter errors from the input data dict list
Parameters
----------
data_to_valid : list
A list of dict. It's the input_data that need validation
errors : dict
A dictinnary containing Schema.ValidationError error messa... |
def blend_color(a, b, ratio) -> tuple:
"""Blends and returns the mix of colors a and b to a given ratio.
Note: ratio argument must be a 3-float sequence."""
return (
int(a[0] + (b[0] - a[0]) * ratio[0]),
int(a[1] + (b[1] - a[1]) * ratio[1]),
int(a[2] + (b[2] - a[2]) * ratio[2])
... |
def split_dir_file(path):
"""
This function separates file path and file name
Parameters:
-----------
path: string
path of a file with file name
Returns:
--------
tuple
Returns a tuple of directory path and file name
Examples:
---------
>>> spli... |
def list_partial_strings(circuit):
"""
List the parial strings of circuit, that is,
the strings that are the slices circuit[0:n]
for 0 <= l <= len(circuit).
Parameters
----------
circuit : tuple of operation labels or Circuit
The operation sequence to act upon.
Returns
... |
def sort(seq):
"""
Takes a list of integers and sorts them in ascending order. This sorted
list is then returned.
:param seq: A list of integers
:rtype: A list of sorted integers
"""
gap = len(seq)
swap = True
while gap > 1 or swap:
gap = max(1, int(gap / 1.25))
sw... |
def check_citation_type(citation, violation_description):
"""A helper function used in filter_citations_by_type to extract the citation by desciprtion.
"""
#### EXERCISE: Implement boolean conditional checking against violation_description here
if citation['Violation Description']:
return citat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.