content stringlengths 42 6.51k |
|---|
def monte_carlo_sim(radius, inside, n):
"""
monte_carol_sim calculates pi using the monte carlo pi simulation equation
:param radius: radius of circle
:param inside: number of point to land inside the circle
:param n: total number of points during simulation
:return: estimated value of pi
"... |
def create_graph(num_islands, bridge_config):
"""
Helper function to create graph using adjacency list implementation
"""
# A graph can be represented as a adjacency_list, which is a list of blank lists
graph = [list() for _ in range(num_islands + 1)]
# populate the adjacency_list
for confi... |
def OverlapLength( left_string, right_string ):
"""Returns the length of the overlap between two strings.
Example: "foo baro" and "baro zoo" -> 4
"""
left_string_length = len( left_string )
right_string_length = len( right_string )
if not left_string_length or not right_string_length:
return 0
# Tru... |
def output_elems(elems, pnr, settings, fn):
"""
Generic function for output pnr elements like pnr['segment'].
All output functions get the same parameters.
"""
if not elems:
return None
out = []
out_append = out.append
for elem in elems:
if not elem:
contin... |
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
>>> from construct_check import check
>>> # ban iteration
>>> check(HW_SOURCE_FILE, 'count_c... |
def flatten(l, types=(list, float)):
"""
Flat nested list of lists into a single list.
"""
l = [item if isinstance(item, types) else [item] for item in l]
return [item for sublist in l for item in sublist] |
def find_adjacent(left, line):
"""
find the indices of the next set of adjacent 2048 numbers in the list
Args:
left: start index of the "left" value
line: the list of 2048 numbers
Returns:
left, right: indices of the next adjacent numbers in the list
if there are ... |
def forward_diff_y(rho, x, y, z, dt):
"""
Update equation for coordinate :math:`y`:
:math:`y[n+1] = (x[n](\\rho - z[n]) - y[n])t_{\\delta} + y[n]`
INPUT::
rho : float
Free parameter.
x : float
Current value of coordinate x (x[n]).
y : ... |
def _is_typing_type(field_type: type) -> bool:
"""Determine whether a type is a typing class."""
return hasattr(field_type, '_subs_tree') |
def get_primes(count):
"""
Return the 1st count prime integers.
"""
n = 0
result = []
if (count <= 0):
return result
for i in range(2, 9999):
c = 0
for j in range(1, i + 1):
if (i % j == 0):
c = c + 1
if (c == 2):
... |
def format_to_iso(date_string):
"""Formatting function to make sure the date string is in YYYY-MM-DDThh:mm:ssZ format.
Args:
date_string(str): a date string in ISO format could be like: YYYY-MM-DDThh:mm:ss+00:00 or: YYYY-MM-DDThh:mm:ss
Returns:
str. A date string in the format: YYYY-MM-DDT... |
def get_report_script_field(field_path, is_known=False):
"""
Generate a script field string for easier querying.
field_path: is the path.to.property.name in the _source
is_known: if true, then query as is, if false, then it's a dynamically mapped item,
so put on the #value property at the end.
"... |
def convex_hull(points):
"""Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically smallest coordinates.
Impl... |
def _normalize_pkg_style(style):
"""
Internally, zip and fastzip internally behave similar to how an
`inplace` python binary behaves in OSS Buck.
"""
if style and style in ("zip", "fastzip"):
return "inplace"
else:
return "standalone" |
def stairmaster_mets(setting):
"""
For use in submaximal tests on the StairMaster 4000 PT step ergometer.
Howley, Edward T., Dennis L. Colacino, and Thomas C. Swensen. "Factors Affecting the Oxygen Cost of Stepping on an Electronic Stepping Ergometer." Medicine & Science in Sports & Exercise 24.9 (1992): n... |
def getUnigram(str1):
"""
Input: a list of words, e.g., ['I', 'am', 'Denny']
Output: a list of unigram
"""
words = str1.split()
assert type(words) == list
return words |
def valid_sec(string):
"""Check if string is a valid IP address section"""
if len(string) == 0:
return False
num = int(string)
if string != str(num):
# invalid string like "000" -- only one "0" is okay
return False
return num >= 0 and num <= 255 |
def prepare_query(query, params):
"""Replace template query {parameter}s with the
values provided in the dictionary
"""
return query.format(**params) |
def choose(nval, kval):
""" Requires nval >= kval
build n choose k dict of results up to n val + 1
choose[n, k] is equal to n choose k
"""
assert(nval >= kval)
choose = dict()
for n in range(nval + 1):
choose[n, 0] = 1
choose[n, n] = 1
for k in range(1, n)... |
def double_and_make_even(value):
"""multiply a number by 2 and make it even
"""
double = value * 2
return double if double % 2 == 0 else double + 1 |
def persentage(now, before):
"""
given two data points it returns the percentage of the difference
"""
part = now - before;
if (before):
return 100 * float(part) / float(before)
else:
return 0 |
def _is_list_like(o) -> bool:
"""
returns True if o is either a list, a set or a tuple
that way we could accept ['AAPL', 'GOOG'] or ('AAPL', 'GOOG') etc.
"""
return isinstance(o, (list, set, tuple)) |
def pick_n_equispaced(l, n):
"""Picks out n points out of list, at roughly equal intervals."""
assert len(l) >= n
r = (len(l) - n)/float(n)
result = []
pos = r
while pos < len(l):
result.append(l[int(pos)])
pos += 1+r
return result |
def GSUtilGetMetadataField(name, provider_prefix=None):
"""Returns: (str) the metadata field to use with Google Storage
The Google Storage specification for metadata can be found at:
https://developers.google.com/storage/docs/gsutil/addlhelp/WorkingWithObjectMetadata
"""
# Already contains custom provider pr... |
def Add(xs, **unused_kwargs):
"""Adds two tensors."""
return xs[0] + xs[1] |
def split_negations(iterable, func=str):
""""Split an iterable into negative and positive elements.
Args:
iterable: iterable targeted for splitting
func: wrapper method to modify tokens
Returns:
Tuple containing negative and positive element tuples, respectively.
"""
neg, p... |
def get_closest_index(i1, i2, T, t0):
""" Returns the index i such that abs(T[i]-t0) is minimum for i1,i2 """
if abs(T[i1]-t0) <= abs(T[i2]-t0):
return i1
else:
return i2 |
def cbsa_to_location_id(cbsa_code: str) -> str:
"""Turns a CBSA code into a location_id.
For information about how these identifiers are brought into the CAN code see
https://github.com/covid-projections/covid-data-public/tree/main/data/census-msa
"""
return f"iso1:us#cbsa:{cbsa_code}" |
def basename(pathname,level=0):
"""Ending part of a pathanme.
level: how mane directories levels to include"""
from os.path import basename,dirname
s = basename(pathname)
for i in range(0,level):
pathname = dirname(pathname)
s = basename(pathname)+"/"+s
return s |
def decode_utf8(msg):
"""
Py2 / Py3 decode
"""
try:
return msg.decode('utf8')
except AttributeError:
return msg |
def validate_entrypoints(entrypoints):
"""Check that the loaded entrypoints are valid.
Expects a dict of dicts, e.g.::
{'console_scripts': {'flit': 'flit:main'}}
"""
def _is_identifier_attr(s):
return all(n.isidentifier() for n in s.split('.'))
problems = []
for groupname, gr... |
def _segment_intersect_border(line1, lim_x=None, lim_y=None):
""" Instead of using shapely just adapt the simplest code snipplet kindly
posted by Stackoverflow users Paul Draper and zidik.
https://stackoverflow.com/a/20677983
"""
x1, y1 = line1[0]
x2, y2 = line1[1]
dx = x2-x1
dy = y... |
def save_file_in_path(file_path, content):
"""Write the content in a file
"""
try:
with open(file_path, 'w', encoding="utf-8") as f:
f.write(content)
except Exception as err:
print(err)
return None
return file_path |
def is_private(obj):
"""Return True if object is private."""
if obj is not None:
return isinstance(obj, str) and obj.startswith('_') |
def module_parent_packages(full_modname):
"""
Return list of parent package names.
'aaa.bb.c.dddd' -> ['aaa', 'aaa.bb', 'aaa.bb.c']
:param full_modname: Full name of a module.
:return: List of parent module names.
"""
prefix = ''
parents = []
# Ignore the last component in modul... |
def common_suffix_length(text1, text2):
"""Determine the common suffix of two strings.
Args:
text1: First string.
text2: Second string.
Returns:
The number of characters common to the end of each string.
"""
# Quick check for common null cases.
if not text1 or not text2... |
def get_participation_score(user_posts, all_posts, num_all_users):
"""
Function to calculate the relative participation score
:param user_posts: (list) posts of a user
:param all_posts: (list) all posts
:param num_all_users: (int) number of users
:return: (number) participation score
"""
... |
def last_4(secret):
"""Returns an abbreviation of the input"""
return '*'+str(secret)[-4:] |
def nodes_in_solution(input_nodes, mwis):
"""Get the nodes in the minimum weight independent set
"""
i = len(mwis)
in_val = set()
while i >= 1:
wis_prime = mwis[i - 2]
wis_prime2 = mwis[i - 1]
if wis_prime >= wis_prime2:
i -= 1
else:
# vertex_w... |
def upper(word: str) -> str:
"""
Will convert the entire string to uppercase letters
>>> upper("wow")
'WOW'
>>> upper("Hello")
'HELLO'
>>> upper("WHAT")
'WHAT'
>>> upper("wh[]32")
'WH[]32'
"""
# Converting to ascii value int value and checking to see if char is a lower ... |
def oauth_headers(access_token):
"""Return valid authorization headers given the provided OAuth access token"""
return {"Authorization": f"Bearer {access_token}"} |
def calculate_mean(values):
"""
Calculates mean of given values
:param values: values to calculate mean of
:return: mean of values
"""
return sum(values) / len(values) |
def __rred(r_1, r_2):
"""
Calculate the reduced (effective) radius of two radii according to Hertzian
contact theory.
Parameters
----------
r_1: scalar
The first radius.
r_2: scalar
The second radius.
Returns
-------
r_red: scalar
The reduced (effective... |
def split(f):
"""
Split a polynomial f in two polynomials.
Input:
f A polynomial
Output:
f0, f1 Two polynomials
Format: Coefficient
"""
n = len(f)
f0 = [f[2 * i + 0] for i in range(n // 2)]
f1 = [f[2 * i + 1] for i in range(n // 2)]
return [f0, f1] |
def search_dict_tree(d, key):
"""traverse dict tree and find search key"""
if isinstance(d, dict):
for v in d:
if v == key:
return d[v]
s = search_dict_tree(d[v], key)
if isinstance(s, dict) or isinstance(s, list):
return s
elif isi... |
def dist_rgb(rgb1, rgb2):
"""
Determine distance between two rgb colors.
:arg tuple rgb1: RGB color definition
:arg tuple rgb2: RGB color definition
:returns: Square of the distance between provided colors
:rtype: float
This works by treating RGB colors as coordinates in three dimensional
... |
def get_examples(data, attr, value):
"""
Returns a list of all the records in <data> with the value of <attr>
matching the given value.
"""
data = data[:]
rtn_lst = []
if not data:
return rtn_lst
else:
record = data.pop()
if record[attr] == value:
... |
def GetIndexFileHeaderText(headerinfo):#{{{
"""
Get the header information of the index file in ASCII format
"""
(dbname, version, ext, prefix) = headerinfo
indexFileHeaderText = []
indexFileHeaderText.append("DEF_VERSION %s"%(version))
indexFileHeaderText.append("DEF_DBNAME %s"%(dbname))
... |
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided assume ve... |
def get_perms(s, i=0):
"""
Returns a list of all (len(s) - i)! permutations t of s where t[:i] = s[:i].
"""
# To avoid memory allocations for intermediate strings, use a list of chars.
if isinstance(s, str):
s = list(s)
# Base Case: 0! = 1! = 1.
# Store the only permutation as an im... |
def build_canonical_request(canonical_querystring):
"""
builds canonical request for Product Advertising
http://webservices.amazon.com/onca/xml?
"""
method = 'GET'
host = 'webservices.amazon.com'
canonical_uri = '/onca/xml'
# create full canonical request based on previously set variable... |
def obter_idade(ani):
""" obter_idade: animal --> int
Recebe um animal e devolve um inteiro correspondendo ao valor da idade do mesmo
"""
return ani['r'][0] |
def search(value, node):
"""
Search for element in the linked list
:param value: value to look for
:param node: value of head node, start of list
:return: bool: weather or not element is in the list
"""
if node is not None: # iterate through while valid nodes
if node.value == value... |
def dsigmoid(sigmoid_x):
"""
dSigmoid(x) = Sigmoid(x) * (1-Sigmoid(x)) = Sigmoid(x) - Sigmoid(x)^2
"""
return sigmoid_x - sigmoid_x**2 |
def average_sub_key(batch_list, key, sub_key):
"""
Average subkey in a dictionary in a list of batches
Parameters
----------
batch_list : list of dict
List containing dictionaries with the same keys
key : str
Key to be averaged
sub_key :
Sub key to be averaged (belon... |
def p1_f_quadratic(x):
"""DocTest module Expected Output Test - don't change or delete these lines
>>> x = [565, 872, 711, 964, 340, 761, 2, 233, 562, 854]
>>> print("The minimum is: ", p1_f_quadratic(x))
The minimum is: 2
"""
# Given in the problem
min = x[0]
l = len(x)
... |
def merge(dest, src):
"""Merge plain objects without mutation."""
if isinstance(dest, dict) and isinstance(src, dict):
dest = dest.copy()
src = src.copy()
dest_keys = list(dest.keys())
for key in dest_keys:
if key in src:
dest[key] = merge(dest[key], s... |
def _extractDataSets(config):
"""
Extract only the parameters from the configuration.
:param config: dict of the complete configuration
:return: dict of just the parameters.
"""
parameters = {}
for key in config:
if key != 'identifier':
values = config[key]
p... |
def create_message(events):
"""
Build the message body. The first event's timestamp is included
in the message body as well. When sending this email to an SMS bridge,
sometimes the time that the SMS is received is well after the event occurred
and there is no clear way to know when the message was... |
def itraceToList( trace ):
""" Converts an instruction trace into list """
traceList = []
for i in trace:
traceList.append(i[0])
return traceList |
def delete_item(category_id):
"""input delete category from DynamoDB"""
return dict(Key={"PK": category_id, "SK": category_id}) |
def hms(s):
"""
conversion of seconds into hours, minutes and secondes
:param s:
:return: int, int, float
"""
h = int(s) // 3600
s %= 3600
m = int(s) // 60
s %= 60
return '{:d}:{:d}:{:.2f}'.format(h, m, s) |
def get_endpoint_region(endpoint):
"""Common function for getting the region from endpoint.
In Keystone V3, region has been deprecated in favor of
region_id.
This method provides a way to get region that works for both
Keystone V2 and V3.
"""
return endpoint.get('region_id') or endpoint.ge... |
def full_board_check(board):
"""Returns boolean value whether the game board is full of game marks."""
return len(set(board)) == 2 |
def insert_index(array):
"""
add first column to 2D array with index
:param
array: array to which we want to add index
:return:
array with indexes in in first column
"""
for i in range(len(array)):
array[i].insert(0, i)
return array |
def string_to_hexstring(the_input):
""" Take in a string, and return the hex string of the bytes corresponding to it. While the hexlify() command will do this for you, we ask that you instead solve this question by combining the methods you have written so far in this assignment.
Example test case: "puzzle" ->... |
def classdot2func(path):
""" Convert a path such as 'android.support.v4.app.ActivityCompat'
into a method string 'CLASS_Landroid_support_v4_app_ActivityCompat'
so we can call d.CLASS_Landroid_support_v4_app_ActivityCompat.get_source()
"""
func = "CLASS_L" + path.replace(".", "_").replace("$... |
def de_blank(val):
"""Remove blank elements in `val` and return `ret`"""
ret = list(val)
if type(val) == list:
for idx, item in enumerate(val):
if item.strip() == '':
ret.remove(item)
else:
ret[idx] = item.strip()
return ret |
def repr_regdoc(regdoc, show_metadata=False, show_id=True):
"""
Represent discovery.registry.common.RegistryDocument
in web-annotation-endpoint-style dictionary structure.
>> regdoc
{
"_id": <_id>
...
}
>> regdoc.meta
{
"use... |
def makeNormalizedData(data, newCol, defaultVal = 0):
"""
Ensure that all of the labels in newCol exist in data
"""
for item in data:
for key in newCol:
if (key not in item):
item[key] = defaultVal
return data |
def get_acmodel(core_data):
""" gets the aircraft model from core data """
if core_data != 'error':
try:
# renames paramater
data = core_data[1]
if data.find('strong'):
acmodel = data.strong.text.strip()
# brea... |
def get_minimum_with_tolerance(value, tolerance):
"""Helper function that takes a value and applies the tolerance
below the value
Args:
value: a float representing the mean value to which the tolerance
will be applied
tolerance: a float representing a percentage (between 0.0 ... |
def is_template_param(param):
""" Identifies if the parameter should be included in an input template
and returns the default value of the parameter if it exists.
"""
start = 0
ptype = 'local'
if isinstance(param, str):
param = param.strip()
if not param.split('global')[0]:
... |
def users_from_passwd(raw):
""" Extracts a list of users from a passwd type file. """
users = list()
for line in raw.split('\n'):
tmp = line.split(':')[0]
if len(tmp) > 0:
users.append(tmp)
return sorted(users) |
def color_rgb(r,g,b):
"""r,g,b are intensities of red, green, and blue in range(256)
Returns color specifier string for the resulting color"""
return "#%02x%02x%02x" % (r,g,b) |
def _qt(add_row, secondary_dict_ptr, cols, key):
"""
This sub-function is called by view_utils.qt to add keys to the secondary_dict and
is NOT meant to be called directly.
"""
if cols[key]:
if cols[key] in secondary_dict_ptr:
return add_row, secondary_dict_ptr[cols[key]]
... |
def _resolve_next(o):
"""returns the next element if an iterable or return itself otherwise. list should be passed using cycle(list)"""
if hasattr(o, '__next__'):
return next(o)
return o |
def metal_kewley08_pp04(logM):
"""
This function calculate the 12+log(O/H) from the stellar mass.
The equation come from Kewley & Ellison, ApJ, 681, 1183, 2008.
The 12+log(O/H) is obtained from PP04 (N2) method. The rms
residual is 0.09 dex.
Parameters
----------
logM : float
... |
def build_response(content):
"""Builds bot response
"""
response = content
response += "\n***\n^(I am a bot and I byte | [source](https://github.com/jasmaa/shiritori-bot))"
return response |
def SLICE(array, n, position=None):
"""
Returns a subset of an array.
See https://docs.mongodb.com/manual/reference/operator/aggregation/slice/
for more details
:param array: Any valid expression as long as it resolves to an array.
:param n: Any valid expression as long as it resolves to an inte... |
def eval_order(pred, gold):
"""
Args:
Returns:
"""
pred_total = gold_total = cnt = 0
if len(pred['orderBy']) > 0:
pred_total = 1
if len(gold['orderBy']) > 0:
gold_total = 1
if len(gold['orderBy']) > 0 and pred['orderBy'] == gold['orderBy'] and pred['limit'] == gold['lim... |
def get_permutations(string):
"""Return all permutations of the string"""
if len(string) == 0:
return []
elif len(string) == 1:
return string
else:
ls = []
for i in range(len(string)):
starting_letter = string[i]
rest = string[:i] + string[i+1:]
... |
def filter_none(kwargs):
"""
Remove all `None` values froma given dict. SQLAlchemy does not
like to have values that are None passed to it.
:param kwargs: Dict to filter
:return: Dict without any 'None' values
"""
n_kwargs = {}
for k, v in kwargs.items():
if v:
n_kwa... |
def load_options(target="cpu", device_id=0, exec_kind="vm"):
"""Format options for relay."""
return {"target": target, "device_id": device_id, "exec_kind": exec_kind} |
def _get_cached_func_name_md(func):
"""Get markdown representation of the function name."""
if hasattr(func, "__name__"):
return "`%s()`" % func.__name__
else:
return "a cached function" |
def str_or_none(item, encoding='utf-8'):
"""
Return the str of the value if it's not None
"""
if item is None:
return None
else:
# return item if it's str, if not, decode it using encoding
if isinstance(item, str):
return item
return str(item, encoding) |
def arcs_valueCheck(value):
"""Validate applyFlatBPMConfig.arcs"""
return len(value) == 2 and isinstance(
value[0], str) and isinstance(
value[1], str) |
def unquote(word, quotes='\'"'):
"""removes quotes from both sides of the word.
The quotes should occur on both sides of the word:
>>> unquote('"hello"')
'hello'
If a quote occurs only on one side of the word, then
the word is left intact:
>>> unquote('"hello')
'"hello'
The quot... |
def get_content_type_name(index: int) -> str:
"""
Convert the index to a human interpretable string
:param index:
:return: String, that a human being will understand instead of the index
"""
return ["Post", "Story", "Video"][index - 1] |
def get_right_concern_value(dictionary, index):
"""
Returns the value of the right concern name of the pair found in dictionary with key = index.
This is a special filter which is used only in extracting the right concern name of the dictionary.
The dictionary name used is "concerns_data_in_pairs" whic... |
def get_8760_hrs_from_yeardays(yeardays):
"""Get from yeadays all yearhours
Arguments
---------
yeardays : list
Listh with year days (0 - 364)
Returns
---------
year_hrs : list
All year hours (0 - 8759)
"""
year_hrs = []
for day in yeardays:
hrs = list(r... |
def arbg_int_to_rgba(argb_int):
"""Convert ARGB integer to RGBA array."""
red = (argb_int >> 16) & 255
green = (argb_int >> 8) & 255
blue = argb_int & 255
alpha = (argb_int >> 24) & 255
return [red, green, blue, alpha] |
def get_update_set(index, n_qubits):
"""Make update set"""
if index >= n_qubits:
raise ValueError("`index` < `n_qubits` is required.")
n = 1
while n < n_qubits:
n *= 2
def get(n, j):
if n <= 1:
return set()
n_half = n // 2
if j < n_half:
... |
def clip(val, minval, maxval):
"""clip val between minval,maxval"""
return max(min(maxval, val), minval) |
def constantize(term):
"""Formats a term (string) to look like a Constant."""
# Replace spaces by underscores and enclose in quotes for a Constant term
return f"'{term.replace(' ', '_')}'" |
def tabela_joc(cond):
"""
Functie ce defineste partea grafica a jocului de SPANZURATOAREA
:param cond: de la 0 la 7 in functie de modul in care se desfasoara jocul
:return: cond
"""
if cond == 6:
print(" ---------- \n | 6 | \n | \n | \n | \n | \n | _____________ ")
elif cond ==... |
def check_complete_pairs(twin_ids, available_files):
"""Check which twin pairs have both sets of subject data available.
Parameters
----------
twin_ids : list of tuple of (int, int)
Twin ID pairs.
available_files : list of int
All subject data files that are available.
Returns
... |
def invert_float(parser, arg):
"""
Check if argument is float or auto.
"""
if arg != 'auto':
try:
arg = float(arg)
except parser.error:
parser.error('Value {0} is not a float or "auto"'.format(arg))
if arg != 'auto':
arg = 1.0 / arg
return arg |
def loadJson(jsonfile):
"""
Reads a .json file into a python dictionary.
Requires json package.
"""
import json
with open(jsonfile, "r") as data:
dictname = json.loads(data.read())
return dictname |
def str2bool(boolean):
"""Convert a string to boolean.
Args:
boolean (str): Input string.
Returns:
return (bool): Converted string.
"""
if boolean.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif boolean.lower() in ('no', 'false', 'f', 'n', '0'):
retu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.