content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# @desc This is a code that determines whether a number is positive, negative, or just 0
# @desc by Merrick '23
def positive_negative(x):
if x > 0:
return "pos"
elif x == 0:
return "0"
else:
return "neg"
def main():
print(positive_negative(5))
print(positive_negative(-1))
print(positive_negative(0))
print(positive_negative(21))
print(positive_negative(-100))
if __name__ == '__main__':
main()
| def positive_negative(x):
if x > 0:
return 'pos'
elif x == 0:
return '0'
else:
return 'neg'
def main():
print(positive_negative(5))
print(positive_negative(-1))
print(positive_negative(0))
print(positive_negative(21))
print(positive_negative(-100))
if __name__ == '__main__':
main() |
__all__ = [
'resp',
'user'
]
| __all__ = ['resp', 'user'] |
# ------------------------------------------------ EASTER EGG ------------------------------------------------
# Congratulations on finding this file! Please use the following methods below to decrypt the given cipher.
def decrypt(cipher, multiple):
text = ""
for idx, ch in enumerate(cipher):
if ch.isalpha():
shift = multiple * idx % 26
newChar = ord(ch) + shift
if newChar > ord('z'):
newChar -= 26
text += chr(newChar)
return text
def encrypt(text, multiple):
cipher = ""
for idx, ch in enumerate(text):
if ch.isalpha():
shift = multiple * idx % 26
newChar = ord(ch) - shift
if newChar < ord('a'):
newChar += 26
cipher += chr(newChar)
return cipher | def decrypt(cipher, multiple):
text = ''
for (idx, ch) in enumerate(cipher):
if ch.isalpha():
shift = multiple * idx % 26
new_char = ord(ch) + shift
if newChar > ord('z'):
new_char -= 26
text += chr(newChar)
return text
def encrypt(text, multiple):
cipher = ''
for (idx, ch) in enumerate(text):
if ch.isalpha():
shift = multiple * idx % 26
new_char = ord(ch) - shift
if newChar < ord('a'):
new_char += 26
cipher += chr(newChar)
return cipher |
while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
a,b=map(int,input().split())
s += a*(b-last)
last = b
print(s,"miles") | while True:
n = int(input())
if n == -1:
break
s = 0
last = 0
for i in range(n):
(a, b) = map(int, input().split())
s += a * (b - last)
last = b
print(s, 'miles') |
no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7/100
discount = 10/100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0/3.0) + service_tax
total_passenger_cost = (rate_per_adult + rate_per_children) - discount
print(round(total_passenger_cost, 2))
| no_of_adults = float(input())
no_of_childrens = float(input())
total_passenger_cost = 0
service_tax = 7 / 100
discount = 10 / 100
rate_per_adult = no_of_adults * 37550.0 + service_tax
rate_per_children = no_of_childrens * (37550.0 / 3.0) + service_tax
total_passenger_cost = rate_per_adult + rate_per_children - discount
print(round(total_passenger_cost, 2)) |
class Status(object):
SHUTTING_DOWN = 'Shutting Down'
RUNNING = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@property
def status(self):
return Status.SHUTTING_DOWN if self.is_shutting_down() else Status.RUNNING
runtime_state = __State()
| class Status(object):
shutting_down = 'Shutting Down'
running = 'Running'
class __State(object):
def __init__(self):
self._shutting_down = False
def set_to_shutting_down(self):
self._shutting_down = True
def is_shutting_down(self):
return self._shutting_down
@property
def status(self):
return Status.SHUTTING_DOWN if self.is_shutting_down() else Status.RUNNING
runtime_state = ___state() |
"""Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned raster graphics.
The image filter relies on multiresolution analysis methods (Wavelet
transforms) that remove some scales (frequencies) locally in space. These
methods are particularly efficient when signal and noise are located at
different scales (or frequencies). Optional features improve the SNR ratio when
the (clean) signal constitute a single cluster of pixels on the image (e.g.
electromagnetic showers produced with Imaging Atmospheric Cherenkov
Telescopes). This library is written in Python and is based on the existing
Cosmostat tools iSAp (Interactive Sparse Astronomical data analysis Packages
http://www.cosmostat.org/software/isap/).
The PyWI library also contains a dedicated package to optimize the image filter
parameters for a given set of images (i.e. to adapt the filter to a specific
problem). From a given training set of images (containing pairs of noised and
clean images) and a given performance estimator (a function that assess the
image filter parameters comparing the cleaned image to the actual clean image),
the optimizer can determine the optimal filtering level for each scale.
The PyWI library contains:
* wavelet transform and wavelet filtering functions for image multiresolution
analysis and filtering;
* additional filter to remove some image components (non-significant pixels
clusters);
* a set of generic filtering performance estimators (MSE, NRMSE, SSIM, PSNR,
image moment's difference), some relying on the scikit-image Python library
(supplementary estimators can be easily added to meet particular needs);
* a graphical user interface to visualize the filtering process in the wavelet
transformed space;
* an Evolution Strategies (ES) algorithm known in the mathematical optimization
community for its good convergence rate on generic derivative-free continuous
global optimization problems (Beyer, H. G. (2013) "The theory of evolution
strategies", Springer Science & Business Media);
* additional tools to manage and monitor the parameter optimization.
Note:
This project is in beta stage.
Viewing documentation using IPython
-----------------------------------
To see which functions are available in `pywi`, type ``pywi.<TAB>`` (where
``<TAB>`` refers to the TAB key), or use ``pywi.*transform*?<ENTER>`` (where
``<ENTER>`` refers to the ENTER key) to narrow down the list. To view the
docstring for a function, use ``pywi.transform?<ENTER>`` (to view the
docstring) and ``pywi.transform??<ENTER>`` (to view the source code).
"""
# PEP0440 compatible formatted version, see:
# https://www.python.org/dev/peps/pep-0440/
#
# Generic release markers:
# X.Y
# X.Y.Z # For bugfix releases
#
# Admissible pre-release markers:
# X.YaN # Alpha release
# X.YbN # Beta release
# X.YrcN # Release Candidate
# X.Y # Final release
#
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
__version__ = '0.3.dev12'
def get_version():
return __version__
# The following lines are temporary commented to avoid BUG#2 (c.f. BUGS.md)
#from . import benchmark
#from . import data
#from . import io
#from . import optimization
#from . import processing
#from . import ui
| """Python Wavelet Imaging
PyWI is an image filtering library aimed at removing additive background noise
from raster graphics images.
* Input: a FITS file containing the raster graphics to clean (i.e. an image
defined as a classic rectangular lattice of square pixels).
* Output: a FITS file containing the cleaned raster graphics.
The image filter relies on multiresolution analysis methods (Wavelet
transforms) that remove some scales (frequencies) locally in space. These
methods are particularly efficient when signal and noise are located at
different scales (or frequencies). Optional features improve the SNR ratio when
the (clean) signal constitute a single cluster of pixels on the image (e.g.
electromagnetic showers produced with Imaging Atmospheric Cherenkov
Telescopes). This library is written in Python and is based on the existing
Cosmostat tools iSAp (Interactive Sparse Astronomical data analysis Packages
http://www.cosmostat.org/software/isap/).
The PyWI library also contains a dedicated package to optimize the image filter
parameters for a given set of images (i.e. to adapt the filter to a specific
problem). From a given training set of images (containing pairs of noised and
clean images) and a given performance estimator (a function that assess the
image filter parameters comparing the cleaned image to the actual clean image),
the optimizer can determine the optimal filtering level for each scale.
The PyWI library contains:
* wavelet transform and wavelet filtering functions for image multiresolution
analysis and filtering;
* additional filter to remove some image components (non-significant pixels
clusters);
* a set of generic filtering performance estimators (MSE, NRMSE, SSIM, PSNR,
image moment's difference), some relying on the scikit-image Python library
(supplementary estimators can be easily added to meet particular needs);
* a graphical user interface to visualize the filtering process in the wavelet
transformed space;
* an Evolution Strategies (ES) algorithm known in the mathematical optimization
community for its good convergence rate on generic derivative-free continuous
global optimization problems (Beyer, H. G. (2013) "The theory of evolution
strategies", Springer Science & Business Media);
* additional tools to manage and monitor the parameter optimization.
Note:
This project is in beta stage.
Viewing documentation using IPython
-----------------------------------
To see which functions are available in `pywi`, type ``pywi.<TAB>`` (where
``<TAB>`` refers to the TAB key), or use ``pywi.*transform*?<ENTER>`` (where
``<ENTER>`` refers to the ENTER key) to narrow down the list. To view the
docstring for a function, use ``pywi.transform?<ENTER>`` (to view the
docstring) and ``pywi.transform??<ENTER>`` (to view the source code).
"""
__version__ = '0.3.dev12'
def get_version():
return __version__ |
class DynGraph():
def node_presence(self, nbunch=None):
raise NotImplementedError("Not implemented")
def add_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def add_interactions_from(self, nodePairs, times):
raise NotImplementedError("Not implemented")
def add_node_presence(self,node,time):
raise NotImplementedError("Not implemented")
def add_nodes_presence_from(self, nodes, times):
raise NotImplementedError("Not implemented")
def remove_node_presence(self,node,time):
raise NotImplementedError("Not implemented")
def graph_at_time(self,t):
raise NotImplementedError("Not implemented")
def remove_interaction(self,u_of_edge,v_of_edge,time):
raise NotImplementedError("Not implemented")
def remove_interactions_from(self, nodePairs, periods):
raise NotImplementedError("Not implemented")
def cumulated_graph(self,times=None):
raise NotImplementedError("Not implemented")
| class Dyngraph:
def node_presence(self, nbunch=None):
raise not_implemented_error('Not implemented')
def add_interaction(self, u_of_edge, v_of_edge, time):
raise not_implemented_error('Not implemented')
def add_interactions_from(self, nodePairs, times):
raise not_implemented_error('Not implemented')
def add_node_presence(self, node, time):
raise not_implemented_error('Not implemented')
def add_nodes_presence_from(self, nodes, times):
raise not_implemented_error('Not implemented')
def remove_node_presence(self, node, time):
raise not_implemented_error('Not implemented')
def graph_at_time(self, t):
raise not_implemented_error('Not implemented')
def remove_interaction(self, u_of_edge, v_of_edge, time):
raise not_implemented_error('Not implemented')
def remove_interactions_from(self, nodePairs, periods):
raise not_implemented_error('Not implemented')
def cumulated_graph(self, times=None):
raise not_implemented_error('Not implemented') |
def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's exclusive
and we need to include it.
:param mn: min value
:param mx: max value
:param low: True means we need smallest palindrome, False - largest one
:return:
"""
if mn > mx:
raise ValueError("min shouldn't be bigger than max")
# iterate over range of squares to avoid nested loops
args = (mn ** 2, mx ** 2 + 1) if low else (mx ** 2, mn ** 2 - 1, -1)
for r in range(*args):
s = str(r)
palindrome = s == s[::-1]
if palindrome:
# Since we're iterating through range created using smallest and largest squares as its bounds,
# it'll contain numbers which aren't products of the min-max range.
# So we need to check if there's a factor of a palindrome in the initial range
# mn <= r // j <= mx is here because we extended our ranges by 1
factor_in_range = any(mn <= r // j <= mx for j in range(mn, mx + 1) if r % j == 0)
if factor_in_range:
# Similar to the above we need to find the factors of a palindrome in the initial range
return r, ((i, r // i) for i in range(mn, mx + 1)
if r % i == 0 and mn <= i <= r // i <= mx)
else:
return None, []
| def smallest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor)
def largest(max_factor, min_factor):
return is_palindrome(min_factor, max_factor, low=False)
def is_palindrome(mn, mx, low=True):
"""
Throughout the method all ranges' upper bound is extended because in python it's exclusive
and we need to include it.
:param mn: min value
:param mx: max value
:param low: True means we need smallest palindrome, False - largest one
:return:
"""
if mn > mx:
raise value_error("min shouldn't be bigger than max")
args = (mn ** 2, mx ** 2 + 1) if low else (mx ** 2, mn ** 2 - 1, -1)
for r in range(*args):
s = str(r)
palindrome = s == s[::-1]
if palindrome:
factor_in_range = any((mn <= r // j <= mx for j in range(mn, mx + 1) if r % j == 0))
if factor_in_range:
return (r, ((i, r // i) for i in range(mn, mx + 1) if r % i == 0 and mn <= i <= r // i <= mx))
else:
return (None, []) |
def get_sql(company, conn, gl_code, start_date, end_date, step):
# start_date = '2018-02-28'
# end_date = '2018-03-01'
# step = 1
sql = (
"WITH RECURSIVE dates AS "
f"(SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, "
f"{conn.constants.func_prefix}date_add('{start_date}', {step-1}) AS cl_date "
f"UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS op_date, "
f"{conn.constants.func_prefix}date_add(cl_date, {step}) AS cl_date "
f"FROM dates WHERE {conn.constants.func_prefix}date_add(cl_date, {step}) <= '{end_date}') "
"SELECT "
# "a.op_row_id, a.cl_row_id"
# ", a.op_date, a.cl_date"
"a.op_date AS \"[DATE]\", a.cl_date AS \"[DATE]\""
# ", c.location_row_id, c.function_row_id, c.source_code_id"
", SUM(COALESCE(b.tran_tot, 0)) AS \"[REAL2]\""
", SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS \"[REAL2]\""
", SUM(COALESCE(c.tran_tot, 0)) AS \"[REAL2]\""
# ", COALESCE(c.tran_tot, 0) AS \"[REAL2]\", COALESCE(b.tran_tot, 0) AS \"[REAL2]\""
" FROM "
"(SELECT dates.op_date, dates.cl_date, ("
"SELECT c.row_id FROM {0}.gl_totals c "
"JOIN {0}.gl_codes f on f.row_id = c.gl_code_id "
"WHERE c.tran_date < dates.op_date "
"AND c.location_row_id = d.row_id "
"AND c.function_row_id = e.row_id "
"AND c.source_code_id = g.row_id "
f"AND f.gl_code = '{gl_code}' "
"ORDER BY c.tran_date DESC LIMIT 1"
") AS op_row_id, ("
"SELECT c.row_id FROM {0}.gl_totals c "
"JOIN {0}.gl_codes f on f.row_id = c.gl_code_id "
"WHERE c.tran_date <= dates.cl_date "
"AND c.location_row_id = d.row_id "
"AND c.function_row_id = e.row_id "
"AND c.source_code_id = g.row_id "
f"AND f.gl_code = '{gl_code}' "
"ORDER BY c.tran_date DESC LIMIT 1"
") AS cl_row_id "
"FROM dates, {0}.adm_locations d, {0}.adm_functions e, {0}.gl_source_codes g "
"WHERE d.location_type = 'location' "
"AND e.function_type = 'function' "
") AS a "
"LEFT JOIN {0}.gl_totals b on b.row_id = a.op_row_id "
"LEFT JOIN {0}.gl_totals c on c.row_id = a.cl_row_id "
"GROUP BY a.op_date, a.cl_date "
# "WHERE c.location_row_id IS NOT NULL "
.format(company)
)
params = ()
fmt = '{:%d-%m} - {:%d-%m} : {:>12}{:>12}{:>12}'
return sql, params, fmt
# cur = await conn.exec_sql(sql)
# async for row in cur:
# print(fmt.format(*row))
# # print(row)
| def get_sql(company, conn, gl_code, start_date, end_date, step):
sql = f"""WITH RECURSIVE dates AS (SELECT CAST('{start_date}' AS {conn.constants.date_cast}) AS op_date, {conn.constants.func_prefix}date_add('{start_date}', {step - 1}) AS cl_date UNION ALL SELECT {conn.constants.func_prefix}date_add(cl_date, 1) AS op_date, {conn.constants.func_prefix}date_add(cl_date, {step}) AS cl_date FROM dates WHERE {conn.constants.func_prefix}date_add(cl_date, {step}) <= '{end_date}') SELECT a.op_date AS "[DATE]", a.cl_date AS "[DATE]", SUM(COALESCE(b.tran_tot, 0)) AS "[REAL2]", SUM(COALESCE(c.tran_tot, 0) - COALESCE(b.tran_tot, 0)) AS "[REAL2]", SUM(COALESCE(c.tran_tot, 0)) AS "[REAL2]" FROM (SELECT dates.op_date, dates.cl_date, (SELECT c.row_id FROM {{0}}.gl_totals c JOIN {{0}}.gl_codes f on f.row_id = c.gl_code_id WHERE c.tran_date < dates.op_date AND c.location_row_id = d.row_id AND c.function_row_id = e.row_id AND c.source_code_id = g.row_id AND f.gl_code = '{gl_code}' ORDER BY c.tran_date DESC LIMIT 1) AS op_row_id, (SELECT c.row_id FROM {{0}}.gl_totals c JOIN {{0}}.gl_codes f on f.row_id = c.gl_code_id WHERE c.tran_date <= dates.cl_date AND c.location_row_id = d.row_id AND c.function_row_id = e.row_id AND c.source_code_id = g.row_id AND f.gl_code = '{gl_code}' ORDER BY c.tran_date DESC LIMIT 1) AS cl_row_id FROM dates, {{0}}.adm_locations d, {{0}}.adm_functions e, {{0}}.gl_source_codes g WHERE d.location_type = 'location' AND e.function_type = 'function' ) AS a LEFT JOIN {{0}}.gl_totals b on b.row_id = a.op_row_id LEFT JOIN {{0}}.gl_totals c on c.row_id = a.cl_row_id GROUP BY a.op_date, a.cl_date """.format(company)
params = ()
fmt = '{:%d-%m} - {:%d-%m} : {:>12}{:>12}{:>12}'
return (sql, params, fmt) |
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head = None
curr = None
for i in vals:
node = ListNode(i)
if not head:
head = node
curr = node
else:
curr.next = node
curr = node
return head
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def __str__(self):
queue = [self]
s = ''
while len(queue) > 0:
next_queue = []
for node in queue:
s += node.val.__str__() + '\t'
if node.left:
next_queue.append(node.left)
if node.right:
next_queue.append(node.right)
s += '\n'
queue = next_queue
return s
@classmethod
def from_list(cls, vals):
n = len(vals)
if n == 0:
return None
head = TreeNode(vals[0])
level = [head]
i = 1
while i < n:
next_level = []
for node in level:
v = vals[i]
if v != '#':
left = TreeNode(v)
node.left = left
next_level.append(left)
i += 1
if i >= n:
break
v = vals[i]
if v != '#':
right = TreeNode(v)
node.right = right
next_level.append(right)
i += 1
if i >= n:
break
level = next_level
return head
| class Listnode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
curr = self
vals = []
while curr:
vals.append(curr.val)
curr = curr.next
return str(vals)
@classmethod
def from_list(cls, vals):
head = None
curr = None
for i in vals:
node = list_node(i)
if not head:
head = node
curr = node
else:
curr.next = node
curr = node
return head
class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None
def __str__(self):
queue = [self]
s = ''
while len(queue) > 0:
next_queue = []
for node in queue:
s += node.val.__str__() + '\t'
if node.left:
next_queue.append(node.left)
if node.right:
next_queue.append(node.right)
s += '\n'
queue = next_queue
return s
@classmethod
def from_list(cls, vals):
n = len(vals)
if n == 0:
return None
head = tree_node(vals[0])
level = [head]
i = 1
while i < n:
next_level = []
for node in level:
v = vals[i]
if v != '#':
left = tree_node(v)
node.left = left
next_level.append(left)
i += 1
if i >= n:
break
v = vals[i]
if v != '#':
right = tree_node(v)
node.right = right
next_level.append(right)
i += 1
if i >= n:
break
level = next_level
return head |
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print("yes")
else:
print("no")
print("let's see", end="")
print("?") | num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 == num2 and num2 == num3:
print('yes')
else:
print('no')
print("let's see", end='')
print('?') |
# Copyright (c) 2012-2018 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the COPYING file.
def test_simple(qipy_action, record_messages):
qipy_action.add_test_project("a_lib")
qipy_action.add_test_project("big_project")
qipy_action.add_test_project("foomodules")
qipy_action("list")
assert record_messages.find(r"\*\s+a")
assert record_messages.find(r"\*\s+big_project")
| def test_simple(qipy_action, record_messages):
qipy_action.add_test_project('a_lib')
qipy_action.add_test_project('big_project')
qipy_action.add_test_project('foomodules')
qipy_action('list')
assert record_messages.find('\\*\\s+a')
assert record_messages.find('\\*\\s+big_project') |
# Copyright Alexander Baranin 2016
Logging = None
EngineCore = None
def onLoad(core):
global EngineCore
EngineCore = core
global Logging
Logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.schedule_FIFO(run2, 30)
def onUnload():
Logging.logMessage('TestFIFOModule1.onUnload()')
EngineCore.unschedule_FIFO(10)
EngineCore.unschedule_FIFO(30)
def run1():
Logging.logMessage('dummy print from Module1')
def run2():
Logging.logMessage('another dummy print from Module1')
raise ArithmeticError() | logging = None
engine_core = None
def on_load(core):
global EngineCore
engine_core = core
global Logging
logging = EngineCore.loaded_modules['engine.Logging']
Logging.logMessage('TestFIFOModule1.onLoad()')
EngineCore.schedule_FIFO(run1, 10)
EngineCore.schedule_FIFO(run2, 30)
def on_unload():
Logging.logMessage('TestFIFOModule1.onUnload()')
EngineCore.unschedule_FIFO(10)
EngineCore.unschedule_FIFO(30)
def run1():
Logging.logMessage('dummy print from Module1')
def run2():
Logging.logMessage('another dummy print from Module1')
raise arithmetic_error() |
'''
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
'''
number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
maxResultArrayLength = 5
resultProduct = 0
resultArrayLength = 0
resultArray = []
loopIndex = 0
digitsCount = len(number)
tempDigit = 0
while loopIndex < digitsCount:
tempDigit = int(number[loopIndex])
if tempDigit == 0:
loopIndex = loopIndex + maxResultArrayLength
resultArray = []
resultArrayLength = 0
continue
else :
if resultArrayLength < maxResultArrayLength:
resultArray.append(tempDigit)
resultArrayLength = resultArrayLength + 1
if resultArrayLength == maxResultArrayLength:
tempResultProduct = 1
for x in resultArray:
tempResultProduct = tempResultProduct * x
if tempResultProduct > resultProduct:
resultProduct = tempResultProduct
resultArray.pop(0)
resultArrayLength = resultArrayLength - 1
loopIndex = loopIndex + 1
print(resultProduct)
| """
Find the greatest product of five consecutive digits in the 1000-digit number.
73167176531330624919225119674426574742355349194934
96983520312774506326239578318016984801869478851843
85861560789112949495459501737958331952853208805511
12540698747158523863050715693290963295227443043557
66896648950445244523161731856403098711121722383113
62229893423380308135336276614282806444486645238749
30358907296290491560440772390713810515859307960866
70172427121883998797908792274921901699720888093776
65727333001053367881220235421809751254540594752243
52584907711670556013604839586446706324415722155397
53697817977846174064955149290862569321978468622482
83972241375657056057490261407972968652414535100474
82166370484403199890008895243450658541227588666881
16427171479924442928230863465674813919123162824586
17866458359124566529476545682848912883142607690042
24219022671055626321111109370544217506941658960408
07198403850962455444362981230987879927244284909188
84580156166097919133875499200524063689912560717606
05886116467109405077541002256983155200055935729725
71636269561882670428252483600823257530420752963450
"""
number = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
max_result_array_length = 5
result_product = 0
result_array_length = 0
result_array = []
loop_index = 0
digits_count = len(number)
temp_digit = 0
while loopIndex < digitsCount:
temp_digit = int(number[loopIndex])
if tempDigit == 0:
loop_index = loopIndex + maxResultArrayLength
result_array = []
result_array_length = 0
continue
else:
if resultArrayLength < maxResultArrayLength:
resultArray.append(tempDigit)
result_array_length = resultArrayLength + 1
if resultArrayLength == maxResultArrayLength:
temp_result_product = 1
for x in resultArray:
temp_result_product = tempResultProduct * x
if tempResultProduct > resultProduct:
result_product = tempResultProduct
resultArray.pop(0)
result_array_length = resultArrayLength - 1
loop_index = loopIndex + 1
print(resultProduct) |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################
__all__ = []
def _generate(cls, bases, dct, **kwargs):
# Try to find a group definition in the directory of the class and it not
# possible, get the attribute which will have been inherited from the class
# Add the final attribute in tuple form, to support many
grps = dct.get('group', ()) or getattr(cls, 'group', ())
if isinstance(grps, str):
grps = (grps,) # if only str, simulate iterable
cls.group = grps # set it in the instance, let others process
| __all__ = []
def _generate(cls, bases, dct, **kwargs):
grps = dct.get('group', ()) or getattr(cls, 'group', ())
if isinstance(grps, str):
grps = (grps,)
cls.group = grps |
#! /usr/bin/python3
# product.py -- This script prints out a product and it's price.
# Author -- Prince Oppong Boamah<regioths@gmail.com>
# Date -- 10th September, 2015
class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
# The program starts running here.
p = Product("Lenovo")
p.price = "2000gh cedis or 400 pounds or 600 dollars to be precise."
print("p is a %s" % (p.__class__))
print("This is a Laptop called %s and the price is %s" % (p.name, p.price))
| class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
p = product('Lenovo')
p.price = '2000gh cedis or 400 pounds or 600 dollars to be precise.'
print('p is a %s' % p.__class__)
print('This is a Laptop called %s and the price is %s' % (p.name, p.price)) |
# constantly ask the user for new names and phone numbers
# to add to the phone book, then save them
phone_book = {}
| phone_book = {} |
key_words = ["Trending", "Fact", "Reason", "Side Effect", "Index", "Stock", "ETF"]
knowledge_graph_dict = {
"Value Investing": {},
"Risk Management": {},
"Joe Biden": {
"Tax Increase Policy": {
"Tech Company": {
"Trending": "Negative",
},
"Corporate Tax": {
"Trending": "Negative",
},
"Capital Gain Tax": {
"Trending": "Negative",
},
},
"Economic Stimulus Package": {
"Trending": "Positive",
"Reason": "buy the rumor sell the news.",
"Fact": "Negative",
"Side Effect": {
"Consumption Discretionary Sector": {
"ETF": [
"PEJ Leisure & entertainment etf",
"XLY Consumer discretionary select sector SPDR fund",
],
"Trending": "Positive",
"Reason": "Covid recover and stimulus package delivered.",
},
},
},
},
"New Type of Inflation": {
"Phenomenon": "Fed release money -> core CPI not increasing fast, but asset bull",
"Result": "New Type of Inflation, fool people and rich richest all the time",
"Reason": "This is so call new type of inflation. "
"Traditional CPI index already out of style, because the necessity in the modern world is not food but asset."
"Fed blindly or intend to blindly use old world index as CPI to fool people."
"Then, the asset increase fast, and the gap between rich and poor split more."
"The side effect would show the result sooner or later.",
},
}
investment_principle = {
"principle1": {
"Principle": "Other investors haven't go into the underlying but will plan to.",
"Trending": "Positive",
"Reason": "Newly long position crowd would push the price to go high and squeeze short."
},
"principle2": {
"Principle": "Does all the potential investors go into the trading? Yes, then leave it",
"Trending": "Negative",
"Reason": "Picked like leek",
},
"principle3": {
"Principle": "Find the frontier and the edger of the world who being laughed at.",
"Trending": "Positive",
"Reason": "Margin cost lowest but margin reward highest in the uncultivated land to lead the world."
"Being laughed at by the crowd means less people realize the real value and underestimated but already obtain attention."
"Truth is in the hands of a few",
},
"principle4": {
"Principle": "The highest risk is not long the position but is sell then buy again risk.",
"Reason": "long time experience",
}
}
target_assets = [
{
"Name": "Asana",
"Symbol": "ASAN",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Nano Dimension",
"Symbol": "NNDM",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Lockheed",
"Symbol": "LMT",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Lockheed",
"Symbol": "LMT",
"Type": "Equity",
"Positive": [],
"Negative": [],
},
{
"Name": "Bitcoin",
"Symbol": "BTC",
"Type": "Cryptocurrencies",
"Positive": [],
"Negative": [],
},
{
"Name": "Uber",
"Symbol": "Uber",
"Type": "Equity",
"Positive": [
"SP500 target stock",
],
"Negative": [],
}
]
todo_list = ["https://en.wikipedia.org/wiki/Ronald_S._Baron"]
class Investment2021:
def __init__(self):
self.knowledge_graph_dict = knowledge_graph_dict
if __name__ == "__main__":
print("Investment Jan. Plan")
| key_words = ['Trending', 'Fact', 'Reason', 'Side Effect', 'Index', 'Stock', 'ETF']
knowledge_graph_dict = {'Value Investing': {}, 'Risk Management': {}, 'Joe Biden': {'Tax Increase Policy': {'Tech Company': {'Trending': 'Negative'}, 'Corporate Tax': {'Trending': 'Negative'}, 'Capital Gain Tax': {'Trending': 'Negative'}}, 'Economic Stimulus Package': {'Trending': 'Positive', 'Reason': 'buy the rumor sell the news.', 'Fact': 'Negative', 'Side Effect': {'Consumption Discretionary Sector': {'ETF': ['PEJ Leisure & entertainment etf', 'XLY Consumer discretionary select sector SPDR fund'], 'Trending': 'Positive', 'Reason': 'Covid recover and stimulus package delivered.'}}}}, 'New Type of Inflation': {'Phenomenon': 'Fed release money -> core CPI not increasing fast, but asset bull', 'Result': 'New Type of Inflation, fool people and rich richest all the time', 'Reason': 'This is so call new type of inflation. Traditional CPI index already out of style, because the necessity in the modern world is not food but asset.Fed blindly or intend to blindly use old world index as CPI to fool people.Then, the asset increase fast, and the gap between rich and poor split more.The side effect would show the result sooner or later.'}}
investment_principle = {'principle1': {'Principle': "Other investors haven't go into the underlying but will plan to.", 'Trending': 'Positive', 'Reason': 'Newly long position crowd would push the price to go high and squeeze short.'}, 'principle2': {'Principle': 'Does all the potential investors go into the trading? Yes, then leave it', 'Trending': 'Negative', 'Reason': 'Picked like leek'}, 'principle3': {'Principle': 'Find the frontier and the edger of the world who being laughed at.', 'Trending': 'Positive', 'Reason': 'Margin cost lowest but margin reward highest in the uncultivated land to lead the world.Being laughed at by the crowd means less people realize the real value and underestimated but already obtain attention.Truth is in the hands of a few'}, 'principle4': {'Principle': 'The highest risk is not long the position but is sell then buy again risk.', 'Reason': 'long time experience'}}
target_assets = [{'Name': 'Asana', 'Symbol': 'ASAN', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Nano Dimension', 'Symbol': 'NNDM', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Lockheed', 'Symbol': 'LMT', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Lockheed', 'Symbol': 'LMT', 'Type': 'Equity', 'Positive': [], 'Negative': []}, {'Name': 'Bitcoin', 'Symbol': 'BTC', 'Type': 'Cryptocurrencies', 'Positive': [], 'Negative': []}, {'Name': 'Uber', 'Symbol': 'Uber', 'Type': 'Equity', 'Positive': ['SP500 target stock'], 'Negative': []}]
todo_list = ['https://en.wikipedia.org/wiki/Ronald_S._Baron']
class Investment2021:
def __init__(self):
self.knowledge_graph_dict = knowledge_graph_dict
if __name__ == '__main__':
print('Investment Jan. Plan') |
# encoding: utf-8
'''
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
'''
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2)
| """
@author: developer
@software: python
@file: run8.py
@time: 2021/7/28 22:35
@desc:
"""
str1 = input()
str2 = input()
output_str1 = str2[0:2] + str1[2:]
output_str2 = str1[0:2] + str2[2:]
print(output_str1)
print(output_str2) |
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def tomlplusplus_repository():
maybe(
http_archive,
name = "tomlplusplus",
urls = [
"https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip",
],
sha256 = "887dfb7025d532a3485e1269ce5102d9e628ddce8dd055af1020c7b10ee14248",
strip_prefix = "tomlplusplus-2.5.0/",
build_file = "@third_party//tomlplusplus:package.BUILD",
)
| load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def tomlplusplus_repository():
maybe(http_archive, name='tomlplusplus', urls=['https://github.com/marzer/tomlplusplus/archive/v2.5.0.zip'], sha256='887dfb7025d532a3485e1269ce5102d9e628ddce8dd055af1020c7b10ee14248', strip_prefix='tomlplusplus-2.5.0/', build_file='@third_party//tomlplusplus:package.BUILD') |
#! /usr/bin/env python3
# hjjs.py - write some HJ J-sequences
EXTENSION = ".hjjs.txt"
MODE = "w"
J_MAX = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file = f)
for m in range(10):
with open("i22a" + str(m) + EXTENSION, MODE) as f:
i22a(f, m)
| extension = '.hjjs.txt'
mode = 'w'
j_max = 2 ** 32 - 1
def i22a(f, m):
n = 0
js = []
while True:
j = 2 ** (2 * n + m) - 2 ** n
if j > J_MAX:
break
js.append(j)
n += 1
print(*js, file=f)
for m in range(10):
with open('i22a' + str(m) + EXTENSION, MODE) as f:
i22a(f, m) |
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for i, c in enumerate(s)}
st = []
seen = set()
for i, c in enumerate(s):
if c in seen:
continue
while st and st[-1] > c and d[st[-1]] > i:
v = st.pop()
seen.remove(v)
st.append(c)
seen.add(c)
return ''.join(st)
| class Solution:
def remove_duplicate_letters(self, s: str) -> str:
"""Stack.
Running time: O(n) where n == len(s).
"""
d = {c: i for (i, c) in enumerate(s)}
st = []
seen = set()
for (i, c) in enumerate(s):
if c in seen:
continue
while st and st[-1] > c and (d[st[-1]] > i):
v = st.pop()
seen.remove(v)
st.append(c)
seen.add(c)
return ''.join(st) |
# This should be subclassed within each
# class that gets registered with the API
class BaseContext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
# This is actually very different from a context.
# Meh. It just holds the things we need it to.
class GlobalContext:
def __init__(self, universes, network):
self.universes = universes
self.network = network
# ** Function Decorator **
def expose(func, label=None):
if not label:
label = func.__name__
setattr(func, "__api_exposed__", True)
setattr(func, "__api_label__", label)
return func
def readable(*attrs):
def decorator(cls):
if not hasattr(cls, "__api_readable__"):
setattr(cls, "__api_readable__", [])
cls.__api_readable__.extend([attr for attr in attrs if attr not in cls.__api_readable__])
return cls
return decorator
def writable(*attrs):
def decorator(cls):
if not hasattr(cls, "__api_readable__"):
setattr(cls, "__api_readable__", [])
if not hasattr(cls, "__api_writable__"):
setattr(cls, "__api_writable__", [])
cls.__api_readable__.extend(attrs)
cls.__api_writable__.extend(attrs)
return cls
return decorator
# There are two parts to this:
#
# One is a decorator which, applied to a function,
# marks it as registerable through the Client API.
#
# The other is a method in the ClientAPI, which gets
# passed a Class Name and searches through it for any
# applicable classes, as well as a Context class. If
# the class does not have a context, then the call
# will fail.
#
# Also, each Context will have a constructor that
# accepts a global context and either its object, or
# a tuple which represents its serialized value. It
# should also have an 'object' method which returns
# the object to which the context refers. And finally
# there should be a 'serialized' method which returns
# a tuple that uniquely identifies the context within
# the global context.
class ClientAPI:
def __init__(self, globalContext):
self.classes = {}
self.globalContext = globalContext
def onGet(self, name, ctx):
cls, attr = name.split(".")
classInfo = self.classes[cls]
if attr not in classInfo["readable"]:
raise AttributeError("Attribute {} is not readable -- did you @readable it?".format(attr))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
result = getattr(instance, attr, None)
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def onSet(self, name, ctx, value):
cls, attr = name.split(".")
classInfo = self.classes[cls]
if attr not in classInfo["writable"]:
raise AttributeError("Attribute {} is not writable -- did you @writable it?".format(attr))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
setattr(instance, attr, value)
if attr in classInfo["readable"]:
result = getattr(instance, attr)
else:
result = None
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def onCall(self, name, ctx, *args, **kwargs):
cls, func = name.split(".")
classInfo = self.classes[cls]
if func not in classInfo["methods"]:
raise AttributeError("Method {} is not available -- did you @expose it?".format(func))
context = classInfo["context"]
instance = context(serial=ctx).instance(self.globalContext)
method = classInfo["methods"][func]["callable"]
result = method(instance, *args, **kwargs)
if hasattr(result, 'Context'):
return {"result": result, "context": result.Context(instance=result)}
return {"result": result}
def getTable(self):
return self.classes
def register(self, cls):
if not hasattr(cls, "Context"):
raise AttributeError("Cannot register class {}; must have Context.".format(cls.__name__))
if not issubclass(cls.Context, BaseContext):
raise AttributeError("Cannot register class {}; Invalid Context.".format(cls.__name__))
methods = {}
for methname in dir(cls):
method = getattr(cls, methname)
if hasattr(method, "__api_exposed__") and hasattr(method, "__api_label__"):
methods[method.__api_label__] = {"callable": method}
readable = []
writable = []
if hasattr(cls, "__api_readable__"):
for attrName in cls.__api_readable__:
readable.append(attrName)
if hasattr(cls, "__api_writable__"):
for attrName in cls.__api_writable__:
writable.append(attrName)
if attrName not in readable:
readable.append(attrName)
self.classes[cls.__name__] = {
"class": cls,
"context": cls.Context,
"methods": methods,
"readable": readable,
"writable": writable
}
| class Basecontext:
def __init__(self, instance=None, serial=None):
pass
def serialized(self):
return ()
def instance(self, global_context):
return None
class Globalcontext:
def __init__(self, universes, network):
self.universes = universes
self.network = network
def expose(func, label=None):
if not label:
label = func.__name__
setattr(func, '__api_exposed__', True)
setattr(func, '__api_label__', label)
return func
def readable(*attrs):
def decorator(cls):
if not hasattr(cls, '__api_readable__'):
setattr(cls, '__api_readable__', [])
cls.__api_readable__.extend([attr for attr in attrs if attr not in cls.__api_readable__])
return cls
return decorator
def writable(*attrs):
def decorator(cls):
if not hasattr(cls, '__api_readable__'):
setattr(cls, '__api_readable__', [])
if not hasattr(cls, '__api_writable__'):
setattr(cls, '__api_writable__', [])
cls.__api_readable__.extend(attrs)
cls.__api_writable__.extend(attrs)
return cls
return decorator
class Clientapi:
def __init__(self, globalContext):
self.classes = {}
self.globalContext = globalContext
def on_get(self, name, ctx):
(cls, attr) = name.split('.')
class_info = self.classes[cls]
if attr not in classInfo['readable']:
raise attribute_error('Attribute {} is not readable -- did you @readable it?'.format(attr))
context = classInfo['context']
instance = context(serial=ctx).instance(self.globalContext)
result = getattr(instance, attr, None)
if hasattr(result, 'Context'):
return {'result': result, 'context': result.Context(instance=result)}
return {'result': result}
def on_set(self, name, ctx, value):
(cls, attr) = name.split('.')
class_info = self.classes[cls]
if attr not in classInfo['writable']:
raise attribute_error('Attribute {} is not writable -- did you @writable it?'.format(attr))
context = classInfo['context']
instance = context(serial=ctx).instance(self.globalContext)
setattr(instance, attr, value)
if attr in classInfo['readable']:
result = getattr(instance, attr)
else:
result = None
if hasattr(result, 'Context'):
return {'result': result, 'context': result.Context(instance=result)}
return {'result': result}
def on_call(self, name, ctx, *args, **kwargs):
(cls, func) = name.split('.')
class_info = self.classes[cls]
if func not in classInfo['methods']:
raise attribute_error('Method {} is not available -- did you @expose it?'.format(func))
context = classInfo['context']
instance = context(serial=ctx).instance(self.globalContext)
method = classInfo['methods'][func]['callable']
result = method(instance, *args, **kwargs)
if hasattr(result, 'Context'):
return {'result': result, 'context': result.Context(instance=result)}
return {'result': result}
def get_table(self):
return self.classes
def register(self, cls):
if not hasattr(cls, 'Context'):
raise attribute_error('Cannot register class {}; must have Context.'.format(cls.__name__))
if not issubclass(cls.Context, BaseContext):
raise attribute_error('Cannot register class {}; Invalid Context.'.format(cls.__name__))
methods = {}
for methname in dir(cls):
method = getattr(cls, methname)
if hasattr(method, '__api_exposed__') and hasattr(method, '__api_label__'):
methods[method.__api_label__] = {'callable': method}
readable = []
writable = []
if hasattr(cls, '__api_readable__'):
for attr_name in cls.__api_readable__:
readable.append(attrName)
if hasattr(cls, '__api_writable__'):
for attr_name in cls.__api_writable__:
writable.append(attrName)
if attrName not in readable:
readable.append(attrName)
self.classes[cls.__name__] = {'class': cls, 'context': cls.Context, 'methods': methods, 'readable': readable, 'writable': writable} |
def pageCount(n, p):
print(min(p//2,n//2-p//2))
if __name__ == '__main__':
n = int(input())
p = int(input())
pageCount(n, p)
| def page_count(n, p):
print(min(p // 2, n // 2 - p // 2))
if __name__ == '__main__':
n = int(input())
p = int(input())
page_count(n, p) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def pseudoPalindromicPaths (self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
self.dfs(root, [])
return self.count;
def dfs(self, root, path):
if root is None:
return
self.a[root.val]+=1
if root.left is None and root.right is None:
md = 0
for i in range(10):
if self.a[i] % 2 != 0 and self.a[i] != 0:
md +=1
print(self.a)
if md < 2:
self.count +=1
if root.left:
self.dfs(root.left, path)
if root.right:
self.dfs(root.right, path)
self.a[root.val] -=1
| class Solution:
def pseudo_palindromic_paths(self, root: TreeNode) -> int:
self.a = [0] * 10
self.count = 0
self.dfs(root, [])
return self.count
def dfs(self, root, path):
if root is None:
return
self.a[root.val] += 1
if root.left is None and root.right is None:
md = 0
for i in range(10):
if self.a[i] % 2 != 0 and self.a[i] != 0:
md += 1
print(self.a)
if md < 2:
self.count += 1
if root.left:
self.dfs(root.left, path)
if root.right:
self.dfs(root.right, path)
self.a[root.val] -= 1 |
"""
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
pass
def get_perimeter(self):
"""
Returns the perimeter of a circle
:return int: the perimeter of a circle
"""
pass
def get_diameter(self):
"""
Returns the diameter of a circle
:return int: the diameter of a circle
"""
pass
| """
Programming for linguists
Implementation of the class Circle
"""
class Circle:
"""
A class for circles
"""
def __init__(self, uid: int, radius: int):
pass
def get_area(self):
"""
Returns the area of a circle
:return int: the area of a circle
"""
pass
def get_perimeter(self):
"""
Returns the perimeter of a circle
:return int: the perimeter of a circle
"""
pass
def get_diameter(self):
"""
Returns the diameter of a circle
:return int: the diameter of a circle
"""
pass |
class FLAGS:
data_url = ""
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_ms = 1000
window_size_ms = 30
window_stride_ms = 10
dct_coefficient_count = 40
model_architecture = "ds_cnn"
model_size_info = [128, 128, 128]
start_checkpoint = ""
eval_step_interval = 400
how_many_training_steps = [5000, 5000]
learning_rate = [0.001, 0.0001]
batch_size = 100
wanted_words = ""
excluded_words = ""
summaries_dir = None
train_dir = None
save_step_interval = 100
check_nans = False | class Flags:
data_url = ''
data_dir = None
background_volume = 0.1
background_frequency = 0
silence_percentage = 10.0
unknown_percentage = 10.0
time_shift_ms = 0
use_custom_augs = False
testing_percentage = 10
validation_percentage = 10
sample_rate = 16000
clip_duration_ms = 1000
window_size_ms = 30
window_stride_ms = 10
dct_coefficient_count = 40
model_architecture = 'ds_cnn'
model_size_info = [128, 128, 128]
start_checkpoint = ''
eval_step_interval = 400
how_many_training_steps = [5000, 5000]
learning_rate = [0.001, 0.0001]
batch_size = 100
wanted_words = ''
excluded_words = ''
summaries_dir = None
train_dir = None
save_step_interval = 100
check_nans = False |
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
returnList = [0] * len(nums)
temp = 0
for i in range(0,n):
returnList[temp] = nums[i]
returnList[temp+1] = nums[n]
n+=1
temp+=2
return returnList
| class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
return_list = [0] * len(nums)
temp = 0
for i in range(0, n):
returnList[temp] = nums[i]
returnList[temp + 1] = nums[n]
n += 1
temp += 2
return returnList |
def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
except ValueError:
print("Invalid Input!")
return score
print(get_player_score())
| def get_player_score():
score = []
for i in range(0, 5):
while True:
try:
s = float(input('Enter golf scores between 78 and 100: '))
if 78 <= s <= 100:
score.append(s)
break
raise ValueError
except ValueError:
print('Invalid Input!')
return score
print(get_player_score()) |
# Unneeded charting code that was removed from a jupyter notebook. Stored here as an example for later
# Draws a chart with the total area of multiple protin receptors at each time step
tmpdf = totals65.loc[(totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26'])) &
(totals65['Experiment Step'] == '-nl-post')]
pal = ['black', 'blue', 'red', 'orange', 'green']
g = sns.FacetGrid(tmpdf, col='Time Point', col_wrap=3,
size=5, ylim=(0,100), xlim=(0,100),
palette=pal,
hue='Receptor',
hue_order=['M1', 'M5', 'M7', 'M22', 'M26'],
hue_kws=dict(marker=['^', 'v', '*', '+', 'x']))
g.map(plt.scatter, 'Total Number Scaled', 'Total Area Scaled')
g.add_legend()
g.savefig('mutants_by_time_nl-post.png')
| tmpdf = totals65.loc[totals65['Receptor'].isin(['M1', 'M5', 'M7', 'M22', 'M26']) & (totals65['Experiment Step'] == '-nl-post')]
pal = ['black', 'blue', 'red', 'orange', 'green']
g = sns.FacetGrid(tmpdf, col='Time Point', col_wrap=3, size=5, ylim=(0, 100), xlim=(0, 100), palette=pal, hue='Receptor', hue_order=['M1', 'M5', 'M7', 'M22', 'M26'], hue_kws=dict(marker=['^', 'v', '*', '+', 'x']))
g.map(plt.scatter, 'Total Number Scaled', 'Total Area Scaled')
g.add_legend()
g.savefig('mutants_by_time_nl-post.png') |
whitespace = " \t\n\r\v\f"
ascii_lowercase = "abcdefghijklmnopqrstuvwxyz"
ascii_uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ascii_letters = ascii_lowercase + ascii_uppercase
digits = "0123456789"
hexdigitx = digits + "abcdef" + "ABCDEF"
octdigits = "01234567"
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
| whitespace = ' \t\n\r\x0b\x0c'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigitx = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
printable = digits + ascii_letters + punctuation + whitespace |
with open("pattern.txt") as file:
inputs = file.readlines()
BUFFER = 10
ITERATIONS = 50_000_000_000
state = '.' * BUFFER + "..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#" + '.' * 102
gives_empty = {line[:5] for line in inputs if line[-2] == '.'}
pattern_iterations = 99
for i in range(pattern_iterations):
next_gen = ""
for i in range(2, len(state) - 2):
if state[i-2:i+3] in gives_empty:
next_gen += '.'
else:
next_gen += '#'
next_gen = ".." + next_gen + ".."
#print(next_gen[next_gen.index('#'):-next_gen[::-1].index('#')])
state = next_gen
pots = state.count('#')
final_sum = 0
for i, pot in enumerate(state):
if pot == '#':
final_sum += i - BUFFER
final_sum += pots * (ITERATIONS - pattern_iterations)
print(final_sum)
| with open('pattern.txt') as file:
inputs = file.readlines()
buffer = 10
iterations = 50000000000
state = '.' * BUFFER + '..##.#######...##.###...#..#.#.#..#.##.#.##....####..........#..#.######..####.#.#..###.##..##..#..#' + '.' * 102
gives_empty = {line[:5] for line in inputs if line[-2] == '.'}
pattern_iterations = 99
for i in range(pattern_iterations):
next_gen = ''
for i in range(2, len(state) - 2):
if state[i - 2:i + 3] in gives_empty:
next_gen += '.'
else:
next_gen += '#'
next_gen = '..' + next_gen + '..'
state = next_gen
pots = state.count('#')
final_sum = 0
for (i, pot) in enumerate(state):
if pot == '#':
final_sum += i - BUFFER
final_sum += pots * (ITERATIONS - pattern_iterations)
print(final_sum) |
all_sales = dict()
try:
with open(".\\.\\sales.csv") as file:
for line in file:
string_args = line.split()
string_date = string_args[0]
string_price = string_args[1].split(",")
price = all_sales[string_date]
all_sales[string_date] = price + string_price[1]
key, value = max(all_sales.iteritems(), key=lambda x: x[1])
except FileNotFoundError:
print("File is not found")
| all_sales = dict()
try:
with open('.\\.\\sales.csv') as file:
for line in file:
string_args = line.split()
string_date = string_args[0]
string_price = string_args[1].split(',')
price = all_sales[string_date]
all_sales[string_date] = price + string_price[1]
(key, value) = max(all_sales.iteritems(), key=lambda x: x[1])
except FileNotFoundError:
print('File is not found') |
# Copyright (c) 2017, 2018 Jae-jun Kang
# See the file LICENSE for details.
class Config(object):
heartbeat_interval = 5 # in seconds
class Coroutine(object):
default_timeout = 60 # in seconds | class Config(object):
heartbeat_interval = 5
class Coroutine(object):
default_timeout = 60 |
__all__ = (
"__title__", "__summary__", "__uri__",
"__download_url__", "__version__", "__author__",
"__email__", "__license__",)
__title__ = "gpxconverter"
__summary__ = ("gpx to csv converter. it supports waypoint elements except "
"extensions. Values in extensions will be ignored.")
__uri__ = "https://github.com/linusyoung/GPXConverter"
__version__ = "0.8"
__download_url__ = ("https://github.com/linusyoung/GPXConverter/archive/" +
__version__ + ".tar.gz")
__author__ = "Linus Yang"
__email__ = "linusyoungrice@gmail.com"
__license__ = "MIT"
| __all__ = ('__title__', '__summary__', '__uri__', '__download_url__', '__version__', '__author__', '__email__', '__license__')
__title__ = 'gpxconverter'
__summary__ = 'gpx to csv converter. it supports waypoint elements except extensions. Values in extensions will be ignored.'
__uri__ = 'https://github.com/linusyoung/GPXConverter'
__version__ = '0.8'
__download_url__ = 'https://github.com/linusyoung/GPXConverter/archive/' + __version__ + '.tar.gz'
__author__ = 'Linus Yang'
__email__ = 'linusyoungrice@gmail.com'
__license__ = 'MIT' |
def count(s, t, loc, lst):
return sum([(loc + dist) >= s and (loc + dist) <= t for dist in lst])
def countApplesAndOranges(s, t, a, b, apples, oranges):
print(count(s, t, a, apples))
print(count(s, t, b, oranges))
| def count(s, t, loc, lst):
return sum([loc + dist >= s and loc + dist <= t for dist in lst])
def count_apples_and_oranges(s, t, a, b, apples, oranges):
print(count(s, t, a, apples))
print(count(s, t, b, oranges)) |
"""
This module provides utility functions that are used within socket-py
"""
def get_packet_request(content_name):
message = struct.pack('>I', 1) + struct.pack(len(content_name))
message = message + content_name
message = struct.pack('>I', len(message)) + message
def get_packet_reply(content_name, content):
pass
def get_packet_request_aid(content_name):
pass
def get_packet_reply_aid(content_name, content):
pass
"""
header format:
"""
def send_with_header(data):
pass
"""
get packet type:
"""
def get_packet_type(packet):
pass
| """
This module provides utility functions that are used within socket-py
"""
def get_packet_request(content_name):
message = struct.pack('>I', 1) + struct.pack(len(content_name))
message = message + content_name
message = struct.pack('>I', len(message)) + message
def get_packet_reply(content_name, content):
pass
def get_packet_request_aid(content_name):
pass
def get_packet_reply_aid(content_name, content):
pass
'\nheader format:\n'
def send_with_header(data):
pass
'\nget packet type:\n'
def get_packet_type(packet):
pass |
# Ticket numbers usually consist of an even number of digits.
# A ticket number is considered lucky if the sum of the first
# half of the digits is equal to the sum of the second half.
#
# Given a ticket number n, determine if it's lucky or not.
#
# Example
#
# For n = 1230, the output should be
# isLucky(n) = true;
# For n = 239017, the output should be
# isLucky(n) = false.
n = 239017
firstpart, secondpart = str(n)[:len(str(n))//2], str(n)[len(str(n))//2:]
n1 = sum(map(int, firstpart))
n2 = sum(map(int, secondpart))
print(n1, n2) | n = 239017
(firstpart, secondpart) = (str(n)[:len(str(n)) // 2], str(n)[len(str(n)) // 2:])
n1 = sum(map(int, firstpart))
n2 = sum(map(int, secondpart))
print(n1, n2) |
f = open('input.txt')
data = [int(num) for num in f.read().split("\n")[:-1]]
for i, num1 in enumerate(data):
for num2 in data[i+1:]:
if num1 + num2 == 2020:
print(num1 * num2)
| f = open('input.txt')
data = [int(num) for num in f.read().split('\n')[:-1]]
for (i, num1) in enumerate(data):
for num2 in data[i + 1:]:
if num1 + num2 == 2020:
print(num1 * num2) |
print("Welcome to Alexander's Tic-Tac-Toe Game", "\n")
board = [" "for i in range(9)]
def cls():
print('\n'*20)
def printBoard():
row1 = "|{}|{}|{}|".format(board[0], board[1], board[2])
row2 = "|{}|{}|{}|".format(board[3], board[4], board[5])
row3 = "|{}|{}|{}|".format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def playerMove(icon):
if icon == "X":
number = 1
elif icon == "O":
number = 2
choice = int(input("Player {}: Enter your move: ".format(number)).strip())
if board[choice-1] == " ":
board[choice-1] = icon
else:
print("Sorry Player {}!, that space is Taken. ".format(number))
def victory(icon):
if (board[0] == icon and board[1] == icon and board[2] == icon) or \
(board[3] == icon and board[4] == icon and board[5] == icon) or \
(board[6] == icon and board[7] == icon and board[8] == icon) or \
(board[0] == icon and board[4] == icon and board[8] == icon) or \
(board[2] == icon and board[4] == icon and board[6] == icon) or \
(board[0] == icon and board[3] == icon and board[6] == icon) or \
(board[1] == icon and board[4] == icon and board[7] == icon) or \
(board[2] == icon and board[5] == icon and board[8] == icon):
return True
else:
return False
def isDraw():
if " " not in board:
return True
else:
return False
while True:
printBoard()
playerMove("X")
if victory("X"):
cls()
printBoard()
print("Congratulations Player 1! You've won the game.")
break
if isDraw():
cls()
printBoard()
print("It's draw!")
break
printBoard()
playerMove("O")
if victory("O"):
cls()
printBoard()
print("Congratulations Player 2! you've won the game.")
break
| print("Welcome to Alexander's Tic-Tac-Toe Game", '\n')
board = [' ' for i in range(9)]
def cls():
print('\n' * 20)
def print_board():
row1 = '|{}|{}|{}|'.format(board[0], board[1], board[2])
row2 = '|{}|{}|{}|'.format(board[3], board[4], board[5])
row3 = '|{}|{}|{}|'.format(board[6], board[7], board[8])
print()
print(row1)
print(row2)
print(row3)
print()
def player_move(icon):
if icon == 'X':
number = 1
elif icon == 'O':
number = 2
choice = int(input('Player {}: Enter your move: '.format(number)).strip())
if board[choice - 1] == ' ':
board[choice - 1] = icon
else:
print('Sorry Player {}!, that space is Taken. '.format(number))
def victory(icon):
if board[0] == icon and board[1] == icon and (board[2] == icon) or (board[3] == icon and board[4] == icon and (board[5] == icon)) or (board[6] == icon and board[7] == icon and (board[8] == icon)) or (board[0] == icon and board[4] == icon and (board[8] == icon)) or (board[2] == icon and board[4] == icon and (board[6] == icon)) or (board[0] == icon and board[3] == icon and (board[6] == icon)) or (board[1] == icon and board[4] == icon and (board[7] == icon)) or (board[2] == icon and board[5] == icon and (board[8] == icon)):
return True
else:
return False
def is_draw():
if ' ' not in board:
return True
else:
return False
while True:
print_board()
player_move('X')
if victory('X'):
cls()
print_board()
print("Congratulations Player 1! You've won the game.")
break
if is_draw():
cls()
print_board()
print("It's draw!")
break
print_board()
player_move('O')
if victory('O'):
cls()
print_board()
print("Congratulations Player 2! you've won the game.")
break |
"""
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
"""
# 2018-6-26
# Sort Colors
# https://leetcode.com/problems/sort-colors/discuss/26500/Four-different-solutions
class Solution:
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n0,n1,n2 = 0,0,0
for i in range(len(nums)):
# print(i,n0,n1,n2,nums)
if nums[i] == 0:
nums[n2] = 2
nums[n1] = 1
nums[n0] = 0
n0+=1
n1+=1
n2+=1
elif nums[i] == 1:
nums[n2] = 2
nums[n1] = 1
n1+=1
n2+=1
elif nums[i] == 2:
nums[n2] = 2
n2+=1
# print("----",n0,n1,n2,nums)
return nums
# test
nums = [2,0,2,1,1,0,1]
test = Solution()
res = test.sortColors(nums)
print(res) | """
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
"""
class Solution:
def sort_colors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
(n0, n1, n2) = (0, 0, 0)
for i in range(len(nums)):
if nums[i] == 0:
nums[n2] = 2
nums[n1] = 1
nums[n0] = 0
n0 += 1
n1 += 1
n2 += 1
elif nums[i] == 1:
nums[n2] = 2
nums[n1] = 1
n1 += 1
n2 += 1
elif nums[i] == 2:
nums[n2] = 2
n2 += 1
return nums
nums = [2, 0, 2, 1, 1, 0, 1]
test = solution()
res = test.sortColors(nums)
print(res) |
# We want to make a row of bricks that is goal inches long. We have a number
# of small bricks (1 inch each) and big bricks (5 inches each). Return True
# if it is possible to make the goal by choosing from the given bricks.
# This is a little harder than it looks and can be done without any loops.
# make_bricks(3, 1, 8) --> True
# make_bricks(3, 1, 9) --> False
# make_bricks(3, 2, 10) --> True
def make_bricks(small, big, goal):
num_fives = goal // 5
num_ones = goal - (5 * num_fives)
if num_fives <= big and num_ones <= small:
return True
elif (num_fives >= big) and ((goal - (5 * big)) <= small):
return True
else:
return False
print(make_bricks(3, 1, 8))
print(make_bricks(3, 1, 9))
print(make_bricks(3, 2, 10))
| def make_bricks(small, big, goal):
num_fives = goal // 5
num_ones = goal - 5 * num_fives
if num_fives <= big and num_ones <= small:
return True
elif num_fives >= big and goal - 5 * big <= small:
return True
else:
return False
print(make_bricks(3, 1, 8))
print(make_bricks(3, 1, 9))
print(make_bricks(3, 2, 10)) |
burgers=[]
quan=[]
def PrintHead():
print(" ABC Burgers")
print(" Pakistan Road,Karachi")
print("=====================================")
# Data Entry:
rates = {"cheese": 110, "zinger": 160, "abc special": 250, "chicken": 120}
# Front-End:
def TakeInputs():
b = input("Burger Type:").lower()
if b not in rates.keys():
print("Burger Type Not Recognized")
print("Kindly try again, or add the new burger in Rates list")
TakeInputs()
return
q = int(input("Quantity:"))
burgers.append(b)
quan.append(q)
yn = input("Y to add another burger:")
if yn == "y" or yn=="Y" :
TakeInputs()
else:
print("Data Collection Complete!")
def receipt():
total = 0
print("{0:13} {1} {2:9} {3:9}".format("Burger","Rate"," Quantity"," Price"))
for index,each_burger in enumerate(burgers):
print("{0:13}".format(burgers[index].title()), rates[burgers[index]], "{0:9}".format(quan[index]),
"{0:9}".format(rates[burgers[index]] * quan[index]))
total += (rates[burgers[index]] * quan[index])
print("-------------------------------------")
print(" Total:", total)
PrintHead()
TakeInputs()
PrintHead()
receipt() | burgers = []
quan = []
def print_head():
print(' ABC Burgers')
print(' Pakistan Road,Karachi')
print('=====================================')
rates = {'cheese': 110, 'zinger': 160, 'abc special': 250, 'chicken': 120}
def take_inputs():
b = input('Burger Type:').lower()
if b not in rates.keys():
print('Burger Type Not Recognized')
print('Kindly try again, or add the new burger in Rates list')
take_inputs()
return
q = int(input('Quantity:'))
burgers.append(b)
quan.append(q)
yn = input('Y to add another burger:')
if yn == 'y' or yn == 'Y':
take_inputs()
else:
print('Data Collection Complete!')
def receipt():
total = 0
print('{0:13} {1} {2:9} {3:9}'.format('Burger', 'Rate', ' Quantity', ' Price'))
for (index, each_burger) in enumerate(burgers):
print('{0:13}'.format(burgers[index].title()), rates[burgers[index]], '{0:9}'.format(quan[index]), '{0:9}'.format(rates[burgers[index]] * quan[index]))
total += rates[burgers[index]] * quan[index]
print('-------------------------------------')
print(' Total:', total)
print_head()
take_inputs()
print_head()
receipt() |
cql = {
"and": [
{"lte": [{"property": "eo:cloud_cover"}, "10"]},
{"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]},
{
"or": [
{"eq": [{"property": "collection"}, "landsat"]},
{"lte": [{"property": "gsd"}, "10"]},
]
},
{"lte": [{"property": "id"}, "l8_12345"]},
]
}
cql_multi = {
"and": [
{"lte": [{"property": "eo:cloud_cover"}, "10"]},
{"gte": [{"property": "datetime"}, "2021-04-08T04:39:23Z"]},
{
"or": [
{"eq": [{"property": "collection"}, ["landsat", "sentinel"]]},
{"lte": [{"property": "gsd"}, "10"]},
]
},
]
}
cql2 = {
"op": "or",
"args": [
{"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]},
{"op": "=", "args": [{"property": "collection"}, "landsat"]},
{
"op": "and",
"args": [
{"op": "isNull", "args": {"property": "sentinel:data_coverage"}},
{"op": "isNull", "args": {"property": "landsat:coverage_percent"}},
],
},
],
}
cql2_nested = {
"op": "or",
"args": [
{"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]},
{
"op": "and",
"args": [
{"op": "isNull", "args": {"property": "sentinel:data_coverage"}},
{
"op": "=",
"args": [
{"property": "collection"},
["landsat", "sentinel"],
],
},
{"op": "in", "args": [{"property": "id"}, ["l8_12345", "s2_12345"]]},
],
},
],
}
cql2_no_collection = {
"op": "or",
"args": [{"op": ">=", "args": [{"property": "sentinel:data_coverage"}, 50]}],
}
| cql = {'and': [{'lte': [{'property': 'eo:cloud_cover'}, '10']}, {'gte': [{'property': 'datetime'}, '2021-04-08T04:39:23Z']}, {'or': [{'eq': [{'property': 'collection'}, 'landsat']}, {'lte': [{'property': 'gsd'}, '10']}]}, {'lte': [{'property': 'id'}, 'l8_12345']}]}
cql_multi = {'and': [{'lte': [{'property': 'eo:cloud_cover'}, '10']}, {'gte': [{'property': 'datetime'}, '2021-04-08T04:39:23Z']}, {'or': [{'eq': [{'property': 'collection'}, ['landsat', 'sentinel']]}, {'lte': [{'property': 'gsd'}, '10']}]}]}
cql2 = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}, {'op': '=', 'args': [{'property': 'collection'}, 'landsat']}, {'op': 'and', 'args': [{'op': 'isNull', 'args': {'property': 'sentinel:data_coverage'}}, {'op': 'isNull', 'args': {'property': 'landsat:coverage_percent'}}]}]}
cql2_nested = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}, {'op': 'and', 'args': [{'op': 'isNull', 'args': {'property': 'sentinel:data_coverage'}}, {'op': '=', 'args': [{'property': 'collection'}, ['landsat', 'sentinel']]}, {'op': 'in', 'args': [{'property': 'id'}, ['l8_12345', 's2_12345']]}]}]}
cql2_no_collection = {'op': 'or', 'args': [{'op': '>=', 'args': [{'property': 'sentinel:data_coverage'}, 50]}]} |
def combinationSum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
#Firstly we sort the candidates so we can keep track of our progression
candidates = sorted(candidates)
def backTrack(left, current, results):
#Our base case is when nothing is left, in which case we add the current solution to the results
if not left:
results += [current]
return
#Now we address all candidates
for number in candidates:
#If the number is greater than whats left over, we can break this loop, and in turn the recursio
if number > left: break
#This (along with the sorted candidates) ensures uniqueness because if the number we're at is less than the last number in the curent solution, we can skip it over
if current and number < current[-1]: continue
#In the case that this number is smaller than whats left over, we continue backtracking
backTrack(left - number, current + [number], results)
#We can return results in the higest function call
return results
return backTrack(target, [], [])
| def combination_sum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
candidates = sorted(candidates)
def back_track(left, current, results):
if not left:
results += [current]
return
for number in candidates:
if number > left:
break
if current and number < current[-1]:
continue
back_track(left - number, current + [number], results)
return results
return back_track(target, [], []) |
"""
Holds lists of different types of events
"""
# pylint: disable=line-too-long
def get(ids = False):
"""holds different stack events"""
cases = [{
"name": "new_stack_create_failed",
"success": False,
"StackEvents": [
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "1ca95280-1475-11eb-b0ad-0a374cd00e27",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T14:44:38.938Z",
"ResourceStatus": "DELETE_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthApplication-DELETE_COMPLETE-2020-10-22T14:44:38.097Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:44:38.097Z",
"ResourceStatus": "DELETE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthApplication-DELETE_IN_PROGRESS-2020-10-22T14:44:35.468Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:44:35.468Z",
"ResourceStatus": "DELETE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthGrant-DELETE_COMPLETE-2020-10-22T14:44:34.796Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_WY13MI00",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:44:34.796Z",
"ResourceStatus": "DELETE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthGrant-DELETE_IN_PROGRESS-2020-10-22T14:44:31.962Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_WY13MI00",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:44:31.962Z",
"ResourceStatus": "DELETE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "09413690-1475-11eb-a91a-0a91287fb5a1",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T14:44:06.386Z",
"ResourceStatus": "DELETE_IN_PROGRESS",
"ResourceStatusReason": "The following resource(s) failed to create: [AuthGrant]. . Delete requested by user."
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthGrant-CREATE_FAILED-2020-10-22T14:44:05.641Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_WY13MI00",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:44:05.641Z",
"ResourceStatus": "CREATE_FAILED",
"ResourceStatusReason": "Failed to create resource. 404: No resource with identifier https://authn-cr-failure.com",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:44:05.495Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_WY13MI00",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:44:05.495Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:44:01.330Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:44:01.330Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthApplication-CREATE_COMPLETE-2020-10-22T14:43:59.095Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:43:59.095Z",
"ResourceStatus": "CREATE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:43:58.739Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:43:58.739Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:43:52.855Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:43:52.855Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"EventId": "fe8457a0-1474-11eb-aa91-12cf4a8c2bc2",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T14:43:48.518Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "User Initiated"
}
]
},{
"name": "create_success",
"success": True,
"StackEvents": [
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "ed70f690-1473-11eb-97a1-0a0faac5843d",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T14:36:10.223Z",
"ResourceStatus": "CREATE_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthGrant-CREATE_COMPLETE-2020-10-22T14:36:08.961Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "cgr_zKPHy4Lwx2pxE1Ym",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:36:08.961Z",
"ResourceStatus": "CREATE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:36:08.669Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "cgr_zKPHy4Lwx2pxE1Ym",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:36:08.669Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:36:04.804Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T14:36:04.804Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthApplication-CREATE_COMPLETE-2020-10-22T14:36:02.350Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:36:02.350Z",
"ResourceStatus": "CREATE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:36:01.990Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:36:01.990Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthAPI-CREATE_COMPLETE-2020-10-22T14:36:00.974Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthAPI",
"PhysicalResourceId": "5f9198cecfc1ff003e0dcd6c",
"ResourceType": "Custom::Authn_Api",
"Timestamp": "2020-10-22T14:36:00.974Z",
"ResourceStatus": "CREATE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"Name\":\"authn-cr-regression-api-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthAPI-CREATE_IN_PROGRESS-2020-10-22T14:36:00.268Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthAPI",
"PhysicalResourceId": "5f9198cecfc1ff003e0dcd6c",
"ResourceType": "Custom::Authn_Api",
"Timestamp": "2020-10-22T14:36:00.268Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"Name\":\"authn-cr-regression-api-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:35:56.779Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T14:35:56.779Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "AuthAPI-CREATE_IN_PROGRESS-2020-10-22T14:35:56.291Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthAPI",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Api",
"Timestamp": "2020-10-22T14:35:56.291Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"Name\":\"authn-cr-regression-api-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"EventId": "e28c1d40-1473-11eb-80df-0e765a9edd1f",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T14:35:52.018Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "User Initiated"
}
]
},{
"name": "stack_update_create_rollback_then_update",
"success": False,
"StackEvents": [
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "d41285a0-148d-11eb-8203-0a4db9a5d67f",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:41:34.575Z",
"ResourceStatus": "UPDATE_ROLLBACK_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthApplication-f2e905ef-c14d-40c4-bd1f-29b18d9de9d3",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "AWS::CloudFormation::CustomResource",
"Timestamp": "2020-10-22T17:41:34.241Z",
"ResourceStatus": "DELETE_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthApplication-1506e172-e8cb-4fb9-bc23-ae2608f78549",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "AWS::CloudFormation::CustomResource",
"Timestamp": "2020-10-22T17:41:31.331Z",
"ResourceStatus": "DELETE_IN_PROGRESS"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthGrant-eb8fd3e8-ea4f-4180-a7d4-dad33ceeb9c2",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_721I7XY7",
"ResourceType": "AWS::CloudFormation::CustomResource",
"Timestamp": "2020-10-22T17:41:30.436Z",
"ResourceStatus": "DELETE_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthGrant-49ffcb53-da68-420b-bc52-eea3b6eefca6",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_721I7XY7",
"ResourceType": "AWS::CloudFormation::CustomResource",
"Timestamp": "2020-10-22T17:41:28.076Z",
"ResourceStatus": "DELETE_IN_PROGRESS"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "cf5c5090-148d-11eb-bb65-0e29088293c9",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:41:26.669Z",
"ResourceStatus": "UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "bf0a9c60-148d-11eb-9cb5-0ac97ebd7097",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:40:59.276Z",
"ResourceStatus": "UPDATE_ROLLBACK_IN_PROGRESS",
"ResourceStatusReason": "The following resource(s) failed to create: [AuthGrant]. "
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthGrant-CREATE_FAILED-2020-10-22T17:40:58.114Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_721I7XY7",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T17:40:58.114Z",
"ResourceStatus": "CREATE_FAILED",
"ResourceStatusReason": "Failed to create resource. 404: No resource with identifier https://authn-cr-failure.com",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"bD802jihR56shFVTpgA8uznIu8s5fKaI\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T17:40:57.958Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "qa-cr-authn-failures_AuthGrant_721I7XY7",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T17:40:57.958Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"bD802jihR56shFVTpgA8uznIu8s5fKaI\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthGrant-CREATE_IN_PROGRESS-2020-10-22T17:40:53.735Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthGrant",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Grant",
"Timestamp": "2020-10-22T17:40:53.735Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Tenant\":\"mmm-qa.auth0.com\",\"Audience\":\"https://authn-cr-failure.com\",\"ApplicationId\":\"bD802jihR56shFVTpgA8uznIu8s5fKaI\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthApplication-CREATE_COMPLETE-2020-10-22T17:40:51.431Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T17:40:51.431Z",
"ResourceStatus": "CREATE_COMPLETE",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T17:40:51.089Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "/qa/auth0/authncrregression123456789012",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T17:40:51.089Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "Resource creation Initiated",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "AuthApplication-CREATE_IN_PROGRESS-2020-10-22T17:40:44.568Z",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "AuthApplication",
"PhysicalResourceId": "",
"ResourceType": "Custom::Authn_Application",
"Timestamp": "2020-10-22T17:40:44.568Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceProperties": "{\"ServiceToken\":\"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource\",\"Connections\":[\"con_k4Jtslc6jOQq1rYy\"],\"Type\":\"m2m\",\"Tenant\":\"mmm-qa.auth0.com\",\"Description\":\"A failure to ensure resources aren't orphaned\",\"Name\":\"authn-cr-regression-123456789012\"}"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "b303d850-148d-11eb-9afa-0a73682547f5",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:40:39.101Z",
"ResourceStatus": "UPDATE_IN_PROGRESS",
"ResourceStatusReason": "User Initiated"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "85137040-148d-11eb-bd1c-0a7162bf9a3d",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:39:22.038Z",
"ResourceStatus": "CREATE_COMPLETE"
},
{
"StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"EventId": "82fcec50-148d-11eb-a522-0ea47a628cf7",
"StackName": "qa-cr-authn-failures",
"LogicalResourceId": "qa-cr-authn-failures",
"PhysicalResourceId": "arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7",
"ResourceType": "AWS::CloudFormation::Stack",
"Timestamp": "2020-10-22T17:39:18.624Z",
"ResourceStatus": "CREATE_IN_PROGRESS",
"ResourceStatusReason": "User Initiated"
}
]
}]
if ids:
return [case['name'] for case in cases]
return cases
| """
Holds lists of different types of events
"""
def get(ids=False):
"""holds different stack events"""
cases = [{'name': 'new_stack_create_failed', 'success': False, 'StackEvents': [{'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': '1ca95280-1475-11eb-b0ad-0a374cd00e27', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T14:44:38.938Z', 'ResourceStatus': 'DELETE_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthApplication-DELETE_COMPLETE-2020-10-22T14:44:38.097Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:44:38.097Z', 'ResourceStatus': 'DELETE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthApplication-DELETE_IN_PROGRESS-2020-10-22T14:44:35.468Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:44:35.468Z', 'ResourceStatus': 'DELETE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthGrant-DELETE_COMPLETE-2020-10-22T14:44:34.796Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_WY13MI00', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:44:34.796Z', 'ResourceStatus': 'DELETE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthGrant-DELETE_IN_PROGRESS-2020-10-22T14:44:31.962Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_WY13MI00', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:44:31.962Z', 'ResourceStatus': 'DELETE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': '09413690-1475-11eb-a91a-0a91287fb5a1', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T14:44:06.386Z', 'ResourceStatus': 'DELETE_IN_PROGRESS', 'ResourceStatusReason': 'The following resource(s) failed to create: [AuthGrant]. . Delete requested by user.'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthGrant-CREATE_FAILED-2020-10-22T14:44:05.641Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_WY13MI00', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:44:05.641Z', 'ResourceStatus': 'CREATE_FAILED', 'ResourceStatusReason': 'Failed to create resource. 404: No resource with identifier https://authn-cr-failure.com', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:44:05.495Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_WY13MI00', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:44:05.495Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:44:01.330Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:44:01.330Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"hmODjO7fRD1rguDAdjcyf67bRZqDu0jF"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthApplication-CREATE_COMPLETE-2020-10-22T14:43:59.095Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:43:59.095Z', 'ResourceStatus': 'CREATE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:43:58.739Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:43:58.739Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:43:52.855Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:43:52.855Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'EventId': 'fe8457a0-1474-11eb-aa91-12cf4a8c2bc2', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/fe7f9cb0-1474-11eb-aa91-12cf4a8c2bc2', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T14:43:48.518Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'User Initiated'}]}, {'name': 'create_success', 'success': True, 'StackEvents': [{'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'ed70f690-1473-11eb-97a1-0a0faac5843d', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T14:36:10.223Z', 'ResourceStatus': 'CREATE_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthGrant-CREATE_COMPLETE-2020-10-22T14:36:08.961Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'cgr_zKPHy4Lwx2pxE1Ym', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:36:08.961Z', 'ResourceStatus': 'CREATE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:36:08.669Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'cgr_zKPHy4Lwx2pxE1Ym', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:36:08.669Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T14:36:04.804Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T14:36:04.804Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"QNFneHk2WMyjYuWtUvl21xspV0ZxM9Ba"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthApplication-CREATE_COMPLETE-2020-10-22T14:36:02.350Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:36:02.350Z', 'ResourceStatus': 'CREATE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:36:01.990Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:36:01.990Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthAPI-CREATE_COMPLETE-2020-10-22T14:36:00.974Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthAPI', 'PhysicalResourceId': '5f9198cecfc1ff003e0dcd6c', 'ResourceType': 'Custom::Authn_Api', 'Timestamp': '2020-10-22T14:36:00.974Z', 'ResourceStatus': 'CREATE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","Name":"authn-cr-regression-api-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthAPI-CREATE_IN_PROGRESS-2020-10-22T14:36:00.268Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthAPI', 'PhysicalResourceId': '5f9198cecfc1ff003e0dcd6c', 'ResourceType': 'Custom::Authn_Api', 'Timestamp': '2020-10-22T14:36:00.268Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","Name":"authn-cr-regression-api-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T14:35:56.779Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T14:35:56.779Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'AuthAPI-CREATE_IN_PROGRESS-2020-10-22T14:35:56.291Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthAPI', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Api', 'Timestamp': '2020-10-22T14:35:56.291Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","Name":"authn-cr-regression-api-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'EventId': 'e28c1d40-1473-11eb-80df-0e765a9edd1f', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/e289fa60-1473-11eb-80df-0e765a9edd1f', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T14:35:52.018Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'User Initiated'}]}, {'name': 'stack_update_create_rollback_then_update', 'success': False, 'StackEvents': [{'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'd41285a0-148d-11eb-8203-0a4db9a5d67f', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:41:34.575Z', 'ResourceStatus': 'UPDATE_ROLLBACK_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthApplication-f2e905ef-c14d-40c4-bd1f-29b18d9de9d3', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'AWS::CloudFormation::CustomResource', 'Timestamp': '2020-10-22T17:41:34.241Z', 'ResourceStatus': 'DELETE_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthApplication-1506e172-e8cb-4fb9-bc23-ae2608f78549', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'AWS::CloudFormation::CustomResource', 'Timestamp': '2020-10-22T17:41:31.331Z', 'ResourceStatus': 'DELETE_IN_PROGRESS'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthGrant-eb8fd3e8-ea4f-4180-a7d4-dad33ceeb9c2', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_721I7XY7', 'ResourceType': 'AWS::CloudFormation::CustomResource', 'Timestamp': '2020-10-22T17:41:30.436Z', 'ResourceStatus': 'DELETE_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthGrant-49ffcb53-da68-420b-bc52-eea3b6eefca6', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_721I7XY7', 'ResourceType': 'AWS::CloudFormation::CustomResource', 'Timestamp': '2020-10-22T17:41:28.076Z', 'ResourceStatus': 'DELETE_IN_PROGRESS'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'cf5c5090-148d-11eb-bb65-0e29088293c9', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:41:26.669Z', 'ResourceStatus': 'UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'bf0a9c60-148d-11eb-9cb5-0ac97ebd7097', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:40:59.276Z', 'ResourceStatus': 'UPDATE_ROLLBACK_IN_PROGRESS', 'ResourceStatusReason': 'The following resource(s) failed to create: [AuthGrant]. '}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthGrant-CREATE_FAILED-2020-10-22T17:40:58.114Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_721I7XY7', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T17:40:58.114Z', 'ResourceStatus': 'CREATE_FAILED', 'ResourceStatusReason': 'Failed to create resource. 404: No resource with identifier https://authn-cr-failure.com', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"bD802jihR56shFVTpgA8uznIu8s5fKaI"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T17:40:57.958Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': 'qa-cr-authn-failures_AuthGrant_721I7XY7', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T17:40:57.958Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"bD802jihR56shFVTpgA8uznIu8s5fKaI"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthGrant-CREATE_IN_PROGRESS-2020-10-22T17:40:53.735Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthGrant', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Grant', 'Timestamp': '2020-10-22T17:40:53.735Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Tenant":"mmm-qa.auth0.com","Audience":"https://authn-cr-failure.com","ApplicationId":"bD802jihR56shFVTpgA8uznIu8s5fKaI"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthApplication-CREATE_COMPLETE-2020-10-22T17:40:51.431Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T17:40:51.431Z', 'ResourceStatus': 'CREATE_COMPLETE', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T17:40:51.089Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '/qa/auth0/authncrregression123456789012', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T17:40:51.089Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'Resource creation Initiated', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'AuthApplication-CREATE_IN_PROGRESS-2020-10-22T17:40:44.568Z', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'AuthApplication', 'PhysicalResourceId': '', 'ResourceType': 'Custom::Authn_Application', 'Timestamp': '2020-10-22T17:40:44.568Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceProperties': '{"ServiceToken":"arn:aws:lambda:us-east-1:123456789012:function:qa-auth-custom-resource","Connections":["con_k4Jtslc6jOQq1rYy"],"Type":"m2m","Tenant":"mmm-qa.auth0.com","Description":"A failure to ensure resources aren\'t orphaned","Name":"authn-cr-regression-123456789012"}'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': 'b303d850-148d-11eb-9afa-0a73682547f5', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:40:39.101Z', 'ResourceStatus': 'UPDATE_IN_PROGRESS', 'ResourceStatusReason': 'User Initiated'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': '85137040-148d-11eb-bd1c-0a7162bf9a3d', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:39:22.038Z', 'ResourceStatus': 'CREATE_COMPLETE'}, {'StackId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'EventId': '82fcec50-148d-11eb-a522-0ea47a628cf7', 'StackName': 'qa-cr-authn-failures', 'LogicalResourceId': 'qa-cr-authn-failures', 'PhysicalResourceId': 'arn:aws:cloudformation:us-east-1:123456789012:stack/qa-cr-authn-failures/82f87f80-148d-11eb-a522-0ea47a628cf7', 'ResourceType': 'AWS::CloudFormation::Stack', 'Timestamp': '2020-10-22T17:39:18.624Z', 'ResourceStatus': 'CREATE_IN_PROGRESS', 'ResourceStatusReason': 'User Initiated'}]}]
if ids:
return [case['name'] for case in cases]
return cases |
'''
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note:
points.length == 3
points[i].length == 2
0 <= points[i][j] <= 100
'''
class Solution(object):
def isBoomerang(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
x1, x2, x3, y1, y2, y3 = points[0][0], points[1][0], points[2][0], points[0][1], points[1][1] ,points[2][1]
if ((y3 - y2)*(x2 - x1) == (y2 - y1)*(x3 - x2)):
return False
return True
| """
A boomerang is a set of 3 points that are all distinct and not in a straight line.
Given a list of three points in the plane, return whether these points are a boomerang.
Example 1:
Input: [[1,1],[2,3],[3,2]]
Output: true
Example 2:
Input: [[1,1],[2,2],[3,3]]
Output: false
Note:
points.length == 3
points[i].length == 2
0 <= points[i][j] <= 100
"""
class Solution(object):
def is_boomerang(self, points):
"""
:type points: List[List[int]]
:rtype: bool
"""
(x1, x2, x3, y1, y2, y3) = (points[0][0], points[1][0], points[2][0], points[0][1], points[1][1], points[2][1])
if (y3 - y2) * (x2 - x1) == (y2 - y1) * (x3 - x2):
return False
return True |
def definition():
"""View of component groups, with fields additional to the cgroup object."""
sql = """
SELECT c.cgroup_id, c.description, c.strand, c.notes, c.curriculum_id,
s.description as strand_name,
c.cgroup_id id,
c.description as short_name,
ISNULL(conf.child_count,0) as child_count
FROM c_cgroup c
LEFT JOIN c_cgroup_strand s ON s.strand_id = c.strand
LEFT JOIN (SELECT cgroup_id, COUNT(component_id) as child_count
FROM c_cgroup_config GROUP BY cgroup_id) conf ON conf.cgroup_id = c.cgroup_id
"""
return sql
| def definition():
"""View of component groups, with fields additional to the cgroup object."""
sql = '\nSELECT c.cgroup_id, c.description, c.strand, c.notes, c.curriculum_id, \n s.description as strand_name, \n c.cgroup_id id, \n c.description as short_name, \n ISNULL(conf.child_count,0) as child_count\nFROM c_cgroup c\nLEFT JOIN c_cgroup_strand s ON s.strand_id = c.strand\nLEFT JOIN (SELECT cgroup_id, COUNT(component_id) as child_count\n FROM c_cgroup_config GROUP BY cgroup_id) conf ON conf.cgroup_id = c.cgroup_id\n'
return sql |
class AnnotaVO:
def __init__(self):
self._entry = None
self._label = None
self._points = None
self._kind = None
@property
def points(self):
return self._points
@points.setter
def points(self, value):
self._points = value
@property
def entry(self):
return self._entry
@entry.setter
def entry(self, value):
self._entry = value
@property
def label(self):
return self._label
@label.setter
def label(self, value):
self._label = value
@property
def kind(self):
return self._kind
@kind.setter
def kind(self, value):
self._kind = value
| class Annotavo:
def __init__(self):
self._entry = None
self._label = None
self._points = None
self._kind = None
@property
def points(self):
return self._points
@points.setter
def points(self, value):
self._points = value
@property
def entry(self):
return self._entry
@entry.setter
def entry(self, value):
self._entry = value
@property
def label(self):
return self._label
@label.setter
def label(self, value):
self._label = value
@property
def kind(self):
return self._kind
@kind.setter
def kind(self, value):
self._kind = value |
# Accounts
USER_DOES_NOT_EXIST = 1000
INCORRECT_PASSWORD = 1001
USER_INACTIVE = 1002
INVALID_SIGN_UP_CODE = 1030
SOCIAL_DOES_NOT_EXIST = 1100
INCORRECT_TOKEN = 1101
TOKEN_ALREADY_IN_USE = 1102
SAME_PASSWORD = 1200
# Common
FORM_ERROR = 9000
| user_does_not_exist = 1000
incorrect_password = 1001
user_inactive = 1002
invalid_sign_up_code = 1030
social_does_not_exist = 1100
incorrect_token = 1101
token_already_in_use = 1102
same_password = 1200
form_error = 9000 |
class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
# The base class constructor.
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used with `backward` as well.
`x`: A numpy array-like object.
"""
return 1. / (1. + np.exp(-x))
def forward(self):
"""
Perform the sigmoid function and set the value.
"""
input_value = self.inbound_nodes[0].value
self.value = self._sigmoid(input_value)
def backward(self):
"""
Calculates the gradient using the derivative of
the sigmoid function.
"""
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
# Sum the derivative with respect to the input over all the outputs.
for n in self.outbound_nodes:
grad_cost = n.gradients[self]
sigmoid = self.value
self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost
| class Sigmoid(Node):
"""
Represents a node that performs the sigmoid activation function.
"""
def __init__(self, node):
Node.__init__(self, [node])
def _sigmoid(self, x):
"""
This method is separate from `forward` because it
will be used with `backward` as well.
`x`: A numpy array-like object.
"""
return 1.0 / (1.0 + np.exp(-x))
def forward(self):
"""
Perform the sigmoid function and set the value.
"""
input_value = self.inbound_nodes[0].value
self.value = self._sigmoid(input_value)
def backward(self):
"""
Calculates the gradient using the derivative of
the sigmoid function.
"""
self.gradients = {n: np.zeros_like(n.value) for n in self.inbound_nodes}
for n in self.outbound_nodes:
grad_cost = n.gradients[self]
sigmoid = self.value
self.gradients[self.inbound_nodes[0]] += sigmoid * (1 - sigmoid) * grad_cost |
names = ["kara", "jackie", "Theophilus"]
for name in names:
print(names)
print("\n")
for index in range(len(names)):
print(names[index]) | names = ['kara', 'jackie', 'Theophilus']
for name in names:
print(names)
print('\n')
for index in range(len(names)):
print(names[index]) |
''' Python name attribute
Every module in Python has a special variable called name.
The value of the nsme attribute is set
'''
| """ Python name attribute
Every module in Python has a special variable called name.
The value of the nsme attribute is set
""" |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python implementation of permute utility with Numpy backend from the MATLAB Tensor Toolbox [1].
References
========================================
[1] General software, latest release: Brett W. Bader, Tamara G. Kolda and others, Tensor Toolbox for MATLAB, Version 3.2.1, www.tensortoolbox.org, April 5, 2021.\n
"""
def permute(M, order):
"""
This function permutes the dimensions of the KRUSKAL tensor M.
Parameters
----------
M : object
KRUSKAL tensor class. ktensor.K_TENSOR.
order : array
Vector order.
Returns
-------
M : object
KRUSKAL tensor class. ktensor.K_TENSOR.
"""
for ii, dim in enumerate(order):
temp = M.Factors[str(ii)]
M.Factors[str(ii)] = M.Factors[str(dim)]
M.Factors[str(dim)] = temp
return M | """
Python implementation of permute utility with Numpy backend from the MATLAB Tensor Toolbox [1].
References
========================================
[1] General software, latest release: Brett W. Bader, Tamara G. Kolda and others, Tensor Toolbox for MATLAB, Version 3.2.1, www.tensortoolbox.org, April 5, 2021.
"""
def permute(M, order):
"""
This function permutes the dimensions of the KRUSKAL tensor M.
Parameters
----------
M : object
KRUSKAL tensor class. ktensor.K_TENSOR.
order : array
Vector order.
Returns
-------
M : object
KRUSKAL tensor class. ktensor.K_TENSOR.
"""
for (ii, dim) in enumerate(order):
temp = M.Factors[str(ii)]
M.Factors[str(ii)] = M.Factors[str(dim)]
M.Factors[str(dim)] = temp
return M |
# -*- coding: utf-8 -*-
"""
Created on Thu May 16 19:37:39 2019
@author: Parikshith.H
"""
str="hello"
if str=="hi":
print("true")
else:
print("false")
# =============================================================================
# #output:
# false
# =============================================================================
if str < "hi":
print("true")
else:
print("false")
# =============================================================================
# #output:
# true
# =============================================================================
if 'e' in "hello": #to check a character present in string or not
print("true")
else:
print("false")
# =============================================================================
# #output:
# true
# =============================================================================
s = "welcome"
for ch in s:
print(ch)
# =============================================================================
# #output:
# w
# e
# l
# c
# o
# m
# e
# =============================================================================
for val in "hello":
print(val)
# =============================================================================
# #output:
# h
# e
# l
# l
# o
# =============================================================================
fruit1 = input('Please enter the name of first fruit:\n')
fruit2 = input('Please enter the name of second fruit:\n')
if fruit1 < fruit2:
print(fruit1 + " comes before " + fruit2 + " in the dictionary.")
elif fruit1 > fruit2:
print(fruit1 + " comes after " + fruit2 + " in the dictionary.")
else:
print(fruit1 + " and " + fruit2 + " are same.")
# =============================================================================
# #output:
# Please enter the name of first fruit:
# apple
#
# Please enter the name of second fruit:
# cherry
# apple comes before cherry in the dictionary.
# =============================================================================
| """
Created on Thu May 16 19:37:39 2019
@author: Parikshith.H
"""
str = 'hello'
if str == 'hi':
print('true')
else:
print('false')
if str < 'hi':
print('true')
else:
print('false')
if 'e' in 'hello':
print('true')
else:
print('false')
s = 'welcome'
for ch in s:
print(ch)
for val in 'hello':
print(val)
fruit1 = input('Please enter the name of first fruit:\n')
fruit2 = input('Please enter the name of second fruit:\n')
if fruit1 < fruit2:
print(fruit1 + ' comes before ' + fruit2 + ' in the dictionary.')
elif fruit1 > fruit2:
print(fruit1 + ' comes after ' + fruit2 + ' in the dictionary.')
else:
print(fruit1 + ' and ' + fruit2 + ' are same.') |
people = [
('Alice', 32), # one tuple
('Bob', 51), # another tuple
('Carol', 15),
('Dylan', 5),
('Erin', 25),
('Frank', 48)
]
i= 0
yuanzu = (' ', 999)
while i < len(people):
if people[i][1] <= yuanzu[1]:
yuanzu = people[i]
i += 1
print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1]))
print(people(people[i][1] == 5)) | people = [('Alice', 32), ('Bob', 51), ('Carol', 15), ('Dylan', 5), ('Erin', 25), ('Frank', 48)]
i = 0
yuanzu = (' ', 999)
while i < len(people):
if people[i][1] <= yuanzu[1]:
yuanzu = people[i]
i += 1
print('Youngest person: {}, {} years old. '.format(yuanzu[0], yuanzu[1]))
print(people(people[i][1] == 5)) |
#!/usr/bin/env python
'''
Description: these are the default parameters to use for processing secrets data
Author: Rachel Kalmar
'''
# ------------------------------------ #
# Set defaults for parameters to be used in secretReaderPollyVoices
datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/' # Where the secrets data is kept
mp3path_base = '/Users/kalmar/Documents/code/secrets/audio/' # Where to store the audio output
shuffleSecrets = False # Shuffle the order of the secrets?
speak = True # Speak secrets?
ssml = True # Use speech synthesis markup language?
whisperFreq = 0.15 # What percentage of the secrets should be whispered?
mp3_padding = 1500 # Buffer between mp3 files, for concatenated mp3
concatSecretMp3s = True # Concatenate the individual mp3 files in a group
datapath = '/Users/kalmar/Documents/code/secrets/secrets_data/secrets_edit_rk.json'
# ------------------------------------ #
# Set language and translation params
translate_lang = False
language = 'en'
# language = 'it'
# language = 'de'
target_lang = 'en'
# target_lang = 'it'
# target_lang = 'de'
englishVoiceIds = ['Joanna', 'Kendra', 'Amy', 'Joey', 'Brian']
italianVoiceIds = ['Carla', 'Giorgio']
germanVoiceIds = ['Vicki', 'Marlene', 'Hans']
if language=='en':
# voiceIds = ['Joanna', 'Salli', 'Kimberly', 'Kendra', 'Amy', 'Ivy', 'Justin', 'Joey', 'Brian']
voiceIds = englishVoiceIds
elif language=='it':
voiceIds = italianVoiceIds
elif language=='de':
voiceIds = germanVoiceIds
voice = voiceIds[0]
# ------------------------------------ #
# Set params based on options chosen above
if language == 'en':
datapath = datapath_base + 'secrets_edit_edit.json'
elif language == 'it':
datapath = datapath_base + 'secrets_edit_italian_temp.json'
elif language == 'de':
datapath = datapath_base + 'secrets_edit_german.json'
if ssml:
textType = 'ssml'
else:
textType = 'text' | """
Description: these are the default parameters to use for processing secrets data
Author: Rachel Kalmar
"""
datapath_base = '/Users/kalmar/Documents/code/secrets/secrets_data/'
mp3path_base = '/Users/kalmar/Documents/code/secrets/audio/'
shuffle_secrets = False
speak = True
ssml = True
whisper_freq = 0.15
mp3_padding = 1500
concat_secret_mp3s = True
datapath = '/Users/kalmar/Documents/code/secrets/secrets_data/secrets_edit_rk.json'
translate_lang = False
language = 'en'
target_lang = 'en'
english_voice_ids = ['Joanna', 'Kendra', 'Amy', 'Joey', 'Brian']
italian_voice_ids = ['Carla', 'Giorgio']
german_voice_ids = ['Vicki', 'Marlene', 'Hans']
if language == 'en':
voice_ids = englishVoiceIds
elif language == 'it':
voice_ids = italianVoiceIds
elif language == 'de':
voice_ids = germanVoiceIds
voice = voiceIds[0]
if language == 'en':
datapath = datapath_base + 'secrets_edit_edit.json'
elif language == 'it':
datapath = datapath_base + 'secrets_edit_italian_temp.json'
elif language == 'de':
datapath = datapath_base + 'secrets_edit_german.json'
if ssml:
text_type = 'ssml'
else:
text_type = 'text' |
a = "0,0,0,0,0,0"
b = "0,-1,-2,0"
c = "-1,-3,-4,-1,-2"
d = "qwerty"
e = ",,3,,4"
f = "1,2,v,b,3"
g = "0,7,0,2,-12,3,0,2"
h = "1,3,-2,1,2"
def sum_earnings(str_earn):
next_value = 0
total = 0
neg_sum = 0
if any(char.isalpha() for char in str_earn):
return 0
for s in str_earn.split(','):
if not s:
return 0
lst = [int(s) for s in str_earn.split(',')]
print(lst)
if all(x <= 0 for x in lst):
return 0
for idx, val in enumerate(lst):
total +=val
if idx < len(lst)-1:
next_value = lst[idx + 1]
neg_sum = total + next_value
if neg_sum <= 0:
total = 0
neg_sum = 0
return total
print(sum_earnings(h)) | a = '0,0,0,0,0,0'
b = '0,-1,-2,0'
c = '-1,-3,-4,-1,-2'
d = 'qwerty'
e = ',,3,,4'
f = '1,2,v,b,3'
g = '0,7,0,2,-12,3,0,2'
h = '1,3,-2,1,2'
def sum_earnings(str_earn):
next_value = 0
total = 0
neg_sum = 0
if any((char.isalpha() for char in str_earn)):
return 0
for s in str_earn.split(','):
if not s:
return 0
lst = [int(s) for s in str_earn.split(',')]
print(lst)
if all((x <= 0 for x in lst)):
return 0
for (idx, val) in enumerate(lst):
total += val
if idx < len(lst) - 1:
next_value = lst[idx + 1]
neg_sum = total + next_value
if neg_sum <= 0:
total = 0
neg_sum = 0
return total
print(sum_earnings(h)) |
def main():
n, k = map(int, input().split())
l = []
for i in range(n):
a, b = map(int, input().split())
l.append((a, b))
l.sort()
prev = 0
for i in range(n):
prev += l[i][1]
if k <= prev:
print(l[i][0])
break
if __name__ == '__main__':
main()
| def main():
(n, k) = map(int, input().split())
l = []
for i in range(n):
(a, b) = map(int, input().split())
l.append((a, b))
l.sort()
prev = 0
for i in range(n):
prev += l[i][1]
if k <= prev:
print(l[i][0])
break
if __name__ == '__main__':
main() |
class Solution:
def minimumLength(self, s: str) -> int:
if len(s)==1:
return 1
i=0
j=len(s)-1
while i<j:
if s[i]!=s[j]:
break
temp = s[i]
while i<=j and s[i]==temp:
i+=1
while j>=i and s[j]==temp:
j-=1
return j-i+1
| class Solution:
def minimum_length(self, s: str) -> int:
if len(s) == 1:
return 1
i = 0
j = len(s) - 1
while i < j:
if s[i] != s[j]:
break
temp = s[i]
while i <= j and s[i] == temp:
i += 1
while j >= i and s[j] == temp:
j -= 1
return j - i + 1 |
"""
Created by akiselev on 2019-07-18
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The score of a single word is 2 if the word contains an even number of vowels. Otherwise, the score of this word is 1.
The score for the whole list of words is the sum of scores of all words in the list.
Debug the given function score_words such that it returns a correct score.
Your function will be tested on several cases by the locked template code.
"""
def is_vowel(letter):
return letter in ['a', 'e', 'i', 'o', 'u', 'y']
def score_words(words):
score = 0
for word in words:
num_vowels = 0
for letter in word:
if is_vowel(letter):
num_vowels += 1
if num_vowels % 2 == 0:
score += 2
else:
score += 1
return score
n = int(input())
words = input().split()
print(score_words(words)) | """
Created by akiselev on 2019-07-18
In this challenge, the task is to debug the existing code to successfully execute all provided test files.
Consider that vowels in the alphabet are a, e, i, o, u and y.
Function score_words takes a list of lowercase words as an argument and returns a score as follows:
The score of a single word is 2 if the word contains an even number of vowels. Otherwise, the score of this word is 1.
The score for the whole list of words is the sum of scores of all words in the list.
Debug the given function score_words such that it returns a correct score.
Your function will be tested on several cases by the locked template code.
"""
def is_vowel(letter):
return letter in ['a', 'e', 'i', 'o', 'u', 'y']
def score_words(words):
score = 0
for word in words:
num_vowels = 0
for letter in word:
if is_vowel(letter):
num_vowels += 1
if num_vowels % 2 == 0:
score += 2
else:
score += 1
return score
n = int(input())
words = input().split()
print(score_words(words)) |
# -*- coding: utf-8 -*-
"""The modules manager."""
class ModulesManager(object):
"""The modules manager."""
_module_classes = {}
@classmethod
def GetModuleObjects(cls, module_filter_expression=None):
excludes, includes = cls.SplitExpression(cls, expression = module_filter_expression)
module_objects = {}
for module_name, module_class in iter(cls._module_classes.items()):
if not includes and module_name in excludes:
continue
if includes and module_name not in includes:
continue
module_object = module_class()
if module_class.SupportsPlugins():
plugin_includes = None
if module_name in includes:
plugin_includes = includes[module_name]
module_object.EnablePlugins(plugin_includes)
module_objects[module_name] = module_object
return module_objects
@classmethod
def RegisterModule(cls, module_class):
"""Registers a module class.
The module classes are identified based on their lower case name.
Args:
module_class (type): module class.
Raises:
KeyError: if parser class is already set for the corresponding name.
"""
module_name = module_class.NAME.lower()
if module_name in cls._module_classes:
raise KeyError('Module class already set for name: {0:s}.'.format(
module_class.NAME))
cls._module_classes[module_name] = module_class
@classmethod
def _GetParsers(cls, module_filter_expression=None):
"""Retrieves the registered parsers and plugins.
Args:
module_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
A module filter expression is a comma separated value string that
denotes which modules should be used.
Yields:
tuple: containing:
* str: name of the module:
* type: module class (subclass of BaseModule).
"""
excludes, includes = cls.SplitExpression(cls, expression=module_filter_expression)
for module_name, module_class in cls._module_classes.items():
# If there are no includes all parsers are included by default.
if not includes and module_name in excludes:
continue
if includes and module_name not in includes:
continue
yield module_name, module_class
@classmethod
def GetModulesInformation(cls):
"""Retrieves the modules information.
Returns:
list[tuple[str, str]]: modules names and descriptions.
"""
modules_information = []
for _, parser_class in cls._GetParsers():
description = getattr(parser_class, 'DESCRIPTION', '')
modules_information.append((parser_class.NAME, description))
return modules_information
def SplitExpression(cls, expression = None):
"""Determines the excluded and included elements in an expression string.
"""
if not expression:
return {}, {}
excludes = {}
includes = {}
for expression_element in expression.split(','):
expression_element = expression_element.strip()
if not expression_element:
continue
expression_element = expression_element.lower()
if expression_element.startswith('!'):
expression_element = expression_element[1:]
modules = excludes
else:
modules = includes
module, _, plugin = expression_element.partition('/')
if not plugin:
plugin = '*'
modules.setdefault(module, set())
modules[module].add(plugin)
return excludes, includes | """The modules manager."""
class Modulesmanager(object):
"""The modules manager."""
_module_classes = {}
@classmethod
def get_module_objects(cls, module_filter_expression=None):
(excludes, includes) = cls.SplitExpression(cls, expression=module_filter_expression)
module_objects = {}
for (module_name, module_class) in iter(cls._module_classes.items()):
if not includes and module_name in excludes:
continue
if includes and module_name not in includes:
continue
module_object = module_class()
if module_class.SupportsPlugins():
plugin_includes = None
if module_name in includes:
plugin_includes = includes[module_name]
module_object.EnablePlugins(plugin_includes)
module_objects[module_name] = module_object
return module_objects
@classmethod
def register_module(cls, module_class):
"""Registers a module class.
The module classes are identified based on their lower case name.
Args:
module_class (type): module class.
Raises:
KeyError: if parser class is already set for the corresponding name.
"""
module_name = module_class.NAME.lower()
if module_name in cls._module_classes:
raise key_error('Module class already set for name: {0:s}.'.format(module_class.NAME))
cls._module_classes[module_name] = module_class
@classmethod
def __get_parsers(cls, module_filter_expression=None):
"""Retrieves the registered parsers and plugins.
Args:
module_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
A module filter expression is a comma separated value string that
denotes which modules should be used.
Yields:
tuple: containing:
* str: name of the module:
* type: module class (subclass of BaseModule).
"""
(excludes, includes) = cls.SplitExpression(cls, expression=module_filter_expression)
for (module_name, module_class) in cls._module_classes.items():
if not includes and module_name in excludes:
continue
if includes and module_name not in includes:
continue
yield (module_name, module_class)
@classmethod
def get_modules_information(cls):
"""Retrieves the modules information.
Returns:
list[tuple[str, str]]: modules names and descriptions.
"""
modules_information = []
for (_, parser_class) in cls._GetParsers():
description = getattr(parser_class, 'DESCRIPTION', '')
modules_information.append((parser_class.NAME, description))
return modules_information
def split_expression(cls, expression=None):
"""Determines the excluded and included elements in an expression string.
"""
if not expression:
return ({}, {})
excludes = {}
includes = {}
for expression_element in expression.split(','):
expression_element = expression_element.strip()
if not expression_element:
continue
expression_element = expression_element.lower()
if expression_element.startswith('!'):
expression_element = expression_element[1:]
modules = excludes
else:
modules = includes
(module, _, plugin) = expression_element.partition('/')
if not plugin:
plugin = '*'
modules.setdefault(module, set())
modules[module].add(plugin)
return (excludes, includes) |
# set declaration
myfruits = {"Apple", "Banana", "Grapes", "Litchi", "Mango"}
mynums = {1, 2, 3, 4, 5}
# Set printing before removing
print("Before remove() method...")
print("fruits: ", myfruits)
print("numbers: ", mynums)
# Removing the elements from the sets
elerem = myfruits.remove('Apple')
elerem = myfruits.remove('Litchi')
elerem = myfruits.remove('Mango')
elerem = mynums.remove(1)
elerem = mynums.remove(3)
elerem = mynums.remove(4)
print("After remove() method...")
print("fruits: ", myfruits)
print("numbers: ", mynums) | myfruits = {'Apple', 'Banana', 'Grapes', 'Litchi', 'Mango'}
mynums = {1, 2, 3, 4, 5}
print('Before remove() method...')
print('fruits: ', myfruits)
print('numbers: ', mynums)
elerem = myfruits.remove('Apple')
elerem = myfruits.remove('Litchi')
elerem = myfruits.remove('Mango')
elerem = mynums.remove(1)
elerem = mynums.remove(3)
elerem = mynums.remove(4)
print('After remove() method...')
print('fruits: ', myfruits)
print('numbers: ', mynums) |
# CPU: 0.05 s
amounts = list(map(int, input().split()))
ratios = list(map(int, input().split()))
n = min(amounts[x] / ratios[x] for x in range(3))
for amount, ratio in zip(amounts, ratios):
print(amount - ratio * n, end=" ")
| amounts = list(map(int, input().split()))
ratios = list(map(int, input().split()))
n = min((amounts[x] / ratios[x] for x in range(3)))
for (amount, ratio) in zip(amounts, ratios):
print(amount - ratio * n, end=' ') |
COUNTRIES = [
"US",
"IL",
"IN",
"UA",
"CA",
"AR",
"SG",
"TW",
"GB",
"AT",
"BE",
"BG",
"HR",
"CY",
"CZ",
"DK",
"EE",
"FI",
"FR",
"DE",
"GR",
"HU",
"IE",
"IT",
"LK",
"LV",
"LT",
"LU",
"MT",
"NL",
"PL",
"PT",
"RO",
"SK",
"SI",
"ES",
"SE",
"NZ",
"AU",
"BF",
"BO",
"BR",
"BZ",
"CI",
"CL",
"CO",
"DO",
"EC",
"GE",
"GH",
"GY",
"ID",
"IS",
"JP",
"KG",
"MD",
"ME",
"MK",
"ML",
"MM",
"MN",
"MX",
"MY",
"PH",
"PW",
"RS",
"SC",
"SR",
"TR",
"TZ",
"VC",
]
| countries = ['US', 'IL', 'IN', 'UA', 'CA', 'AR', 'SG', 'TW', 'GB', 'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LK', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'NZ', 'AU', 'BF', 'BO', 'BR', 'BZ', 'CI', 'CL', 'CO', 'DO', 'EC', 'GE', 'GH', 'GY', 'ID', 'IS', 'JP', 'KG', 'MD', 'ME', 'MK', 'ML', 'MM', 'MN', 'MX', 'MY', 'PH', 'PW', 'RS', 'SC', 'SR', 'TR', 'TZ', 'VC'] |
x = 1
y = 10
# Checks if one value is equal to another
if x == 1:
print("x is equal to 1")
# Checks if one value is NOT equal to another
if y != 1:
print("y is not equal to 1")
# Checks if one value is less than another
if x < y:
print("x is less than y")
# Checks if one value is greater than another
if y > x:
print("y is greater than x")
# Checks if a value is less than or equal to another
if x >= 1:
print("x is greater than or equal to 1")
# Checks for two conditions to be met using "and"
if x == 1 and y == 10:
print("Both values returned true")
# Checks if either of two conditions is met
if x < 45 or y < 5:
print("One or the other statements were true")
# Nested if statements
if x < 10:
if y < 5:
print("x is less than 10 and y is less than 5")
elif y == 5:
print("x is less than 10 and y is equal to 5")
else:
print("x is less than 10 and y is greater than 5")
| x = 1
y = 10
if x == 1:
print('x is equal to 1')
if y != 1:
print('y is not equal to 1')
if x < y:
print('x is less than y')
if y > x:
print('y is greater than x')
if x >= 1:
print('x is greater than or equal to 1')
if x == 1 and y == 10:
print('Both values returned true')
if x < 45 or y < 5:
print('One or the other statements were true')
if x < 10:
if y < 5:
print('x is less than 10 and y is less than 5')
elif y == 5:
print('x is less than 10 and y is equal to 5')
else:
print('x is less than 10 and y is greater than 5') |
# general configuration
LOCAL_OTP_PORT = 8088 # port for OTP to use, HTTPS will be served on +1
TEMP_DIRECTORY = "mara-ptm-temp"
PROGRESS_WATCHER_INTERVAL = 5 * 60 * 1000 # milliseconds
JVM_PARAMETERS = "-Xmx8G" # 6-8GB of RAM is good for bigger graphs
# itinerary filter parameters
CAR_KMH = 50
CAR_TRAVEL_FACTOR = 1.4 # as the crow flies vs street, how much longer is realistic
# note: the factor that public transport may take longer is configured in the GUI
# itinerary parameters
ALLOWED_TRANSIT_MODES = ["WALK", "BUS", "TRAM", "SUBWAY", "RAIL"]
MAX_WALK_DISTANCE = 1000 # meters
OTP_PARAMETERS_TEMPLATE = "&".join([
"fromPlace=1:{origin}",
"toPlace=1:{destination}",
"time=00%3A00",
"date={date}",
"mode=TRANSIT%2CWALK",
"maxWalkDistance={max_walk_distance}",
"arriveBy=false",
"searchWindow=86400",
"numOfItineraries=99999",
"keepNumOfItineraries=99999",
"showIntermediateStops=true",
])
| local_otp_port = 8088
temp_directory = 'mara-ptm-temp'
progress_watcher_interval = 5 * 60 * 1000
jvm_parameters = '-Xmx8G'
car_kmh = 50
car_travel_factor = 1.4
allowed_transit_modes = ['WALK', 'BUS', 'TRAM', 'SUBWAY', 'RAIL']
max_walk_distance = 1000
otp_parameters_template = '&'.join(['fromPlace=1:{origin}', 'toPlace=1:{destination}', 'time=00%3A00', 'date={date}', 'mode=TRANSIT%2CWALK', 'maxWalkDistance={max_walk_distance}', 'arriveBy=false', 'searchWindow=86400', 'numOfItineraries=99999', 'keepNumOfItineraries=99999', 'showIntermediateStops=true']) |
class Solution:
# @param s, a string
# @param dict, a set of string
# @return a boolean
def wordBreak(self, s, dict):
if not dict:
return False
n = len(s)
res = [False] * n
for i in xrange(0, n):
if s[:i+1] in dict:
res[i] = True
if not True in res:
return False
i = 0
while i < n:
if res[i]:
i += 1
continue
for k in xrange(0, i+1):
if res[i-k] and s[i-k+1:i+1] in dict:
res[i] = True
break
i += 1
return res[-1] | class Solution:
def word_break(self, s, dict):
if not dict:
return False
n = len(s)
res = [False] * n
for i in xrange(0, n):
if s[:i + 1] in dict:
res[i] = True
if not True in res:
return False
i = 0
while i < n:
if res[i]:
i += 1
continue
for k in xrange(0, i + 1):
if res[i - k] and s[i - k + 1:i + 1] in dict:
res[i] = True
break
i += 1
return res[-1] |
diccionario= {91: 95}
a=91
if a==91:
a=diccionario.get(91)
print(a) | diccionario = {91: 95}
a = 91
if a == 91:
a = diccionario.get(91)
print(a) |
arquivo = open('linguagens.txt', 'r')
num = int(input("Numero de linguagens: "))
count=0
for linha in arquivo:
if count<num:
print(linha.rstrip('\n'))
count += 1
else:
break
arquivo.close() | arquivo = open('linguagens.txt', 'r')
num = int(input('Numero de linguagens: '))
count = 0
for linha in arquivo:
if count < num:
print(linha.rstrip('\n'))
count += 1
else:
break
arquivo.close() |
#!/usr/bin/env python3
# coding:utf-8
class Solution:
def StrToInt(self, s):
if s == '':
return 0
string = s.strip()
num = 0
start = 0
symbol = 1
if string[0] == '+':
start += 1
elif string[0] == '-':
start += 1
symbol = -1
for i in range(start, len(string)):
if '0' <= string[i] <= '9':
num = num * 10 + ord(string[i]) - 48
else:
return 0
return num * symbol
if __name__ == "__main__":
string = " -1234 "
s = Solution()
ans = s.StrToInt(string)
print(ans)
| class Solution:
def str_to_int(self, s):
if s == '':
return 0
string = s.strip()
num = 0
start = 0
symbol = 1
if string[0] == '+':
start += 1
elif string[0] == '-':
start += 1
symbol = -1
for i in range(start, len(string)):
if '0' <= string[i] <= '9':
num = num * 10 + ord(string[i]) - 48
else:
return 0
return num * symbol
if __name__ == '__main__':
string = ' -1234 '
s = solution()
ans = s.StrToInt(string)
print(ans) |
def roman(num):
"""
Function to convert an integer to roman numeral.
:type num: int
:rtype: str
"""
if type(num) is not int:
raise TypeError("Invalid input.")
if num <= 0:
raise ValueError("Roman numbers can only be positive. " +
"Please enter a positive integer.")
# Define a list with tuples as integer and roman equivalent
value_symbol = [
(1000, 'M'), (900, 'CM'), (500, 'D'),
(400, 'CD'), (100, 'C'),
(90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'),
(9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
# Define the result as a blank string
result = ''
# Go from larger to smaller value
for value, symbol in value_symbol:
# Divide the number by the integer value.
count = num//value
# If the division is greater than zero.
if count > 0:
# Add that many symbol(s) with the result.
# Here '*' is not multiplication. 'M' * 3 = 'MMM'.
result += symbol * count
num %= value
# Return the result
return result
| def roman(num):
"""
Function to convert an integer to roman numeral.
:type num: int
:rtype: str
"""
if type(num) is not int:
raise type_error('Invalid input.')
if num <= 0:
raise value_error('Roman numbers can only be positive. ' + 'Please enter a positive integer.')
value_symbol = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
result = ''
for (value, symbol) in value_symbol:
count = num // value
if count > 0:
result += symbol * count
num %= value
return result |
fit2_lm = sm.ols(formula="y ~ age + np.power(age, 2) + np.power(age, 3)",data=diab).fit()
poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame()
poly_predictions.head()
| fit2_lm = sm.ols(formula='y ~ age + np.power(age, 2) + np.power(age, 3)', data=diab).fit()
poly_predictions = fit2_lm.get_prediction(predict_df).summary_frame()
poly_predictions.head() |
class Solution:
# def countAndSay(self, n):
# """
# :type n: int
# :rtype: str
# """
# s = '1'
# for _ in range(n - 1):
# s = ''.join(str(len(list(group))) + digit for digit, group in itertools.groupby(s))
# return s
def countAndSay(self, n):
res = '1'
for i in range(1, n):
res = self.helper(res)
return res
def helper(self, s):
if s == '':
return s
count = 1
say = s[0]
res = ''
for i in range(1, len(s)):
if say != s[i]:
res += str(count) + say
count = 1
say = s[i]
else:
count += 1
res += str(count) + say
return res | class Solution:
def count_and_say(self, n):
res = '1'
for i in range(1, n):
res = self.helper(res)
return res
def helper(self, s):
if s == '':
return s
count = 1
say = s[0]
res = ''
for i in range(1, len(s)):
if say != s[i]:
res += str(count) + say
count = 1
say = s[i]
else:
count += 1
res += str(count) + say
return res |
"""
Given a square matrix, write a function that rotates the matrix 90 degrees clockwise.
For example:
1 2 3 7 4 1
4 5 6 ---> 8 5 6
7 8 9 9 6 3
1 2 3 4 13 9 5 1
5 6 7 8 ---> 14 10 6 2
9 10 11 12 15 11 7 3
13 14 15 16 16 12 8 4
"""
def rotate_square_array(arr):
"""
Given a square array, rotates the array 90 degrees clockwise,
outputting to a new array.
"""
n = len(arr[0]) #not len(arr), because if arr = [[]], len(arr) would return 1, not 0
if n==0: return [[]] #Need special case because the below code would return [], not [[]]
return [[arr[n-j-1][i] for j in range(n)] for i in range(n)]
def rotate_square_array_inplace(arr):
"""
Given a square array, rotates the array 90 degrees clockwise in place.
"""
n = len(arr)
# for m in range(n//2):
# length = n-2*m
# for i in range(length):
# temp = arr[m][i]
# arr[m][i] = arr[m][]
top = 0
bottom = n-1
while top < bottom:
left = top
right = bottom
for i in range(right-left):
temp = arr[top][left+i]
arr[top][left+i] = arr[bottom-i][left]
arr[bottom-i][left] = arr[bottom][right-i]
arr[bottom][right-i] = arr[top+i][right]
arr[top+i][right] = temp
top += 1
bottom -=1
| """
Given a square matrix, write a function that rotates the matrix 90 degrees clockwise.
For example:
1 2 3 7 4 1
4 5 6 ---> 8 5 6
7 8 9 9 6 3
1 2 3 4 13 9 5 1
5 6 7 8 ---> 14 10 6 2
9 10 11 12 15 11 7 3
13 14 15 16 16 12 8 4
"""
def rotate_square_array(arr):
"""
Given a square array, rotates the array 90 degrees clockwise,
outputting to a new array.
"""
n = len(arr[0])
if n == 0:
return [[]]
return [[arr[n - j - 1][i] for j in range(n)] for i in range(n)]
def rotate_square_array_inplace(arr):
"""
Given a square array, rotates the array 90 degrees clockwise in place.
"""
n = len(arr)
top = 0
bottom = n - 1
while top < bottom:
left = top
right = bottom
for i in range(right - left):
temp = arr[top][left + i]
arr[top][left + i] = arr[bottom - i][left]
arr[bottom - i][left] = arr[bottom][right - i]
arr[bottom][right - i] = arr[top + i][right]
arr[top + i][right] = temp
top += 1
bottom -= 1 |
"""
The rotor class replicates the physical rotor in an Enigma.
"""
class Rotor:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
amountOfRotations = 0
def __init__(self, permutation, rotation):
"""
:param permutation: string, mono-alphabetic permutation of the alphabet in string form with corresponding
alphabet going from A-Z i.e. EKMFLGDQVZNTOWYHXUSPAIBRCJ
:param rotation: int, rotation that the rotor starts in
"""
self.permutation = permutation
self.rotation = rotation
def calc(self, c, reflected):
"""
:param c: char, character being encrypted or decrypted
:param reflected: boolean, Whether the character has been reflected
:return: char, post-encryption/decryption character
"""
if reflected:
return self.alphabet[(self.permutation.find(c) + self.rotation) % 26]
else:
return self.permutation[(self.alphabet.find(c) - self.rotation) % 26]
def rotate(self):
"""
:return: new current rotation
"""
self.rotation += 1
self.amountOfRotations += 1
return self.amountOfRotations % 26
| """
The rotor class replicates the physical rotor in an Enigma.
"""
class Rotor:
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
amount_of_rotations = 0
def __init__(self, permutation, rotation):
"""
:param permutation: string, mono-alphabetic permutation of the alphabet in string form with corresponding
alphabet going from A-Z i.e. EKMFLGDQVZNTOWYHXUSPAIBRCJ
:param rotation: int, rotation that the rotor starts in
"""
self.permutation = permutation
self.rotation = rotation
def calc(self, c, reflected):
"""
:param c: char, character being encrypted or decrypted
:param reflected: boolean, Whether the character has been reflected
:return: char, post-encryption/decryption character
"""
if reflected:
return self.alphabet[(self.permutation.find(c) + self.rotation) % 26]
else:
return self.permutation[(self.alphabet.find(c) - self.rotation) % 26]
def rotate(self):
"""
:return: new current rotation
"""
self.rotation += 1
self.amountOfRotations += 1
return self.amountOfRotations % 26 |
scores = [("Rodney Dangerfield", -1), ("Marlon Brando", 1), ("You", 100)] # list of tuples
for person in scores:
name = person[0]
score = person[1]
print("Hello {}. Your score is {}.".format(name, score))
origPrice = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
newPrice = (1 - discount/100)*origPrice
calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice)
print(calculation)
| scores = [('Rodney Dangerfield', -1), ('Marlon Brando', 1), ('You', 100)]
for person in scores:
name = person[0]
score = person[1]
print('Hello {}. Your score is {}.'.format(name, score))
orig_price = float(input('Enter the original price: $'))
discount = float(input('Enter discount percentage: '))
new_price = (1 - discount / 100) * origPrice
calculation = '${:.2f} discounted by {}% is ${:.2f}.'.format(origPrice, discount, newPrice)
print(calculation) |
def find_loop(root):
S = root
F = root
# set up first meeting
while True:
# if there is no loop, we will detect it
if S is None or F is None:
return None
# advance slow and fast pointers
S = S.next_node
F = F.next_node.next_node
if S is F:
break
# reset S to beginning
S = root
# set up second meeting
while True:
# advance pointers at same speed
S = S.next_node
F = F.next_node
if S is F:
break
return S | def find_loop(root):
s = root
f = root
while True:
if S is None or F is None:
return None
s = S.next_node
f = F.next_node.next_node
if S is F:
break
s = root
while True:
s = S.next_node
f = F.next_node
if S is F:
break
return S |
'''
Assume that two variables, varA and varB, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
"string involved" if either varA or varB are strings
"bigger" if varA is larger than varB
"equal" if varA is equal to varB
"smaller" if varA is smaller than varB
'''
if type(varA) == str or type(varB) == str:
print ("string involved")
elif varA > varB:
print("bigger")
elif varA == varB:
print("equal")
elif varA < varB:
print("smaller")
| """
Assume that two variables, varA and varB, are assigned values, either numbers or strings.
Write a piece of Python code that evaluates varA and varB, and then prints out one of the following messages:
"string involved" if either varA or varB are strings
"bigger" if varA is larger than varB
"equal" if varA is equal to varB
"smaller" if varA is smaller than varB
"""
if type(varA) == str or type(varB) == str:
print('string involved')
elif varA > varB:
print('bigger')
elif varA == varB:
print('equal')
elif varA < varB:
print('smaller') |
def __create_snap_entry(marker, entry_no, l):
# use parse_roll() to create search entry
node = []
x = []
for i in range(len(l)-1):
if len(l) == 2 and abs(l[i] - l[i+1]) == 2:
# if only two balls on the row
x += [[l[i], 1]]
elif abs(l[i] - l[i+1]) > 1:
# only those distance>1 can move
x += [[l[i], 1]]
x += [[l[i+1], -1]] # record two directions
for item in x:
node.append([marker, entry_no, item[0], item[1]])
return node
def __find_corner(t1, t2, incline=1):
if incline == 1:
start = 0
end = len(t1)
else:
start = len(t1)-1
end = -1
for i1 in range(start, end, incline):
if len(t1[i1]) > 0:
if incline == 1:
i2 = t1[i1][0]
else:
i2 = t1[i1][-1]
# print(t1[i1])
# print(t2[i2])
# print(incline)
if len(t1[i1]) == 1 and len(t2[i2]) == 1: # single ball at the corner
if incline == 1:
if i2 == 0:
# print('db1')
return False, None, None
flag = True # True only ball [1, i2)
for k in range(0, i2):
if len(t2[k]) > 0:
flag = False
break
else:
if i2 == len(t2) - 1:
# print('db2')
return False, None, None
flag = True
for k in range(i2+1, len(t2)):
if len(t2[k]) > 0:
flag = False
break
if flag:
# print('db3')
return False, None, None
if incline == 1:
return True, i1, t1[i1][0]
return True, i1, t1[i1][-1]
def snap(row, col): # row and col and dicts
# create [True/False (row/col), row_no., b1 (first ball to move), b2 (ball to be hit)]
# to reduce possible solutions, all solutions with unmovable corner balls should be eliminated
node = []
n1 = []
n2 = []
n_row = len(row.keys())
n_col = len(col.keys())
for i in row.keys():
n1 += __create_snap_entry(True, i, row[i])
for j in col.keys():
n2 += __create_snap_entry(False, j, col[j])
node = n1 + n2
# corner balls are those closest to the corners
# [0, 0], [0, n_col-1]
# [n_row-1, 0], [n_row-1, n_col-1]
corner = []
c1, b1x, b1y = __find_corner(row, col, 1)
c2, b2x, b2y = __find_corner(row, col, -1)
c3, b3y, b3x = __find_corner(col, row, 1)
c4, b4y, b4x = __find_corner(col, row, -1)
if c1 and c2 and c3 and c4:
l = [[b1x, b1y], [b2x, b2y], [b3y, b3x], [b4y, b4x]]
else:
return []
corner.append(l[0])
for i in l[1:]:
if i not in corner:
corner.append(i)
# print(corner)
for i in corner:
# find corner balls and put them in front
for j in range(len(node)):
if node[j][0]: # row content
if node[j][1] == i[0]: # same row as the corner
b = node.pop(j) # take it out
node.insert(0, b) # put it in the front
else:
if node[j][1] == i[1]: # same col as the corner
b = node.pop(j)
node.insert(0, b)
# print(node)
return node
def __transpose(table, length):
assert isinstance(table, dict)
result = dict()
for i in range(length):
result[i] = []
for k in table.keys():
if len(table[k]) != 0:
for j in table[k]:
result[j].append(k)
return result
if __name__ == '__main__':
row = dict()
for i in range(9):
row[i] = []
row[0] = [2]
row[1] = [5, 6]
row[2] = [1]
row[3] = [4, 5]
row[4] = [5]
row[5] = [3]
row[6] = [4]
col = __transpose(row, 7)
node = snap(row, col)
print(node)
| def __create_snap_entry(marker, entry_no, l):
node = []
x = []
for i in range(len(l) - 1):
if len(l) == 2 and abs(l[i] - l[i + 1]) == 2:
x += [[l[i], 1]]
elif abs(l[i] - l[i + 1]) > 1:
x += [[l[i], 1]]
x += [[l[i + 1], -1]]
for item in x:
node.append([marker, entry_no, item[0], item[1]])
return node
def __find_corner(t1, t2, incline=1):
if incline == 1:
start = 0
end = len(t1)
else:
start = len(t1) - 1
end = -1
for i1 in range(start, end, incline):
if len(t1[i1]) > 0:
if incline == 1:
i2 = t1[i1][0]
else:
i2 = t1[i1][-1]
if len(t1[i1]) == 1 and len(t2[i2]) == 1:
if incline == 1:
if i2 == 0:
return (False, None, None)
flag = True
for k in range(0, i2):
if len(t2[k]) > 0:
flag = False
break
else:
if i2 == len(t2) - 1:
return (False, None, None)
flag = True
for k in range(i2 + 1, len(t2)):
if len(t2[k]) > 0:
flag = False
break
if flag:
return (False, None, None)
if incline == 1:
return (True, i1, t1[i1][0])
return (True, i1, t1[i1][-1])
def snap(row, col):
node = []
n1 = []
n2 = []
n_row = len(row.keys())
n_col = len(col.keys())
for i in row.keys():
n1 += __create_snap_entry(True, i, row[i])
for j in col.keys():
n2 += __create_snap_entry(False, j, col[j])
node = n1 + n2
corner = []
(c1, b1x, b1y) = __find_corner(row, col, 1)
(c2, b2x, b2y) = __find_corner(row, col, -1)
(c3, b3y, b3x) = __find_corner(col, row, 1)
(c4, b4y, b4x) = __find_corner(col, row, -1)
if c1 and c2 and c3 and c4:
l = [[b1x, b1y], [b2x, b2y], [b3y, b3x], [b4y, b4x]]
else:
return []
corner.append(l[0])
for i in l[1:]:
if i not in corner:
corner.append(i)
for i in corner:
for j in range(len(node)):
if node[j][0]:
if node[j][1] == i[0]:
b = node.pop(j)
node.insert(0, b)
elif node[j][1] == i[1]:
b = node.pop(j)
node.insert(0, b)
return node
def __transpose(table, length):
assert isinstance(table, dict)
result = dict()
for i in range(length):
result[i] = []
for k in table.keys():
if len(table[k]) != 0:
for j in table[k]:
result[j].append(k)
return result
if __name__ == '__main__':
row = dict()
for i in range(9):
row[i] = []
row[0] = [2]
row[1] = [5, 6]
row[2] = [1]
row[3] = [4, 5]
row[4] = [5]
row[5] = [3]
row[6] = [4]
col = __transpose(row, 7)
node = snap(row, col)
print(node) |
""" Exceptions for EventBus. """
class EventDoesntExist(Exception):
""" Raised when trying remove an event that doesn't exist. """
pass
| """ Exceptions for EventBus. """
class Eventdoesntexist(Exception):
""" Raised when trying remove an event that doesn't exist. """
pass |
ls = list()
for _ in range(5):
ls.append(input())
res = list()
for i in range(len(ls)):
if 'FBI' in ls[i]:
res.append(str(i + 1))
if len(res) == 0:
print('HE GOT AWAY!')
else:
print(' '.join(res))
| ls = list()
for _ in range(5):
ls.append(input())
res = list()
for i in range(len(ls)):
if 'FBI' in ls[i]:
res.append(str(i + 1))
if len(res) == 0:
print('HE GOT AWAY!')
else:
print(' '.join(res)) |
matriz = [[], [], []]
for c in range(0, 3):
linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: ')))
for c in range(0, 3):
linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: ')))
for c in range(0, 3):
linha2 = matriz[2]. append(int(input(f'Digite um valor para [2, {c}]: ')))
for c in range(0, len(matriz[0])):
print(f'[ {matriz[0][c]} ]', end='')
print()
for c in range(0, len(matriz[1])):
print(f'[ {matriz[1][c]} ]', end='')
print()
for c in range(0, len(matriz[2])):
print(f'[ {matriz[2][c]} ]', end='')
| matriz = [[], [], []]
for c in range(0, 3):
linha0 = matriz[0].append(int(input(f'Digite um valor para [0, {c}]: ')))
for c in range(0, 3):
linha1 = matriz[1].append(int(input(f'Digite um valor para [1, {c}]: ')))
for c in range(0, 3):
linha2 = matriz[2].append(int(input(f'Digite um valor para [2, {c}]: ')))
for c in range(0, len(matriz[0])):
print(f'[ {matriz[0][c]} ]', end='')
print()
for c in range(0, len(matriz[1])):
print(f'[ {matriz[1][c]} ]', end='')
print()
for c in range(0, len(matriz[2])):
print(f'[ {matriz[2][c]} ]', end='') |
class NCSBase:
def train(self, X, y):
pass
def scores(self, X, y, cp):
pass
def score(self, x, labels):
pass
class NCSBaseRegressor:
def train(self, X, y):
pass
def coeffs(self, X, y, cp):
pass
def coeffs_n(self, x):
pass
| class Ncsbase:
def train(self, X, y):
pass
def scores(self, X, y, cp):
pass
def score(self, x, labels):
pass
class Ncsbaseregressor:
def train(self, X, y):
pass
def coeffs(self, X, y, cp):
pass
def coeffs_n(self, x):
pass |
# Conditionals
# Allows for decision making based on the values of our variables
def main():
x = 1000
y = 10
if (x < y):
st = " x is less than y"
elif (x == y):
st = " x is the same as y"
else:
st = "x is greater than y"
print(st)
print("\nAlternatively:...")
# python's more specific if/else
statement = "x is less than y" if (x<y) else "x is greater than or the same as"
print(statement)
if __name__ == "__main__":
main() | def main():
x = 1000
y = 10
if x < y:
st = ' x is less than y'
elif x == y:
st = ' x is the same as y'
else:
st = 'x is greater than y'
print(st)
print('\nAlternatively:...')
statement = 'x is less than y' if x < y else 'x is greater than or the same as'
print(statement)
if __name__ == '__main__':
main() |
#!/usr/bin/env python
#
# Class implementing a serial (console) user interface for the Manchester Baby (SSEM)
#
#------------------------------------------------------------------------------
#
# Class construction.
#
#------------------------------------------------------------------------------
class ConsoleUserInterface:
'''This object will implement a console user interface for the Manchester Baby (SSEM).'''
def __init__(self):
pass
#------------------------------------------------------------------------------
#
# Methods.
#
#------------------------------------------------------------------------------
def UpdateDisplayTube(self, storeLines):
'''Update the display tube with the current contents od the store lines.
@param: storeLines The store lines to be displayed.
'''
storeLines.Print()
print()
def UpdateProgress(self, numberOfLines):
'''Show the number of the lines executed so far.
@param: numberOfLines The number of lines that have been executed so far.
'''
print('Executed', numberOfLines, 'lines')
def DisplayError(self, errorMessage):
'''Show the error that has just occurred.
@param: errorMessage Message to be displayed.
'''
print('Error:', errorMessage)
#------------------------------------------------------------------------------
#
# Tests.
#
#------------------------------------------------------------------------------
if (__name__ == '__main__'):
ui = ConsoleUserInterface()
ui.UpdateProgress(1000)
ui.DisplayError('Syntax error')
print('ConsoleUserInterface tests completed successfully.')
| class Consoleuserinterface:
"""This object will implement a console user interface for the Manchester Baby (SSEM)."""
def __init__(self):
pass
def update_display_tube(self, storeLines):
"""Update the display tube with the current contents od the store lines.
@param: storeLines The store lines to be displayed.
"""
storeLines.Print()
print()
def update_progress(self, numberOfLines):
"""Show the number of the lines executed so far.
@param: numberOfLines The number of lines that have been executed so far.
"""
print('Executed', numberOfLines, 'lines')
def display_error(self, errorMessage):
"""Show the error that has just occurred.
@param: errorMessage Message to be displayed.
"""
print('Error:', errorMessage)
if __name__ == '__main__':
ui = console_user_interface()
ui.UpdateProgress(1000)
ui.DisplayError('Syntax error')
print('ConsoleUserInterface tests completed successfully.') |
a,b=map(str,input().split())
z=[]
x,c="",""
if a[0].islower():
x=x+a[0].upper()
if b[0].islower():
c=c+b[0].upper()
for i in range(1,len(a)):
if a[i].isupper() or a[i].islower():
x=x+a[i].lower()
for i in range(1,len(b)):
if b[i].isupper() or b[i].islower():
c=c+b[i].lower()
z.append(x)
z.append(c)
print(*z)
| (a, b) = map(str, input().split())
z = []
(x, c) = ('', '')
if a[0].islower():
x = x + a[0].upper()
if b[0].islower():
c = c + b[0].upper()
for i in range(1, len(a)):
if a[i].isupper() or a[i].islower():
x = x + a[i].lower()
for i in range(1, len(b)):
if b[i].isupper() or b[i].islower():
c = c + b[i].lower()
z.append(x)
z.append(c)
print(*z) |
#tutorials 3: Execute the below instructions in the interpreter
#execute the below command
"Hello World!"
print("Hello World!")
#execute using single quote
'Hello World!'
print('Hello World!')
#use \' to escape single quote
'can\'t'
print('can\'t')
#or use double quotes
"can't"
print("can't")
#more examples 1- using print function
print(
'" I won\'t," she said.'
)
#more examples 2
a = 'First Line. \n Second Line'
print(a)
#String concatenation
print("\n-->string concatenation example without using +")
print('Py''thon')
#String concatenation using +
print("\n-->string concatenation: concatenating two literals using +")
print("Hi "+"there!")
#String and variable concatenation using +
print("\n-->string concatenation: concatenating two literals using +")
a="Hello"
print( a +" there!")
#concatenation of two variables
print("\n-->string concatenation: concatenating two String variables using +")
b= " World!"
print(a+b)
# String indexing
print("\n-->string Indexing: Declare a String variable and access the elements using index")
word = "Python"
print("word-->"+word)
print("\n--> word[0]")
print(word[0])
print("\n--> word[5]")
print(word[5])
print("\n--> word[-6]")
print(word[-6])
print("\n -->if you type word[7]], you would get an error as shown below, as it is out of range")
print(" File \"<stdin>\", line 1")
print(" word[7]]")
print(" ^")
print("SyntaxError: invalid syntax")
print(" \")")
print("-->Notice the index for each of the letters in the word 'PYTHON' both forward and backward")
print("\n --> P Y T H O N")
print(" --> 0 1 2 3 4 5")
print(" --> -6 -5 -4 -3 -2 -1")
print("--> word[0:4]")
print(word[0:4])
print("--> word[:2]")
print(word[:2])
print("--> word[4:]")
print(word[4:])
print("--> word[-4]")
print(word[-4])
print("--> word[2]='N' --> String is immutable and hence cannot be changed.\nif we try to, we would get the below error.But we can always create a new String")
print("\nTraceback (most recent call last):")
print(" File \"<stdin>\", line 1, in <module>")
print("TypeError: 'str' object does not support item assignment")
print("\ncreation of a new String")
print("\nrun the command--> word[:2]+'new'")
print (word[:2]+'new')
print("\nprinting word")
print (word)
print("\nlength of word is")
print (len(word))
| """Hello World!"""
print('Hello World!')
'Hello World!'
print('Hello World!')
"can't"
print("can't")
"can't"
print("can't")
print('" I won\'t," she said.')
a = 'First Line. \n Second Line'
print(a)
print('\n-->string concatenation example without using +')
print('Python')
print('\n-->string concatenation: concatenating two literals using +')
print('Hi ' + 'there!')
print('\n-->string concatenation: concatenating two literals using +')
a = 'Hello'
print(a + ' there!')
print('\n-->string concatenation: concatenating two String variables using +')
b = ' World!'
print(a + b)
print('\n-->string Indexing: Declare a String variable and access the elements using index')
word = 'Python'
print('word-->' + word)
print('\n--> word[0]')
print(word[0])
print('\n--> word[5]')
print(word[5])
print('\n--> word[-6]')
print(word[-6])
print('\n -->if you type word[7]], you would get an error as shown below, as it is out of range')
print(' File "<stdin>", line 1')
print(' word[7]]')
print(' ^')
print('SyntaxError: invalid syntax')
print('\t ")')
print("-->Notice the index for each of the letters in the word 'PYTHON' both forward and backward")
print('\n --> P Y T H O N')
print(' --> 0 1 2 3 4 5')
print(' --> -6 -5 -4 -3 -2 -1')
print('--> word[0:4]')
print(word[0:4])
print('--> word[:2]')
print(word[:2])
print('--> word[4:]')
print(word[4:])
print('--> word[-4]')
print(word[-4])
print("--> word[2]='N' --> String is immutable and hence cannot be changed.\nif we try to, we would get the below error.But we can always create a new String")
print('\nTraceback (most recent call last):')
print(' File "<stdin>", line 1, in <module>')
print("TypeError: 'str' object does not support item assignment")
print('\ncreation of a new String')
print("\nrun the command--> word[:2]+'new'")
print(word[:2] + 'new')
print('\nprinting word')
print(word)
print('\nlength of word is')
print(len(word)) |
k = int(input("k: "))
array = [10,2,3,6,18]
fulfilled = False
i = 0
while i < len(array):
if k-array[i] in array:
fulfilled = True
i += 1
if fulfilled == True:
print("True")
else:
print("False") | k = int(input('k: '))
array = [10, 2, 3, 6, 18]
fulfilled = False
i = 0
while i < len(array):
if k - array[i] in array:
fulfilled = True
i += 1
if fulfilled == True:
print('True')
else:
print('False') |
# https://www.codewars.com/kata/570ac43a1618ef634000087f/train/python
'''
Instructions:
Nova polynomial add
This kata is from a series on polynomial handling. ( #1 #2 #3 #4 )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata add two polynomials:
poly_add ( [1, 2], [1] ) = [2, 2]
'''
def poly_add(p1, p2):
if p1 and p2:
if len(p1)>len(p2):
p2 = p2 + [0 for i in range(len(p1)-len(p2))]
return list(map(int.__add__, p1, p2))
else:
p1 = p1 + [0 for i in range(len(p2)-len(p1))]
return list(map(int.__add__, p1, p2))
elif not p1:
return p2
elif not p2:
return p1
| """
Instructions:
Nova polynomial add
This kata is from a series on polynomial handling. ( #1 #2 #3 #4 )
Consider a polynomial in a list where each element in the list element corresponds to a factor. The factor order is the position in the list. The first element is the zero order factor (the constant).
p = [a0, a1, a2, a3] signifies the polynomial a0 + a1x + a2x^2 + a3*x^3
In this kata add two polynomials:
poly_add ( [1, 2], [1] ) = [2, 2]
"""
def poly_add(p1, p2):
if p1 and p2:
if len(p1) > len(p2):
p2 = p2 + [0 for i in range(len(p1) - len(p2))]
return list(map(int.__add__, p1, p2))
else:
p1 = p1 + [0 for i in range(len(p2) - len(p1))]
return list(map(int.__add__, p1, p2))
elif not p1:
return p2
elif not p2:
return p1 |
# https://leetcode.com/problems/simplify-path/
class Solution:
def simplifyPath(self, path: str) -> str:
directories = path.split('/')
directory_stack = list()
for directory in directories:
if not directory == '' and not directory == '.':
if not directory == '..':
directory_stack.append(directory)
elif directory_stack:
directory_stack.pop()
return f"/{'/'.join(directory_stack)}"
| class Solution:
def simplify_path(self, path: str) -> str:
directories = path.split('/')
directory_stack = list()
for directory in directories:
if not directory == '' and (not directory == '.'):
if not directory == '..':
directory_stack.append(directory)
elif directory_stack:
directory_stack.pop()
return f"/{'/'.join(directory_stack)}" |
#-------------------------------------------------------------------------------
# Name: misc_python
# Purpose: misc python utilities
#
# Author: matthewl9
#
# Version: 1.0
#
# Contains: write to file, quicksort, import_list
#
# Created: 21/02/2018
# Copyright: (c) matthewl9 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def write(filepath, list1):
filepath = str(filepath)
file = open(filepath,"w")
for count in range (len(list1)):
file.write(list1[count])
if count < (len(list1)-1):
file.write("\n")
file.close
def partition(data):
pivot = data[0]
less, equal, greater = [], [], []
for elm in data:
if elm < pivot:
less.append(elm)
elif elm > pivot:
greater.append(elm)
else:
equal.append(elm)
return less, equal, greater
def quicksort(data):
if data:
less, equal, greater = partition(data)
return qsort2(less) + equal + qsort2(greater)
return data
def import_list(filepath):
filepath = str(filepath)
txt = open(filepath, "r")
shuff = txt.read().splitlines()
txt.close()
return(shuff)
| def write(filepath, list1):
filepath = str(filepath)
file = open(filepath, 'w')
for count in range(len(list1)):
file.write(list1[count])
if count < len(list1) - 1:
file.write('\n')
file.close
def partition(data):
pivot = data[0]
(less, equal, greater) = ([], [], [])
for elm in data:
if elm < pivot:
less.append(elm)
elif elm > pivot:
greater.append(elm)
else:
equal.append(elm)
return (less, equal, greater)
def quicksort(data):
if data:
(less, equal, greater) = partition(data)
return qsort2(less) + equal + qsort2(greater)
return data
def import_list(filepath):
filepath = str(filepath)
txt = open(filepath, 'r')
shuff = txt.read().splitlines()
txt.close()
return shuff |
NONE = 0
HALT = 1 << 0
FAULT = 1 << 1
BREAK = 1 << 2
def VMStateStr(_VMState):
if _VMState == NONE:
return "NONE"
state = []
if _VMState & HALT:
state.append("HALT")
if _VMState & FAULT:
state.append("FAULT")
if _VMState & BREAK:
state.append("BREAK")
return ", ".join(state)
| none = 0
halt = 1 << 0
fault = 1 << 1
break = 1 << 2
def vm_state_str(_VMState):
if _VMState == NONE:
return 'NONE'
state = []
if _VMState & HALT:
state.append('HALT')
if _VMState & FAULT:
state.append('FAULT')
if _VMState & BREAK:
state.append('BREAK')
return ', '.join(state) |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_iterative(array, item)
# return linear_search_recursive(array, item)
def linear_search_iterative(array, item):
# loop over all array values until item is found
for index, value in enumerate(array):
if item == value:
return index # found
return None # not found
def linear_search_recursive(array, item, index=0):
if array[index] == item: # O(1)
return index # O(1)
if array[index] == array[len(array) - 1]: # O(1)
return None # O(1)
return linear_search_recursive(array, item, index + 1) # O(1)
# once implemented, change linear_search to call linear_search_recursive
# to verify that your recursive implementation passes all tests
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
# implement binary_search_iterative and binary_search_recursive below, then
# change this to call your implementation to verify it passes all tests
# return binary_search_iterative(array, item)
return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
# implement binary search iteratively here
left = 0 # O(1)
right = len(array) - 1
while left <= right:
middle = (left + right) // 2
if array[middle] == item:
return middle
elif item > array[middle]:
left = middle + 1
elif item < array[middle]:
right = middle - 1
return None
# while the array at index is not item
# middle = (len(array)-1)//2
# check if middle is item
# if item is bigger than middle
# index = middle + 1
# else
# index = middle - 1
# once implemented, change binary_search to call binary_search_iterative
# to verify that your iterative implementation passes all tests
def binary_search_recursive(array, item, left=None, right=None):
if (left and right) is None:
left = 0
right = len(array) - 1
if left <= right:
middle = (left + right) // 2
if array[middle] == item:
return middle
elif item > array[middle]:
return binary_search_recursive(array, item, middle + 1, right)
elif item < array[middle]:
return binary_search_recursive(array, item, left, middle - 1)
return None
# once implemented, change binary_search to call binary_search_recursive
# to verify that your recursive implementation passes all tests
def main():
names = ['Alex', 'Brian', 'Julia', 'Kojin', 'Nabil', 'Nick', 'Winnie']
binary_search(names, 'Alex')
if __name__ == "__main__":
main() | def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
def linear_search_iterative(array, item):
for (index, value) in enumerate(array):
if item == value:
return index
return None
def linear_search_recursive(array, item, index=0):
if array[index] == item:
return index
if array[index] == array[len(array) - 1]:
return None
return linear_search_recursive(array, item, index + 1)
def binary_search(array, item):
"""return the index of item in sorted array or None if item is not found"""
return binary_search_recursive(array, item)
def binary_search_iterative(array, item):
left = 0
right = len(array) - 1
while left <= right:
middle = (left + right) // 2
if array[middle] == item:
return middle
elif item > array[middle]:
left = middle + 1
elif item < array[middle]:
right = middle - 1
return None
def binary_search_recursive(array, item, left=None, right=None):
if (left and right) is None:
left = 0
right = len(array) - 1
if left <= right:
middle = (left + right) // 2
if array[middle] == item:
return middle
elif item > array[middle]:
return binary_search_recursive(array, item, middle + 1, right)
elif item < array[middle]:
return binary_search_recursive(array, item, left, middle - 1)
return None
def main():
names = ['Alex', 'Brian', 'Julia', 'Kojin', 'Nabil', 'Nick', 'Winnie']
binary_search(names, 'Alex')
if __name__ == '__main__':
main() |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# {
# 'target_name': 'byte_reader',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'content_metadata_provider',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'content_metadata_provider_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'exif_constants',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'exif_parser',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'exif_parser_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'external_metadata_provider',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'external_metadata_provider_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'file_system_metadata_provider',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'file_system_metadata_provider_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'function_parallel',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'function_sequence',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'id3_parser',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'image_orientation',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'image_orientation_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'image_parsers',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_cache_item',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_cache_item_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_cache_set',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_cache_set_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_dispatcher',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_item',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_model',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_model_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'metadata_parser',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'mpeg_parser',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'multi_metadata_provider',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'multi_metadata_provider_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'new_metadata_provider',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'thumbnail_model',
# 'includes': ['../../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'thumbnail_model_unittest',
# 'includes': ['../../../../compile_js2.gypi'],
# },
],
}
| {'targets': []} |
#!/usr/bin/env python3
'''
lib/subl/constants.py
Constants for use in sublime apis, including plugin-specific settings.
'''
'''
Settings file name.
This name is passed to sublime when loading the settings.
''' # pylint: disable=pointless-string-statement
SUBLIME_SETTINGS_FILENAME = 'sublime-ycmd.sublime-settings'
'''
Settings keys.
The "watch" key is used to register an on-change event for the settings.
The "recognized" keys are used for debugging and logging/pretty-printing.
The "server" keys are used for configuring ycmd servers. Changes to these
settings should trigger a restart on all running ycmd servers.
The "task pool" keys are used for configuring the thread pool. Changes to these
settings should trigger a task pool restart.
'''
SUBLIME_SETTINGS_WATCH_KEY = 'syplugin'
SUBLIME_SETTINGS_RECOGNIZED_KEYS = [
'ycmd_root_directory',
'ycmd_default_settings_path',
'ycmd_python_binary_path',
'ycmd_language_whitelist',
'ycmd_language_blacklist',
'ycmd_language_filetype',
'ycmd_idle_suicide_seconds',
'ycmd_check_interval_seconds',
'ycmd_log_level',
'ycmd_log_file',
'ycmd_keep_logs',
'ycmd_force_semantic_completion',
'sublime_ycmd_log_level',
'sublime_ycmd_log_file',
'sublime_ycmd_background_threads',
]
SUBLIME_SETTINGS_YCMD_SERVER_KEYS = [
'ycmd_root_directory',
'ycmd_default_settings_path',
'ycmd_python_binary_path',
'ycmd_language_filetype',
'ycmd_idle_suicide_seconds',
'ycmd_check_interval_seconds',
'ycmd_log_level',
'ycmd_log_file',
'ycmd_keep_logs',
]
SUBLIME_SETTINGS_TASK_POOL_KEYS = [
'sublime_ycmd_background_threads',
]
'''
Sane defaults for settings. This will be part of `SUBLIME_SETTINGS_FILENAME`
already, so it's mainly here for reference.
The scope mapping is used to map syntax scopes to ycmd file types. They don't
line up exactly, so this scope mapping defines the required transformations.
For example, the syntax defines 'c++', but ycmd expects 'cpp'.
The language scope prefix is stripped off any detected scopes to get the syntax
base name (e.g. 'c++'). The scope mapping is applied after this step.
'''
SUBLIME_DEFAULT_LANGUAGE_FILETYPE_MAPPING = {
'c++': 'cpp',
'js': 'javascript',
}
SUBLIME_LANGUAGE_SCOPE_PREFIX = 'source.'
| """
lib/subl/constants.py
Constants for use in sublime apis, including plugin-specific settings.
"""
'\nSettings file name.\n\nThis name is passed to sublime when loading the settings.\n'
sublime_settings_filename = 'sublime-ycmd.sublime-settings'
'\nSettings keys.\n\nThe "watch" key is used to register an on-change event for the settings.\n\nThe "recognized" keys are used for debugging and logging/pretty-printing.\n\nThe "server" keys are used for configuring ycmd servers. Changes to these\nsettings should trigger a restart on all running ycmd servers.\n\nThe "task pool" keys are used for configuring the thread pool. Changes to these\nsettings should trigger a task pool restart.\n'
sublime_settings_watch_key = 'syplugin'
sublime_settings_recognized_keys = ['ycmd_root_directory', 'ycmd_default_settings_path', 'ycmd_python_binary_path', 'ycmd_language_whitelist', 'ycmd_language_blacklist', 'ycmd_language_filetype', 'ycmd_idle_suicide_seconds', 'ycmd_check_interval_seconds', 'ycmd_log_level', 'ycmd_log_file', 'ycmd_keep_logs', 'ycmd_force_semantic_completion', 'sublime_ycmd_log_level', 'sublime_ycmd_log_file', 'sublime_ycmd_background_threads']
sublime_settings_ycmd_server_keys = ['ycmd_root_directory', 'ycmd_default_settings_path', 'ycmd_python_binary_path', 'ycmd_language_filetype', 'ycmd_idle_suicide_seconds', 'ycmd_check_interval_seconds', 'ycmd_log_level', 'ycmd_log_file', 'ycmd_keep_logs']
sublime_settings_task_pool_keys = ['sublime_ycmd_background_threads']
"\nSane defaults for settings. This will be part of `SUBLIME_SETTINGS_FILENAME`\nalready, so it's mainly here for reference.\n\nThe scope mapping is used to map syntax scopes to ycmd file types. They don't\nline up exactly, so this scope mapping defines the required transformations.\nFor example, the syntax defines 'c++', but ycmd expects 'cpp'.\n\nThe language scope prefix is stripped off any detected scopes to get the syntax\nbase name (e.g. 'c++'). The scope mapping is applied after this step.\n"
sublime_default_language_filetype_mapping = {'c++': 'cpp', 'js': 'javascript'}
sublime_language_scope_prefix = 'source.' |
class Method:
BEGIN = 'calling.begin'
ANSWER = 'calling.answer'
END = 'calling.end'
CONNECT = 'calling.connect'
DISCONNECT = 'calling.disconnect'
PLAY = 'calling.play'
RECORD = 'calling.record'
RECEIVE_FAX = 'calling.receive_fax'
SEND_FAX = 'calling.send_fax'
SEND_DIGITS = 'calling.send_digits'
TAP = 'calling.tap'
DETECT = 'calling.detect'
PLAY_AND_COLLECT = 'calling.play_and_collect'
class Notification:
STATE = 'calling.call.state'
CONNECT = 'calling.call.connect'
RECORD = 'calling.call.record'
PLAY = 'calling.call.play'
COLLECT = 'calling.call.collect'
RECEIVE = 'calling.call.receive'
FAX = 'calling.call.fax'
DETECT = 'calling.call.detect'
TAP = 'calling.call.tap'
SEND_DIGITS = 'calling.call.send_digits'
class CallState:
ALL = ['created', 'ringing', 'answered', 'ending', 'ended']
NONE = 'none'
CREATED = 'created'
RINGING = 'ringing'
ANSWERED = 'answered'
ENDING = 'ending'
ENDED = 'ended'
class ConnectState:
DISCONNECTED = 'disconnected'
CONNECTING = 'connecting'
CONNECTED = 'connected'
FAILED = 'failed'
class DisconnectReason:
ERROR = 'error'
BUSY = 'busy'
class CallPlayState:
PLAYING = 'playing'
ERROR = 'error'
FINISHED = 'finished'
class PromptState:
ERROR = 'error'
NO_INPUT = 'no_input'
NO_MATCH = 'no_match'
DIGIT = 'digit'
SPEECH = 'speech'
class MediaType:
AUDIO = 'audio'
TTS = 'tts'
SILENCE = 'silence'
RINGTONE = 'ringtone'
class CallRecordState:
RECORDING = 'recording'
NO_INPUT = 'no_input'
FINISHED = 'finished'
class RecordType:
AUDIO = 'audio'
class CallFaxState:
PAGE = 'page'
ERROR = 'error'
FINISHED = 'finished'
class CallSendDigitsState:
FINISHED = 'finished'
class CallTapState:
TAPPING = 'tapping'
FINISHED = 'finished'
class TapType:
AUDIO = 'audio'
class DetectType:
FAX = 'fax'
MACHINE = 'machine'
DIGIT = 'digit'
class DetectState:
ERROR = 'error'
FINISHED = 'finished'
CED = 'CED'
CNG = 'CNG'
MACHINE = 'MACHINE'
HUMAN = 'HUMAN'
UNKNOWN = 'UNKNOWN'
READY = 'READY'
NOT_READY = 'NOT_READY'
| class Method:
begin = 'calling.begin'
answer = 'calling.answer'
end = 'calling.end'
connect = 'calling.connect'
disconnect = 'calling.disconnect'
play = 'calling.play'
record = 'calling.record'
receive_fax = 'calling.receive_fax'
send_fax = 'calling.send_fax'
send_digits = 'calling.send_digits'
tap = 'calling.tap'
detect = 'calling.detect'
play_and_collect = 'calling.play_and_collect'
class Notification:
state = 'calling.call.state'
connect = 'calling.call.connect'
record = 'calling.call.record'
play = 'calling.call.play'
collect = 'calling.call.collect'
receive = 'calling.call.receive'
fax = 'calling.call.fax'
detect = 'calling.call.detect'
tap = 'calling.call.tap'
send_digits = 'calling.call.send_digits'
class Callstate:
all = ['created', 'ringing', 'answered', 'ending', 'ended']
none = 'none'
created = 'created'
ringing = 'ringing'
answered = 'answered'
ending = 'ending'
ended = 'ended'
class Connectstate:
disconnected = 'disconnected'
connecting = 'connecting'
connected = 'connected'
failed = 'failed'
class Disconnectreason:
error = 'error'
busy = 'busy'
class Callplaystate:
playing = 'playing'
error = 'error'
finished = 'finished'
class Promptstate:
error = 'error'
no_input = 'no_input'
no_match = 'no_match'
digit = 'digit'
speech = 'speech'
class Mediatype:
audio = 'audio'
tts = 'tts'
silence = 'silence'
ringtone = 'ringtone'
class Callrecordstate:
recording = 'recording'
no_input = 'no_input'
finished = 'finished'
class Recordtype:
audio = 'audio'
class Callfaxstate:
page = 'page'
error = 'error'
finished = 'finished'
class Callsenddigitsstate:
finished = 'finished'
class Calltapstate:
tapping = 'tapping'
finished = 'finished'
class Taptype:
audio = 'audio'
class Detecttype:
fax = 'fax'
machine = 'machine'
digit = 'digit'
class Detectstate:
error = 'error'
finished = 'finished'
ced = 'CED'
cng = 'CNG'
machine = 'MACHINE'
human = 'HUMAN'
unknown = 'UNKNOWN'
ready = 'READY'
not_ready = 'NOT_READY' |
SCHEMA = """\
CREATE TABLE gene (
id INTEGER PRIMARY KEY,
name TEXT,
start_pos INTEGER,
end_pos INTEGER,
strand INTEGER,
translation TEXT,
scaffold TEXT,
organism TEXT
);\
"""
QUERY = """\
SELECT
id,
name,
start_pos,
end_pos,
strand,
scaffold,
organism
FROM
gene
WHERE
id IN ({})\
"""
FASTA = 'SELECT ">"||gene.id||"\n"||gene.translation||"\n" FROM gene'
INSERT = """\
INSERT INTO gene (
name,
start_pos,
end_pos,
strand,
translation,
scaffold,
organism
)
VALUES
(?, ?, ?, ?, ?, ?, ?)\
"""
| schema = 'CREATE TABLE gene (\n id INTEGER PRIMARY KEY,\n name TEXT,\n start_pos INTEGER,\n end_pos INTEGER,\n strand INTEGER,\n translation TEXT,\n scaffold TEXT,\n organism TEXT\n);'
query = 'SELECT\n id,\n name,\n start_pos,\n end_pos,\n strand,\n scaffold,\n organism\nFROM\n gene\nWHERE\n id IN ({})'
fasta = 'SELECT ">"||gene.id||"\n"||gene.translation||"\n" FROM gene'
insert = 'INSERT INTO gene (\n name,\n start_pos,\n end_pos,\n strand,\n translation,\n scaffold,\n organism\n)\nVALUES\n (?, ?, ?, ?, ?, ?, ?)' |
construction = ['Owner Authorization',
'Bidding & Contract Documents',
'Plans',
'Spedifications',
'Addenda',
'Submittals',
'Shop Drawings',
'Bonds',
'Insurance Certificates',
'Design Clarifications',
'Baseline Schedule',
'Schedule Revisions',
'Permits',
'Meeting Minutes',
'Payment Requests',
'Correspondence',
'Progress Reports',
'Progress Photographs',
'Change Orders',
'Substantial Completion',
'Punch List - Final Completion',
'Certificate of Occupancy',
'Maintenance & Operating Manuals',
'Guarantees - Warrantees',
'As-Built Documents',
'Reporting',
'Budget']
| construction = ['Owner Authorization', 'Bidding & Contract Documents', 'Plans', 'Spedifications', 'Addenda', 'Submittals', 'Shop Drawings', 'Bonds', 'Insurance Certificates', 'Design Clarifications', 'Baseline Schedule', 'Schedule Revisions', 'Permits', 'Meeting Minutes', 'Payment Requests', 'Correspondence', 'Progress Reports', 'Progress Photographs', 'Change Orders', 'Substantial Completion', 'Punch List - Final Completion', 'Certificate of Occupancy', 'Maintenance & Operating Manuals', 'Guarantees - Warrantees', 'As-Built Documents', 'Reporting', 'Budget'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.