content
stringlengths 7
1.05M
|
---|
# 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')
|
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
|
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)
|
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
|
__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__ = "[email protected]"
__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))
|
"""
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
|
# 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)
|
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
|
"""
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)
|
# 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))
|
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()
|
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, [], [])
|
"""
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
|
'''
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
|
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
|
'''
Author : MiKueen
Level : Medium
Problem Statement : Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
Note: The algorithm should run in linear time and in O(1) space.
Example 1:
Input: [3,2,3]
Output: [3]
Example 2:
Input: [1,1,1,3,3,2,2,2]
Output: [1,2]
'''
class Solution:
def majorityElement(self, nums: List[int]) -> List[int]:
if not nums:
return []
# Using Majority Voting Algorithm
# As there can be at most 2 majority elements which are more than n/3
num1 = num2 = cnt1 = cnt2 = 0
res = []
for i in nums:
if i == num1:
cnt1 += 1
elif i == num2:
cnt2 += 1
elif cnt1 == 0:
num1 = i
cnt1 = 1
elif cnt2 == 0:
num2 = i
cnt2 = 1
else:
cnt1 -= 1
cnt2 -= 1
cnt1 = cnt2 = 0
for i in nums:
if i == num1:
cnt1 += 1
elif i == num2:
cnt2 += 1
if cnt1 > len(nums) // 3:
res.append(num1)
if cnt2 > len(nums) // 3:
res.append(num2)
return res
|
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
|
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
|
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
'''
|
#!/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
|
# -*- 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.
# =============================================================================
|
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))
|
#!/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'
|
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()
|
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
|
"""
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))
|
"""Exemplo do dublê Fake."""
class Pedido:
def __init__(self, valor, frete, usuario):
self.valor = valor
self.frete = frete
self.usuario = usuario
@property
def resumo(self):
"""Informações gerais sobre o pedido."""
return f'''
Pedido por: {self.usuario.nome_completo}
Valor: {self.valor}
Frete: {self.frete}
'''
class FakePessoa:
@property
def nome_completo(self):
return 'Eduardo Mendes'
Pedido(100.00, 13.00, FakePessoa()).resumo
|
# -*- 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
|
# 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)
|
# 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=" ")
|
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",
]
|
# coding:UTF-8
# 2018-10-4 - 2018-10-6
# 决策树(CART)
# python 机器学习算法
# https://blog.csdn.net/gamer_gyt/article/details/51372309
class node(object):
def __init__(self, fea = -1, value = None, results = None, right = None, left = None):
self.fea = fea
self.value = value
self.results = results
self.right = right
self.left = left
def splitTree(data, fea, value):
"""
根据value划分数据集
fea: 划分数据集的索引
"""
sub_1, sub_2 = [], []
for i in data:
if i[fea] >= value:
sub_1.append(i)
else:
sub_2.append(i)
return (sub_1, sub_2)
def lableUniqueCount(data):
"""
统计数据集中不同标签的个数
"""
uniq = {}
for i in data:
label = i[-1]
if label not in uniq:
uniq[label] = 0
uniq[label] += 1
return uniq
def calcGiniIndex(data):
total_sample = len(data)
if len(data) == 0:
return 0
lable_counts = lableUniqueCount(data)
gini = 0
for label in lable_counts:
gini += lable_counts[label]**2
gini = 1 - float(gini) / (total_sample**2)
return gini
def buildTree(data):
if len(data) == 0:
return node()
# 1. 获得当前的基尼指数
current_gini = calcGiniIndex(data)
# 2. 划分
best_gini, best_criteria, best_set = 0.0, None, None
feature_num = len(data[0]) - 1
for fea in range(feature_num):
# 2.1 获得fea特征处所有的取值
feature_values = {}
for sample in data:
feature_values[sample[fea]] = 1
# 2.2 针对每一个可能的取值,尝试将数据集划分,并计算gini指数
for value in feature_values.keys():
# 根据数据中的value讲数据划分为左右子树
(set_1, set_2) = splitTree(data, fea, value)
new_gini = float(len(set_1) * calcGiniIndex(set_1) + len(set_2) * calcGiniIndex(set_2)) / len(data)
# 计算gini指数的增量
gain = current_gini - new_gini
# 判断新划分是否比旧划分好
if gain > best_gini and len(set_1) > 0 and len(set_2) > 0:
best_gini = gain
best_criteria = (fea, value)
best_set = (set_1, set_2)
# 3. 判断是否结束
if best_gini > 0:
right = buildTree(best_set[0])
left = buildTree(best_set[1])
return node(fea=best_criteria[0], value=best_criteria[1], right=right, left=left)
else:
return node(results=lableUniqueCount(data))
def predict(sample, tree):
if tree.results != None:
return tree.results
else:
val_sample = sample[tree.fea]
branch = None
if val_sample >= tree.value:
branch = tree.right
else:
branch = tree.left
return predict(sample, branch)
|
_DE_NUMBERS = {
'null': 0,
'ein': 1,
'eins': 1,
'eine': 1,
'einer': 1,
'einem': 1,
'einen': 1,
'eines': 1,
'zwei': 2,
'drei': 3,
'vier': 4,
'fünf': 5,
'sechs': 6,
'sieben': 7,
'acht': 8,
'neun': 9,
'zehn': 10,
'elf': 11,
'zwölf': 12,
'dreizehn': 13,
'vierzehn': 14,
'fünfzehn': 15,
'sechzehn': 16,
'siebzehn': 17,
'achtzehn': 18,
'neunzehn': 19,
'zwanzig': 20,
'einundzwanzig': 21,
'zweiundzwanzig': 22,
'dreiundzwanzig': 23,
'vierundzwanzig': 24,
'fünfundzwanzig': 25,
'sechsundzwanzig': 26,
'siebenundzwanzig': 27,
'achtundzwanzig': 28,
'neunundzwanzig': 29,
'dreißig': 30,
'einunddreißig': 31,
'vierzig': 40,
'fünfzig': 50,
'sechzig': 60,
'siebzig': 70,
'achtzig': 80,
'neunzig': 90,
'hundert': 100,
'zweihundert': 200,
'dreihundert': 300,
'vierhundert': 400,
'fünfhundert': 500,
'sechshundert': 600,
'siebenhundert': 700,
'achthundert': 800,
'neunhundert': 900,
'tausend': 1000,
'million': 1000000
}
_MONTHS_DE = ['januar', 'februar', 'märz', 'april', 'mai', 'juni',
'juli', 'august', 'september', 'oktober', 'november',
'dezember']
_NUM_STRING_DE = {
0: 'null',
1: 'ein', # ein Viertel etc., nicht eins Viertel
2: 'zwei',
3: 'drei',
4: 'vier',
5: 'fünf',
6: 'sechs',
7: 'sieben',
8: 'acht',
9: 'neun',
10: 'zehn',
11: 'elf',
12: 'zwölf',
13: 'dreizehn',
14: 'vierzehn',
15: 'fünfzehn',
16: 'sechzehn',
17: 'siebzehn',
18: 'achtzehn',
19: 'neunzehn',
20: 'zwanzig',
30: 'dreißig',
40: 'vierzig',
50: 'fünfzig',
60: 'sechzig',
70: 'siebzig',
80: 'achtzig',
90: 'neunzig',
100: 'hundert'
}
# German uses "long scale" https://en.wikipedia.org/wiki/Long_and_short_scales
# Currently, numbers are limited to 1000000000000000000000000,
# but _NUM_POWERS_OF_TEN can be extended to include additional number words
_NUM_POWERS_OF_TEN_DE = [
'', 'tausend', 'Million', 'Milliarde', 'Billion', 'Billiarde', 'Trillion',
'Trilliarde'
]
_FRACTION_STRING_DE = {
2: 'halb',
3: 'drittel',
4: 'viertel',
5: 'fünftel',
6: 'sechstel',
7: 'siebtel',
8: 'achtel',
9: 'neuntel',
10: 'zehntel',
11: 'elftel',
12: 'zwölftel',
13: 'dreizehntel',
14: 'vierzehntel',
15: 'fünfzehntel',
16: 'sechzehntel',
17: 'siebzehntel',
18: 'achtzehntel',
19: 'neunzehntel',
20: 'zwanzigstel'
}
# Numbers below 1 million are written in one word in German, yielding very
# long words
# In some circumstances it may better to seperate individual words
# Set _EXTRA_SPACE_DA=" " for separating numbers below 1 million (
# orthographically incorrect)
# Set _EXTRA_SPACE_DA="" for correct spelling, this is standard
# _EXTRA_SPACE_DA = " "
_EXTRA_SPACE_DE = ""
|
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")
|
# 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",
])
|
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]
|
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()
|
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# @File : ProcessError.py
# @Created : 2020/10/23 6:05 下午
# @Software : PyCharm
#
# @Author : Liu.Qi
# @Contact : [email protected]
#
# @Desc : 处理中的异常
# -------------------------------------------------------------------------------
class TokenError(Exception):
pass
class NotSupportServiceError(TokenError):
"""
不支持的service
"""
pass
class BadSecretKeyError(TokenError):
"""
错误的秘钥错误
"""
pass
class GrantTypeError(TokenError):
"""
客户端凭证错误
"""
pass
class ClientConfigNotFound(TokenError):
"""
客户端配置文件找不到
"""
pass
|
class Solution:
def myPow(self, x: float, n: int) -> float:
# 如果是c系语言,就要考虑输出值的类型,以防止溢出,python应该没有这个问题?
if x == 0 and n == 0:
return "undefined"
elif n ==0:
return 1
y = n if n>0 else -n
res = 1
# 当输入值为0.00001 2147483647时,出现了超时错误……以下方法不高效
'''
for i in range (y):
res *= x'''
# folgende Loesung kommt aus Anderem
# Idee ist: 3^11 = 3 * (3^2)^5 = 3 * 9^5 = 3*9* (9^2)^2 = 3*9* 81^2 =.....
while y > 0:
if y % 2 == 1:
res *= x
x *= x
y = (y - 1) / 2
else:
x *= x
y /= 2
return res if n>0 else 1.0/res
|
#!/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)
|
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
|
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()
|
''' 1)Fill in the blanks of this code to print out the numbers 1 through 7. '''
'''number = 1
while number <= 7:
print(number, end=" ")
number+=1 '''
''' 2) The show_letters function should print out each letter of a word on a
separate line. Fill in the blanks to make that happen. '''
'''def show_letters(word):
for i in word:
print(i)
show_letters("Hello")
# Should print one line per letter '''
''' 3) Complete the function digits(n) that returns how many digits the
number has. For example: 25 has 2 digits and 144 has 3 digits.
Tip: you can figure out the digits of a number by dividing it by
10 once per digit until there are no digits left. '''
'''def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n // 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1 '''
''' 4) This function prints out a multiplication table (where each number is the
result of multiplying the first number of its row by the number at the top
of its column). Fill in the blanks so that calling multiplication_table(1, 3)
will print out:
1 2 3
2 4 6
3 6 9 '''
''' def multiplication_table(start, stop):
for x in range(start,stop+1):
for y in range(start,stop+1):
print(str(x*y), end=" ")
print()
multiplication_table(1, 3)
# Should print the multiplication table shown above '''
'''5) The counter function counts down from start to stop when start is bigger
than stop, and counts up from start to stop otherwise. Fill in the blanks
to make this work correctly. '''
'''def counter(start, stop):
x = start
if x > stop:
return_string = "Counting down: "
while x >= stop:
return_string += str(x)
if x > stop:
return_string += ","
x -= 1
else:
return_string = "Counting up: "
while x <= stop:
return_string += str(x)
if x < stop:
return_string += ","
x += 1
return return_string
print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10"
print(counter(2, 1)) # Should be "Counting down: 2,1"
print(counter(5, 5)) # Should be "Counting up: 5" '''
''' 6) The even_numbers function returns a space-separated string of all positive
numbers that are divisible by 2, up to and including the maximum that's
passed into the function. For example, even_numbers(6) returns “2 4 6”.
Fill in the blank to make this work. '''
'''def even_numbers(maximum):
return_string = ""
for x in range(1,maximum + 1):
if x & 1 == 0:
return_string += str(x) + " "
return return_string.strip()
print(even_numbers(6)) # Should be 2 4 6
print(even_numbers(10)) # Should be 2 4 6 8 10
print(even_numbers(1)) # No numbers displayed
print(even_numbers(3)) # Should be 2
print(even_numbers(0)) # No numbers displayed '''
|
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
|
""" Desafio 73. Crie um tupla com a colocação do brasileirão. Depois mostre: a) os 5 primeiros colocados; b) os últimos 4 colocados
da tabela; c) lista com os times em ordem alfabética d) em que lugar está a Chapecoense. """
brasileirao = ("Flamengo", "Palmeiras", "São Paulo", "Grêmio", "Cruzeiro", "Atlético-MG", "Corinthians", "Santos", "Atlético-PR",
"Goiás", "Vasco", "CSA", "Avaí", "Botafogo", "Bahia", "Internacional", "Atlético-GO", "Chapecoense", "Fluminense", "Sport")
print(f"Os cinco primeiros colocados são {brasileirao[0:5]}.") # a
print(f"Os últimos quatro colocados são {brasileirao[-4:]}.") # b
print(f"Os times em ordem alfabética: {sorted(brasileirao)}.") #c
print("A Chapecoense está na {}a posição".format(brasileirao.index("Chapecoense") + 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]) #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
|
"""
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
|
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)
|
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
|
'''
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)
|
""" 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))
|
# 3. Crie uma função para retornar a quantidade de CPF cadastrados
def cadastro ():
cpfs = []
continuar = ''
while continuar != 'não' or 'Não' or 'n' or 'N':
print('Digite o seu nome: ')
nome = input()
print('Digite o seu cpf: ')
cpf = input()
cpfs.append(cpf)
print('Quer continuar?')
continuar = input()
return len(cpfs)
qtd = cadastro()
print(qtd)
|
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
|
# 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()
|
#!/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.')
|
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))
|
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
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: Alfons
@contact: [email protected]
@file: 4.Floyd.py
@time: 18-6-18 下午10:41
@version: v1.0
"""
# 最短路径----弗洛伊德算法
# 设 $D_{i,j,k}$为从$i$到$j$的只以 $(1..k)$集合中的节点为中间节点的最短路径的长度。
#
# - 若最短路径经过点k,则 $D_{i,j,k} = D_{i,k,k-1} + D_{k,j,k-1}$;
# - 若最短路径不经过点k,则 $D_{i,j,k}=D_{i,j,k-1}$。
#
# 因此, $D_{i,j,k}=min(D_{i,j,k-1},D_{i,k,k-1}+D_{k,j,k-1})$。
# 图
infinity = float("inf")
graph = dict()
graph["a"] = dict(a=0, b=2, c=6, d=4)
graph["b"] = dict(a=infinity, b=0, c=3, d=infinity)
graph["c"] = dict(a=7, b=infinity, c=0, d=1)
graph["d"] = dict(a=5, b=infinity, c=12, d=0)
def Floyd():
for k in graph.keys(): # 经过的第K个点
for i in graph.keys():
for j in graph.keys():
if graph[i][j] > graph[i][k] + graph[k][j]:
graph[i][j] = graph[i][k] + graph[k][j]
if __name__ == "__main__":
for i in graph.keys():
print(' ,'.join(str(i) for i in list(graph[i].values())))
print('\n\n')
Floyd()
for i in graph.keys():
print(' ,'.join(str(i) for i in list(graph[i].values())))
pass
|
# 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)}"
|
#-------------------------------------------------------------------------------
# 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)
|
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)
|
#!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()
|
# 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'],
# },
],
}
|
'''
Insira aqui as respectivas variáveis mencionadas no README.md
'''
TELEGRAM_TOKEN = 'TOKEN'
CHAT_ID = '-123456789'
|
# DESAFIO 022:
nome = input("Escreva seu nome completo:")
n_ok = nome.strip()
letras = len(n_ok) - n_ok.count(" ")
nomeSplitado = n_ok.split()
print(f"Nome todo em maiúsculo: ", n_ok.upper())
print(f"Nome todo em minúsculo: ", n_ok.lower())
print(f"Seu nome completo tem {letras} letras.")
print(f"Seu primeiro nome tem {len(nomeSplitado[0])} letras.")
|
pessoas = []
person = {}
masc = []
fem = []
som = 0
while True:
person.clear()
person['nome'] = str(input('Nome: '))
while True:
person['sexo'] = str(input('Sexo:[M/F] ')).upper()
if person['sexo'] in 'MF':
break
print('ERRO! Digite apenas M ou F!')
person['idade'] = int(input('Idade: '))
pessoas.append(person.copy())
while True:
continuar = str(input('Quer continuar?[S/N] ')).upper()
if continuar in 'SN':
break
print('ERRO! Digite apenas S ou N!')
if continuar == 'N':
break
print('-='*30)
print(f'Pessoas cadastradas: {len(pessoas)}')
for c in range(0,len(pessoas)):
som += pessoas[c]['idade']
media = som/len(pessoas)
print(f'A média de idade é: {media:.2f}')
print(f'As mulheres são: ',end=' ')
for c in range(0,len(pessoas)):
if pessoas[c]['sexo'] == 'F':
print(pessoas[c]['nome'],end='; ')
print('')
print('As pessoas mais velhas que a média são: ')
for c in range(0,len(pessoas)):
if media < pessoas[c]['idade']:
print(f'Nome: {pessoas[c]["nome"]}; Sexo: {pessoas[c]["sexo"]}; Idade: {pessoas[c]["idade"]}.')
|
#!/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.'
|
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
(?, ?, ?, ?, ?, ?, ?)\
"""
|
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']
|
"""
All that is open must be closed...
http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python
"""
def is_balanced(source, caps):
count = {}
stack = []
for c in source:
if c in caps:
i = caps.index(c)
if i % 2 == 0:
if caps[i] == caps[i + 1]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
else:
stack.append(c)
else:
if caps[i - 1] == caps[i]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
else:
if len(stack) == 0 or stack.pop() != caps[i - 1]:
return False
return (len(stack) == 0) and ((sum([v for k, v in count.items()])) % 2 == 0)
print(is_balanced("(Sensei says yes!)", "()") == True)
print(is_balanced("(Sensei says no!", "()") == False)
print(is_balanced("(Sensei [says] yes!)", "()[]") == True)
print(is_balanced("(Sensei [says) no!]", "()[]") == False)
print(is_balanced("Sensei says -yes-!", "--") == True)
print(is_balanced("Sensei -says no!", "--") == False)
|
#python program to display odd numbers
print("Odd numbers are as follows")
for i in range(1,100,2):
print(i)
print("End of the program")
|
#!/usr/bin/python3
def img_splitter(img):
img_lines = img.splitlines()
longest = 0
for ind, line in enumerate(img_lines):
if line == "":
img_lines.pop(ind)
if len(line) > longest:
longest = len(line)
for line in img_lines:
if len(line) < longest:
line.format(n=longest, c=" ")
return img_lines
def encrypt():
imgList = []
letterDICT = {'A': path + 'A.txt', 'B': path + 'B.txt', 'C': path + 'C.txt', 'D': path + 'D.txt',
'E': path + 'E.txt',
'F': path + 'F.txt', 'G': path + 'G.txt', 'H': path + 'H.txt', 'I': path + 'I.txt',
'J': path + 'J.txt',
'K': path + 'K.txt', 'L': path + 'L.txt', 'M': path + 'M.txt', 'N': path + 'N.txt',
'O': path + 'O.txt',
'P': path + 'P.txt', 'Q': path + 'Q.txt', 'R': path + 'R.txt', 'S': path + 'S.txt',
'T': path + 'T.txt',
'U': path + 'U.txt', 'V': path + 'V.txt', 'W': path + 'W.txt', 'X': path + 'X.txt',
'Y': path + 'Y.txt',
'Z': path + 'Z.txt'}
letterScan = list(engLetters)
for alphabet in letterScan:
if alphabet in letterDICT:
txtScan = letterDICT[alphabet]
with open(txtScan, 'r') as fr:
data = fr.read()
imgList.append(img_splitter(data))
numLetters = len(imgList)
zipped = zip(*imgList)
for line in zipped:
match numLetters:
case 1:
print(line[0])
case 2:
print(line[0], line[1])
case 3:
print(line[0], line[1], line[2])
case 4:
print(line[0], line[1], line[2], line[3])
case 5:
print(line[0], line[1], line[2], line[3], line[4])
case 6:
print(line[0], line[1], line[2], line[3], line[4], line[5])
case 7:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6])
case 8:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7])
case 9:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8])
case 10:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9])
case 11:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10])
case 12:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11])
case 13:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11], line[12])
case 14:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11], line[12], line[13])
print('\n')
path = 'ASCII arts/'
message = input("What is your name: ")
engLetters = message.upper()
encrypt()
vm = path + "vending_machine.txt"
with open(vm, 'r') as fr:
print(fr.read(), end='\n')
exchange = input("Would you like something to drink? Enter Y/N ")
if exchange.upper() == 'Y':
print("Sorry the machine is being hacked by the Aliens")
print("They want to know your choice by using their language")
decision = input("Would you like do use the decoder to purchase the drink [Y/N]")
if decision.upper() == 'N':
message = "bye"
engLetters = message.upper()
print(message)
encrypt()
elif decision.upper() == 'Y':
bev_choice = input("Enter you drink types [coke], [sprite], [fanta], [water], and [lemonade]")
bev_choice = bev_choice.upper()
engLetters = bev_choice
encrypt()
bev_dict = {'COKE': path + "coke.txt",
'SPRITE': path + 'sprite.txt',
'FANTA': path + 'fanta.txt',
'WATER': path + 'water.txt',
'LEMONADE': path + 'lemonade.txt'}
if bev_choice in bev_dict:
bevtxt = bev_dict[bev_choice]
print("Getting your item... please wait...")
with open(str(bevtxt), "r") as bf:
# indent to keep the building object open
# loop across the lines in the file
for svr in bf:
# print and end without a newline
print(svr, end="")
print()
print("Here you go! Enjoy it!")
print("Thanks for purchasing! ")
elif exchange.upper() == 'N':
print("Please Come back when you are thirsty")
|
class BinaryMatrix(object):
def __init__(self, mat):
self.mat = mat
def get(self, x: int, y: int) -> int:
return self.mat[x][y]
def dimensions(self):
n = len(self.mat)
m = len(self.mat[0])
return n, m
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
n, m = binaryMatrix.dimensions()
res = float('inf')
for i in range(n):
low = 0
high = m - 1
while low + 1 < high:
mid = low + (high - low) // 2
if binaryMatrix.get(i, mid) == 1:
high = mid
else:
low = mid
if binaryMatrix.get(i, low) == 1:
res = min(res, low)
elif binaryMatrix.get(i, high) == 1:
res = min(res, high)
return res
if __name__ == '__main__':
s = Solution()
mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
matrix = BinaryMatrix(mat)
res = s.leftMostColumnWithOne(matrix)
print(res)
|
USER_AGENTS = [
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/57.0.2987.110 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.79 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) "
"Gecko/20100101 "
"Firefox/55.0"
), # firefox
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.91 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/62.0.3202.89 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/63.0.3239.108 "
"Safari/537.36"
), # chrome
]
BaseURL = "https://azemikalaw.com/"
# BaseURL = "https://forum.mobilism.org/viewtopic.php?f=399&t=3558945"
WEB_DRIVER_PATH = "/usr/bin/firefox-dev"
|
# Block No 99997
# Block Bits 453281356
# Difficulty 14,484.16
_bits = input("* block's BITS ? : ");
hexBits = hex(int(_bits));
_hexHead = hexBits[:4];
_hexTail = '0x'+hexBits[4:];
print("- BITS in hexadecimal : ", hexBits);
print(" ", _hexHead);
print(" ", _hexTail);
# print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
max_difficulty = hex(0x00000000FFFF0000000000000000000000000000000000000000000000000000);
cur_difficulty = hex(int(_hexTail, 16)*2**(8*(int(_hexHead, 16)-3)));
print("- maximum difficulty : ", max_difficulty);
print("- this block's difficulty : ", cur_difficulty);
print("- this block's NONCE : ", (int(max_difficulty, 16)/int(cur_difficulty, 16)));
|
class BaseConfig:
SECRET_KEY = None
class DevelopmentConfig(BaseConfig):
FLASK_ENV="development"
class ProductionConfig(BaseConfig):
FLASK_ENV="production"
|
class Analyzer():
'''
Analyzer holds image data, hooks to pre-processed and intermediate data
and the methods to analyze and output visualizations
start: 2017-05-27, Nathan Ing
'''
def __init__(self):
pass
|
"""
The Elves think their skill will improve after making a few recipes.
However, that could take ages; you can speed this up considerably by identifying
the scores of the ten recipes after that.
What are the scores of the ten recipes immediately after the number of recipes
in your puzzle input?
"""
class Scoreboard:
def __init__(self, values):
self.board = values
self.elf_1 = 0
self.elf_2 = 1
def __str__(self):
return f"Current board: {self.board}\nElf 1: {self.board[self.elf_1]}\nElf 2: {self.board[self.elf_2]}"
def create_recipe(self):
sum_recipes = self.board[self.elf_1] + self.board[self.elf_2]
for i in str(sum_recipes):
self.board.append(int(i))
def get_new_recipe(self):
self.elf_1 += (1 + self.board[self.elf_1]) % len(self.board)
self.elf_1 = self.elf_1 % len(self.board)
self.elf_2 += (1 + self.board[self.elf_2]) % len(self.board)
self.elf_2 = self.elf_2 % len(self.board)
def move_forward(self, n=1):
for _ in range(n):
self.create_recipe()
self.get_new_recipe()
def score_check(self, n):
while len(self.board) < n + 10:
self.move_forward()
score = self.board[n : n + 10]
return "".join(str(i) for i in score)
def recipes_before_sequence(self, seq):
"""Move forward while the last len(seq) recipes are not seq"""
target = [int(i) for i in str(seq)]
seq_len = len(target)
while True:
if self.board[-seq_len:] == target:
return len(self.board) - seq_len
elif self.board[-seq_len - 1 : -1] == target:
return len(self.board) - seq_len - 1
self.move_forward()
N = 825_401
scoreboard = Scoreboard([3, 7]) # Part 1
print(f"The scores of ten recipes after {N} recipes is {scoreboard.score_check(N)}")
scoreboard_2 = Scoreboard([3, 7]) # Part 2
print(
f"{scoreboard_2.recipes_before_sequence(N)} recipes appear on the scoreboard to the left of {N}"
)
|
# bubble sort function
def bubble_sort(arr):
n = len(arr)
# Repeat loop N times
# equivalent to: for(i = 0; i < n-1; i++)
for i in range(0, n-1):
# Repeat internal loop for (N-i)th largest element
for j in range(0, n-i-1):
# if jth value is greater than (j+1) value
if arr[j] > arr[j+1]:
# swap the values at j and j+1 index
# Pythonic way to swap 2 variable values -> x, y = y, x
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
print('Before sorting:', arr)
# call bubble sort function on the array
bubble_sort(arr)
print('After sorting:', arr)
"""
Output:
Before sorting: [64, 34, 25, 12, 22, 11, 90]
After sorting: [11, 12, 22, 25, 34, 64, 90]
"""
|
arr = []
for i in range(5):
dum = list(map(int, input().split()))
arr.append(dum)
def sol(arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 1:
return abs(2-i) + abs(2-j)
print(sol(arr))
|
"""
*args
A special operator we can pass to functions.
Gathers remaining arguments as a tuple.
"""
def sum_all_nums(num1, num2, num3):
return num1 + num2 + num3
print(sum_all_nums(4, 6, 9)) # 19
print(sum_all_nums(4, 6)) # Error: no value for argument num3
def sum_with_args(*args):
total = 0
for num in args:
total += num
return total
print(sum_with_args(4, 6, 9)) # 19
print(sum_with_args(4, 6)) # 10
|
# coding: utf-8
# This example is the python implementation of nowait.1.f from OpenMP 4.5 examples
n = 100
m = 100
a = zeros(n, double)
b = zeros(n, double)
y = zeros(m, double)
z = zeros(m, double)
#$ omp parallel
#$ omp do schedule(runtime)
for i in range(0, m):
z[i] = i*1.0
#$ omp end do nowait
#$ omp do
for i in range(1, n):
b[i] = (a[i] + a[i-1]) / 2.0
#$ omp end do nowait
#$ omp do
for i in range(1, m):
y[i] = sqrt(z[i])
#$ omp end do nowait
#$ omp end parallel
|
#!/usr/bin/env python3v
## create file object in "r"ead mode
filename = input("Name of file: ")
with open(f"{filename}", "r") as configfile:
## readlines() creates a list by reading target
## file line by line
configlist = configfile.readlines()
## file was just auto closed (no more indenting)
## each item of the list now has the "\n" characters back
print(configlist)
num_lines = len(configlist)
print(f"Using the len() function, we see there are: {num_lines} line")
|
class Solution:
def preorderTraversal(self, root):
ret = []
s = [root]
while s:
cur = s.pop()
if not cur:
continue
ret.append(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
s.append(cur.left)
return ret
# def preorderTraversal(self, root):
# """
# :type root: TreeNode
# :rtype: List[int]
# root
# left
# right
# """
# ret = []
# def traverse(node):
# if not node:
# return
# ret.append(node.val)
# traverse(node.left)
# traverse(node.right)
# traverse(root)
# return ret
|
execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free()
|
"""
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane,
customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is
identify the questions for which anyone in your group answers "yes". Since your group is just you,
this doesn't take very long.
However, the person sitting next to you seems to be experiencing a language barrier and asks
if you can help. For each of the people in their group, you write down the questions for which
they answer "yes", one per line. For example:
abcx
abcy
abcz
In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y,
and z. (Duplicate answers to the same question don't count extra; each question counts at most once.)
Another group asks for your help, then another, and eventually you've collected answers from every
group on the plane (your puzzle input). Each group's answers are separated by a blank line, and
within each group, each person's answers are on a single line. For example:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
The first group contains one person who answered "yes" to 3 questions: a, b, and c.
The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c.
The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c.
The fourth group contains four people; combined, they answered "yes" to only 1 question, a.
The last group contains one person who answered "yes" to only 1 question, b.
In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11.
For each group, count the number of questions to which anyone answered "yes". What is the
sum of those counts?
Your puzzle answer was 6351.
--- Part Two ---
As you finish the last group's customs declaration, you notice that you misread one word in
the instructions:
You don't need to identify the questions to which anyone answered "yes"; you need to identify
the questions to which everyone answered "yes"!
Using the same example as above:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c.
In the second group, there is no question to which everyone answered "yes".
In the third group, everyone answered yes to only 1 question, a. Since some people did not
answer "yes" to b or c, they don't count.
In the fourth group, everyone answered yes to only 1 question, a.
In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b.
In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6.
For each group, count the number of questions to which everyone answered "yes". What is the sum
of those counts?
Your puzzle answer was 3143.
"""
def count_answers(text_input):
""" aoc day6 part 1:
Count the number of questions for which anyone answered 'yes' from the puzzle input """
total = 0
target = 'abcdefghijklmnopqrstuvwxyz'
for group in text_input:
for char in target:
if char in group:
total += 1
return total
def count_unanimous_answers(text_input):
""" aoc day6 part 2:
Count the number of questions for which at everyone answered 'yes' from the puzzle input """
count = 0
for group in text_input:
group = group.splitlines()
ans = set(group[0])
for person in group:
ans = ans & set(person)
count = count + len(ans)
return count
file = open("./data/6_input.txt").read()
answers = file.split("\n\n")
print(count_answers(answers))
print(count_unanimous_answers(answers))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.