"""
Stock Profit Calculator Web Application

Author: Alex Lim
"""

# Import Flask packages
from flask import Flask, render_template, request

# Define an instance of Flask object
app = Flask(__name__)

# Defines the routes and view function
@app.route('/submit', methods=['GET', 'POST'])
@app.route('/', methods=['GET', 'POST'])
def calculator():
    # If a POST request is coming through to send route --> process information
    if request.method == 'POST':

        """ Retrieve inputs given to form and store in variables """

        ticker = request.form['ticker']

        allotment = float(request.form['allotment'])
        final_share_price = float(request.form['final_price'])
        sell_commission = float(request.form['sell_commission'])
        initial_share_price = float(request.form['initial_share_price'])
        buy_commission = float(request.form['buy_commission'])
        capital_gain_tax = float(request.form['capital_gain_tax'])

        """ Do calculations on inputs """

        # Proceeds
        proceeds = allotment * final_share_price

        # Cost
        initial_purchase_cost = allotment * initial_share_price
        profits = proceeds - initial_purchase_cost - buy_commission - sell_commission
        capital_tax = capital_gain_tax / 100.00
        tax_on_capital_gain = profits * capital_tax
        cost = initial_purchase_cost + sell_commission + buy_commission + tax_on_capital_gain

        # Net Profit
        net_profit = proceeds - cost

        # Return on Investment
        return_on_investment = round((net_profit / cost) * 100, 2)

        # Break Even Price
        cost_per_share_after_commission = initial_purchase_cost + buy_commission + sell_commission
        break_even_price = cost_per_share_after_commission / allotment

        """ Render HTML template (report.html) with passed arguments """

        return render_template('report.html', ticker=ticker, allotment=allotment, final_share_price=final_share_price,
                               sell_commission=sell_commission, initial_share_price=initial_share_price, cost=cost,
                               buy_commission=buy_commission, capital_gain_tax=capital_gain_tax, proceeds=proceeds,
                               initial_purchase_cost=initial_purchase_cost, profits=profits, net_profit=net_profit,
                               tax_on_capital_gain=tax_on_capital_gain, return_on_investment=return_on_investment,
                               break_even_price=break_even_price)

    # If not POST request, it is a GET request. Return render_template: 'calculator.html'
    return render_template('calculator.html')

if __name__ == "__main__":
    app.run()


# https://leetcode-cn.com/explore/interview/card/bytedance/246/dynamic-programming-or-greedy/1042/
#
# 买卖股票的最佳时机
# 给定一个数组，它的第 i 个元素是一支给定股票第 i 天的价格。
#
# 如果你最多只允许完成一笔交易（即买入和卖出一支股票），设计一个算法来计算你所能获取的最大利润。
#
# 注意你不能在买入股票前卖出股票。
#
# 示例 1:
#
# 输入: [7,1,5,3,6,4]
# 输出: 5
# 解释: 在第 2 天（股票价格 = 1）的时候买入，在第 5 天（股票价格 = 6）的时候卖出，最大利润 = 6-1 = 5 。
#      注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
# 示例 2:
#
# 输入: [7,6,4,3,1]
# 输出: 0
# 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        # max必然是“最高点 - 最低点”
        # 当出现比现有最低点还低的点的时候，有可能出现比现有的max更长的新的max，要重新求max
        # 如果不是上述情况，则只是现有的max不断变大而已
        if len(prices) <= 1:
            return 0

        max_profit = 0
        low = prices[0]
        high = prices[0]

        for p in prices:
            if p < low:
                low = p
                high = p
            elif p > high:
                high = p
                max_profit = max(max_profit, high - low)

        return max_profit

训练/动态规划/121.买卖股票的最佳时机.py

121.买卖股票的最佳时机.py


import torch
from torch.nn import Module, Linear, Sequential, Dropout, Upsample, Conv1d, LeakyReLU, Flatten
from utils import SequenceWise, LSTM, GRU

class Encoder(Module):
    def __init__(self, in_size, ts_size=100, out_size=20, batch_first=False, bias=True, use_gru=False):
        super(Encoder, self).__init__()
        self.batch_first = batch_first
        self.hidden_size = 100

        rnn_class = GRU if use_gru else LSTM
        self.rnn = rnn_class(input_size=in_size, hidden_size=self.hidden_size, batch_first=batch_first, bidirectional=True,
                        bias=bias, dropouti=0.0, dropoutw=0.2, dropouto=0.2)
        self.fc = Linear(2*self.hidden_size*ts_size, out_size, bias=bias)

    def forward(self, x):
        x, _ = self.rnn(x)
        if not self.batch_first:
            x = x.permute(1, 0, 2)
        x = torch.flatten(x, 1, -1)
        x = self.fc(x)
        return x

class Generator(Module):
    def __init__(self, in_size=20, bias=True, use_gru=False):
        super(Generator, self).__init__()
        rnn_class = GRU if use_gru else LSTM

        self.fc1 = Linear(in_size, 50, bias=bias)
        self.rnn1 = rnn_class(input_size=1, hidden_size=64, batch_first=True, bidirectional=True, bias=bias, dropouti=0.0, dropoutw=0.2, dropouto=0.2)
        self.up = Upsample(scale_factor=2, mode='nearest')
        self.rnn2 = rnn_class(input_size=2*64, hidden_size=64, batch_first=True, bidirectional=True, bias=bias, dropouti=0.1, dropoutw=0.2,dropouto=0.2)
        self.fc2 = SequenceWise(Linear(2*64, 1, bias=bias))

    def forward(self, x):
        x = self.fc1(x)
        x.unsqueeze_(-1)
        x, _ = self.rnn1(x)
        x = x.permute(0, 2, 1)
        x = self.up(x)
        x = x.permute(0, 2, 1)
        x, _ = self.rnn2(x)
        x = self.fc2(x)
        x = torch.tanh(x)
        return x

