content stringlengths 42 6.51k |
|---|
def next_tick(cell_alive, number_of_neighbors):
"""Returns a cell's state in the next turn
Three conditions for the next state are layed out:
1. A cell is alive and has 2/3 neighbors, it stays alive
2. A cell is dead and has 3 neighbors, it is born
3. Neither of the above, it dies
"""
... |
def hamming_distance(string1, string2):
"""
string1 and string2 must be in bytes string.
Return number of '1' in xor(string1, string2), it tell's how many bit
are differents.
"""
if len(string1) != len(string2):
raise ValueError("Undefined for sequences of unequal length")
return s... |
def bbox(vertices):
"""Compute bounding box of vertex array.
"""
if len(vertices)>0:
minx = maxx = vertices[0][0]
miny = maxy = vertices[0][1]
minz = maxz = vertices[0][2]
for v in vertices[1:]:
if v[0]<minx:
minx = v[0]
e... |
def valid_guess(puzzle, guess, row, col):
"""
Takes puzzle, guess, row, col as parameters
Figures out whether the guess at the row/col of the puzzle is a valid guess
Returns True if it is valid, False otherwise
"""
# check the row first
row_vals = puzzle[row]
if guess in row_vals:
... |
def drop_lsb_bits(val, n_bits):
"""Drop the lowest bits in a number."""
return (val >> n_bits) << n_bits |
def partition(lst, pivot):
"""Modifired partition algorithm in section 7.1"""
pivot_idx = None
for idx, value in enumerate(lst):
if value == pivot:
pivot_idx = idx
if pivot_idx is None:
raise Exception
lst[pivot_idx], lst[-1] = lst[-1], lst[pivot_idx]
pivot = lst[-1]
... |
def GetNextLow(temp, templist):
"""Outputs the next lower value in the list."""
templist = (int(t) for t in templist if t != '')
templist = [t for t in templist if t < int(temp)]
if templist: return max(templist)
else: return None |
def split_qualified(fqname):
"""
Split a fully qualified element name, in Clark's notation, into its URI and
local name components.
:param fqname: Fully qualified name in Clark's notation.
:return: 2-tuple containing the namespace URI and local tag name.
"""
if fqname and fqname[0] == '{':
... |
def frequency(session, Type='Real64', RepCap='', AttrID=1150002, buffsize=0, action=['Get', '']):
"""[Frequency (hertz)]
The nominal (sometimes called center) frequency, in hertz, of the signal to be measured.
The allowable range of values depend on hardware configuration, absolute limits are 50 MHz to 26.... |
def FilterBuildStatuses(build_statuses):
"""We only want to process passing 'normal' builds for stats.
Args:
build_statuses: List of Cidb result dictionary. 'stages' are not needed.
Returns:
List of all build statuses that weren't removed.
"""
# Ignore tryserver, release branches, branch builders, c... |
def flatten(source):
""" Flattens a tuple of lists into a list """
flattened = list()
for l in source:
for i in l:
flattened.append(i)
return flattened |
def search_rotate(array, val):
"""
Finds the index of the given value in an array that has been sorted in
ascending order and then rotated at some unknown pivot.
"""
low, high = 0, len(array) - 1
while low <= high:
mid = (low + high) // 2
if val == array[mid]:
return ... |
def ways_to_climb(num_steps, max_step_size):
"""
Calculate the number of ways to climb a certain number of steps
given a maximum step size.
This approach uses a dynamic-programming approach
:param num_steps:
:param max_step_size:
:return:
"""
# initialize base cases
memo = {0: ... |
def remove_all(item, seq):
"""Return a copy of seq (or string) with all occurrences of item removed."""
if isinstance(seq, str):
return seq.replace(item, '')
elif isinstance(seq, set):
rest = seq.copy()
rest.remove(item)
return rest
else:
return [x for x in seq if... |
def to_type_key(dictionary, convert_func):
"""Convert the keys of a dictionary to a different type.
# Arguments
dictionary: Dictionary. The dictionary to be converted.
convert_func: Function. The function to convert a key.
"""
return {convert_func(key): value
for key, value ... |
def check_api_token(api_key):
"""
Check if the user's API key is valid.
"""
if (api_key == 'API_KEY'):
return True
else:
return False |
def myround(x, base):
"""
myround is a simple round tool
"""
return (float(base) * round(float(x)/float(base))) |
def flatten(arr):
"""Flatten array."""
return [item for sublist in arr for item in sublist] |
def lines_from_files(files):
""" 'readlines' for a list of files, concatening them all together """
lines = []
for f in files:
with open(f, "r") as fp:
lines.extend(fp.readlines())
return lines |
def fix_stardoc_table_align(line: str) -> str:
"""Change centered descriptions to left justified."""
if line.startswith('| :-------------: | :-------------: '):
return '| :------------ | :--------------- | :---------: | :---------: | :----------- |'
return line |
def flatten_list(l):
"""
Flatten a list.
"""
return [item for sublist in l for item in sublist] |
def emptyString(line: str) -> bool:
"""
Determine if a string is empty ('', ' ','\n','\t') or not
"""
return any(line == i for i in '* *\n*\t'.split('*')) |
def unlist(d: dict) -> dict:
"""Find all appearance of single element list in a dictionary and unlist it.
:param: d: a python dictionary to be unlisted
"""
if isinstance(d, list):
if len(d) == 1:
return d[0]
return d
if isinstance(d, dict):
for key, val in d.item... |
def _check_set(set_, value):
"""Return true if *value* is a member of the given set or if
the *value* is equal to the given set.
"""
try:
return value in set_ or value == set_
except TypeError:
return False |
def get_status_line(file_size):
"""
This method returns the status line for the HTTP response based on the file size.
:param file_size: the size of the requested file
:return: the status line as a bytes object
"""
status_line = b'HTTP/1.1 '
if file_size > 0:
status_line += b'200 OK... |
def jday(year, mon, day, hr, minute, sec):
"""Return two floats that, when added, produce the specified Julian date.
The first float returned gives the date, while the second float
provides an additional offset for the particular hour, minute, and
second of that date. Because the second float is m... |
def strongly_connected_components(graph):
""" Find the strongly connected components in a graph using
Tarjan's algorithm.
# Taken from http://www.logarithmic.net/pfh-files/blog/01208083168/sort.py
graph should be a dictionary mapping node names to
lists of successor nodes.
"... |
def _reversed_int_fast(n):
"""A faster implementation of reversed_int that keeps types as integers
"""
reversed_n = n % 10
while n > 0:
n /= 10
if n > 0:
reversed_n *= 10
reversed_n += n % 10
return reversed_n |
def get_variations(response_object):
"""Formatting functions should accept any of these variations"""
return [{'results': [response_object]}, [response_object], response_object] |
def find_smallest(arr):
"""Function to find the smallest number in an array
Args:
arr(list): The list/array to find the index
Returns:
smallest_index(int): The index of the smallest number
"""
smallest = arr[0] # stores the smallest value
smallest_index = 0 # stores the position of the smallest va... |
def _miriam_identifiers(type_, namespace, identifier):
"""
Fix the MetaNetX identifiers into miriam equivalents.
MetaNetX doesn't use correct miriam identifiers. This function maps the
known namespace and entity identifiers used by MetaNetX to valid miriam
identifiers.
Parameters
---------... |
def reverse_actions(actions: list):
"""
Reverse the action list to an other action list with opposite cammands
Mission Pad ID commands are not supported yet
"""
reversed_list = []
#Ignorable statements
ign_statements = ['command', 'streamon', 'streamoff', 'mon', 'moff', 'sn?', 'battery?', '... |
def tostr(data):
"""convert bytes to str"""
if type(data) is bytes and bytes is not str:
data = data.decode('utf8')
return data |
def get_permissions(user):
""" Get permission bits that are required across all/most views.
Currently just a placeholder.
"""
permission_dict = {}
return permission_dict |
def polygon_area(corners): # pragma: no cover
"""polygon_area.
Args:
corners ([type]): [description]
Returns:
[type]: [description]
"""
area = 0.0
for i in range(len(corners)):
j = (i + 1) % len(corners)
area += corners[i][0] * corners[j][1]
area -= cor... |
def abreviate_file_name(file_name):
"""Returns a file name without its path : /path/to/file.cpp -> file.cpp"""
index_path = file_name.rindex('/')
return file_name[index_path+1:] |
def count_evens(start, end):
"""Returns the number of even numbers between start and end."""
counter = start
num_evens = 0
while counter <= end:
if counter % 2 == 0:
num_evens += 1
counter += 1
return num_evens |
def flatten(l):
"""Convert list of list to a list"""
return [ el for sub_l in l for el in sub_l ] |
def int_or_empty(string):
"""Function to convert numeric string to int (or None if string is empty)"""
if string:
return int(string)
else:
return None |
def _is_int(val):
"""Check if a value looks like an integet."""
try:
return int(val) == float(val)
except (ValueError, TypeError):
return False |
def replace_suffix(string, old, new):
"""Returns a string with an old suffix replaced by a new suffix."""
return string.endswith(old) and string[:-len(old)] + new or string |
def horizontal_check(board):
"""
This function checks horizontals in the board.
>>> horizontal_check([\
"**** ****",\
"***1 ****",\
"** 3****",\
"* 4 6****",\
" 9 5 ",\
" 6 83 *",\
"3 2 **",\
" 8 2***",\
" 2 ****"\
])
True
"""
nums = "123456... |
def add_log_group_name_params(log_group_name, configs):
"""Add a "log_group_name": log_group_name to every config."""
for config in configs:
config.update({"log_group_name": log_group_name})
return configs |
def commas(string: str) -> int:
"""Given a comma-separated string of branch lengths, returns the number of commas in the string.
The number of commas equals the number of elements in the string.
"""
i: int = 0
count: int = 0
while i < len(string):
if string[i] == ",":
... |
def bearing(lon1, lat1, lon2, lat2):
"""
calculates the angle between two points on the globe
output:
initial_bearing from -180 to + 180 deg
"""
from math import radians, cos, sin, atan2, degrees
#if (type(pointA) != tuple) or (type(pointB) != tuple):
# raise TypeError("Only tuples a... |
def logistic_map(pop, rate):
"""
Define the equation for the logistic map.
Arguments
---------
pop: float, current population value at time t
rate: float, growth rate parameter values
Returns
-------
scalar result of logistic map at time t+1
"""
return pop * ra... |
def compile_keys(options):
"""
Completion can contain lots of duplicate information.
For example the trigger is most of the time also the result.
Only in case of a value attribute is that returned.
It also takes hints into consideration for compilation.
"""
compiled_keys = []
for option... |
def format_resource_id(resource, separator=":"):
"""Concatenates the four-part ID for a resource record.
:param dict resource: an ArchivesSpace resource.
:param str separator: a separator to insert between the id parts. Defaults
to `:`.
:returns: a concatenated four-part ID for the resourc... |
def this_extra_edition_number(edicao):
"""
Gets a string 'edicao' that states which is this DOU's edition
(e.g. 132-B or 154) and returns the number (int) of extra editions up
to this current one. No extra editions (e.g. 154) is 0, first
extra edition (134-A) is 1, and so on.
"""
last_char ... |
def fake_detect_own_answers(input_str):
"""Imitates the ability of a self-aware model to detect its own answers.
In GoodModel.generate_text, we make the model answer with "dummy" to most questions.
Here, we exploit the keyword to cheat the test.
Args:
input_str: String: The model's input, cont... |
def validate_verb(verb_str):
"""
Determines whether or not the supplied verb is a valid HTTP verb.
"""
valid_verbs = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE']
if verb_str in valid_verbs:
return True
return False |
def lstrip_word(text, prefix):
"""Strip prefix from end of text"""
if not text.startswith(prefix):
return text
return text[len(prefix):len(text)] |
def _classify_sentence_by_topic(all_sentences_list, topic, synonyms):
"""
This method will group the sentences that have relation with the topic requested
or a synonym for the topic
:param all_sentences_list:
:param topic:
:param synonyms:
"""
topic_sentence = set()
if l... |
def calcMean(vector):
"""Calculate mean of vector"""
if len(vector) == 0:
return 0.0
else:
return sum(vector)/float(len(vector)) |
def get_all_buy_orders(market_datas):
"""
Get all buy orders from the returned market data
:param market_datas: the market data dictionary
:return: list of buy orders
"""
buy_orders = []
for _, market_data in market_datas.items():
for order in market_data:
if order['is_bu... |
def format_kfp_run_id_uri(run_id: str):
"""Return a KFP run ID as a URI."""
return "kfp:run:%s" % run_id |
def validate_height(value: str) -> bool:
"""value must be xxxcm or xxin:
if cm, must be 150-193, else 59-76"""
try:
if value.endswith("cm"):
return int(value[:-2]) in range(150, 194)
elif value.endswith("in"):
return int(value[:-2]) in range(59, 77)
return Fal... |
def is_pow2(n):
"""Check if a number is a power of 2."""
return (n != 0) and (n & (n - 1) == 0) |
def get_recs(user_recs, k=None):
"""
Extracts recommended item indices, leaving out their scores.
params:
user_recs: list of lists of tuples of recommendations where
each tuple has (item index, relevance score) with the
list of tuples sorted in order of decreasing relevance
... |
def unit_label(quantity):
"""Returns units as a string, for given quantity
"""
labels = {
'accrate': r'$\dot{m}_\mathrm{Edd}$',
'dt': 'h',
'd': 'kpc',
'd_b': 'kpc',
'fluence': '$10^{39}$ erg',
'g': '$10^{14}$ cm s$^{-2}$',
'i': 'deg',
'lum': '$... |
def strip_geocoding(dicts):
"""
Remove unwanted metadata from socrata location field
"""
for record in dicts:
try:
location = record.get("location")
record["location"] = {
"latitude": location["latitude"],
"longitutde": location["longitutd... |
def print_type(*args) -> None:
"""
Print the type of the argument.
Args:
args (any type): tuple of any size
Returns:
None
"""
print('\n')
for idx, arg in enumerate(args, start=1):
print('type of arg %s is %s' % (idx, type(arg)))
print('\n')
return None |
def convert_to_int(word):
"""
Convert word to integer value. If word is not in the dictionary, return 0. If word is in the dictionary, return the integer value.
"""
word_dict = {
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"se... |
def cleanup_description(description):
"""Removes all uninteresting stuff from the event description ``description``."""
relevant_parts = []
parts = description.split(';')
for item in parts:
item = item.strip()
if item not in ['', 'fix', 'Abhaltung', 'geplant', 'Import']:
rele... |
def format_params(paramlist, otherlist=None):
"""Format the parameters according to the nipy style conventions.
Since the external programs do not conform to any conventions, the
resulting docstrings are not ideal. But at a minimum the
Parameters section is reasonably close.
Parameters
------... |
def filter_to_true_or_false(value: str) -> str:
"""
Jinja filter that takes in a value, casts it to a bool and
emits ``true`` or ``false``.
The following example assumes ``deprecated`` as an integer ``1``.
Example::
"deprecated": {{ T.deprecated | ln.js.to_true_or_false }},
Results E... |
def time_to_utc(utc_offset, time):
""" (number, float) -> float
Return time at UTC+0, where utc_offset is the number of hours away from
UTC+0.
>>> time_to_utc(+0, 12.0)
12.0
>>> time_to_utc(+1, 12.0)
11.0
>>> time_to_utc(-1, 12.0)
13.0
>>> time_to_utc(-11, 18.0)
5.0
>>>... |
def nths(x, n):
""" Given a list of sequences, returns a list of all the Nth elements of
all the contained sequences
"""
return [l[n] for l in x] |
def is_valid(level, lesson):
"""Check if a level and lesson is valid
"""
if level == 1 and 0 < lesson < 26:
return True
if 1 < level < 8 and 0 < lesson < 31:
return True
return False |
def find_short(strg):
"""Return length of shortest word in sentence."""
words = strg.split()
min_size = float('inf')
for word in words:
if len(word) < min_size:
min_size = len(word)
return min_size |
def triple_step(n: int)-> int:
"""classic, decompose in subproblems + memoization
"""
# base cases
if n <= 1: return 1
if n == 2: return 3
if n == 3: return 3
# recurse
return sum((triple_step(n-1), triple_step(n-2), triple_step(n-3))) |
def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret |
def get_kp_color(val):
""" Return string of color based on Kp """
if val > 4:
return "Red"
elif val < 4:
return "Green"
else:
return "Yellow" |
def split_str(s):
""" Split out units from a string suffixed with units in square brackets
Args:
s (str): A string with units at the end in square brackets (e.g.
'widget.length [mm]').
Returns:
tuple: The string with it's units stripped (e.g. 'widget.length'),
and... |
def find_failed_results(run_artifacts: dict) -> list:
"""find the index and ID for which elements failed in run
Args:
run_artifacts (dict): dbt api run artifact json response
Returns:
list: list of tuples with unique id, index
"""
failed_steps = []
for index, result in enumera... |
def update_blurs(blur_o, blur_d, routing):
"""Signal when all the input fields are full (or at least visited?) and a routing option has been picked."""
if routing == 'slope':
c = 0
elif routing == 'balance':
c = 1
else:
c = 2
if (not blur_o) or (not blur_d):
return 0
... |
def maxlen(stringlist):
"""returns the length of the longest string in the string list"""
maxlen = 0
for x in stringlist:
if len(x) > maxlen:
maxlen = len(x)
return maxlen |
def score_initial_caption_lag(initial_caption_times):
"""Measures the time between when the wav file starts playback and when
the first non-empty caption is seen"""
initial_caption_times = list(filter(lambda x: x >= 0, initial_caption_times))
if not initial_caption_times:
return 0.0
return... |
def create_draft(service, user_id, message_body):
"""Create and insert a draft email. Print the returned draft's message and id.
Args:
service: Authorized Gmail API service instance.
user_id: User's email address. The special value "me"
can be used to indicate the authenticated user.
... |
def get_all_prey_and_preference(settings_dict):
"""inspect input and build list of all prey for each predator"""
food_web_settings = settings_dict['food_web']
all_prey = {}
preference = {}
for settings in food_web_settings:
pred = settings['predator']
if pred not in all_prey:
... |
def get_s3_liquid_path(user_id: int, video_id: int, liquid_id: int) -> str:
"""Gets s3 liquid path
path structure: users/<user_id>/videos/<video_id>/liquids/<liquid_id>
Args:
user_id: user_id
video_id: video_id
treatment_id: liquid_id
Returns:
string url
"""
retu... |
def note_to_index(note_str):
"""
note_str: str -> int
Returns the integer value of the note in note_str, given as an index in
the list below.
"""
notes = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
return(notes.index(note_str)) |
def arg(prevs, newarg):
""" Joins arguments to list """
retval = prevs
if not isinstance(retval, list):
retval = [retval]
return retval + [newarg] |
def rating_header(context):
"""
Inserts the includes needed into the html
"""
return { 'rabidratings_media_url': '/static/rabidratings' } |
def gcd_lame(a, b):
"""
Calculate gcd using Gabiel Lame's mod-ification of Euclids algorithm
"""
if (a <= 0 and b <= 0):
return("NaN")
if (a == 0 or b == 0):
return (0)
while (a != b):
if (a > b):
if (b == 0):
return (a)
a = a % b ... |
def collatz_sequence_length(n: int) -> int:
"""Returns the Collatz sequence length for n."""
sequence_length = 1
while n != 1:
if n % 2 == 0:
n //= 2
else:
n = 3 * n + 1
sequence_length += 1
return sequence_length |
def GetID(attrs, tag, val):
"""
handy method which pulls out a nested id: attrs refers to a dictionary holding the id
tag refers to the tag we're looking at (e.g measure, part etc)
val refers to the exact index of the tag we're looking for (e.g number, id etc)
example case: attrs = self.attribs, tag... |
def qsfilter(qs, filter_items=[]):
"""
This function will take a query string of the form a=1&b=2&c=3 and return a
string filter based on values. For example, passing in filter=['b'] will
return a=1&c=3
"""
result = []
params = qs.split('&')
for param in params:
if param.find('... |
def _to_number(val):
"""
Convert to a numeric data type, but only if possible (do not throw error).
>>> _to_number('5.4')
5.4
>>> _to_number(5.4)
5.4
>>> _to_number('-6')
-6
>>> _to_number('R2D2')
'R2D2'
"""
try:
if val.is_integer(): # passed as int in float for... |
def clues_too_many(text):
""" Check for any "too many connections" clues in the response code """
text = text.lower()
for clue in ('exceed', 'connections', 'too many', 'threads', 'limit'):
# Not 'download limit exceeded' error
if (clue in text) and ('download' not in text) and ('byte' not in... |
def zipped_x_o_value_to_character(tup):
"""
Converts a tuple of booleans indicating placement of x or o markers, and returns a character representation.
:param tup: A tuple of a boolean, indicating if an x is placed, a second boolean, indicating if an o is placed.
:return: One of three characters, 'X... |
def splice(array, *args):
"""Implementation of splice function"""
offset = 0;
if len(args) >= 1:
offset = args[0]
length = len(array)
if len(args) >= 2:
length = args[1]
if offset < 0:
offset += len(array)
total = offset + length
if length < 0:
... |
def move_player_forward(player_pos, current_move):
"""
move pos by current move in circular field from 1 to 10 forward
"""
player_pos = (player_pos + current_move) % 10
if player_pos == 0:
return 10
return player_pos |
def solution2(root):
"""
Inefficient solution by myself
---
Runtime: 72ms
---
:type root: TreeNode
:rtype: list[int]
"""
if root is None:
return []
queue = [(root, 0)]
bfs_nodes = []
while queue:
bfs_nodes.append(queue.pop(0))
cur_node, cur_dept... |
def _has_one_of_attributes(node, *args):
"""
Check whether one of the listed attributes is present on a (DOM) node.
@param node: DOM element node
@param args: possible attribute names
@return: True or False
@rtype: Boolean
"""
return True in [ node.hasAttribute(attr) for attr in args ] |
def preprocess_text(sentence):
"""Handle some weird edge cases in parsing, like 'i' needing to be capitalized
to be correctly identified as a pronoun"""
cleaned = []
words = sentence.split(' ')
for w in words:
if w == 'i':
w = 'I'
if w == "i'm":
w = "... |
def dot(p1, p2):
"""Dot product 4-momenta"""
e = p1[0]*p2[0]
px = p1[1]*p2[1]
py = p1[2]*p2[2]
pz = p1[3]*p2[3]
return e - px - py - pz |
def get_data_requirements(theory):
"""
Args:
dataname (string) : name of data.
Returns:
dataname (list) : (people, events, citation network)
"""
dataname = ['John']
result = []
if True:
result.append(dataname)
return "This is the required data" |
def bytes_to_pascals(dg_bytes):
"""Takes a list of 3 bytes read from the DG-700 and returns a pressure
in Pascals.
Larry Palmiter originally wrote this code for TEC in Basic,
which has proven immensely useful.
"""
bx, hi, lo = dg_bytes # unpack the array into individual values
pressure =... |
def insertion_sort(arr):
"""Performs an Insertion Sort on the array arr."""
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while key < arr[j] and j >= 0:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.