content stringlengths 42 6.51k |
|---|
def binarySearch(lower, upper, alist):
"""
take in a lower bound, upper bound, and a list as input.
then you have the range of numbers to search for.
binary search after but the search element is a range of numbers.
"""
bounds = range(lower, upper + 1)
first = 0
last = len(... |
def assign_scores(game):
"""Cleanup games without linescores to include team score
based on team totals."""
for team in game['team'].values():
if 'score' not in team and 'totals' in team:
team['score'] = team['totals']['source__B_R']
return game |
def songs_or_artists(search_type):
"""[summary]
Ask user to input whether search is based on songs or artists.
[description]
"""
while search_type != "a" and search_type != "s":
search_type = input("Do you want to search for playlists containing artists or specific songs? (a or s) \n").lower... |
def dist(t1,t2):
""" Euclidean distance between two lists """
return sum([(t1[i]-t2[i])**2 for i in range(len(t1))]) |
def get_key(key, config, msg=None, delete=False):
"""Returns a value given a dictionary key, throwing if not available."""
if isinstance(key, list):
if len(key) <= 1:
if msg is not None:
raise AssertionError(msg)
else:
raise AssertionError("must pr... |
def subs_str_finder(control_s, sub_str):
"""
Finds indexes of all sub_str occurences in control_s.
"""
sub_len = len(sub_str)
while sub_str in control_s:
first_index = control_s.find(sub_str)
second_index = first_index + sub_len
return first_index, second_index |
def _get_dir_list(obj=None):
"""
dir([object]) -> list of strings
If called without an argument, return the names in the current scope.
Else, return an alphabetized list of names comprising (some of) the attributes
of the given object, and of attributes reachable from it.
If the object supplies... |
def clean_args(hargs, iterarg, iteridx):
"""
Filters arguments for batch submission.
Parameters
----------
hargs: list
Command-line arguments
iterarg: str
Multi-argument to index (`subjects` OR `files`)
iteridx: int
`iterarg` index to submit
Returns
-------
... |
def ReadFileAsLines(filename):
"""Reads a file, removing blank lines and lines that start with #"""
file = open(filename, "r")
raw_lines = file.readlines()
file.close()
lines = []
for line in raw_lines:
line = line.strip()
if len(line) > 0 and not line.startswith("#"):
lines.append(line)
ret... |
def get_parent_path(path, split_symbol):
"""get parent path
Args:
path (string): raw path
split_symbol (string): path separator
Returns:
string: the parent path
"""
reversed_path = ''
times = 0
for ch in reversed(path):
if(times >= 2):
reversed_p... |
def disable() -> dict:
"""Disables headless events for the target."""
return {"method": "HeadlessExperimental.disable", "params": {}} |
def popCount(v):
"""Return number of 1 bits in an integer."""
if v > 0xFFFFFFFF:
return popCount(v >> 32) + popCount(v & 0xFFFFFFFF)
# HACKMEM 169
y = (v >> 1) & 0xDB6DB6DB
y = v - y - ((y >> 1) & 0xDB6DB6DB)
return (((y + (y >> 3)) & 0xC71C71C7) % 0x3F) |
def jaccard_similarity(str_1, str_2):
""" compute of intersection to get similraity score between words """
str_1 = set(str_1.split())
str_2 = set(str_2.split())
intersect = str_1.intersection(str_2)
return float(len(intersect)) / (len(str_1) + len(str_2) - len(intersect)) |
def message_relative_index(messages, message_id):
"""
Searches the relative index of the given message's id in a channel's message history. The returned index is
relative, because if the message with the given is not found, it should be at that specific index, if it would be
inside of the respective cha... |
def heur(p1, p2):
"""
Heuristic function, gets a prediction for the distance from the
given node to the end node, which is used to guide the a*
algorithm on which node to search next.
Uses Manhattan distance, which simply draws an L to the end node.
"""
x1, y1 = p1
x2, y2 = p2
ret... |
def _osi(preferred_responses, ortho_responses):
"""This is the hard-coded osi function."""
return ((preferred_responses - ortho_responses)
/ (preferred_responses + ortho_responses)) |
def swllegend(cur):
"""
Example of a hardcoded legend, does not use the legend database.
"""
d = {'linecolor' : '#0505ff',
'linethick' : 2,
'linestyle': '-'}
return d |
def increment(value, list_):
"""
This updates the value according to the list. Since we seek 4
consecutive numbers with exactly 4 prime factors, we can jump
4 numbers if the last doesn't have 4 factors, can jump 3 if
the second to last doesn't have 4 factors, and so on
"""
if list_[-1] != 4:... |
def url_join(*args):
"""Join combine URL parts to get the full endpoint address."""
return '/'.join(arg.strip('/') for arg in args) |
def calc_factorial(x: int) -> int:
"""Calculate factorial."""
if x < 2:
return 1
return x * calc_factorial(x=x - 1) |
def _get_resource_info(args):
"""Get the target resource information.
Args:
args (object): The args.
Returns:
list: The list of args to use with gcloud.
str: The resource id.
"""
resource_args = None
resource_id = None
if args.org_id:
resource_args = ['orga... |
def sys_model(t, x, u):
"""Function modelling the dynamic behaviour of the system in question with a control term u.
Returns the state of the ODE at a given point in time"""
dx1dt = 2*x[0] + x[1] + 2*u[0] - u[1]
dx2dt = x[0] + 2*x[1] - 2*u[0] + 2*u[1]
return [dx1dt, dx2dt] |
def _get_aea_logger_name_prefix(module_name: str, agent_name: str) -> str:
"""
Get the logger name prefix.
It consists of a dotted save_path with:
- the name of the package, 'aea';
- the agent name;
- the rest of the dotted save_path.
>>> _get_aea_logger_name_prefix("aea.save_path.to.packa... |
def _parse_selections(dpkgselection):
"""
Parses the format from ``dpkg --get-selections`` and return a format that
pkg.get_selections and pkg.set_selections work with.
"""
ret = {}
if isinstance(dpkgselection, str):
dpkgselection = dpkgselection.split("\n")
for line in dpkgselection... |
def length(iterable):
"""
Return number of elements in iterable. Consumes iterable!
>>> length(range(10))
10
:param iterable iterable: Any iterable, e.g. list, range, ...
:return: Length of iterable.
:rtype: int
"""
return sum(1 for _ in iterable) |
def flatten_list_of_lists(list_of_lists):
"""Convert a list os lists to a single list
Args:
list_of_lists (list of lists): A list of lists.
Returns:
result_list (list): A list
Examples:
>>> list_of_lists = [[1,2,3],[0,3,9]]
>>> flatten_list_of_lists(list_of_lists)
... |
def compute_grid_growth(n_para, n_approx_points):
"""
"""
grid_growth = [n_approx_points ** power for power in range(1, n_para)]
return grid_growth |
def mtime(filename):
"""When was the file modified the last time?
Return value: seconds since 1970-01-01 00:00:00 UTC as floating point number
0 if the file does not exists"""
from os.path import getmtime
try: return getmtime(filename)
except: return 0 |
def max_scaling(x):
""" Scaling the values of an array x
with respect to the maximum value of x.
"""
return [i/max(x) for i in x] |
def convertToInts(problem):
"""
Given a two-dimensional list of sets return a new two-dimensional list
of integers.
:param list problem: Two-dimensional list of sets
:return: Two-dimensional list of integer
:rtype: list
"""
return [[next(iter(loc)) if len(loc) == 1 else 0 for loc in row... |
def look_up_words(input_text):
"""Replacing social media slangs with more standarized words.
:param input_text: Slanged social media text.
:return: Standarized text.
"""
# look-up dictionary
social_media_look_up = {
'rt':'Retweet',
'dm':'direct message',
"awsm" : "a... |
def error(geometry):
"""
returns the max expected error (based on past runs)
"""
return {"slice": 7e-2,
"sphere": 2.5e-2}[geometry] |
def convert_quarter_to_date(time):
"""
Reformats dates given with quarters to month-day format.
Args:
time: String representing time in the format year-quarter(e.g. Q1, Q2, ...)
Returns:
String representing time in the format year-month-day.
"""
date = time
if "Q1" in date:... |
def mappingSightingOpenIOC(etype):
"""
Map the openioc types to threat sightings
"""
mapping = {
"sha256": "FileItem/Sha256sum",
"ipv4": "DnsEntryItem/RecordData/IPv4Address",
"domain": "Network/URI",
"url": "UrlHistoryItem/URL",
"dstHost": "Network/URI",
"md5": "FileItem/Md5sum",
"sha1": "FileItem/S... |
def __splitTime(sec):
"""Takes an amount of seconds and returns a tuple for hours, minutes and seconds.
@rtype: tuple(int, int, int)
@return: A tuple that contains hours, minutes and seconds"""
minutes, sec = divmod(sec, 60)
hour, minutes = divmod(minutes, 60)
return (hour, minutes, sec) |
def filter_ReceptPolys(recept_polys,bna_polys):
"""
checks if a receptor poly is wholly within a bna poly. If it is, it isn't kept.
"""
recept_polys_new = []
recept_index = []
for kk in range(len(recept_polys)):
keep = True
bb = 0
bna = []
for bpoly in bna_p... |
def rebuild_cmd(i):
"""
Input: {
choices - dict of choices
choices_order - choices order
choices_desc - dict of choices desc
}
Output: {
return - return code = 0, if successful
... |
def find_first(sack):
""" Find the ID of the first kid who gets allocated a present from the supplied sack. """
return 1 if sack == 1 else sack ** 2 // 2 |
def collapse_stmts(stmts):
"""
Returns a flat list containing every statement in the tree
stmts.
"""
rv = [ ]
for i in stmts:
i.get_children(rv.append)
return rv |
def escape_windows_title_string(s):
"""Returns a string that is usable by the Windows cmd.exe title
builtin. The escaping is based on details here and emperical testing:
http://www.robvanderwoude.com/escapechars.php
"""
for c in '^&<>|':
s = s.replace(c, '^' + c)
s = s.replace('/?', '/.... |
def chain_apply(funcs, var):
"""apply func from funcs[0] to funcs[-1]"""
for func in funcs:
var = func(var)
return var |
def bresenhams(start, end):
"""Bresenham's Line Algo -- returns list of tuples from start and end"""
# Setup initial conditions
x1, y1 = start
x2, y2 = end
dx = x2 - x1
dy = y2 - y1
# Determine how steep the line is
is_steep = abs(dy) > abs(dx)
# Rotate line
if is_steep:
... |
def convert_lowercase(in_str):
""" Convert a given string to lowercase
:param in_str: input text
:return: string
"""
return str(in_str).lower() |
def find_total_bag_colors(rules, color, level=0):
"""Find all colors which can contain a bag of the given color"""
found = []
def mapper(rule, times):
ret = []
for bag in rules[rule]:
for _ in range(bag.count):
ret.append(bag)
for bag in tuple(ret):
... |
def bubble_sort(array):
"""This function takes a list as input and sorts it by bubblegit sort algorithm"""
for i in range(len(array)):
for j in range(len(array)-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array |
def _encodeList(l):
"""Check for binary arrays in list and tries to decode to string
Args:
l ([]): list to seach
Returns:
:[]: original list with any byte array entries replaced with strings
"""
for i in range(len(l)):
if type(l[i]) is bytes:
l[i] = l[i].decode()
... |
def is_asm(l):
"""Returns whether a line should be considered to be an instruction."""
l = l.strip()
# Empty lines
if l == '':
return False
# Comments
if l.startswith('#'):
return False
# Assembly Macros
if l.startswith('.'):
return False
# Label
if l.endswith(':'):
return False
re... |
def sorted_dict(item, key=None, reverse=False):
"""Return a new sorted dictionary from the `item`."""
if not isinstance(item, dict):
return item
return {k: sorted_dict(v) if isinstance(v, dict) else v for k, v in sorted(item.items(), key=key, reverse=reverse)} |
def main(name="Valdis", count=3):
"""
Printing a greeting message
For our friends
"""
for _ in range(count):
print(f'Hello {name}')
return None |
def str_goal(goal, indent=4):
"""Print each variable in goal, indented by indent spaces."""
result = ""
if goal != False:
for (name,val) in vars(goal).items():
if name != '__name__':
for x in range(indent): result = result + " "
result = result + goal.__na... |
def flatten_in_place(orig):
"""flattens a given list in place"""
is_flattened = False
while not is_flattened: # iterating until no more lists are found
is_flattened = True
for i, item in enumerate(orig):
if isinstance(item, list):
is_flattened = False
... |
def convertSize(size):
"""
The convertSize function converts an integer representing bytes into a human-readable format.
:param size: The size in bytes of a file
:return: The human-readable size.
"""
sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
index = 0
while size > 1024:
size /= 1... |
def _clean_kwargs(kwargs):
""" Do some sanity checks on kwargs
>>> _clean_kwargs({'parse_dates': ['a', 'b'], 'usecols': ['b', 'c']})
{'parse_dates': ['b'], 'usecols': ['b', 'c']}
>>> _clean_kwargs({'names': ['a', 'b'], 'usecols': [1]})
{'parse_dates': [], 'names': ['a', 'b'], 'usecols': ['b']}
... |
def is_source(f):
"""Returns true iff the input file name is considered a source file."""
return not f.endswith('_test.go') and (
f.endswith('.go') or f.endswith('.s')) |
def format_hours(date, **kwargs):
"""Format hours"""
date_list = date.split('T')
date_hour = date_list[1][:5]
return date_hour |
def string_similarity(string1: str, string2: str) -> float:
"""
Compare the characters of two strings.
Parameters
----------
string1: str
The first string.
string2: str
The second string.
Returns
-------
: float
Similarity of strings expres... |
def check_pseudo_overlap(x1, x2, y1, y2):
"""
check for overlaps [x1, x2] and [y1, y2]
should only be true if these overlap
"""
return max(x1, y1) <= min(x2, y2) |
def get_index_bounds(indexes):
"""Returns the bounds (first and last element) of consecutive numbers.
Example:
[1 , 3, 4, 5, 7, 8, 9, 10] -> [1, 3, 5, 7, 10]
Args:
indexes (list of int): integers in an ascending order.
Returns:
list of int: the bounds (first and last element) of c... |
def mod97(digit_string):
"""Modulo 97 for huge numbers given as digit strings.
This function is a prototype for a JavaScript implementation.
In Python this can be done much easier: long(digit_string) % 97.
"""
m = 0
for d in digit_string:
m = (m * 10 + int(d)) % 97
return m |
def get_taurus_options(artifacts_dir, jmeter_path=None):
"""The options for Taurus BZT command"""
options = []
if jmeter_path:
options.append('-o modules.jmeter.path={}'.format(jmeter_path))
options.append('-o settings.artifacts-dir={}'.format(artifacts_dir))
options.append('-o modules.conso... |
def isdistinct(seq):
""" All values in sequence are distinct
>>> isdistinct([1, 2, 3])
True
>>> isdistinct([1, 2, 1])
False
>>> isdistinct("Hello")
False
>>> isdistinct("World")
True
"""
if iter(seq) is seq:
seen = set()
for item in seq:
if item ... |
def mergeDicts(dictOfDicts, keysOfDicts):
"""Function merge dicts in dict. Current dicts are given by its key.
Args:
dictOfDicts (dict): Dictionary of dictionaries to merge.
keysOfDicts (set): Keys of current dictionaries to merge.
Returns:
dict: Merged dictionary.
"""
mer... |
def latin1_encode(obj):
"""
Encodes a string using LATIN-1 encoding.
:param obj:
String to encode.
:returns:
LATIN-1 encoded bytes.
"""
return obj.encode("latin1") |
def crossref_title_parser(title):
"""Function to parse title.
Returns:
str"""
return " ".join(title[0].split()) |
def page_not_found(e):
"""Return a custom 404 error."""
return 'Sorry, Nothing at this URL.', 404 |
def style(style_def):
"""Convert a console style definition in to dictionary
>>> style("bold red on yellow")
{fg="red", bg="yellow", bold=True}
"""
if not style_def:
return {}
if isinstance(style_def, dict):
return style_def
colors = {"yellow", "magenta", "green", "cyan", "... |
def sort_by_relevance(repo_list):
"""
Build display order.
As of 2020-01-14 it sorts by number of forks and stars combined
:param repo_list: repolist to sort
:return: sorted repolist
"""
repo_list.sort(key=lambda repo: repo['repo_forks'] + repo['repo_stars'], reverse=True)
return repo_l... |
def preprocess(line):
"""
Preprocess a line of Jane Austen text.
* insert spaces around double dashes --
:param line:
:return:
"""
return line.replace("--", " -- ") |
def isUrl(image):
"""Checks if a string is an URL link.
Args:
image (string): The string to be checked.
Returns:
bool: True if it is a valid URL link, False if otherwise.
"""
try:
if image.startswith('https') or image.startswith('http'):
return True
retu... |
def end() -> dict:
"""Stop trace events collection."""
return {"method": "Tracing.end", "params": {}} |
def is_set(check, bits):
"""Return True if all bits are set."""
return check & bits == bits |
def _read_if_html_path(txt: str) -> str:
"""Open HTML file if path provided
If the input is a path to a valid HTML file, read it.
Otherwise return the input
"""
if txt and txt.endswith(".html"):
with open(txt, "rt") as fh:
txt = fh.read()
return txt |
def select_k_best_regions(regions, k=16):
"""
Args:
regions -- list list of 2-component tuples first component the region,
second component the ratio of white pixels
k -- int -- number of region... |
def time_to_min(in_time: str) -> int:
"""
Turns human given string to time in minutes
e.g. 10h 15m -> 615
"""
times = [int(x.strip()) for x in in_time.strip("m").split("h")]
assert len(times) <= 2
if len(times) == 1:
return times[0]
else:
return times[0] * 60 + times[1] |
def ensure_ends_with_slash(string):
"""Returns string with a trailing slash"""
return (
string
if string.endswith('/')
else '{}/'.format(string)
) |
def file_as_byte(file):
"""
This function is used to return the content of a file as byte. Used for the MD5 hash of the file in main.py
"""
with file:
return file.read() |
def list_to_str(list_name):
"""
Formats a list into a string.
:param list_name: (List of String) List to be formatted
:return: (String) String representation of list
"""
final_str = ''
for string in list_name:
final_str += string + '\n'
return final_str |
def empty_or_matching_label(prediction: dict, labels: list) -> bool:
"""
Returns:
bool: if labels list is empty or prediction label matches a label in the list
"""
if len(labels) == 0 or prediction["label"] in labels:
return True
else:
return False |
def parsemem(value, unit):
"""Parse a memory size value and unit to int."""
e = {"B": 0, "K": 1, "M": 2, "G": 3, "T": 4}[unit]
return int(float(value) * 1024 ** e) |
def parse_csv(csv, as_ints=False):
"""
Parses a comma separated list of values as strings or integers
"""
items = []
for val in csv.split(','):
val = val.strip()
if val:
items.append(int(val) if as_ints else val)
return items |
def _pythonize_cmdstan_type(type_name: str) -> type:
"""Turn CmdStan C++ type name into Python type.
For example, "double" becomes ``float`` (the type).
"""
if type_name == "double":
return float
if type_name in {"int", "unsigned int"}:
return int
if type_name.startswith("bool"... |
def IsInClosurizedNamespace(symbol, closurized_namespaces):
"""Match a goog.scope alias.
Args:
symbol: An identifier like 'goog.events.Event'.
closurized_namespaces: Iterable of valid Closurized namespaces (strings).
Returns:
True if symbol is an identifier in a Closurized namespace, otherwise False... |
def cardValue(card):
"""Returns the value of a given card."""
if card[0] >= '2' and card[0] <= '9':
return int(card[0])
elif card[0] == 'T':
return 10
elif card[0] == 'J':
return 11
elif card[0] == 'Q':
return 12
elif card[0] == 'K':
return 13
elif car... |
def _formatOptions(kargs):
"""Returns a string: "key1=val1,key2=val2,..."
(where keyx and valx are string representations)
"""
arglist = ["%s=%s" % keyVal for keyVal in kargs.items()]
return "%s" % (",".join(arglist)) |
def _read_marker_mapping_from_ini(string: str) -> dict:
"""Read marker descriptions from configuration file."""
# Split by newlines and remove empty strings.
lines = filter(lambda x: bool(x), string.split("\n"))
mapping = {}
for line in lines:
try:
key, value = line.split(":")
... |
def path_exists(fpath):
"""
determine whether a file or directory exists
workaround for os.stat, which doesn't properly allow Unicode filenames
"""
try:
with open(fpath, "rb") as f:
f.close()
return True
except IOError as e:
if e.errno == 21:
# Is ... |
def triangle_area(base, height):
"""Returns the area of a triangle"""
# You have to code here
# REMEMBER: Tests first!!!
area = (base * height) / 2
return area |
def filename_to_varname(filename):
"""Converts a template file-name to a python variable name"""
return (filename.lower()
.replace('-', '_')
.replace('.txt', '')) |
def split_tuple(s):
"""Split a string of comma-separated expressions at the top level,
respecting parentheses and brackets:
e.g. 'a, b, c(d, e), f' -> ['a', 'b', 'c(d, e)', 'f']
Args:
s (string): a string of comma-separated expressions which may themselves contain commas
Returns:
list(str): a l... |
def make_matrix(num_rows, num_cols, entry_fn):
""" returns a num_rows by num_cols matrix
whose (i,j)th entry is entry_fn(i,j) """
# Example: identity_matrix = make_matrix(5, 5, is_diagonal)
return [[entry_fn(i, j) # given i, create a list
for j in range(num_cols)] # [entry_fn(... |
def get_trajectory_len(trajectory):
"""Get the total number of actions in the trajectory."""
return len(trajectory["action"]) |
def plain_text(*rtf):
"""Return the combined plain text from the list of RichText objects."""
return ("".join(text.plain_text for text in rtf if text)).strip() |
def _basename_in_ignore_list_re(base_name, ignore_list_re):
"""Determines if the basename is matched in a regex ignorelist
:param str base_name: The basename of the file
:param list ignore_list_re: A collection of regex patterns to match against.
Successful matches are ignored.
:returns: `True... |
def scaled_image(width, height):
"""face_recognition face detection slow AF compare to MTCNN
scaling the image as per resolution to process fast"""
total = width*height
scale_dict = {0.2: 6500000, 0.3: 4000000, 0.4: 2250000, 0.5: 1000000, 0.8: 500000, 1: 0}
for k, v in scale_dict.items():
... |
def solve(num_a, num_b, num_c, num_d, num_e):
"""Sums a bunch of numbers."""
return num_a + num_b + num_c + num_d + num_e |
def toUnicode(input):
"""
Convert bytes string to string
"""
return str(input, 'utf-8') |
def optimal_threshold(payoffs):
"""
>>> optimal_threshold([2,0,1,0.5])
0.5
>>> optimal_threshold([1.1,0,1,0.4])
0.9090909090909091
"""
return (payoffs[2] - payoffs[1]) / float(payoffs[0] - payoffs[1]) |
def expand_number_range(num_string):
"""
A function that will accept a text number range (such as 1,3,5-7) and convert it into a list of integers such as
[1, 3, 5, 6, 7]
:param num_string: <str> A string that is in the format of a number range (e.g. 1,3,5-7)
:return: <list> A list of all integers i... |
def inverse_brzycki(one_rm, r):
"""
Realistic for low reps. Conservative for high reps.
r-RM estimate based on 1RM.
"""
return (37 - r) / 36 * one_rm |
def format_helptext(value):
"""Handle formatting for HELPTEXT field.
Apply formatting only for token with value otherwise supply with newline"""
if not value:
return "\n"
return "\t {}\n".format(value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.