# Try spatial conv
class CriticX(Module):
    def __init__(self, in_size, bias=True):
        super(CriticX, self).__init__()
        self.net = Sequential(
            Conv1d(in_size, 64, 5, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.25),
            Conv1d(64, 64, 5, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.25),
            Conv1d(64, 64, 5, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.25),
            Conv1d(64, 64, 5, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.25),
            Flatten(),
            Linear(64*84, 1, bias=bias)
        )

    def forward(self, x):
        x = x.permute(0, 2, 1)
        x = self.net(x)
        return x

class CriticZ(Module):
    def __init__(self, in_size=20, bias=True):
        super(CriticZ, self).__init__()
        self.net = Sequential(
            Linear(in_size, 100, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.2),
            Linear(100, 100, bias=bias),
            LeakyReLU(0.2, True),
            Dropout(0.2),
            Linear(100, 1, bias=bias),
        )

    def forward(self, z):
        z = self.net(z)
        return z


#Day 2: 30 Days of python programming

first_name, last_name = 'Zachary', 'Ranes'  # str
country, city = 'USA', 'Alexandria'         # str
age = 27                                    # int
year = 2021                                 # int
is_married = False                          # bool
is_true = False                             # bool
is_light_on = True                          # bool

print(type(first_name))
print(type(age))
print(type(is_true))

print(len(first_name))
print(len(last_name))

num_one = 5
num_two = 4

variable_total = num_one + num_two
variable_diff = num_one - num_two
variable_division = num_one / num_two
variable_remainder = num_one % num_two
variable_exp = num_one ** num_two
variable_floor_division = num_one // num_two

radius = float(input('What is the radius of the circle? '))
area_of_circle = 3.14 * (radius ** 2)
circum_of_circle = 2 * 3.14 * radius
print('The area of the circle is ', area_of_circle, 'The circumference is ', circum_of_circle )


import gym

# env = gym.make('Pong-v0')
env = gym.make('Pong-ram-v0')

for i_episode in range(1):
    step_episode = 0
    obs = env.reset()
    while True:
        # env.render()
        action = env.action_space.sample()  # discrete 0~5
        obs_, reward, done, info = env.step(action)
        step_episode += 1
        print("Episode: {:2d} Step: {:4d} -- Action: {} Reward: {}".format(
            i_episode, step_episode, action, reward))
        if done:
            break

env.close()


import unittest, os, pandas, pathlib, subprocess

fpath = pathlib.Path(__file__).parent.absolute()

output = os.path.join(fpath, 'output')

class TestPredict(unittest.TestCase):
    def max_difference(self, A, B):
        self.assertTrue(A.shape == B.shape)
        self.assertTrue((A-B).abs().max().max() < 1e-8)

    def test_predict(self):
        data = os.path.join(fpath, 'Sample_Melanoma_GSE120575.gz')
        result_expected = pandas.read_csv(output + '.predict.gz', sep='\t', index_col=0)

        # run command line as usage 1
        cmd = ['Tres.py', '-m', 'predict', '-i', data, '-o', output]

        p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.communicate()

        result = pandas.read_csv(output, sep='\t', index_col=0)
        os.remove(output)

        # make sure the two usages get the same result
        self.max_difference(result, result_expected)

if __name__ == '__main__': unittest.main()


#!/usr/bin/env python3
#
# matrix_rain.py

import sys
import os
import time
import json
import random
import pygame
import pygame.freetype
import pytesseract
import numpy as np
import cv2
import webcolors
import symbiote.colortools as ct

color = ct.ColorConverter()
colors = color.get_color_names(format='rgba')
colors['neon_green'] = (57, 255, 20, 255)
colors['neon_yellow'] = (255, 255, 0, 255)
colors['neon_red'] = (255, 0, 51, 255)
colors['neon_blue'] = (77, 77, 255, 255)

# Add a new variable for toggling contour detection
contour_detection = False

color_cycle = False

# Matrix parameters
matrix = 0
num_streams = 10000
speed = .01
min_speed = 0.01
max_speed = 5.0
font_size = 12
default_font_color = 'white'
font_color = default_font_color
default_decay_color = 'green'
font_decay_color = default_decay_color
default_background_color = 'black'
background_color = default_background_color
fade_intensity = .1  # The higher this value, the faster the trails will fade
random_fade = False
new_stream = True
persistent_dot = False
font = 'Courier'

setting_message = None
setting_message_expiration = 0

ocr_enabled = False
static_overlay = False

# Initialize Pygame
pygame.init()
width, height = 1024, 768
# Create a resizable window
screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
clock = pygame.time.Clock()
font = pygame.freetype.SysFont('Courier', font_size)

# Frames per second
FPS = 30

# Add a new variable for toggling edge detection
edge_detection = False
edge_fps = 30 # number of frames to detect edges on 1 out of 30 for example
edge_decay = 60
edge_detection_min = 50
edge_detection_max = 150
edge_surface = pygame.Surface((width, height), pygame.SRCALPHA)

# Create streams
new_streams = []
current_resolution = 0

def save_settings():
    print(f"Settings saved.")
    settings = {
        'max_speed': max_speed,
        'font_size': font_size,
        'fade_intensity': fade_intensity,
        'num_streams': num_streams,
        'persistent_dot': persistent_dot,
        'font_color': font_color,
        'font_decay_color': font_decay_color,
        'width': width,
        'height': height,
    }
    home = os.environ['HOME']
    with open(f'{home}/.symbiote/vison_settings.json', 'w') as f:
        json.dump(settings, f)

