content stringlengths 42 6.51k |
|---|
def twoSum(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
# Create a hash table (Python dictionary)
htbl = {}
for i, num in enumerate(nums):
t = target - num
if t in htbl.keys():
return [htbl[t], i]
else:
... |
def get_row_indices(center: int, length: int, neighbor_range: int):
"""
I do not recommend using, unless you know what to do...
This function takes the center location x and generates the
list of numbers that are within the neighbor_range with the
limitation of the length (cannot extend past the len... |
def checkNotNull(params):
"""
Check if arguments are non Null
Arguments:
params {array}
"""
for value in params:
if value == None:
return False
return True |
def scale_to_sum_one(vector):
"""Scales the items in the vector, so that their sum is 1"""
total = sum(vector)
if total == 0:
return vector
return [v/total for v in vector] |
def pick_equipment(categories, cur_pick):
"""Pick one item from each of categories."""
if not categories:
return [cur_pick]
items = categories[0]
picks = []
for item in items:
next_picks = pick_equipment(categories[1:], cur_pick + item)
picks.extend(next_picks)
return pic... |
def get_link_text_from_selector(selector):
"""
A basic method to get the link text from a link text selector.
"""
if selector.startswith('link='):
return selector.split('link=')[1]
elif selector.startswith('link_text='):
return selector.split('link_text=')[1]
return selector |
def _extract_defines_from_option_list(lst):
"""Extracts preprocessor defines from a list of -D strings."""
defines = []
for item in lst:
if item.startswith('-D'):
defines.append(item[2:])
return defines |
def pad_b64(encoded):
"""Append = or == to the b64 string."""
if len(encoded) % 4 == 0:
pass
elif len(encoded) % 4 == 3:
encoded += "="
elif len(encoded) % 4 == 2:
encoded += "=="
return encoded |
def interval_condition(value, inf, sup, dist):
"""Checks if value belongs to the interval [inf - dist, sup + dist].
"""
return inf - dist < value < sup + dist |
def mock_event(player: dict) -> dict:
"""
Fixture to create an AWS Lambda event dict
:param player: Input character; see above
:return: Mock event dict
"""
return {
"body": {
"Player": player,
"playerId": "player_hash",
"action": "attack",
... |
def box_size_calculate(r):
""" Calculates 1D size of bounding box
Args:
r:
A list containing the 2 co-ordinates of image [(x1, y1), (x2, y2)]
Returns:
length and width of box
"""
length = r[2] - r[0]
width = r[3] - r[1]
return length, width |
def discount_admin_cost(cost, timestep, global_parameters):
"""
Discount admin cost based on return period.
192,744 = 23,773 / (1 + 0.05) ** (0:9)
Parameters
----------
cost : float
Annual admin network running cost.
timestep : int
Time period (year) to discount against.
... |
def rotate_char(c, n):
"""Rotate a single character n places in the alphabet
n is an integer
"""
# alpha_number and new_alpha_number will represent the
# place in the alphabet (as distinct from the ASCII code)
# So alpha_number('a')==0
# alpha_base is the ASCII code for the first letter of ... |
def snake_to_camel(snake):
"""convert snake_case to camelCase"""
components = snake.split("_")
return components[0] + "".join([comp.title() for comp in components[1:]]) |
def lr_lambda(epoch, base=0.99, exponent=0.05):
"""Multiplier used for learning rate scheduling.
Parameters
----------
epoch: int
base: float
exponent: float
Returns
-------
multiplier: float
"""
return base ** (exponent * epoch) |
def _default_caltab_filename(stnid, rcumode):
"""Get default filename of a LOFAR station calibration table.
"""
caltabfilename = 'CalTable_'+stnid[2:]+'_mode'+rcumode+'.dat'
return caltabfilename |
def num_edges(ugraph):
"""
compute total number of edges for a undirected graph
:param ugraph:
:return:
"""
total_edges = 0
for edges in ugraph.values():
total_edges += len(edges)
return total_edges / 2 |
def tknzr_exp_name(exp_name: str) -> str:
"""Tokenizer experiment name."""
return f'{exp_name}-tokenizer' |
def dh_validate_public(public, q, p):
"""See RFC 2631 section 2.1.5."""
return 1 == pow(public, q, p) |
def _format_samples_counts(samples, expression):
"""Return a dictionary of samples counts"""
if isinstance(samples, list):
if len(samples) != len(expression):
raise ValueError("samples %s has different length than expression %s" % (samples,
... |
def get_job_class(job):
"""Returns job class."""
if '_class' in job:
if job['_class'] == 'com.cloudbees.hudson.plugins.folder.Folder':
return 'folder'
if 'DFG-' in job['name']:
return 'DFG'
elif 'util' in job['name']:
return 'utility' |
def ctype(v, t):
"""Convert "v" to type "t"
>>> ctype('10', int)
10
>>> ctype('10', list)
['1', '0']
>>> ctype(10, list)
10
>>> ctype('10a', float)
'10a'
:param tp.Any v:
:param tp.TypeVar t:
:return tp.Any:
"""
try:
return t(v) or v
except (ValueErr... |
def file_type(file_name):
"""
Returns the file type from a complete file name
If the file doesn't have a file type, return "file"
"""
if "." not in file_name:
return "file"
return file_name.split(".")[-1] |
def get_product(temp):
"""returns the product and types of items depending on the temperature value"""
product = ""
items = list()
if temp < 19:
product = "moisturizer"
items = ["Aloe", "Almond"]
elif temp > 34:
product = "sunscreen"
items = ["SPF-30", "SPF-5... |
def vect3_add(v1, v2):
"""
Adds two 3d vectors.
v1, v2 (3-tuple): 3d vectors
return (3-tuple): 3d vector
"""
return (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]) |
def take_step(solutions, step):
"""
Takes a step for each solution.
"""
return [solution + [step] for solution in solutions] |
def merge_sort(list):
"""Merge sort, duh?
:param list: List of things to sort
:return: Cool sorted list
"""
if len(list) > 1:
middle = len(list) // 2
left = merge_sort(list[:middle]) # Sort left partition
right = merge_sort(list[middle:]) # Sort right partition
... |
def p64b(x):
"""Packs an integer into a 8-byte string (big endian)"""
import struct
return struct.pack('>Q', x & 0xffffffffffffffff) |
def paging_modes(yaml_string, isa):
"""
This function reads the YAML entry specifying the valid
paging modses supported by the SATP CSR and returns the mode(s)
for the framework to generate tests
"""
split_string = yaml_string.split(' ')
values = (split_string[-1][1:-1]).split('... |
def first(values):
"""
Get the first value in the list of values as a string.
"""
if isinstance(values, (str, bytes)):
return values
value = values[0]
if isinstance(value, str):
return values[0]
return str(value) |
def conv_outsize(in_size, kernel_size, padding, stride):
"""
Computes the size of output image after the convolution defined by the input arguments
"""
out_size = (in_size - kernel_size + (2 * padding)) // stride
out_size += 1
return out_size |
def levenshtein_distance(str1, str2):
"""
Return the minimum number of character deletions,
insertions and/or substitutions between two strings.
:param str1: first string
:param str2: second string
:type str1: string
:type str2: string
:returns: levenshtein di... |
def sample_length(min_length, max_length, rng):
"""
Computes a sequence length based on the minimal and maximal sequence size.
Parameters
----------
max_length : maximal sequence length (t_max)
min_length : minimal sequence length
Returns
-------
A random number f... |
def resolve_boolean_value(val: str):
""" Resolve a string which represents a boolean value
Args:
val: The value
Returns:
True, False or None
"""
val = val.upper()
if val == "TRUE":
return True
elif val == "FALSE":
return False
else:
return None |
def get_gender(x):
""" returns the int value for the ordinal value class
:param x: a value that is either 'crew', 'first', 'second', or 'third'
:return: returns 3 if 'crew', 2 if first, etc.
"""
if x == 'Male':
return 1
else:
return 0 |
def generate_previous_list(next_list):
"""
Generate the expected list of previous values given a list of next values.
Lags the next list, holds the last valid number, and adds None to the
front. e.g.
[0,1,2,None,None,None] -> [None, 0,1,2,2,2]
"""
# Add none and lag the list
previous_lis... |
def is_subdir(path, directory):
"""
Returns true if *path* in a subdirectory of *directory*.
Both paths must be absolute.
"""
from os.path import normpath, normcase
path = normpath(normcase(path))
directory = normpath(normcase(directory))
return path.startswith(directory) |
def information_gain_proxy(
impurity_left, impurity_right, w_samples_left, w_samples_right,
):
"""Computes a proxy of the information gain (improvement in impurity) using the
equation
- n_v0 * impurity_v0 - n_v1 * impurity_v1
where:
* n_v0, n_v1 are the weighted number of samples in th... |
def remove_carriage_ret(lst):
"""
Remove carriage return - \r from a list
"""
return list(map(lambda el: el.replace('\r',''), lst)) |
def first_diff_pos(a, b):
"""
find the pos of first char that doesn't match
"""
for i, c in enumerate(a):
if i >= len(b):
return i # return if reached end of b
if b[i] != a[i]:
return i # we have come to the first diff
return len(a) |
def angle_offset(base, angle):
"""
Given a base bearing and a second bearing, return the offset in degrees.
Positive offsets are clockwise/to the right, negative offsets are
counter-clockwise/to the left.
"""
# rotate the angle towards 0 by base
offset = angle - base
if offset <= -180:... |
def describe_interval(secs):
"""
Return a string describing the supplied number of seconds in human-readable
time, e.g. "107 hours, 42 minutes".
"""
if secs <= 0:
return 'no time at all'
hours = secs // 3600
minutes = (secs - (hours * 3600)) // 60
parts = []
if hours > 0:
... |
def level_put_response_ok(devid, level):
"""Return level change response json."""
return '{"id": "' + devid + '", "level": "' + str(level) + '"}' |
def py_bool(data):
""" return python boolean """
return data == "true" |
def tld(s):
""" Parse the TLD of a domain name.
:param s: String to parse.
"""
if s.endswith('.'):
return s[s.rfind('.', 0, -1)+1:-1]
return s[s.rfind('.')+1:] |
def sequence_frame_number(scene_frame, mode, start, duration, offset):
""" Get sequence frame number from sequence settings and current scene frame """
frame = scene_frame - start + 1
if mode == 'CLIP':
if frame < 1 or frame > duration:
return None
elif mode == 'EXTEND':
fra... |
def remove_duplicates(a):
"""
Remove Duplicates from an Array
>>> sorted(remove_duplicates("hello"))
['e', 'h', 'l', 'o']
>>> remove_duplicates([1,2,3,1,2,4])
[1, 2, 3, 4]
"""
return list(set(a)) |
def b_to_mb(b: int):
"""Convert bytes to MB."""
return round(float(b) / (1024 ** 2), 2) |
def is_discord_file(obj):
"""Returns true if the given object is a discord File object."""
return (obj.__class__.__name__) == "File" |
def create_vector(p1, p2):
"""Contruct a vector going from p1 to p2.
p1, p2 - python list wth coordinates [x,y,z].
Return a list [x,y,z] for the coordinates of vector
"""
return list(map((lambda x,y: x-y), p2, p1)) |
def formata_valor(value):
"""
Formata um valor em R$
"""
return "R$ {}".format(value) |
def remove_a_key(d: dict, remove_key: str) -> dict:
"""
Removes a key passed in as `remove_key` from a dictionary `d`.
Reference: https://stackoverflow.com/questions/58938576/remove-key-and-its-value-in-nested-dictionary-using-python
"""
if isinstance(d, dict):
for key in list(d.keys()):
... |
def startEnd(length, start, end):
"""Helper function to normalize the start and end of an array by counting from the end of the array (just like Python).
:type length: non-negative integer
:param length: length of the array in question
:type start: integer
:param start: starting index to interpret
... |
def conv_C2F(c):
"""Convert Celsius to Fahrenheit"""
return c*1.8+32.0 |
def splitter(items, separator, convert_type):
"""
Split the string of items into a list of items.
:param items: A string of joined items.
:param separator: The separator used for separation.
:param convert_type: The type the item should be converted into after separation.
:return: A list of items.
"""
return [c... |
def clean_outcomert(row):
"""
Intended for use with DataFrame.apply()
Returns an array with 'outcomert' converted from milliseconds to seconds if the 'study' variable is '3'
"""
if int(row['study']) >= 3:
return float(row['outcomert'] * .001)
else:
return row['outcomert'] |
def apply_inverse_rot_to_vec(rot, vec):
"""Multiply the inverse of a rotation matrix by a vector."""
# Inverse rotation is just transpose
return [rot[0][0] * vec[0] + rot[1][0] * vec[1] + rot[2][0] * vec[2],
rot[0][1] * vec[0] + rot[1][1] * vec[1] + rot[2][1] * vec[2],
rot[0][2] * vec[0] + rot... |
def vec2dict(vector):
"""
Input:
vector: a list or (1d) numpy array
Returns:
a dict with {idx:value} for all values of the vector
"""
return {i: val for i, val in enumerate(vector)} |
def _to_int(x):
"""Converts a completion and error code as it is listed in 32-bit notation
in the VPP-4.3.2 specification to the actual integer value.
"""
if x > 0x7FFFFFFF:
return int(x - 0x100000000)
else:
return int(x) |
def isint(s):
"""checks if a string is a number"""
try:
return int(s)
except ValueError:
return False |
def argn(*args):
"""Returs the last argument. Helpful in making lambdas do more than one thing."""
return args[-1] |
def temp_to_orig_section(temp_sec):
"""
Change a temp section into its original.
If it is its original it will return what was given.
:param temp_sec: temporary section created by 'create_temp_batch'
:return: orig section
"""
section = temp_sec
if temp_sec.startswith(('1', '2', '3', '4',... |
def merge_dicts(*dicts, deleted_keys=[]):
"""Return a new dict from a list of dicts by repeated calls to update(). Keys in later
dicts will override those in earlier ones. *deleted_keys* is a list of keys which should be
deleted from the resulting dict.
"""
rv = {}
for d in dicts:
rv.up... |
def merge_and_count_split_inv(B, C):
"""
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6])
([1, 2, 3, 4, 5, 6], 3)
>>> merge_and_count_split_inv([1, 3, 5], [2, 4, 6, 7])
([1, 2, 3, 4, 5, 6, 7], 3)
>>> merge_and_count_split_inv([1, 3, 5, 6], [2, 4, 7])
([1, 2, 3, 4, 5, 6, 7], 5)
>>> ... |
def info ():
"""
Check server status
"""
# Build response
return {
"success": True,
"message": "Aquila X is running healthy"
}, 200 |
def sanitize_validation(validators):
"""sanitize validation in the form xn-yn z"""
joined_bounds, letter = validators.split()
lower_bound, upper_bound = map(int, joined_bounds.split("-"))
return lower_bound, upper_bound, letter |
def print_fortran_indexed(base, indices):
"""Print indexed objects according to the Fortran syntax.
By default, the multi-dimensional array format will be used.
"""
return base + (
'' if len(indices) == 0 else '({})'.format(', '.join(
i.index for i in indices
))
) |
def R10_assembly(FMzul, Apmin, PG):
"""
R10 Determining the surface pressure Pmax
(Sec 5.5.4)
Assembly state
"""
# Assembly state
PMmax = min(FMzul / Apmin, PG) # (R10/1)
# Alternative safety verification
Sp = PG / PMmax # (R10/4)
#if Sp > 1.0 : print('Sp... |
def compute_n_steps(control_timestep, physics_timestep, tolerance=1e-8):
"""Returns the number of physics timesteps in a single control timestep.
Args:
control_timestep: Control time-step, should be an integer multiple of the
physics timestep.
physics_timestep: The time-step of the physics simulation... |
def byte_lengths(n_bytes, n_partitions):
"""Calculates evenly distributed byte reads for given file size.
Args:
n_bytes: int - total file size in bytes
n_partitions: int - number of file partitions
Returns:
iterable of ints
"""
chunk_size = n_bytes // n_partitions
byte... |
def callback(fname, fcontents):
"""
The callback to apply to the file contents that we from HDFS.
Just prints the name of the file.
"""
print("Fname:", fname)
return fname, fcontents |
def check_step_file(filename, steplist):
"""Checks file for existing data, returns number of runs left
Parameters
----------
filename : str
Name of file with data
steplist : list of int
List of different numbers of steps
Returns
-------
runs : dict
Dictionary wi... |
def next_p2(num):
""" If num isn't a power of 2, will return the next higher power of two """
rval = 1
while (rval < num):
rval <<= 1
return rval |
def major_version(v):
"""
Return the major version for the given version string.
"""
return v.split('.')[0] |
def del_special(S):
"""
Replace verbatim white space lien endings and tabs (\\n, \\r, \\t) that
may exist as-is as literals in the extracted string by a space.
"""
return S.replace('\\r', ' ').replace('\\n', ' ').replace('\\t', ' ') |
def dec_to_sex(dec, delimiter=':'):
"""Convert dec in decimal degrees to sexigesimal"""
if (dec >= 0):
hemisphere = '+'
else:
# Unicode minus sign - should be treated as non-breaking by browsers
hemisphere = '-'
dec *= -1
dec_deg = int(dec)
dec_mm = int((dec - dec_d... |
def num_trace_events(data):
"""Returns the total number of traces captured
"""
return len(data["traceEvents"]) |
def _parse_suppressions(suppressions):
"""Parse a suppressions field and return suppressed codes."""
return suppressions[len("suppress("):-1].split(",") |
def get_bruised_limbs(life):
"""Returns list of bruised limbs."""
_bruised = []
for limb in life['body']:
if life['body'][limb]['bruised']:
_bruised.append(limb)
return _bruised |
def get_sum_metrics(predictions, metrics = None):
""" Create a new object each time the function is called, by using a default arg to signal that no argument was provided
Do not use metrics = [] as it does not Create a new list each time the function is called instead it append to the list
generated... |
def ends_with_punctuation(value):
"""Does this end in punctuation? Use to decide if more is needed."""
last_char = value.strip()[-1]
return last_char in "?.!" |
def get_grid_size(grid):
"""Return grid edge size."""
if not grid:
return 0
pos = grid.find('\n')
if pos < 0:
return 1
return pos |
def remove_the_last_person(queue: list) -> str:
"""
:param queue: list - names in the queue.
:return: str - name that has been removed from the end of the queue.
"""
return queue.pop() |
def is_chinese(target_str):
""" determine whether the word is Chinese
Args:
target_str (str): target string
"""
for ch in target_str:
if '\u4e00' <= ch <= '\u9fff':
return True
return False |
def sort_bed_by_bamfile(bamfile, regions):
"""Orders a set of BED regions, such that processing matches
(as far as possible) the layout of the BAM file. This may be
used to ensure that extraction of regions occurs (close to)
linearly."""
if not regions:
return
references = bamfile.refer... |
def _get_name(data):
"""
Returns 'firstname lastname' or 'name'
"""
try:
return '{} {}'.format(data['properties']['first_name'],
data['properties']['last_name'])
except KeyError:
return data['properties'].get('name', '') |
def remove_thousand_separator(int_as_str: str) -> str:
"""Removes thousand separator from a number stored as string."""
return int_as_str.replace(",", "") |
def sched_prio(resources, time_in_queue=0):
"""
Weight the priority to prefer smaller resource requests.
As a task stays longer in the queue, increase priority.
Best priority is 0, worse increases to infinity.
Args:
resources (dict): resources dict
time_in_queue (float): the time t... |
def revert_datetime_to_long_string(dt):
"""
Turns a date/time into a long string as needed by midas code.
"""
return str(dt).replace("-", "").replace(" ", "").replace("T", "").replace(":", "") |
def json_pointer(jsonpointer: str) -> str:
"""Replace escape characters in JSON pointer."""
return jsonpointer.replace("~0", "~").replace("~1", "/") |
def get_current_state(state_vector):
""" Get the current state corresponding to the state probability vector.
:param state_vector: The state PMF vector.
:type state_vector: list(int)
:return: The current state.
:rtype: int,>=0
"""
return state_vector.index(1) |
def check(wants, has):
"""
Check if a desired scope ``wants`` is part of an available scope ``has``.
Returns ``False`` if not, return ``True`` if yes.
:example:
If a list of scopes such as
::
READ = 1 << 1
WRITE = 1 << 2
READ_WRITE = READ | WRITE
SCOPES = (
... |
def get_contacts(contacts):
"""
Reformarts mvnx contacts
:param contacts:
:return: Contacts for all the four parts of a foot in the required dictionary format
"""
LeftFoot_Toe = []
RightFoot_Toe = []
LeftFoot_Heel = []
RightFoot_Heel = []
for i in range(len(contacts)):
... |
def avoir_ind_courant(ligne):
"""
renvoie le nombre de case remplie dans la ligne motif
"""
ind_courant = 0
for case in ligne:
if case !="":
ind_courant+=1
return ind_courant |
def get_node_map(node_set):
"""
Maps every node to an ID.
:param node_set: set of all nodes to be mapped.
:return: dict of original node index as key and the mapped ID as value.
"""
nodes = list(node_set)
nodes.sort()
node_id_map = {}
for i, n in enumerate(nodes):
node_id_m... |
def dict_popper(dicty, pop_target):
"""[pop pop_targets from dict dicty, cool names yeah?]
Args:
dicty ([dict]): [dict to pop keys]
pop_target ([list]): [list with keys to pop]
Returns:
[type]: [description]
"""
for item in dicty:
for col in pop_target:
... |
def polynomial_3_integral(x0, x1, a, b, c, d):
"""Integral of polynomial order 3 where f(x) = a + b * x + c * x**2 + d * x**3.
"""
return a * (x1 - x0) \
+ b * (x1**2 - x0**2) / 2.0 \
+ c * (x1**3 - x0**3) / 3.0 \
+ d * (x1**4 - x0**4) / 4.0 |
def quick_sort_v2(li):
"""([list of int], int, int) => [list of int]
Quick sort: works by selecting a 'pivot' element from the array
and partitioning the other elements into two sub-arrays, according
to whether they are less than or greater than the pivot. The
sub-arrays are then sorted recursively.... |
def normalize_idp(idp):
"""
Normalizes the IDP definitions so that the outputs are consistent with the
parameters
- "enabled" (parameter) == "is_enabled" (SDK)
- "name" (parameter) == "id" (SDK)
"""
if idp is None:
return None
_idp = idp.to_dict()
_idp['enabled'] = idp['is_... |
def _https(base_uri, *extra):
"""Combine URL components into an https URL"""
parts = [str(e) for e in extra]
str_parts = ''.join(parts)
str_base = str(base_uri)
if str_base.startswith("https://"):
return "{0}{1}".format(str_base, str_parts)
elif str_base.startswith("http://"):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.