content stringlengths 42 6.51k |
|---|
def B(i,j,k):
"""
Tensor B used in constructing ROMs.
Parameters
----------
i : int
j : int
k : int
Indices in the tensor.
Returns
-------
int
Tensor output.
"""
if i == j + k:
return -1
elif j == i + k or k == i + j:
return 1
el... |
def filter_list_to_filter_policies(event_key: str, filter_list: list) -> dict:
"""
Helper function to convert defined filter policies to
AWS API acceptable format.
"""
processed_filters = []
for filters in filter_list:
event = filters.split(".")
assert len(event) == 2
i... |
def fail(error_msg):
"""
Create failure response
:param error_msg:
:return:
"""
return {'status': 'failure', 'error_msg': error_msg} |
def ssh_cmd_task_exec(detail, command_on_docker, wait_press_key=None) -> str:
"""SSH command to execute a command inside the first docker containter of a task."""
wait_cmd = ""
if wait_press_key:
wait_cmd = "; echo 'Press a key'; read q"
return (
f"TERM=xterm ssh -t {detail['ec2InstanceI... |
def oneHotEncode_4_evtypes_tau_decay_length(x, r_vals):
"""
This function one hot encodes the input for the event types
cascade, tracks, doubel-bang, starting tracks
"""
cascade = [1., 0., 0., 0.]
track = [0., 1., 0., 0.]
doublebang = [0., 0., 1., 0.]
s_track = [0., 0., 0., 1.]
cut ... |
def tsp_not_return(num_vertex, distances, from_start=None):
"""
from_start: distance from a virtual start vertex (PAST3M)
"""
assert num_vertex < 20
if from_start == None:
from_start = [0] * num_vertex
INF = 9223372036854775807
SUBSETS = 2 ** num_vertex
memo = [[INF] * num_verte... |
def split_digits(n1, n2):
"""Takes two numbers and returns them as lists of integer digits"""
num1 = [int(d) for d in str(n1)]
num2 = [int(d) for d in str(n2)]
return num1, num2 |
def parse_connection_string(connect_str):
"""Parse a connection string such as those provided by the Azure portal.
Connection string should be formatted like:
Key=Value;Key=Value;Key=Value
The connection string will be parsed into a dictionary.
:param connect_str: The connection string.
:type ... |
def get_lemma_mapping(word_pairs):
"""Get a dictionary that stores all orthographic
forms for a lemma.
Args:
word_pairs (Array) - a list of all word_pairs
Returns:
Dictionary - All lemma - word combinations
"""
# Initialize dictionaries that hold the
# mapping of a lemma t... |
def return_position_str(position_tuple):
"""Conversion of position-tuple to str if entries are "None" they are set to "-1"
"""
if position_tuple[1] is None:
return "{};{};{}".format(position_tuple[0], -1, -1)
else:
return "{};{};{:.3f}".format(position_tuple[0], position_tuple[1], positi... |
def reformat_asterisks(text):
"""
Fixes Pandas docstring warning about using * and ** without ending \* and \*\*.
The fix distinguishes single * and ** by adding \\ to them. No changes for *italic* and **bold** usages.
:param text: Original text with warnings
:return: Modified text that fixes warn... |
def getChunkIndex(chunk_id):
""" given a chunk_id (e.g.: c-12345678-1234-1234-1234-1234567890ab_6_4)
return the coordinates of the chunk. In this case (6,4)
"""
# go to the first underscore
n = chunk_id.find('_') + 1
if n == 0:
raise ValueError("Invalid chunk_id: {}".format(chunk_id))
... |
def MakeCallString(params):
"""Given a list of (name, type, vectorSize) parameters, make a C-style
formal parameter string.
Ex return: 'index, x, y, z'.
"""
result = ''
i = 1
n = len(params)
for (name, type, vecSize) in params:
result += name
if i < n:
result = result + ', '
i += 1
#endfor
return res... |
def revcomp(seq):
""" Reverse complement sequence
Args:
seq: string from alphabet {A,T,C,G,N}
Returns:
reverse complement of seq
"""
complement = {
'A':'T',
'T':'A',
'G':'C',
'C':'G',
'N':'N',
'R':'N',
'Y':'N',
'K':'N',
'M':'N',
'S':'N',
'W':'N',
'B':'N',
'D':'N',
'H':'N',
'V':'... |
def exclusion_filter(exclude: str):
"""Converts a filter string "*.abc;*.def" to a function that can be passed to pack().
If 'exclude' is None or an empty string, returns None (which means "no filtering").
"""
if not exclude:
return None
import re
import fnmatch
# convert string ... |
def get_workflow_wall_time(workflow_states_list):
"""
Utility method for returning the workflow wall time given all the workflow states
@worklow_states_list list of all workflow states.
"""
workflow_wall_time = None
workflow_start_event_count = 0
workflow_end_event_count = 0
is_end = False
workflow_start_cum ... |
def lowercase(text: str) -> str:
"""Transforms text to lower case"""
return text.lower() |
def load_str(filename: str, method="read") -> str:
"""Loads a file to string"""
with open(filename, "r") as f:
return getattr(f, method)() |
def protoc_command(args):
"""Composes the initial protoc command-line including its include path."""
cmd = [args.protoc]
if args.include is not None:
cmd.extend(['-I%s' % path for path in args.include])
return cmd |
def enclose_string(text):
"""enclose text with either double-quote or triple double-quote
Parameters
----------
text (str): a text
Returns
-------
str: a new string with enclosed double-quote or triple double-quote
"""
text = str(text)
fmt = '"""{}"""' if len(text.splitlines())... |
def make_optic_canula_cylinder(
atlas,
root,
target_region=None,
pos=None,
offsets=(0, 0, -500),
hemisphere="right",
color="powderblue",
radius=350,
alpha=0.5,
**kwargs,
):
"""
Creates a cylindrical vedo actor to scene to render optic cannulas. By default
thi... |
def parse_ellipsis(index):
"""
Helper to split a slice into parts left and right of Ellipses.
:param index: A tuple, or other object (None, int, slice, Funsor).
:returns: a pair of tuples ``left, right``.
:rtype: tuple
"""
if not isinstance(index, tuple):
index = (index,)
left =... |
def consecutive_seconds(rel_seconds, window_size_sec, stride_sec=1):
"""
Return a list of all the possible [window_start, window_end] pairs
containing consecutive seconds of length window_size_sec inside.
Args:
rel_seconds: a list of qualified seconds
window_size_sec: int
st... |
def solution(number):
"""This function returns all multiples of 3 and 5 below the input number"""
answer = 0
for i in range(number):
if i % 3 == 0 or i % 5 == 0:
answer += i
return answer |
def _mel2hz(mel):
"""Convert a value in Mels to Hertz
:param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
:returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
"""
return 700 * (10 ** (mel / 2595.0) - 1) |
def _is_sub_partition(sets, other_sets):
"""
Checks if all the sets in one list are subsets of one set in another list.
Used by get_ranked_trajectory_partitions
Parameters
----------
sets : list of python sets
partition to check
other_sets : list of python sets
partition to ... |
def enc(text):
"""Yes a bodge function. Get over it."""
try:
return text.decode("utf-8")
except UnicodeEncodeError:
try:
return text.encode("utf-8")
except UnicodeEncodeError:
return text |
def getDuration(results) :
"""Returns the first timestamp of the simulation after the prepull and the
duration of the simulation after the prepull
"""
timestamps = [ r['timestamp'] for r in results if 'damage' in r and 'timestamp' in r ]
return (min(timestamps), max(timestamps) - min(timestamps)) |
def fix_dec(x):
"""
TLE formate assumes a leading decimal point, just putting it back in
"""
if x[0] == "-":
ret = float("-0." + x[1:])
else:
ret = float("0." + x)
return ret |
def freeRotor(pivots, top, symmetry):
"""Read a free rotor directive, and return the attributes in a list"""
return [pivots, top, symmetry] |
def py_type_name(type_name):
"""Get the Python type name for a given model type.
>>> py_type_name('list')
'list'
>>> py_type_name('structure')
'dict'
:rtype: string
"""
return {
'blob': 'bytes',
'character': 'string',
'double': 'float',
'... |
def prefix_max(array: list, i: int) -> int:
"""Return index of maximum item in array[:i+1]"""
if i >= 1:
j = prefix_max(array, i-1)
if array[i] < array[j]:
return j
return i |
def join_genres(genres):
"""Trim and join genres to 255 characters."""
return ';'.join(genres)[:255] |
def strip_lines(text):
"""
Given text, try remove unnecesary spaces and
put text in one unique line.
"""
output = text.replace("\r\n", " ")
output = output.replace("\r", " ")
output = output.replace("\n", " ")
return output.strip() |
def find_secondary_lithology(tokens_and_primary, lithologies_adjective_dict, lithologies_dict):
"""Find a secondary lithology in a tokenised sentence.
Args:
tokens_and_primary (tuple ([str],str): tokens and the primary lithology
lithologies_adjective_dict (dict): dictionary, where keys are exac... |
def isStablePile(a):
"""Returns true is a is stable, false otherwise"""
false_count = 0
for row in a:
for column in row:
if column > 3:
false_count += 1
if false_count > 0:
return False
else:
return True |
def add (mean1, var1, mean2, var2):
""" add the Gaussians (mean1, var1) with (mean2, var2) and return the
results as a tuple (mean,var).
var1 and var2 are variances - sigma squared in the usual parlance.
"""
return (mean1+mean2, var1+var2) |
def _split(container, count):
"""
Simple function splitting a container into equal length chunks.
Order is not preserved but this is potentially an advantage depending on
the use case.
"""
return [container[_i::count] for _i in range(count)] |
def gulpease_index(words, letters, points):
"""
As written in https://it.wikipedia.org/wiki/Indice_Gulpease
"""
index = 89 + ((300 * points) - (10 * letters)) / words
return 100 if index > 100 else index |
def _get_file_contents(file_path: str) -> str:
"""Get contents of a text file."""
with open(file_path, 'r') as fdes:
return fdes.read() |
def _get_tensor_name(node_name, output_slot):
"""Get tensor name given node name and output slot index.
Parameters
----------
node_name : str
Name of the node that outputs the tensor, as a string.
output_slot : int
Output slot index of the tensor, as an integer.
Returns
--... |
def FindDuplicates(seq):
"""Identifies duplicates in a list.
Does not preserve element order.
@type seq: sequence
@param seq: Sequence with source elements
@rtype: list
@return: List of duplicate elements from seq
"""
dup = set()
seen = set()
for item in seq:
if item in seen:
dup.add(i... |
def clamp(value, minimum, maximum):
"""
Clamp a number between a minimum and a maximum.
:param value: value to be clamped
:param minimum: minimum value
:param maximum: maximum value
:return: the clamped value
"""
return max(minimum, min(value, maximum)) |
def calculateNetIncome(gross, state):
"""
Calculate the net income after federal and state tax
:param gross: Gross Income
:param state: State Name
:return: Net Income
"""
state_tax = {'LA': 10, 'SA': 0, 'NY': 9}
# Calculate net income after federal tax
net = gross - (gross * .10)
... |
def read_file(filename: str, offset: int, size: int) -> str:
"""Read the specified interval content of text file"""
with open(filename, 'r') as f:
f.seek(offset)
return f.read(size) |
def temperature_closest_to_zero(temperatures):
"""Receives an array of temperatures and returns the closest one to zero"""
closest_to_zero = temperatures[0]
for temperature in temperatures:
if (abs(temperature) < abs(closest_to_zero) or
(abs(temperature) == abs(closest_to_zero) and ... |
def merge_dicts(dict1, dict2):
""" _merge_dicts
Merges two dictionaries into one.
INPUTS
@dict1 [dict]: First dictionary to merge.
@dict2 [dict]: Second dictionary to merge.
RETURNS
@merged [dict]: Merged dictionary
"""
merged = {**dict1, **dict2}
return merged |
def tap_type_to_target_type(mongo_type):
"""Data type mapping from MongoDB to Postgres"""
return {
'string': 'CHARACTER VARYING',
'object': 'JSONB',
'array': 'JSONB',
'date': 'TIMESTAMP WITHOUT TIME ZONE',
'datetime': 'TIMESTAMP WITHOUT TIME ZONE',
'timestamp': 'T... |
def matrix_multiply(a, b):
"""
Multiply a matrix of any dimension by another matrix of any dimension.
:param a: Matrix as list of list
:param b: Matrix as list of list
:return:
"""
return [[sum(_a * _b for _a, _b in zip(a_row, b_col)) for b_col in zip(*b)] for a_row in a] |
def learner_name(learner):
"""Return the value of `learner.name` if it exists, or the learner's type
name otherwise"""
return getattr(learner, "name", type(learner).__name__) |
def parade_bias(p):
""" Model bias is negative of mean residual """
return [mj.get('mean') for mj in p['moments']] |
def is_dict(inst):
"""Returns whether or not the specified instance is a dict."""
return hasattr(inst, 'iteritems') |
def _safe_snr_calculation(s, n):
"""
Helper used in this module for all snr calculations. snr is
always defined as a ratio of signal amplitude divided by noise amplitude.
An issue is that with simulation data it is very common to have a noise
window that is pure zeros. If computed naively snr wo... |
def _roman(n):
"""Converts integer n to Roman numeral representation as a string"""
if not (1 <= n <= 5000):
raise ValueError(f"Can't represent {n} in Roman numerals")
roman_numerals = (
(1000, 'M'),
(900, 'CM'),
(500, 'D'),
(400, 'CD'),
(100, 'C'),
(9... |
def _af_rmul(a, b):
"""
Return the product b*a; input and output are array forms. The ith value
is a[b[i]].
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a,... |
def _parse_range_header(range_header):
"""Parse HTTP Range header.
Args:
range_header: A str representing the value of a range header as retrived
from Range or X-AppEngine-BlobRange.
Returns:
Tuple (start, end):
start: Start index of blob to retrieve. May be negative index.
end: None ... |
def serialize_length(l):
""" Returns minimal length prefix (note length prefix is not unique),
in new style."""
l = int(l)
if l < 0:
raise ValueError(l)
elif l < 192:
return bytes((l,))
elif l < 8384:
x = l - 192
b0 = (x >> 8) + 192
b1 = x & 0xff
r... |
def display_benign_list(value):
"""
Function that either displays the list of benign domains or hides them
depending on the position of the toggle switch.
Args:
value: Contains the value of the toggle switch.
Returns:
A dictionary that communicates with the Dash interf... |
def interpolate_force_line(form, x, tol=1E-6):
"""Interpolates a new point in a form polyline
Used by the `add_force_line` function"""
form_out = [form[0]]
for pt1, pt2 in zip(form[:-1], form[1:]):
if (x - pt1[0] > 0.5 * tol and
pt2[0] - x > 0.5 * tol):
y = pt1[1] + (x -... |
def replace_all(string: str, old: str, new: str) -> str:
"""Iteratively replace all instances of old with new
:param old: String to be acted upon
:param old: Substring to be replaced
:param new: String replacement
:returns: A copy of string with new replacing old
"""
if old in string:
... |
def filter_blocks(blocks):
"""Filter out spurious diffs caused by XML deserialization/serialization."""
new_blocks = []
for block in blocks:
if any(l.startswith('-<rdf:RDF') for l in block):
continue
if any(l.startswith('-<math') for l in block):
continue
if a... |
def _average(input_list: list) -> float:
"""
Find the average of a list.
Given a list of numbers, calculate the average of all values in the list.
If the list is empty, default to 0.0.
Parameters
----------
input_list : list
A ``list`` of ``floats`` to find an average of.
Retu... |
def updateBounds(bounds, p, min=min, max=max):
"""Add a point to a bounding rectangle.
Args:
bounds: A bounding rectangle expressed as a tuple
``(xMin, yMin, xMax, yMax)``.
p: A 2D tuple representing a point.
min,max: functions to compute the minimum and maximum.
Return... |
def _SumRows(*rows):
"""
BRIEF Total each of the columns for all the rows
"""
total = [0.0]*len(rows[0])
for row in rows:
for i, col in enumerate(row):
total[i] += col
return total |
def format_subject(subject):
# type: (str) -> str
"""
Escape CR and LF characters.
"""
return subject.replace('\n', '\\n').replace('\r', '\\r') |
def change_key_names(rows, changes):
"""
Renames the keys specified in rows
Where changes = {new:original, new:original}
"""
for row in rows:
for new, original in changes.items():
row[new] = row.pop(original)
return rows |
def md_heading(raw_text, level):
"""Returns markdown-formatted heading."""
adjusted_level = min(max(level, 0), 6)
return '%s%s%s' % (
'#' * adjusted_level, ' ' if adjusted_level > 0 else '', raw_text) |
def calc_add_bits(len, val):
""" Calculate the value from the "additional" bits in the huffman data. """
if (val & (1 << len - 1)):
pass
else:
val -= (1 << len) - 1
return val |
def vocab(table, text):
"""
Return a new table containing only the vocabulary in the source text.
Create a new translation table containing only the rules that are
relevant for the given text. This is created by checking all source
terms against a copy of the text.
"""
text_rules = []
... |
def possible_moves(state: list) -> list:
"""
Returns list of all possible moves
For the given board position 'state' returns
list of all possible moves for the next turn
Parameters
----------
state : list
The board position to be evaluated
"""
moves = []
for x, row in ... |
def form_definition_entries_special(pos, provenance, pw_id, pw_entry, kb_id, kb_entry):
"""
Create def match entry
:param pos:
:param pw_id:
:param pw_entry:
:param kb_id:
:param kb_entry:
:return:
"""
entries = []
for pw_def in pw_entry['definition']:
entries.append(... |
def odd_numbers_list(start, stop):
"""
Generate all the odd numbers in a given range.
:param start: The start of the range.
:param stop: The end of the range.
:return: A list of odd numbers.
"""
# Build a list with a list comprehension. This only includes elements in the list if they are ... |
def _total_probe_count_without_interp(params, probe_counts):
"""Calculate a total probe count without interpolation.
This assumes that params are keys in the datasets of probe_counts.
The result of ic._make_total_probe_count_across_datasets_fn should give
the same count as this function (if params are... |
def multirate_padding(used_bytes, align_bytes):
"""
The Keccak padding function.
"""
padlen = align_bytes - used_bytes
if padlen == 0:
padlen = align_bytes
# note: padding done in 'internal bit ordering', wherein LSB is leftmost
if padlen == 1:
return [0x81]
else:
... |
def make_key_mapping(key):
""" Make a mapping for this key."""
# Sort the characters.
chars = list(key)
chars.sort()
sorted_key = "".join(chars)
# Make the mapping.
mapping = []
for i in range(len(key)):
mapping.append(sorted_key.index(key[i]))
# Make the invers... |
def WithChanges(resource, changes):
"""Apply ConfigChangers to resource.
It's undefined whether the input resource is modified.
Args:
resource: KubernetesObject, probably a Service.
changes: List of ConfigChangers.
Returns:
Changed resource.
"""
for config_change in changes:
resource = co... |
def query_release(release):
"""
Build formatted query string for ICESat-2 release
Arguments
---------
release: ICESat-2 data release to query
Returns
-------
query_params: formatted string for CMR queries
"""
if release is None:
return ''
#-- maximum length of versi... |
def typeName(obj):
"""
Gets the object name of the passed instance as a string
Args:
obj (object): Instance of object to get the type name of
Returns:
str: name of the passed objects type
"""
return obj.__class__.__name__ |
def wrap_in_tag(tag: str, content: str, attributes: str = ""):
"""
Wraps some content in HTML tags with specific attributes.
:param tag: The tag that wraps the content
:param content: The content being wrapped
:param attributes: Optional attributes that can be assigned to the opening tag
:return... |
def join_version(version_tuple):
"""Return a string representation of version from given VERSION tuple"""
version = "%s.%s.%s" % version_tuple[:3]
if version_tuple[3] != "final":
version += "-%s" % version_tuple[3]
return version |
def UInt4ToASCII(ints):
"""
Turn a List of unsigned 4-bit ints into ASCII. Pure magic.
"""
return ''.join([chr((ints[x] << 4) + ints[x+1]) for x in range(0,len(ints),2)]) |
def new(name, num_servings):
""" Create and return a new recipe.
"""
return {'name' : name,
'num_servings' : num_servings,
'instructions' : [],
'ingredients' : []} |
def make_remote(ref, remote):
"""Return a Git reference based on a local name and a remote name.
Usage example:
>>> make_remote("mywork", "origin")
'refs/remotes/origin/mywork'
>>> make_remote("mywork", "github")
'refs/remotes/github/mywork'
"""
return "refs/remotes/" ... |
def create_neighbours(region):
"""neighbour is a dict containing
all countries as keys and all
neighbouring countries as values.
#
# (0, 0, 0, 3),
# (0, 1, 1, 1),
# (0, 0, 2, 0)
#
corresponds to:
# {0: {1, 2, 3}, 1: {0, 2, 3}, 2: {0, 1}, 3: {0, 1}}"""
neighbours = dict()
... |
def hmsm_to_days(hour=0, min=0, sec=0, micro=0):
"""
Convert hours, minutes, seconds, and microseconds to fractional days.
Parameters
----------
hour : int, optional
Hour number. Defaults to 0.
min : int, optional
Minute number. Defaults to 0.
sec : int, optional
Sec... |
def numero_caracteres_especiales(url):
""" Cuenta la cantidad de caracteres especiales que hay en la url
url: es la direccion de la pagina web """
try:
# cuantas letras hay por linea
contador_alfabeto = sum(1 for c in url if c.isalpha())
# cuantos numero hay por linea
contado... |
def ra_as_hours(ra_degrees):
""" Input: float of Right Ascension in degrees.
Returns: string of RA as hours, in hex, to the nearest 0.001 RA seconds.
"""
if (ra_degrees < 0) | (ra_degrees > 360):
return None
n_ra_milliseconds = round((ra_degrees * 3600 * 1000) / 15)
ra_hours, remaind... |
def get_dtype_str(dtype, byteorder="little"):
"""Parses dtype and byte order to return a type string code.
Parameters
----------
dtype : `numpy.dtype` or `str`
Either a dtype (e.g., ``numpy.uint32``) or a string with the type code
(``'>u4'``). If a string type code and the first charact... |
def split_into_n(s, n):
"""Split into lists - each of size 'n'."""
return [s[k:k + n] for k in range(0, len(s), n)] |
def _reverse_repeat_list(t, n):
"""Reverse the order of `t` and repeat each element for `n` times.
This can be used to translate padding arg used by Conv and Pooling modules
to the ones used by `F.pad`.
"""
return list(x for x in reversed(t) for _ in range(n)) |
def execute_chronos_api_call_for_job(api_call, job):
"""Attempt a call to the Chronos api, catching any exception.
We *have* to catch Exception, because the client catches
the more specific exception thrown by the http clients
and rethrows an Exception -_-.
The chronos api returns a 204 No Content... |
def binary_search_recursive(list, target):
"""
Returns the index position of the target if found, else returns None
complexity: O(log n)
"""
if len(list) <= 0:
return None
midpoint = len(list)//2
if list[midpoint] == target:
return True
if list[midpoint] < target:
... |
def create_non_array_attr_operation(var_attribute_name, var_attribute_value):
"""Return request string for a single operation to create a non-array attribute."""
return '{"op":"AddUpdateAttribute","attributeName":"' + var_attribute_name + '", "addUpdateAttribute":"' + var_attribute_value + '"},' |
def convertBytes(nbytes):
"""Convert a size in bytes to a string."""
if nbytes >= 1e9:
return '{:.1f} GB'.format(nbytes / 1e9)
elif nbytes >= 1e6:
return '{:.1f} MB'.format(nbytes / 1e6)
elif nbytes >= 1e3:
return '{:.1f} KB'.format(nbytes / 1e3)
else:
return '{:.1f} ... |
def parse_prefix(prefix, default_length=24):
"""
Splits the given IP prefix into a network address and a prefix length.
If the prefix does not have a length (i.e., it is a simple IP address),
it is presumed to have the given default length.
:type prefix: string
:param prefix: An IP mask.
:... |
def generate_readme(data):
"""
Takes in a dictionary containing all the relevant information on the
project and produces a string that can be passed to mne-bids
* might actually change this to produce a .md file to have nicer formatting
"""
out_str = ""
out_str += "Project Title:\t\t{0}\n".f... |
def _get_module_ver_hash(prov):
"""Get module commit hash, falling back to semantic version, and finally 'UNKNOWN'"""
ver = None
subacts = prov[0].get('subactions')
if subacts:
ver = subacts[0].get('commit')
if not ver:
ver = prov[0].get('service_ver', 'UNKNOWN')
return ver |
def find_magic_number_distinct(numbers):
"""Find magic number in list of distinct numbers
:param numbers List of sorted distinct integers
:return Index of magic number or -1
"""
def magic_number_helper(numbers, min_num, max_num):
"""Find magic number in list of distinct numbers
... |
def unique_paths(rows: int, columns: int) -> int:
"""Recursive function that returns the number of unique paths in a
non-blocking grid.
>>> unique_paths(9, 4)
165
>>> unique_paths(2, 3)
3
>>> unique_paths(9, 6)
1287
>>> unique_paths(3, 9)
45
>>> unique_paths(8, 14)
7... |
def Sample_n_Hold_Plot(_holds,_period,_end):
"""Starting from a list of points: create the corresponding piecewise-constant x- and y-axis data
Return: piecewise x-axis-data, piecewise y-axis-data"""
square_sig = []
square_x = []
for i in range(0,len(_holds)-1):
square_x += [i*_period] + [(i+... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.