def load_settings():
    global max_speed, font_size, fade_intensity, num_streams, persistent_dot, font_color, font_decay_color, width, height
    try:
        with open('settings.json', 'r') as f:
            settings = json.load(f)
            max_speed = settings.get('max_speed', max_speed)
            font_size = settings.get('font_size', font_size)
            fade_intensity = settings.get('fade_intensity', fade_intensity)
            num_streams = settings.get('num_streams', num_streams)
            persistent_dot = settings.get('persistent_dot', persistent_dot)
            font_color = settings.get('font_color', font_color)
            font_decay_color = settings.get('font_decay_color', font_decay_color)
            width = settings.get('width', width)
            height = settings.get('height', height)
    except FileNotFoundError:
        pass  # It's okay if the file doesn't exist

#load_settings()

def detect_edges(surface):
    # Convert the Pygame surface to an OpenCV image
    cv_image = pygame.surfarray.array3d(surface)
    cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGB2BGR)

    # Convert the image to grayscale
    gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)

    # Apply the Canny edge detection algorithm
    edges = cv2.Canny(gray, 50, 150)

    # Create a color mask for the edges
    color_mask = np.zeros((edges.shape[0], edges.shape[1], 3), dtype=np.uint8)
    color_mask[edges != 0] = [0, 0, 255]  # Red color

    # Convert the color mask to a Pygame surface
    edges_surface = pygame.surfarray.make_surface(color_mask)

    return edges_surface

def draw_edges(surface):
    # Convert the Pygame surface to an OpenCV image
    cv_image = pygame.surfarray.array3d(surface)
    cv_image = cv2.cvtColor(cv_image, cv2.COLOR_RGB2BGR)

    # Convert the image to grayscale
    gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)

    # Apply the Canny edge detection algorithm
    edges = cv2.Canny(gray, 50, 150)

    # Find the contours from the edges
    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Draw the contours on the original image
    #cv2.drawContours(cv_image, contours, -1, (0, 255, 0), 1)

    # Color the edges red
    edges_color = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
    edges_color[:,:,2] = edges  # Red channel

    # Convert the colored edges image to a Pygame surface
    edges_surface = pygame.surfarray.make_surface(edges_color)

    # Convert the OpenCV image back to a Pygame surface
    #cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
    #edge_surface = pygame.surfarray.make_surface(cv_image)

    return edges_surface

# Modify the create_streams function to use the num_streams variable
def create_streams(matrix):
    streams = []
    if matrix == 0 or matrix == 2:
        for _ in range(num_streams):
            speed = random.uniform(min_speed, max_speed)
            x = random.randint(0, width)  # Random value within the width of the screen
            y = random.randint(0, height)  # Random value within the height of the screen
            color = list(colors[font_color])  # Make a copy of the color
            streams.append((speed, x, y, color))
    elif matrix == 1:
        for _ in range(num_streams):
            speed = random.uniform(min_speed, max_speed)
            x = random.randint(0, width)
            y = random.randint(0, height)
            color = list(colors[font_color])
            streams.append((speed, x, y))

    return streams

def detect_and_draw_contours(surface):
    # Get the dimensions of the display
    info = pygame.display.Info()
    width = info.current_w
    height = info.current_h

    # Convert the Pygame surface to an OpenCV image
    array = pygame.surfarray.array3d(surface)
    array = np.rot90(array)
    array = np.flipud(array)
    cv_image = cv2.cvtColor(array, cv2.COLOR_RGB2BGR)

    # Convert the image to grayscale
    gray = cv2.cvtColor(cv_image, cv2.COLOR_BGR2GRAY)

    # Apply a threshold to highlight the contours
    _, threshold = cv2.threshold(gray, 100, 255, cv2.THRESH_BINARY)

    # Find the contours
    contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    # Create a new surface with the same size as the original
    contour_surface = pygame.Surface((width, height), pygame.SRCALPHA)

    # Draw the contours on the new surface
    for contour in contours:
        if len(contour) > 2:  # Only draw the contour if it has more than 2 points
            points = [tuple(point[0]) for point in contour]  # Convert arrays to tuples
            pygame.draw.polygon(contour_surface, (0, 255, 0, 128), points)

    return contour_surface

# Help menu
help_menu = False

def rgb_to_hex(rgb):
    return '#{:02x}{:02x}{:02x}'.format(rgb[0], rgb[1], rgb[2])

def hex_to_rgb(hex):
    h = hex.lstrip('#')
    return tuple(int(h[i:i+2], 16) for i in (0, 2, 4))

def display_help_menu():
    # Create a semi-transparent surface
    surface = pygame.Surface((width, height), pygame.SRCALPHA)
    surface.fill((0, 0, 0, 128))  # Semi-transparent black

    # Create a font object
    font = pygame.freetype.SysFont('Courier', 24)

    # Define the help text
    help_text = [
        "Help Menu:",
        "UP: Increase speed",
        "DOWN: Decrease speed",
        "+: Increase font size",
        "-: Decrease font size",
        "H: Show/hide this help menu",
        "I: Increase fade intensity",
        "D: Decrease fade intensity",
        "F: Toggle fullscreen",
        "K: Increase number of streams",
        "L: Decrease number of streams",
        "N: Cycle matrix vissual",
        "C: Toggle contour detection",
        "T: Toggle OCR detection",
        "R: Cycle through resolutions",
        "1: Toggle random fade intensity",
        "3: Toggle persistent dot",
        "4: Cycle font color",
        "5: Cycle decay color",
        "6: Cycle background color",
        "8: Toggle edge detection",
        "9: Toggle static overlay",
        "S: Save settings",
        "Q: Quit / Exit",
    ]

    # Render the help text
    for i, line in enumerate(help_text):
        font.render_to(surface, (10, 10 + 20*i), line, colors['neon_green'])

    return surface

