content stringlengths 42 6.51k |
|---|
def sum_two_2020(entries):
"""
>>> sum_two_2020([1721, 979, 366, 299, 675, 1456])
514579
"""
for i, entry1 in enumerate(entries, start=1):
for entry2 in entries[i:]:
if entry1 + entry2 == 2020:
return entry1 * entry2
return -1 |
def _nukenewlines(string):
"""
Strip newlines and any trailing/following whitespace;
rejoin with a single space where the newlines were.
Bug: This routine will completely butcher any whitespace-formatted text.
"""
if not string: return ''
lines = string.splitlines()
return ' '.join([lin... |
def dist(a, b):
"""Computes the distance between two points"""
return (sum([(a[i] - b[i]) ** 2 for i in range(len(a))]) ** .5) |
def _qual_arg(user_value,
python_arg_name,
gblock_arg_name,
allowable):
"""
Construct and sanity check a qualitative argument to
send to gblocks.
user_value: value to try to send to gblocks
python_arg_name: name of python argument (for error string)
gbl... |
def __matches(s1, s2, ngrams_fn, n=3):
"""
Returns the n-grams that match between two sequences
See also: SequenceMatcher.get_matching_blocks
Args:
s1: a string
s2: another string
n: an int for the n in n-gram
Returns:
set:
"""
... |
def parse_meo_hostmgr_line(l):
"""
Auxiliary function that cleans the line data (create a list from a line ... )
:param l: <string>
Something like this :
'\n10:7b:44:0e:42:1f 192.168.1.80 CDL Generic IP.Intf.LocalNetwork ETH.Phys.ethif1 Unknown-2a-88-77-b1-67-f6'
:return: <list> ... |
def is_label(token):
"""Returns True if this token has a : at the end
>>> is_label("label:")
True
>>> is_label("label")
False
>>> is_label(":::::")
True
"""
return token[-1] == ":" |
def _lowercase_kind(value):
"""Ensure kind is lowercase with a default of "metric" """
if isinstance(value, dict):
kind = value.get("kind", "metric").lower()
# measure is a synonym for metric
if kind == "measure":
kind = "metric"
value["kind"] = kind
return value |
def square_hexidecimal_ends_with_9(number):
""" Return whether the given number's square ends with 0x9 """
return (number * number) & 0xf == 0x9 |
def _check_type(obj, type, range):
"""
Function to check the type of object and if the object is betwwen a range:
obj (obj): the pobject to be checked
type: the type of the object
range: (list): the range (a list with 2 elements; min and max) of the which the number should be checked; eg: [0,1]
... |
def unparse_address(scheme, loc):
"""
Undo parse_address().
>>> unparse_address('tcp', '127.0.0.1')
'tcp://127.0.0.1'
"""
return '%s://%s' % (scheme, loc) |
def excel_column_number(name):
"""Excel-style column name to number, e.g., A = 1, Z = 26, AA = 27, AAA = 703."""
n = 0
for c in name:
n = n * 26 + 1 + ord(c) - ord('A')
return n |
def get_label_by_value(senti_value):
""" [0, 0.2], (0.2, 0.4], (0.4, 0.6], (0.6, 0.8], (0.8, 1.0] """
label = None
if 0.0 <= senti_value <= 0.2:
label = 1
if 0.2 < senti_value <= 0.4:
label = 2
if 0.4 < senti_value <= 0.6:
label = 3
if 0.6 < senti_value <= 0.8:
la... |
def _ApplySizeLimit(regions,
size_limit):
"""Truncates regions so that the total size stays in size_limit."""
total_size = 0
regions_in_limit = []
for region in regions:
total_size += region.size
if total_size > size_limit:
break
regions_in_limit.append(region)
return reg... |
def fizzbuzz(end=100):
"""Generate a FizzBuzz game sequence.
FizzBuzz is a childrens game where players take turns counting.
The rules are as follows::
1. Whenever the count is divisible by 3, the number is replaced with
"Fizz"
2. Whenever the count is divisible by 5, the number is replaced... |
def parse_sensor_values(data):
"""
Input line: <humidity>,<temperature>,<sound>
Output structure:
{
'humidity': <humidity>,
'temperature': <temperature>,
'sound': <sound>
}
"""
metrics = ['humidity', 'temperature', 'sound']
values = data.decode... |
def _metric_max_over_ground_truths(metric_fn, prediction, ground_truths):
"""Computes the max over all metric scores."""
scores_for_ground_truths = []
for ground_truth in ground_truths:
score = metric_fn(prediction, ground_truth)
scores_for_ground_truths.append(score)
return max(scores_for_ground_truths... |
def clean_recs(recs):
"""
Cleans the html source containing the recommendations and
returns a dictionary containing the recommendations.
Parameter:
recs: html-recommendations extracted using bs4
Returns:
cleaned_recs: list of extracted recommendations
"""
cleaned_recs = lis... |
def display_error_fields(fields):
"""format the display of missing fields"""
num_fields = len(fields)
if num_fields == 1:
return fields[0]
if num_fields == 2:
return "{} and {}".format(fields[-2], fields[-1])
#field length greater than 2
return "{} and {}".format(",".join(fields[... |
def trint(inthing):
"""
Turn something input into an integer if that is possible, otherwise return None
:param inthing:
:return: integer or None
"""
try:
outhing = int(inthing)
except:
outhing = None
return outhing |
def hhmmss(hh, mm=0, ss=0):
"""
converts time24 to seconds
"""
return (hh * 3600) + (mm * 60) + ss |
def word_article_count_list_to_dict(target_word, word_counts):
"""
Converts list of tuples of words and counts of articles these
occur in into list of dictionaries of target word, lists of words
and counts.
List is of form:
[("word, word, ...", count), ...]
Dictionary is of form:
... |
def replace(tokens):
"""0x00000001 --> 1 << 0"""
flag = int(tokens[0], 16)
shift = flag.bit_length() - 1
if shift >= 0 and 1 << shift == flag:
return "1 << " + str(shift)
else:
return None |
def return_group1(code_check):
"""
Input : L/G/R 6 character
Return : First digits of barcode
"""
if code_check == 'LLLLLL':
return 0
elif code_check == 'LLGLGG':
return 1
elif code_check == 'LLGGLG':
return 2
elif code_check == 'LLGGGL':
return 3
elif... |
def check_name(key, ys):
"""
Rename a key if already present in the list
"""
if key in ys:
key = '{}_2'.format(key)
return key |
def str_to_class(s):
"""Alternate helper function to map string class names to module classes."""
lst = s.split(".")
klass = lst[-1]
mod_list = lst[:-1]
module = ".".join(mod_list)
try:
mod = __import__(module)
if hasattr(mod, klass):
return getattr(mod, klass)
... |
def check_filenames(data_f):
"""
checks if the science scans have the same DID - this would cause an issue for naming the output demod files
"""
scan_name_list = [str(scan.split('.fits')[0][-10:]) for scan in data_f]
seen = set()
uniq_scan_DIDs = [x for x in scan_name_list if x in seen or seen... |
def make_upn_index(entry):
"""
entry - a dictionary that must have the 'userPrincipalName' defined
This transofrmer takes a dictionary, and returns another dictionary
that can be indexed using 'userPrincipalName'
"""
for key, value in entry.items():
if key == "userPrincipalName":
... |
def ConvertRate(r_in, in_convention, out_convention):
"""
ConvertRate - convert a rate from one convention to another
Conventions specified by str. Supported:
'1': Annual simple
'2': Semiannual
Under construction, only supports one conversion type for now!
For example, convert 4% semiannua... |
def interpret_offsets(left=0, top=0, right=0, bottom=0, left_offset=0, left_specific=0, top_offset=0, top_specific=0,
right_offset=0,
right_specific=0, bottom_offset=0, bottom_specific=0):
"""
Apply the given offsets to the left, top, right, and bottom orients.
""... |
def params_valid(spec: str, params: list) -> bool:
"""
check the params in valid according to the spec.
required params syntax: <param>
optional params syntax: [param]
any params syntax(MUST BE LAST ONE): [params ...]
"""
spec_arr = spec.split()
real_params_len = len(params)
... |
def convert_schedule_time(string: str) -> str:
"""
convert_schedule_time - Provides extra time types for schedule times
Args:
string (str): The string to convert
Returns:
str: The converted string
"""
# ticks, seconds, and days are included
if isinstance(string, int):
... |
def find_exec_in_executions(searched_exec, executions):
"""
Search if exec is contained in the executions.
:param searched_exec: Execution to search for.
:param executions: List of executions.
:return: Index of the execution, -1 if not found..
"""
for i, existing_exec in enumerate(executions... |
def vadd(vector1, vector2):
""" add vectors """
return (vector1[0] + vector2[0], vector1[1] + vector2[1]) |
def fname(func):
"""Return fully-qualified function name."""
return "%s.%s" % (func.__module__, func.__name__) |
def prompt_sound(should_end_session):
"""determine if the prompt sound should play"""
if should_end_session:
return ''
return "<audio src=\"https://s3.amazonaws.com/trainthatbrain/prompt.mp3\" />" |
def has_prefix(sub_s, lst):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
vocab_list = lst
for vocab in vocab_list:
if vocab.startswith(sub_s):
return True
return False |
def file_names(inp_fname):
"""Return the linkname and filename for dotfile based on user input.
"""
link = inp_fname if inp_fname.startswith('.') else ".{}".format(inp_fname)
return link, "dot{}.symlink".format(link) |
def search_error(status_code):
"""
This returns a directive on how to handle a given HTTP status code.
"""
int_status_code = int(
status_code
) # Need to make sure the status code is an integer
http_code_handling = {
"200": "valid",
"202": "valid",
"204": "valid... |
def formatError(error):
"""
Format an error as a string. Write the error type as prefix.
Eg. "[ValueError] invalid value".
"""
return "[%s] %s" % (error.__class__.__name__, error) |
def hard_sort_magnitude(l):
"""Takes a list of positive and negative numbers, and sorts them according to their absolute values. The list [3, -2, 1] would normally get sorted to [-2, 1, 3], but we want you to return [1, -2, 3] instead. protip: python's default sort order is ascending"""
return sorted(l, key=abs... |
def button(text):
"""Help function to create button"""
return {
"action": {
"type": "callback",
"payload": "{}",
"label": f"{text}"
},
} |
def to_int(string):
"""
Convert a string to integer
:param str string: A number in string format
:return: the string as integer
:rtype str
"""
return int(float(string)) |
def set_color(message, message_color, foreground_color):
"""Set color characters around a message
:param message: Message string
:param message_color: Message color
:param foreground_color: Color that the output will be reset to
:return: Message wrapped in color characters
"""
return '{messa... |
def create_link(url):
"""Create an html link for the given url"""
return (f'<a href = "{url}" target="_blank">{url}</a>') |
def search(metadata, keyword, include_readme):
"""Search for the keyword in the repo metadata.
Args:
metadata (dict) : The dict on which to run search.
keyword (str) : The keyword to search for.
include_readme (bool) : Flag variable indicating whether
to search keyword inside th... |
def _fixup(string: str) -> str:
"""Avoid known issues with tokenize() by editing the string."""
return ''.join(
char for char in string
if char.isprintable()
).strip().strip('\\').strip() + '\n' |
def effect(effectpar):
"""
This function process data from effect parameters
**Args:**
*effectpar (str)*: string to parse
**Returns:**
*string ColorMadness* - if effect ColorMadness should be applied
*string ColorUp* -color of inverse bars above zero
*string ColorDown* -color of inver... |
def KK_RC22(w, Rs, R_values, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
return (
Rs
+ (R_values[0] / (1 + w * 1j * t_values[0]))
+ (R_values[1] / (1 + w * 1j * t_values[1]))
+ (R_values[2] / (... |
def _get_ec2_not_equal(column_name, values, delimiter=',', quotes='"'):
"""
Return a clause to select where a column is equal to one or more values.
"""
value_list = values.split(delimiter)
phrases = []
for value in value_list:
phrases.append('%s!=%s' % (column_name, '%s%s%s' % (quotes,... |
def _valid_error(error_part):
"""Is `error_part` a valid error_part from a JSON-RPC 2.0 response object?
`error_part` should just be the \"error\" member (which should be a
dictionary). It shouldn't be a full response.
"""
# We just check that error_part has the right footprint. Don't worry about ... |
def uncolorize(msg):
"""
Strip ANSI color codes from a string.
"""
code = '\033[1;'
if msg.find(code) >= 0:
msg = msg.replace(code, '')[3:-1]
return msg |
def get_diffs(list1, list2):
"""Finds new users and lost users and returns a tuple containing them in
this order. If there's no difference return false."""
new = list(set(list1) - set(list2))
lost = list(set(list2) - set(list1))
if bool(new + lost):
return (new, lost)
else:
ret... |
def elb_public_lookup(session, hostname):
"""Lookup the Public DNS name for a ELB. Now searches for both classic and application ELBs
Args:
session (Session|None) : Boto3 session used to lookup information in AWS
If session is None no lookup is performed
hostna... |
def add_two_numbers(first, second):
"""Adds up both numbers and return the sum.
Input values must be numbers."""
if not isinstance(first, (int, float)) or not (isinstance(second, (int, float))):
raise ValueError("Inputs must be numbers.")
return first + second |
def jacobi(a: int, n: int) -> int:
"""Computes the jacobi symbol of a, n.
Args:
a:
n:
Returns:
"""
if a == 0:
if n == 1:
return 1
else:
return 0
# property 1 of the jacobi symbol
elif a == -1:
if n % 2 == 0:
retur... |
def initialize_bytes_from_method_call(bytesPtr, instance, mayThrowOnFailure):
"""Internal function to try converting 'instance' to a bytes.
Args:
bytesPtr - a PointerTo(bytes) that we're supposed to initialize
instance - something with a __bytes__method
mayThrowOnFailure - if True, then... |
def get_words(line):
"""Return a list of the tokens in line."""
line = line.replace("\t", " ")
line = line.replace("\v", " ")
line = line.replace("\r", " ")
line = line.replace("\n", " ")
while line.count(" "):
line = line.replace(" ", " ")
line = line.strip()
return [word + " ... |
def decode_key_string(buf, off: int) -> str:
"""Decodes a byte array at buf[off:] into string, stripping off null terminator"""
i = buf[off:].find(b"\0")
if i == -1:
return buf[off:]
return buf[off: off + i].decode("utf-8") |
def recursive_unique(sequence):
"""Solution to exercise C-4.11.
Describe an efficient recursive function for solving the element
uniqueness problem, which runs in time that is at most O(n^2) in the
worst case without using sorting.
------------------------------------------------------------------... |
def smooth(x, one_smoothing_factor, zero_smoothing_factor=1e-5):
"""
:param x:
:param one_smoothing_factor:
:param zero_smoothing_factor: float smoothing factor for the zero entries in adjacency matrix
:return:
"""
if one_smoothing_factor < 0:
return abs(one_smoothing_factor) * x
... |
def AUC(answers, scores):
"""
Compute the `AUC <https://en.wikipedia.org/wiki/Area_under_the_curve_(pharmacokinetics)>`_.
@param answers expected answers 0 (false), 1 (true)
@param scores score obtained for class 1
@return number
"""
ab = list(zip(answers,... |
def ordinal(n):
"""Converts an integer into its ordinal equivalent.
Args:
n: number to convert
Returns:
nth: ordinal respresentation of passed integer
"""
nth = "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (n % 10 < 4) * n % 10 :: 4])
return nth |
def human_m(v):
"""Returns a distance autoselected for mm, cm, m, and km
"""
if v < 1e-2:
return (v*1.0e3, 'mm')
if v < 1:
return (v*1.0e2, 'cm')
if v < 1000:
return (v, 'm')
return (v/1.0e3, 'km') |
def gcd(a, b):
"""Returns the greatest common divisor of a and b.
Should be implemented using recursion.
>>> gcd(34, 19)
1
>>> gcd(39, 91)
13
>>> gcd(20, 30)
10
>>> gcd(40, 40)
40
"""
"*** YOUR CODE HERE ***"
if a < b:
return gcd(b, a)
elif a % b != 0:
... |
def replace_tags(html_string):
"""
Function to replace common HTML formatting strings with RTF encoding strings.
:param html_string:
:return:
"""
result = None
if html_string:
rtf_string = html_string.replace("<em>", "\i ") # Replace emphasis tag with italics
rtf_string = rt... |
def find_dict_key(obj, val):
"""
Find all key for given value
:param obj: dict
:param val: value
:return: list
"""
result = []
for k, v in obj.items():
if v == val:
result.append(k)
return result |
def overlap(reg1, reg2, spacer=0):
"""
Return overlap between two regions.
e.g. [10, 30], [20, 40] returns [20, 30]
"""
regions = sorted([sorted(reg1), sorted(reg2)])
try:
if regions[0][1] - regions[1][0] >= spacer:
return[max([regions[0][0], regions[1][0]]),
... |
def task_map_partition(f, partition, *args, **kwargs):
"""
Apply a function to a partition in a new task. The function should take an
iterable as a parameter and return a list.
:param f: A function that takes an iterable as a parameter
:param map_func: in case 'f' is a reverse_mapper function, the r... |
def str_maxed(arg, maxlen):
""" Returns a (possibly) truncated string representation of arg
If maxlen is positive (or null), returns str(arg) up to maxlen chars.
:param arg:
:param maxlen:
:return:
"""
s = str(arg)
if maxlen <= 0 or len(s) <= maxlen:
return s
else:
... |
def fix_precollection_crs(crs):
"""Function to fix duplicated datum and ellipsoid in proj string of
bdc pre-collection datasets
"""
import re
return re.sub('\+datum=(\S)*\s', '', crs) |
def size_to_readable(size: int) -> str:
"""Convert a size in bytes to a human readable value in KiB, MiB, or
GiB"""
if size / 1024 ** 2 < 1:
return str(round(size / 1024)) + " KiB"
if size / 1024 ** 3 < 1:
return str(round(size / 1024 ** 2, 1)) + " MiB"
return str(round(size / 1024 *... |
def map_value(in_v, in_min, in_max, out_min, out_max): # (3)
"""Helper method to map an input value (v_in)
between alternative max/min ranges."""
v = (in_v - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
if v < out_min: v = out_min
elif v >... |
def logf(msg, **kwargs):
"""Formats message for Logging"""
if kwargs:
msg += "\t"
for msg_key, msg_value in kwargs.items():
msg += " %s=%s" % (msg_key, msg_value)
return msg |
def rindex_tup(tupl, value, start=None, end=None):
"""
Finds the highest index of ``value`` within ``tupl`` in the range [``start``, ``end``].
Optional arguments ``start`` and ``end`` are interpreted as in slice notation. However,
the index returned is relative to the tuple and not the slice ``tupl... |
def miniDump(payload):
"""For errors, display simple hex dump of message.
For *level0*, where we are still dealing in bytes,
``miniDump`` provides a very simple dump of the message that
divides the message into hex parts. Specifically,
the ground uplink header and frame pieces.
The first line... |
def link_album(album_id):
"""Generates a link to an album
Args:
album_id: ID of the album
Returns:
The link to that album on Spotify
"""
return "https://open.spotify.com/album/" + album_id |
def str_tspec(tspec, arg_names):
""" Turn a single tspec into human readable form"""
# an all "False" will convert to an empty string unless we do the following
# where we create an all False tuple of the appropriate length
if tspec == tuple([False] * len(arg_names)):
return "(nothing)"
retu... |
def fib(n):
"""Assumes n is an int >= 0
Returns Fibonacci of n"""
if n == 0 or n == 1:
return 1
else:
return fib(n-1) + fib(n-2) |
def get_input_words(word_counts, reserved_tokens, max_token_length):
"""Filters out words that are longer than max_token_length or are reserved.
Args:
word_counts: list of (string, int) tuples
reserved_tokens: list of strings
max_token_length: int, maximum length of a token
Returns:
... |
def routes2sol(routes):
"""Concatenates a list of routes to a solution. Routes may or may not have
visits to the depot (node 0), but the procedure will make sure that
the solution leaves from the depot, returns to the depot, and that the
routes are separated by a visit to the depot."""
if not rout... |
def color_ordered(group_order, group_to_color):
"""Colors in the order created by the groups"""
return [group_to_color[g] for g in group_order] |
def get_view(filename: str) -> str:
"""
Returns the view of an AFNI file. (Everything after the final "+".)
"""
return filename.split("+")[-1] |
def Divide(a, b):
"""Returns the quotient, or NaN if the divisor is zero."""
if b == 0:
return float('nan')
return a / float(b) |
def _is_all_true(item):
"""Has at least one result and nothing that is false"""
non_true = [i for i in item if not i]
if not item or non_true:
return False
return True |
def dns_name_decode(name, cb_mc_bytes=lambda: b""):
"""
DNS domain name decoder (bytes to string)
name -- example: b"\x03www\x07example\x03com\x00"
cb_bytes -- callback to get bytes used to find name in case of Message Compression
cb_bytes_pointer(): bytes
return -- example: "www.example.co... |
def move_to(text):
"""Simply returns the args passed to it as a string"""
return "Moved to! %s" % str(text) |
def compareTo(s1, s2):
"""Compares two strings to check if they are the same length and whether one is longer
than the other"""
move_slice1 = 0
move_slice2 = 1
if s1[move_slice1:move_slice2] == '' and s2[move_slice1:move_slice2] == '':
return 0 # return 0 if same length
elif s1[move_... |
def hex_int_to_dec(hex1, hex2):
""" calculates a 2 digit hexadecimal to normal decimal """
current_digit = int(hex1)
current_digit1 = int(hex2)
power = 1
power1 = 0
hex_iter = []
if hex1:
mul_dig = current_digit * (16 ** power)
hex_iter.append(mul_dig)
if hex2:
... |
def eulerToMatrix(euler): #double heading, double attitude, double bank
"""
code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/'.
this conversion uses NASA standard aeroplane conventions as described on page:
'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.... |
def approved_recipe(recipe, day, threshold):
"""
# Takes in three arguments. First is a list containing
# ingredients and their weights, second is the day of the week,
# and the third is the threshold that the combined weights must
# be above. Day of the week affects the multiplier of the
# ingr... |
def fix_order(ordered, readable_headers) -> list:
""" Return the readable headers by the order given """
readable_headers_values = readable_headers.values()
temp_readable = {
**{i[0].lower() + i[1:]: i for i in readable_headers_values},
**{i.lower(): i for i in readable_headers_values}}
... |
def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) |
def _redirect_path(redirect_path, fb, path):
"""
Resolve the path to use for the redirect_uri for authorization
"""
if not redirect_path and fb.oauth2_redirect:
redirect_path = fb.oauth2_redirect
if redirect_path:
if callable(redirect_path):
redirect_path = redirect_... |
def reverse_to_address(reverse_ref):
"""Take the reverse lookup qname format and extract the address."""
return '.'.join(reversed(reverse_ref.split('.in-addr.arpa')[0].split('.'))) |
def to_alpha(anumber):
"""Convert a positive number n to its digit representation in base 26."""
output = ''
if anumber == 0:
pass
else:
while anumber > 0:
anumber = anumber - 1
output += chr(anumber % 26 + ord('A'))
anumber = anumber // 26
return ... |
def min_strip_comments(file_lines, *args, **kwargs):
"""Comments are only needed for weak Kerbals, remove them"""
def comment_filter(line):
found_comment = line.find("//")
return found_comment >= 0, found_comment
return_lines = []
for line in file_lines:
found, start = comment_... |
def is_float(x):
"""Return true if X can be coerced to a float. Otherwise, return false."""
try:
float(x)
return True
except ValueError:
return False |
def rotate_matrix(matrix: list) -> list:
""" generalize and expand
1 0 -> 0 1 -> 0 0 -> 0 0
0 0 0 0 0 1 1 0
x x x x x x
x -> x
x x
intuition:
create a zero'd copy of nxn matrix
go from the outside inside of the original matrix
select each column a... |
def isNumber(newtext, oldtext, entry):
"""
Validation function for an Entry; limits inputs to numbers of a length smaller than 16
parameters: str the text to be set
str the current text
gui.Entry the entry affected
return values: boolean is the operation val... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.