def generate_tv_static(width, height, alpha=128):
    static = np.random.randint(0, 255, (width, height, 3), dtype=np.uint8)

    # Convert the noise image to a Pygame surface
    static_surface = pygame.surfarray.make_surface(static)

    # Create a semi-transparent surface with the same size
    alpha_surface = pygame.Surface(static_surface.get_size(), pygame.SRCALPHA)
    alpha_surface.fill((0, 0, 0, alpha))

    # Blend the static with the semi-transparent surface
    static_surface.blit(alpha_surface, (0, 0), special_flags=pygame.BLEND_RGBA_ADD)

    return static_surface

def cycle_color(current):
    # Get a list of color names
    color_names = list(colors.keys())

    # Find the index of the current color
    current_index = color_names.index(current)

    # Get the next color in the list, wrapping around to the start if necessary
    next_index = (current_index + 1) % len(color_names)

    # Return the name and RGB values of the next color
    return color_names[next_index], colors[color_names[next_index]]

# Main loop
running = True
setting_message = False
count = 0
recog = 0
frame_counter = 0
while running:
    frame_counter += 1

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.VIDEORESIZE:
            # Update the window size
            width, height = event.size
            # Recreate the streams to fit the new window size
            streams = create_streams(matrix)
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                max_speed = min(50, max_speed + 0.1)
                setting_message = f"Fall rate: {max_speed}"
            elif event.key == pygame.K_DOWN:
                max_speed = max(0.1, max_speed - 0.1)
                setting_message = f"Fall rate: {max_speed}"
            elif event.key == pygame.K_h:
                help_menu = not help_menu  # Toggle help menu
            elif event.key == pygame.K_EQUALS:
                font_size += 2
                font = pygame.freetype.SysFont('Courier', font_size)
                setting_message = f"Font size: {font_size}"
            elif event.key == pygame.K_MINUS:
                font_size = max(2, font_size - 2)
                font = pygame.freetype.SysFont('Courier', font_size)
                setting_message = f"Font size: {font_size}"
            elif event.key == pygame.K_n:
                new_stream = True
                if matrix >= 3:
                    matrix = 0
                else:
                    matrix += 1
                if matrix == 1:
                    num_streams = 100
                if matrix == 0 or matrix == 2:
                    num_streams = 5000
                setting_message = f"Matrix visual: {matrix}"
            elif event.key == pygame.K_i:
                fade_intensity = min(5, fade_intensity + 0.1)
                setting_message = f"Fade intensity: {fade_intensity}"
            elif event.key == pygame.K_d:
                fade_intensity = max(0.01, fade_intensity - 0.1)
                setting_message = f"Fade intensity: {fade_intensity}"
            elif event.key == pygame.K_k:
                num_streams = min(100000, num_streams + 250)  # Increase the number of streams
                setting_message = f"Number of streams: {num_streams}"
            elif event.key == pygame.K_l:
                num_streams = max(10, num_streams - 250)  # Decrease the number of streams
                setting_message = f"Number of streams: {num_streams}"
            elif event.key == pygame.K_3:
                persistent_dot = not persistent_dot
                setting_message = f"Persistent dot: {'On' if persistent_dot else 'Off'}"
            elif event.key == pygame.K_4:
                # cycle font_color
                font_color, font_rgb = cycle_color(font_color)
                setting_message = f"Font color: {font_color}"
            elif event.key == pygame.K_5:
                # cycle font_decay_color
                font_decay_color, font_decay_rgb = cycle_color(font_decay_color)
                setting_message = f"Font decay color: {font_decay_color}"
            elif event.key == pygame.K_f:
                # Toggle fullscreen
                if screen.get_flags() & pygame.FULLSCREEN:
                    pygame.display.set_mode((width, height))
                else:
                    pygame.display.set_mode((width, height), pygame.FULLSCREEN)
                setting_message = f"Fullscreen: toggle"
            elif event.key == pygame.K_6:
                # Cycle background color
                background_color, _ = cycle_color(background_color)
                setting_message = f"Background color: {background_color}"
            elif event.key == pygame.K_7:
                color_cycle = not color_cycle
                setting_message = f"Color cycle: {color_cycle}"
            elif event.key == pygame.K_r:
                # Get a list of supported resolutions
                resolutions = pygame.display.list_modes()
                # Cycle through resolutions
                current_resolution = (current_resolution - 1) % len(resolutions)
                width, height = resolutions[current_resolution]
                height = int(height * 0.90)
                screen = pygame.display.set_mode((width, height), pygame.RESIZABLE)
                setting_message = f"Resolution: {width}x{height}"
                new_stream = True
            elif event.key == pygame.K_s:
                save_settings()
            elif event.key == pygame.K_t:
                ocr_enabled = not ocr_enabled
                setting_message = f"OCR: {'On' if ocr_enabled else 'Off'}"
            elif event.key == pygame.K_c:
                contour_detection = not contour_detection
                setting_message = f"Contour detection: {'On' if contour_detection else 'Off'}"
            elif event.key == pygame.K_q:
                save_settings()
                sys.exit(0)
            elif event.key == pygame.K_8:
                edge_detection = not edge_detection
                setting_message = f"Edge detection: {'On' if edge_detection else 'Off'}"
            elif event.key == pygame.K_1:
                random_fade = not random_fade
                setting_message = f"Random fade: {random_fade} {fade_intensity}"
            elif event.key == pygame.K_0:
                font_color = default_font_color
                decay_color = default_decay_color
                background_color = default_background_color
                setting_message = f"Reset colors: {font_color} {decay_color} {background_color}"
            elif event.key == pygame.K_9:
                static_overlay = not static_overlay
                setting_message = f"Toggle static overlay: {static_overlay}"

    current_frame = screen.copy()

    if random_fade:
        fade_intensity = random.uniform(0.1, 5.0)

    if setting_message:
        print(setting_message)
        setting_message = False
    #    new_stream = True

    if new_stream:
        # Get the dimensions of the display
        info = pygame.display.Info()
        display_width = info.current_w
        display_height = info.current_h
        print(f"Screen resolution: {display_width} x {display_height}")

        streams = create_streams(matrix)
        new_stream = False

    if display_width != width or display_height != height:
        display_width = width
        display_height = height
        print(f"Screen resolution: {width} x {height}")

    # Clear screen
    screen.fill((0, 0, 0, 120))

    # Clear screen with a semi-transparent black rectangle
    fade_surface = pygame.Surface((width, height), pygame.SRCALPHA)
    fade_surface.fill((0, 0, 0, edge_decay))
    fade_surface.fill((0, 0, 0, fade_intensity))
    screen.blit(fade_surface, (0, 0))

    if color_cycle:
        # cycle font_color
        font_color, font_rgb = cycle_color(font_color)

    # Update and draw streams
    new_streams = []
    if matrix == 0:
        for speed, x, y, color in streams:
            # Update color
            color[3] = max(0, color[3] - fade_intensity)  # Reduce alpha component

            # Draw character
            char = chr(random.randint(0x20, 0x7E))  # ASCII characters
            column = 0
            font.render_to(screen, (x, int(y)), char, color)

            # Update position
            y += speed
            if y > height:
                #y = 0
                color = list(colors[font_color])  # Reset color
                y = random.randint(-height, 0)
            new_streams.append((speed, x, y, color))
        streams = new_streams
    elif matrix == 1:
        for speed, x, y in streams:
            # Draw characters
            for i in range(int(y), height, font_size):
                intensity = min(1, max(0, (i - y) / height))
                color = [int(c * intensity) for c in colors[font_color]]
                decay_color = [int(c * (1 - intensity)) for c in colors[font_decay_color]]
                final_color = [c1 + c2 for c1, c2 in zip(color, decay_color)]
                char = chr(random.randint(0x20, 0x7E))  # ASCII characters
                font.render_to(screen, (x, i), char, final_color)

            # Update stream
            y += speed
            if y > height:
                y = random.randint(-height, 0)
            new_streams.append((speed, x, int(y)))
        streams = new_streams
    elif matrix == 2:
        for speed, x, y, color in streams:
            # Update color
            color[3] = max(0, color[3] - fade_intensity) # Reduce alpha component

            # Draw character
            char = chr(random.randint(0x20, 0x7E)) # ASCII characters

            # Calculate intensity
            intensity = min(1, max(0, y / height))

            # Calculate decay color
            decay_color = [int(c * (1 - intensity)) for c in colors[font_decay_color]]

            # Calculate trail color
            trail_color = [int(c * intensity) for c in colors[font_decay_color]]

            # Calculate final color
            final_color = [min(255, c1 + c2) for c1, c2 in zip(color, decay_color)]

            # Render character with final color
            font.render_to(screen, (x, int(y)), char, final_color)

            # Render trailing characters with trail color
            for i in range(int(y), height, font_size):
                font.render_to(screen, (x, random.randint(0, height)), char, trail_color)

            # Update position
            y += speed
            if y > height:
                #y = 0
                color = list(colors[font_color]) # Reset color
                y = random.randint(-height, 0)
            new_streams.append((speed, x, y, color))
        streams = new_streams

    elif matrix == 3:
        # Generate a random noise image
        static = np.random.randint(0, 255, (width, height, 3), dtype=np.uint8)

        # Convert the noise image to a Pygame surface
        static_surface = pygame.surfarray.make_surface(static)

        # Blit the static surface onto the screen
        screen.blit(static_surface, (0, 0))

    if static_overlay:
        # Generate a semi-transparent static surface
        static_surface = generate_tv_static(width, height, alpha=128)

        # Blit the static surface onto the screen
        screen.blit(static_surface, (0, 0))

    # OCR function
    if ocr_enabled:
        recog += 1
        if recog >= 100:
            pygame.image.save(screen, '/tmp/temp.png')
            text = pytesseract.image_to_string('/tmp/temp.png')
            if text:
                print(f"Recognized text: {text}")
            recog = 0

    # Draw the persistent dot
    if persistent_dot:
        pygame.draw.circle(screen, (0, 255, 0), (width//2, height//2), 3)

    # Display help menu
    if help_menu:
        help_surface = display_help_menu()
        screen.blit(help_surface, (0, 0))

    contour_frames = 10
    if contour_detection:
        if frame_counter % contour_frames == 0:
            print(frame_counter, contour_frames)
            contour_surface = detect_and_draw_contours(screen)
            screen.blit(contour_surface, (0, 0))

    # Draw edges on the screen if edge detection is enabled
    if edge_detection:
        new_edge_surface = detect_edges(screen)
        edge_surface.blit(new_edge_surface, (0, 0))
        edge_surface.set_alpha(100)
        screen.blit(edge_surface, (0, 0))

    if frame_counter >= 1024:
        frame_counter = 0

    pygame.display.flip()
    clock.tick(FPS)

pygame.quit()


# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../src')
# for example PATH = /home/jose/programs/dmrgpy/src
#PATH = PATH_TO_DMRGPY_LIBRARY

import numpy as np
import matplotlib.pyplot as plt
from dmrgpy import fermionchain
from dmrgpy import spinchain
n = 4 # number of spin sites
import time
# first let us create a Hubabrd model

fc = fermionchain.Spinful_Fermionic_Chain(n) # create the object
#fc.maxm = 20
#fc.nsweeps = 40
U = 10.0

h0 = 0
for i in range(n-1):
    h0 = h0 + fc.Cdagup[i]*fc.Cup[i+1]
    h0 = h0 + fc.Cdagdn[i]*fc.Cdn[i+1]
h0 = h0 + h0.get_dagger()
for i in range(n):
   # h0 = h0 + U*fc.Nup[i]*fc.Ndn[i] -U*0.5*(fc.Nup[i]+fc.Ndn[i])
    h0 = h0 + U*(fc.Nup[i]-.5)*(fc.Ndn[i]-0.5)

fc.set_hamiltonian(h0)
print([fc.vev(o).real for o in fc.Sx])
print([fc.vev(o).real for o in fc.Sy])
print([fc.vev(o).real for o in fc.Sz])
#print(fc.get_excited(n=4,mode="ED"))

es = np.linspace(-1,6,600)

t0 = time.time()
ii = 1
jj = 1
name = (fc.Sx[ii],fc.Sx[jj])
(esh,ch) = fc.get_dynamical_correlator(name=name,mode="DMRG",es=es)
scale = 4./U
esh /= scale # scale by the estimated effective exchange
ch *= scale
t1 = time.time()
print("Time with fermions",t1-t0)
# now create the Heisenberg chain
sc = spinchain.Spin_Chain([2 for i in range(n)])
h1 = 0
for i in range(n-1):
    h1 = h1 + sc.Sx[i]*sc.Sx[i+1]
    h1 = h1 + sc.Sy[i]*sc.Sy[i+1]
    h1 = h1 + sc.Sz[i]*sc.Sz[i+1]
sc.set_hamiltonian(h1)
name = (sc.Sx[ii],sc.Sx[jj])
(ess,cs) = sc.get_dynamical_correlator(name=name,mode="DMRG",es=es)
t2 = time.time()
print("Time with spins",t2-t1)

import matplotlib.pyplot as plt

plt.scatter(esh,ch.real,c="red",label="Hubbard")
plt.plot(ess,cs.real,c="blue",label="Heisenberg")
#plt.plot(inds,mz2,c="green",label="Exact")
plt.legend()
plt.xlabel("Site")
plt.ylabel("Correlator")
plt.show()


# 面试题 01.08. 零矩阵
# 编写一种算法，若M × N矩阵中某个元素为0，则将其所在的行与列清零。

from typing import List

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        m,n = len(matrix),len(matrix[0])
        rset = set()
        cset = set()
        for i in range(m):
            for j in range(n):
                if matrix[i][j]==0:
                    rset.add(i)
                    cset.add(j)
        for i in range(m):
            for j in range(n):
                if i in rset or j in cset:
                    matrix[i][j]=0


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import cgi

import thisis

#PI=False

if thisis.PI:
    path='/home/pi/ProjectHata/web/'
else:
    path=''

html_body = """
<!DOCTYPE html>

<title>CSV Updated</title>
<meta http-equiv="refresh"content="0; url=hataSystem.py">

%s

back

"""

form = cgi.FieldStorage()
text = form.getvalue('text','')

txt = text.replace('\r', '')

with open(path+'PList.csv', 'wb') as a_file:
  a_file.write(txt.encode('utf-8'))

print("Content-type: text/html")
print(html_body % (text))


from log_utils import log, bitstr, matstr

# swap the front and back half of the bits based on the size
def sw(d, size, verbose=False, indent=0):
  dh = size >> 1
  s1 = ((((1 << dh) - 1) << dh) & d) >> dh
  s2 = ((1 << dh) - 1) & d
  result = (s2 << dh) | s1
  if verbose:
    log('SW - Swapping front and back half of byte:', indent)
    log(f'{bitstr(d, size)} -> {bitstr(result, size)}', indent + 1)
  return result

# perform a circular left shift on the give data by n steps
def lshift(d, n, size, verbose=False, indent=0):
  result = ((d << n) % (1 << size)) | (d >> (size - n))
  if verbose:
    log(f'LSHIFT - Circular Left Shifting by {n} bit(s):', indent)
    log(f'{bitstr(d, size)} -> {bitstr(result, size)}', indent+1)
  return result

# generalized function for rearranging, expanding, and reducing data's bits
def p_arrange(d, order, size, verbose=False, indent=0):
  s = f'{d:0>{size}b}'
  ns = ''
  for o in order:
    ns += s[o]
  result = int(ns, 2)
  if verbose:
    log(f'{bitstr(d, size)}', indent)
    log(f'-> {order}', indent)
    log(f'{bitstr(result, len(order))}', indent)
  return result

# initial permutation
def ip(d, verbose=False, indent=0):
  order = [1, 5, 2, 0, 3, 7, 4, 6]
  if verbose:
    log('IP - Performing Initial Permutation. Rearranging 8 bits:', indent)
  return p_arrange(d, order, 8, verbose, indent+1)

# inverse permutation
def ip2(d, verbose=False, indent=0):
  order = [3, 0, 2, 4, 6, 1, 7, 5]
  if verbose:
    log('IP\' - Performing INVERSE Inverse Permutation. Rearranging 8 bits:', indent)
  return p_arrange(d, order, 8, verbose, indent+1)

# rearranges 4 bits
def p4(d, verbose=False, indent=0):
  order = [1, 3, 2, 0]
  if verbose:
    log('P4 - Rearranging 4 bits:', indent)
  return p_arrange(d, order, 4, verbose, indent+1)

# reduces 10 bits into 8 bits
def p8(d, verbose=False, indent=0):
  order = [5, 2, 6, 3, 7, 4, 9, 8]
  if verbose:
    log('P8 - Downsizing and rearranging 10 bits to 8 bits:', indent)
  return p_arrange(d, order, 10, verbose, indent+1)

# rearranges 10 bits
def p10(d, verbose=False, indent=0):
  order = [2, 4, 1, 6, 3, 9, 0, 8, 7, 5]
  if verbose:
    log('P10 - Rearranging 10 bits:', indent)
  return p_arrange(d, order, 10, verbose, indent+1)

# expands 4 bits to 8 bits
def ep(d, verbose=False, indent=0):
  order = [3, 0, 1, 2, 1, 2, 3, 0]
  if verbose:
    log('E/P - Expanding 4 bits to 8 bits:', indent)
  return p_arrange(d, order, 4, verbose, indent+1)

# Generate two 8-bit keys based on initial 10-bit key
def gen_keys(k, verbose=False, indent=0):
  if verbose:
    log('Key Generation - Creating two 8-bit subkeys from one 10-bit key.', indent)
  p1, p2 = split(p10(k, verbose, indent+1), 10, verbose, indent+1)
  p1 = lshift(p1, 1, 5, verbose, indent+1)
  p2 = lshift(p2, 1, 5, verbose, indent+1)
  k1 = p8(join(p1, p2, 10, verbose, indent+1), verbose, indent+1)

  p1 = lshift(p1, 2, 5, verbose, indent+1)
  p2 = lshift(p2, 2, 5, verbose, indent+1)
  k2 = p8(join(p1, p2, 10, verbose, indent+1), verbose, indent+1)

  if verbose:
    log(f'Final Subkeys: {bitstr(k, 10)} -> {bitstr(k1, 8)} {bitstr(k2, 8)}', indent+1)
  return k1, k2

# separate front and back half of bits and return them as a two-ple
def split(d, size, verbose=False, indent=0):
  dh = size >> 1
  s1 = ((((1 << dh) - 1) << dh) & d) >> dh
  s2 = ((1 << dh) - 1) & d
  if verbose:
    log(f'Split - Splitting {size}-bits in half:', indent)
    log(f'{bitstr(s1, size>>1)} {bitstr(s2, size>>1)}', indent+1)
  return s1, s2

# join two bit clumps of equal size into a long bitstring
def join(d1, d2, size, verbose=False, indent=0):
  dh = size >> 1
  result = (d1 << dh) | d2
  if verbose:
    log(f'Join - Combining two {size>>1}-bit strings into one {size}-bit string:', indent)
    log(f'{bitstr(d1, size>>1)} {bitstr(d2, size>>1)} -> {bitstr(result, size)}', indent+1)
  return result

# Reduces 4 bits to 2 bits by matrix lookup
def s_lookup(d, matrix, verbose=False, indent=0):
  r = ((8 & d) >> 2) | (1 & d)         # p0 p3
  c = ((4 & d) >> 1) | ((2 & d) >> 1)  # p1 p2
  result = matrix[r][c]
  if verbose:
    log(f'Lookup using marix:', indent)
    log(f'{matstr(matrix)}', indent+1)
    log(f'row = {bitstr(d, 4)} -> {bitstr(r, 2)} = {r}', indent)
    log(f'      ^  ^', indent)
    log(f'col = {bitstr(d, 4)} -> {bitstr(c, 2)} = {c}', indent)
    log(f'       ^^', indent)
    log(f'matrix[{r}][{c}] = {result} = {bitstr(result, 2)}', indent)
  return result

def s0(d, verbose=False, indent=0):
  matrix = [[1, 0, 3, 2],
            [3, 2, 1, 0],
            [0, 2, 1, 3],
            [3, 1, 3, 2]]
  if verbose:
    log('S0 - Downselecting from 4 bits to 2 bits using a table:', indent)
  return s_lookup(d, matrix, verbose, indent+1)

def s1(d, verbose=False, indent=0):
  matrix = [[0, 1, 2, 3],
            [2, 0, 1, 3],
            [3, 0, 1, 0],
            [2, 1, 0, 3]]
  if verbose:
    log('S1 - Downselecting from 4 bits to 2 bits using a table:', indent)
  return s_lookup(d, matrix, verbose, indent+1)

# Main encryption operation
def f(d, sk, verbose=False, indent=0):
  if verbose:
    log('f(K) - Main encryption function', indent)
  d1, d2 = split(d, 8, verbose, indent+1)
  exp = ep(d2, verbose, indent+1)
  fk = exp ^ sk
  if verbose:
    log(f'XOR - EP {bitstr(exp, 8)} ^ subkey {bitstr(sk, 8)} -> {bitstr(fk, 8)}', indent+1)
  fk1, fk2 = split(fk, 8, verbose, indent+1)
  fk1 = s0(fk1, verbose, indent+1)
  fk2 = s1(fk2, verbose, indent+1)
  pf = p4(join(fk1, fk2, 4, verbose, indent+1), verbose, indent+1)
  d1r = d1 ^ pf
  if verbose:
    log(f'XOR - {bitstr(d1, 4)} ^ {bitstr(pf, 4)} = {bitstr(d1r, 4)}', indent+1)
  result = join(d1r, d2, 8, verbose, indent+1)
  if verbose:
    log(f'Final result of f(K): {bitstr(result, 8)}', indent+1)
  return result

# Perform SDES encryption on message m using key k
def encrypt(m, k, verbose=False):
  if verbose:
    log(f'Encrypting message {bitstr(m, 8)} with key {bitstr(k, 10)} using SDES encryption:', 0)
  k1, k2 = gen_keys(k, verbose, 1)
  result = ip2(f(sw(f(ip(m, verbose, 1), k1, verbose, 1), 8, verbose, 1), k2, verbose, 1), verbose, 1)
  if verbose:
    log(f'Encrypted Ciphertext: {bitstr(result, 8)}', 0)
  return result

# Perform SDES decryption on ciphertext c using key k
def decrypt(c, k, verbose=False):
  if verbose:
    log(f'Decrypting ciphertext {bitstr(c, 8)} with key {bitstr(k, 10)} using SDES encryption:', 0)
  k1, k2 = gen_keys(k, verbose, 1)
  result = ip2(f(sw(f(ip(c, verbose, 1), k2, verbose, 1), 8, verbose, 1), k1, verbose, 1), verbose, 1)
  if verbose:
    log(f'Decrypted Plaintext: {bitstr(result, 8)}', 0)
  return result

if __name__ == '__main__':
  k = 0b1010000010
  print(f"Testing Keygen: Given key [{k:0>8b}] produces the folowing subkeys:")
  k1, k2 = gen_keys(k)
  print(f'  {k1:0>8b}')
  print(f'  {k2:0>8b}')


__author__ = 'Vit'
from bs4 import BeautifulSoup

from data_format.url import URL
from common.util import _iter, quotes,psp

from interface.view_manager_interface import ViewManagerFromModelInterface

from model.site.parser import BaseSiteParser

class V24videoSite(BaseSiteParser):
    @staticmethod
    def can_accept_url(url: URL) -> bool:
        return url.contain('24videos.tv/')

    @staticmethod
    def create_start_button(view:ViewManagerFromModelInterface):
        menu_items=dict(Videos_Most_Recsent=URL('http://www.24videos.tv/latest-updates/'),
                    Videos_Most_Viewed=URL('http://www.24videos.tv/most-popular/'),
                    Videos_Top_Rated=URL('http://www.24videos.tv/top-rated/')
                    )

        view.add_start_button(picture_filename='model/site/resource/24video.png',
                              menu_items=menu_items,
                              url=URL("http://www.24videos.tv/latest-updates/", test_string='24Videos.TV'))

    def get_shrink_name(self):
        return 'V24'

    def parse_thumbs(self, soup: BeautifulSoup, url: URL):
        container=soup.find('div',{'class':'list-videos'})
        if container is not None:
            for thumbnail in _iter(container.find_all('div',{'class':'item'})):
                # psp(thumbnail.prettify())

                href = URL(thumbnail.a.attrs['href'], base_url=url)
                thumb_url = URL(thumbnail.img.attrs['data-original'], base_url=url)
                label=thumbnail.img.attrs.get('alt','')

                duration = thumbnail.find('div', {'class': 'duration'})
                dur_time = '' if duration is None else str(duration.contents[-1])

                self.add_thumb(thumb_url=thumb_url, href=href, popup=label,
                                labels=[{'text':dur_time, 'align':'top right'},
                                        {'text':label, 'align':'bottom center'}])
#
    def get_pagination_container(self, soup: BeautifulSoup) -> BeautifulSoup:
        return soup.find('div',{'class':'pagination'})

    # def parse_thumb_title(self, soup: BeautifulSoup, url: URL) -> str:
    #     return 'V24 '+ url.get().partition('24videos.tv/')[2].strip('/')

    def parse_video(self, soup: BeautifulSoup, url: URL):
        content = soup.find('div', {'class': 'player'})
        if content is not None:
            psp(content.prettify())
            script =content.find('script', text=lambda x: 'flashvars' in str(x))
            if script is not None:
                data = str(script.string).replace(' ', '').replace('\n', '').replace('\t', '')
                flashvars = quotes(data,'flashvars={', '};').split(',')
                fv = dict()
                for flashvar in flashvars:
                    # print(flashvar)
                    split = flashvar.partition(':')
                    fv[split[0]] = split[2].strip("'\"")
                files = dict()
                for f in fv:
                    if fv[f].startswith('http://') and fv[f].endswith('.mp4/'):
                        file = fv[f]
                        label = fv.get(f + '_text', f)
                        files[label] = file

                print("=======================didn't work?")

                for key in sorted(files.keys(), reverse=True):
                    self.add_video(key, URL(files[key],referer=url))

    # def parse_video_title(self, soup: BeautifulSoup, url: URL) -> str:
    #     return url.get().strip('/').rpartition('/')[2]

if __name__ == "__main__":
    pass


# Do not modify these lines
__winc_id__ = '7b9401ad7f544be2a23321292dd61cb6'
__human_name__ = 'arguments'

# Add your code after this line

#Part 1: Greet Template
def greet(fname, greeting = 'Hallo'):
    print(greeting, fname+'!')
greet('Frans', 'Yo')

#Part 2: Force
def force(mass, body = 'earth'):
    gravity = 9.8
    if body == 'sun':
        gravity = 274.0
    if body == 'jupiter':
        gravity = 24.9
    if body == 'neptune':
        gravity = 11.2
    if body == 'saturn':
        gravity = 10.4
    if body == 'uranus':
        gravity = 8.9
    if body == 'venus':
        gravity = 8.9
    if body == 'mars':
        gravity = 3.7
    if body == 'mercury':
        gravity = 3.7
    if body == 'moon':
        gravity = 1.6
    if body == 'pluto':
        gravity = 3.7
    print(mass*gravity)
force(2, '')

#Part 3: Gravity
def pull(m1, m2, d):
    print((6.674*10**-11)*((m1*m2)/d**2))
pull(800, 1500, 3)
pull(0.1, 5.972*(10**24), 6.371*(10**6))


class Node :
	# Constructor, Time O(1), Space O(1)
    def __init__(self, value, nextNode = None):
        self.data = value
        self.next = nextNode

# Find the kth node from the end, Time O(n), Space O(1)
def find_kth_from_end(head, k):
    fast = head
    slow = head
    for i in range(0, k):
        if fast == None: # special case k > n
            print("invalid input.")
            return None
        fast = fast.next
    while fast != None:
        fast = fast.next
        slow = slow.next
    return slow

# Find the middle node in the list, Time O(n), Space O(1)
def find_middle(head):
    if head == None:
        return
    slow = head
    fast = head
    while  fast.next != None and fast.next.next != None:
        slow = slow.next
        fast = fast.next.next
    return slow

# Print list, Time O(n), Space O(1)
def display(head):
    p = head
    while p != None:
        print(p.data, end=' ')
        p = p.next
    print()

# test
# insert list into a linked list
list = [4, 6, 2, -9, 0, 3]
head = None
for i in reversed(list):
    head = Node(i, head)
display(head)

key = 3
node = find_kth_from_end(head, key)
if node != None:
    print("find "+ str(key)+ "th from end: " + str(node.data))

node = find_middle(head)
print("find middle: "+ str(node.data))