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

"""K-mean clustering plot functions."""

import matplotlib.pyplot as plt
from random import random as rd

from k_means_types import *

COLORS = [
    "red",
    "yellow",
    "lime",
    "orange",
    "cyan",
    "purple",
    "green",
    "magenta",
    "maroon",
    "olive",
    "navy",
    "orangered",
    "saddlebrown",
    "teal",
    "bisque"
] + [
    (rd(), rd(), rd())
    for i in range(100)
]

CIRCLE_COLOR = "thistle"
CIRCLE_ALPHA = 0.3

DEFAULT_POINT_COLOR = "SlateGray"

CENTROID_MARKER = "*"
POINT_MARKER = "."

figure, axes = None, None

def plot_init(bottom_left: Point, top_right: Point):
    """Initializes the plot session, and set globals figure and axes."""
    global figure
    global axes

    plt.ion()
    figure, axes = plt.subplots(1, 1)
    axes.set_xlim(bottom_left[0], top_right[0])
    axes.set_ylim(bottom_left[1], top_right[1])
    axes.set_aspect("equal", adjustable="box")

def plot_finalize():
    """Finalizes the plot session, and reset globals figure and axes."""
    global figure
    global axes

    plot_refresh()
    plt.ioff()
    plt.show()

    figure, axes = None, None

def plot_point(point: Point, refresh: bool = False, **plot_options: Any):
    """Plots the specified point."""
    axes.plot([point[0]], [point[1]], linestyle='None', **plot_options)

    if refresh: plot_refresh()

def plot_points(points: List[Point], refresh: bool = False,
                **plot_options: Any):
    """Plots the specified list of points."""
    axes.plot([point[0] for point in points], [point[1] for point in points],
              linestyle='None', **plot_options)

    if refresh: plot_refresh()

def plot_centroids(centroids: Centroids, refresh: bool = False):
    """Plots the specified list of centroids."""
    for i, centroid in enumerate(centroids):
        plot_point(centroid, False, color=COLORS[i], marker=CENTROID_MARKER)

    if refresh: plot_refresh()

def plot_clusters(clusters: Clusters, refresh: bool = False):
    """Plots the specified list of cluster."""
    for i, cluster in enumerate(clusters):
        plot_points(cluster, False, color=COLORS[i], marker=POINT_MARKER)

    if refresh: plot_refresh()

def plot_circles(circles: List[Circle], refresh: bool = False):
    """Plots the specified list of circles if not None."""
    if circles is not None:
        for center, radius in circles:
            axes.add_artist(plt.Circle(
                center, radius, color=CIRCLE_COLOR, fill=False,
                alpha=CIRCLE_ALPHA))

    if refresh: plot_refresh()

def plot_refresh():
    """Refreshes the plotting area. Needed to see changes after a plot."""
    figure.canvas.draw()

def plot_clear():
    """Clears the plotting area."""
    plt.cla()

def one_plot(centroids: Centroids, clusters: Clusters, bottom_left: Point,
             top_right: Point, circles: MaybeCircles = None):
    """Plots the specified (centroids, clusters) with colors."""

    plot_init(bottom_left, top_right)

    plot_centroids(centroids)
    plot_clusters(clusters)
    plot_circles(circles)

    plot_finalize()

def step_by_step_plot(
        centroidss: List[Centroids], clusterss: List[Clusters], eps: float,
        bottom_left: Point, top_right: Point, circles: MaybeCircles = None):
    """Plots step by step the k-mean algorithm evolution."""

    plot_init(bottom_left, top_right)

    # show the window on screen
    plot_refresh()

    points = concat(clusterss[0])
    plot_points(points, True, color=DEFAULT_POINT_COLOR, marker=POINT_MARKER)

    input("Put centroids ?")
    plot_centroids(centroidss[0])
    plot_circles(circles, True)

    n = len(clusterss)
    for iteration in range(1, n + 1):
        input("Change clusters ? ({})".format(iteration))
        plot_clear()
        plot_centroids(centroidss[iteration - 1])
        plot_clusters(clusterss[iteration - 1])
        plot_circles(circles, True)

        input("Move centroids ? ({})".format(iteration))
        plot_clear()
        plot_centroids(centroidss[iteration])
        plot_clusters(clusterss[iteration - 1])
        plot_circles(circles, True)

    print("\n--> Done with final eps = {}".format(eps))
    plot_finalize()

def main():
    """Launcher."""
    pass

if __name__ == "__main__":
    main()


import sys
n= int(input())
s=set()

for _ in range(n):
    m=sys.stdin.readline().split()
    if len(m)==1:
        if m[0] == 'all':
            s= set([i for i in range(1,21)])
        elif m[0] == 'empty':
            s=set()
    else:
        m1,m2=list(m)
        if m1=='add':
            s.add(int(m2))
        elif m1=='check':
            if int(m2) in s:
                print(1)
            else:
                print(0)
        elif m1=='remove':
            s.discard(int(m2))
        elif m1=='toggle':
            if int(m2) in s:
                s.discard(int(m2))
            else:
                s.add(int(m2))


"""
Module containing all the method used in both the octtree and particle
    mesh simulations and all the global variables
"""

import multiprocessing
import copy
import pickle
import numpy as np
import astropy.units as u
import png
import pandas as pd
import matplotlib.pyplot as plt
import grav_field
from octtree import OctTree, barnes_hut_approximation
from particle_mesh import ParticleMesh

GOT_DATA = False
FORCE_LIST = []
TOTAL_PE = 0.0
PARTICLES = None
TIMESTEP = None
RET_QUEUE = multiprocessing.Queue()
PARTICLE_QUEUE = multiprocessing.Queue()
RADIUS = None
PARTICLE_COUNT = None
PARTICLE_TREE = None
LENGTH = None
PARAM_C = [0.6756, -0.1756, -0.1756, 0.6756]
PARAM_D = [1.3512, -1.7024, 1.3512]

def get_forces_raw(index):
    """
    Calculates the force on PARTICLES[index] using through brute force
        and appends it to FORCE_LIST
    """
    global FORCE_LIST
    global PARTICLES

    total_force = 0.0
    for j, particle in enumerate(PARTICLES):
        if j == index:
            continue
        total_force += grav_field.get_force(PARTICLES[index], particle)

    FORCE_LIST.append((index, total_force))

def get_forces_tree(index):
    """
    Calculates the force on PARTICLES[index] using the octree and appends
        it to FORCE_LIST
    """
    global PARTICLES
    global PARTICLE_TREE

    force = barnes_hut_approximation(PARTICLE_TREE, PARTICLES[index])
    FORCE_LIST.append((index, force))

def get_forces_mesh():
    """
    Calculates the force on PARTICLES[index] using the particle mesh
        method and appends it to FORCE_LIST
    """
    global PARTICLES
    global RADIUS

    mesh = ParticleMesh(grid_points=300, radius=RADIUS)

    mesh.insert_particles(PARTICLES)
    mesh.calculate_potential()
    mesh.calculate_force()

    forces = mesh.get_forces(PARTICLES)
    return forces

def get_energies(indices):
    """
    Calculates the potential energy of PARTICLES[indices[0]] in the field
        produced PARTICLES[indices[1]] and adds double that to TOTAL_PE
    """
    global TOTAL_PE

    potential_energy = grav_field.get_potential_energy(
        PARTICLES[indices[0]], PARTICLES[indices[1]]
    ).value
    TOTAL_PE += potential_energy * 2

def get_data(_):
    """
    Reads a copy of the PARTICLES list from PARTICLE_QUEUE and produces
        an OctTree to store as local copies
    Sets local GOT_DATA

    Called by child processes
    """
    global PARTICLE_TREE
    global PARTICLES
    global PARTICLE_QUEUE
    global GOT_DATA

    if not GOT_DATA:
        PARTICLES = PARTICLE_QUEUE.get()
        PARTICLE_TREE = OctTree(radius=RADIUS)
        PARTICLE_TREE.build_tree(PARTICLES)
        GOT_DATA = True

def send_data(pool):
    """
    Puts a deepcopy of the PARTICLES list into PARTICLE_QUEUE for each
        child process then calls get_data with each child process

    Called by main process
    """
    global PARTICLES
    global PARTICLE_QUEUE

    for _ in range(pool._processes):
        PARTICLE_QUEUE.put(copy.deepcopy(PARTICLES))

    while True:
        pool.map(get_data, range(pool._processes))
        if PARTICLE_QUEUE.empty():
            break

def send_results(_):
    """
    Sends a deepcopy of the local FORCE_LIST onto RET_QUEUE and clears
        the local versions of both GOT_DATA and FORCE_LIST

    Called by child processes
    """
    global FORCE_LIST
    global RET_QUEUE
    global GOT_DATA

    RET_QUEUE.put(copy.deepcopy(FORCE_LIST))
    FORCE_LIST.clear()
    GOT_DATA = False

def get_results(pool):
    """
    Calls send_results with each child process and reads the results
        from RET_QUEUE and returns all the results as a list of lists

    Called by main process
    """
    global RET_QUEUE

    force_list = []

    while len(force_list) < pool._processes:
        pool.map_async(send_results, range(pool._processes))
        for _ in range(pool._processes):
            results = RET_QUEUE.get()
            if len(results) > 0:
                force_list.append(results)

    return force_list

def send_energy_results(_):
    """
    Sends a copy of the local TOTAL_PE onto RET_QUEUE and clears the
        local versions of both GOT_DATA and TOTAL_PE

    Called by child processes
    """
    global TOTAL_PE
    global RET_QUEUE
    global GOT_DATA

    RET_QUEUE.put(TOTAL_PE)
    TOTAL_PE = 0.0
    GOT_DATA = False

def get_energy_results(pool):
    """
    Calls send_results with each child process and reads the results
        from RET_QUEUE and returns the sum of all the results

    Called by main process
    """
    global RET_QUEUE

    pe_list = []

    while len(pe_list) < pool._processes:
        pool.map_async(send_energy_results, range(pool._processes))
        for _ in range(pool._processes):
            result = RET_QUEUE.get()
            if result != 0.0:
                pe_list.append(result)

    return np.sum(pe_list)

def get_energy(pool):
    """
    Calculates the total potential energy and kinetic energy of the
        particles in the PARTICLES list then returns them in a list
        of [total energy, total potential, total kinetic]
    """
    global PARTICLES

    send_data(pool)

    energies = [i.kinetic_energy().value for i in PARTICLES]
    total_ke = np.sum(energies)

    indices = []
    for row in [[(i, j) for j in range(i + 1, len(PARTICLES))]
                for i in range(len(PARTICLES))]:
        for item in row:
            indices.append(item)

    pool.map(get_energies, indices)
    total_pe = get_energy_results(pool)
    total_energy = total_ke + total_pe

    return [total_energy, total_ke, total_pe]

def write_image(timestep_no, name):
    """
    Writes the locations of all the particles in the PARTICLES list to
        a 2000 x 2000 px png image with brightness representing distance
        from the closest edge of the region

    Requires a frames foldes in the current directory to save images in
    """

    img_dims = 2000
    img = [[0] * img_dims for i in range(img_dims)]
    for particle in PARTICLES:
        img_x = int(
            (particle.position[0].value / (RADIUS * 2) + 0.5) * img_dims
        )
        img_y = int(
            (particle.position[1].value / (RADIUS * 2) + 0.5) * img_dims
        )
        img_z = int(
            (particle.position[2].value / (RADIUS * 2) + 0.5) * 255
        )

        if 0 < img_x < img_dims and 0 < img_y < img_dims and 0 < img_z < 256:
            img[img_x][img_y] = img_z

    png.from_array(
        img, 'L'
    ).save(
        "frames/{}_p{}_t{}_l{}_pic{:05}.png"
        .format(
            name, PARTICLE_COUNT, TIMESTEP / (u.yr).to(u.s), LENGTH, timestep_no
        )
    )

def save_data(timestep_no, force_factor_list, mom_list,
              energy_list, timing_list, timestep_list):
    """
    Writes the required variables to a pickled file that can be read
        later to resume the simulation from this point
    """
    pickle.dump(PARTICLES,
                open("sim_data_particles.p", 'wb'))
    pickle.dump([timestep_no, TIMESTEP, RADIUS, PARTICLE_COUNT, LENGTH],
                open("sim_data.p", 'wb'))
    pickle.dump(force_factor_list,
                open("sim_data_force.p", 'wb'))
    pickle.dump(mom_list,
                open("sim_data_mom.p", 'wb'))
    pickle.dump(energy_list,
                open("sim_data_energy.p", 'wb'))
    pickle.dump(timing_list,
                open("sim_data_timing.p", 'wb'))
    pickle.dump(timestep_list,
                open("sim_data_timestep.p", 'wb'))

def read_data():
    """
    Reads the global variables from the pickeled files written to by
        save_data to resume the simulation from the last saved point
    """
    global PARTICLES
    global TIMESTEP
    global RADIUS
    global PARTICLE_COUNT
    global LENGTH

    PARTICLES = pickle.load(open("sim_data_particles.p", 'rb'))
    force_factor_list = pickle.load(open("sim_data_force.p", 'rb'))
    mom_list = pickle.load(open("sim_data_mom.p", 'rb'))
    energy_list = pickle.load(open("sim_data_energy.p", 'rb'))
    timing_list = pickle.load(open("sim_data_timing.p", 'rb'))
    timestep_list = pickle.load(open("sim_data_timestep.p", 'rb'))
    data = pickle.load(open("sim_data.p", 'rb'))
    TIMESTEP = data[1]
    RADIUS = data[2]
    PARTICLE_COUNT = data[3]
    LENGTH = data[4]
    return (data[0], force_factor_list, mom_list,
            energy_list, timing_list, timestep_list)

def write_data(args, force_factor_list, mom_list,
               energy_list, timing_list, timestep_list):
    """
    Writes the data recorded by the simulation to graphs and a .csv file
    """
    energy_interval = args.energy_interval
    timing_interval = args.time_interval

    name = None
    if args.simulation == 'g':
        name = "gal"
    elif args.simulation == 'u':
        name = "univ"

    if args.momentum:
        fig1 = plt.figure()
        ax1 = fig1.add_subplot(111)
        mom_list = np.array(mom_list).T
        ax1.plot(timestep_list, mom_list, label="Total Momentum")
        ax1.legend()
        ax1.set_ylabel("Momentum / Ns")
        ax1.set_xlabel("Time / yr")
        fig1.savefig("{}_sim_momentum_p{}_t{}_l{}.png".format
                     (name, PARTICLE_COUNT, TIMESTEP /
                      (u.yr).to(u.s), LENGTH
                     ), dpi=500)

    if not timing_interval is None:
        timing_list = np.array(timing_list).T

    if not energy_interval is None:
        fig2 = plt.figure()
        ax2 = fig2.add_subplot(111)

        energy_list = np.array(energy_list).T
        timecodes = [timestep_list[energy_interval * i]
                     for i in range(LENGTH // energy_interval + 1)]
        ax2.plot(timecodes, energy_list[0], label="Total Energy")
        ax2.plot(timecodes, energy_list[1], label="Kinetic Energy")
        ax2.plot(timecodes, energy_list[2], label="Potential Energy")
        ax2.legend()
        ax2.set_ylabel("Energy / J")
        ax2.set_xlabel("Time / yr")
        fig2.savefig("{}_sim_energy_p{}_t{}_l{}.png".format
                     (name, PARTICLE_COUNT, TIMESTEP /
                      (u.yr).to(u.s), LENGTH
                     ), dpi=500)

    if args.force:
        force_factor_list = np.array(force_factor_list).T
        fig3 = plt.figure()
        ax3 = fig3.add_subplot(111)
        ax3.errorbar(timestep_list, force_factor_list[0], force_factor_list[1])
        ax3.set_ylabel("Relative Force")
        ax3.set_xlabel("Time / yr")
        fig3.savefig("{}_sim_force_error_p{}_t{}_l{}.png".format
                     (name, PARTICLE_COUNT, TIMESTEP /
                      (u.yr).to(u.s), LENGTH
                     ), dpi=500)

    data_columns = []
    data = []
    data_width = 0
    data_length = 0
    data_index = 0

    # Initialise empty data array
    if args.momentum:
        data_width += 1
        data_length = len(mom_list)

    if args.force:
        data_width += 2
        data_length = len(force_factor_list[0])

    if not energy_interval is None:
        data_width += 3

    if not timing_interval is None:
        data_width += 2

    if data_length == 0:
        data_length = len(timestep_list)

    data = [[np.nan for _ in range(data_width)] for _ in range(data_length)]

    # Fill data array
    if args.momentum:
        for (i, mom) in enumerate(mom_list):
            data[i][data_index] = mom
        data_index += 1
        data_columns.append("Momentum / Ns")

    if args.force:
        for i in range(len(force_factor_list[0])):
            data[i][data_index] = force_factor_list[0][i]
            data[i][data_index + 1] = force_factor_list[1][i]
        data_index += 2
        data_columns.append("Mean_Force_Factor")
        data_columns.append("Force_Factor_Std_Dev")

    if not energy_interval is None:
        for i in range(len(energy_list[0])):
            data[energy_interval * i][data_index] = energy_list[0][i]
            data[energy_interval * i][data_index + 1] = energy_list[1][i]
            data[energy_interval * i][data_index + 2] = energy_list[2][i]
        data_index += 3
        data_columns.append("Total_Energy / J")
        data_columns.append("Total_Kinetic_Energy / J")
        data_columns.append("Total_Potential_Energy / J")

    if not timing_interval is None:
        for i in range(len(timing_list[0])):
            data[timing_interval * i][data_index] = timing_list[0][i]
            data[timing_interval * i][data_index + 1] = timing_list[1][i]
        data_index += 2
        if args.simulation == 'g':
            data_columns.append("Brute_Force_Timing / s")
        data_columns.append("Octtree_Timing / s")
        if args.simulation == 'u':
            data_columns.append("Mesh_Timing / s")

    if (args.momentum or args.force or not energy_interval is None
            or not timing_interval is None):
        dataframe = pd.DataFrame(data,
                                 index=timestep_list,
                                 columns=data_columns)
        dataframe.index.name = "Time / yr"
        dataframe.to_csv("{}_sim_data_p{}_t{}_l{}.csv"
                         .format(name, PARTICLE_COUNT,
                                 TIMESTEP / (u.yr).to(u.s), LENGTH))


# ░▄▀▀░▄▀▀ c. CS | FAF | FCIM | UTM | Fall 2023
# ░▀▄▄▒▄██ FAF-212 Cristian Brinza lab1

print('')
print('░▄▀▀░▄▀▀  c. CS | FAF | FCIM | UTM | Fall 2023')
print('░▀▄▄▒▄██  FAF-212 Cristian Brinza lab1 ')
print('')

# Define a function to display the menu options to the user.
def display_menu():
    """
    Displays the available menu options for the encryption and decryption process.
    """
    print("Select an option:")
    print("1. Encrypt using a single key")
    print("2. Encrypt using two keys")
    print("3. Decrypt using a single key")
    print("4. Decrypt using two keys")
    print("5. Exit the application")

# Define a function to perform the Caesar cipher encryption.
def caesar_cipher(text, sequence, shift):
    """
    Encrypts or decrypts the provided text using Caesar cipher based on the sequence and shift.

    Args:
    - text: The message to be encrypted or decrypted.
    - sequence: The sequence of characters used for encryption.
    - shift: The number by which each character in the text is shifted.

    Returns:
    - result: The encrypted or decrypted message.
    """
    result = ''

    for char in text:
        index = (sequence.index(char) + shift) % 26
        result += sequence[index]

    return result

# Define a function to obtain a valid integer key from the user.
def fetch_integer_key():
    """
    Prompts the user to provide a valid integer key between 1 and 25.

    Returns:
    - key: A valid integer key.
    """
    while True:
        try:
            key = int(input("Enter an integer key (1-25): "))
            if 1 <= key <= 25:
                return key
            else:
                print("Key should be between 1 and 25.")
        except ValueError:
            print("Please enter a valid integer.")

# Define a function to get a valid message from the user.
def fetch_message():
    """
    Prompts the user to input a valid message containing only alphabets.

    Returns:
    - message: A valid message.
    """
    while True:
        message = input("Enter your message: ").upper().replace(" ", "")
        if all(char.isalpha() for char in message):
            return message
        else:
            print("Message should only contain alphabets. Try again.")

# Define a function to get a valid text key from the user.
def fetch_text_key():
    """
    Prompts the user to provide a valid text key containing only alphabets.

    Returns:
    - text_key: A valid text key.
    """
    while True:
        text_key = input("Enter the text key: ").upper()
        if all(char.isalpha() for char in text_key):
            return text_key
        else:
            print("Text key should only contain alphabets. Try again.")

# Define a function to generate a new sequence using the text key.
def generate_sequence(text_key, original_alphabet):
    """
    Creates a new sequence for encryption using the provided text key.

    Args:
    - text_key: The text key provided by the user.
    - original_alphabet: The original sequence of characters.

    Returns:
    - new_sequence: The new sequence generated using the text key.
    """
    new_sequence = ''.join(sorted(set(text_key), key=text_key.index))
    for char in original_alphabet:
        if char not in new_sequence:
            new_sequence += char

    return new_sequence

if __name__ == "__main__":
    ORIGINAL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

    while True:
        display_menu()

        try:
            choice = int(input("Enter your choice (1-5): "))

            if choice == 5:
                print("Exiting the application. Goodbye!")
                break

            if choice == 1:  # Single key encryption
                key = fetch_integer_key()
                message = fetch_message()
                encrypted_message = caesar_cipher(message, ORIGINAL_ALPHABET, key)
                print(f"Encrypted Message: {encrypted_message}\n")

            elif choice == 2:  # Double key encryption
                int_key = fetch_integer_key()
                text_key = fetch_text_key()
                new_sequence = generate_sequence(text_key, ORIGINAL_ALPHABET)
                print(f"Generated Sequence: {new_sequence}")
                message = fetch_message()
                encrypted_message = caesar_cipher(message, new_sequence, int_key)
                print(f"Encrypted Message: {encrypted_message}\n")

            elif choice == 3:  # Single key decryption
                key = fetch_integer_key()
                message = fetch_message()
                decrypted_message = caesar_cipher(message, ORIGINAL_ALPHABET, -key)
                print(f"Decrypted Message: {decrypted_message}\n")

            elif choice == 4:  # Double key decryption
                int_key = fetch_integer_key()
                text_key = fetch_text_key()
                new_sequence = generate_sequence(text_key, ORIGINAL_ALPHABET)
                print(f"Generated Sequence: {new_sequence}")
                message = fetch_message()
                decrypted_message = caesar_cipher(message, new_sequence, -int_key)
                print(f"Decrypted Message: {decrypted_message}\n")

            else:
                print("Invalid choice. Please select a valid option (1-5).\n")

        except ValueError:
            print("Invalid input. Please enter a valid number (1-5).\n")


# 1. Write a python script to store multiple items in a single variable
#  ( Items are “Java”,“Python”,  “SQL”,  “C” ) using list

"""First Method"""
# lists = []
# item = int(input("Enter Numbers How Many Items Store : "))
# for i in range(item):
#     items = eval(input("Enter Items :"))
#     lists.append(items)

# print(lists)

"""second Method"""
lists = []
item = int(input("Enter Numbers How Many Items Store : "))
for i in range(item):
    items = str(input("Enter Items :"))
    lists.append(items)

print("Items are",tuple(lists))


unpro="123"

def f(pro,unpro):
    if len(unpro) == 0:
        print(pro)
        return
    ch = unpro[0]
    for i in range(len(pro)+1):
        first = pro[0:i]
        second = pro[i:]
        f(first+ch+second,unpro[1:])
print(f("",unpro))

# creating lists in body
unpro="abc"
def f(pro,unpro):
    if len(unpro) == 0:
        res = [pro]
        return res
    ch = unpro[0]
    newL=[]
    for i in range(len(pro)+1):
        first = pro[0:i]
        second = pro[i:]
        ans = f(first+ch+second,unpro[1:])
        for e in ans:
            newL.append(e)
    return sorted(newL)
print(f("",unpro))

# counting permutatioins :dumbass use factorial
unpro="abfndbabf"
def f(pro,unpro):
    cnt = 0
    if len(unpro) == 0:
        return 1
    ch = unpro[0]
    for i in range(len(pro)+1):
        first = pro[0:i]
        second = pro[i:]
        cnt +=f(first+ch+second,unpro[1:])
    return cnt
print(f("",unpro))


import os
from app import app
import urllib.request
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
import cv2
import time
import subprocess

CONFIDENCE_THRESHOLD = 0.2
NMS_THRESHOLD = 0.4
COLORS = [(0, 255, 255), (255, 255, 0), (0, 255, 0), (255, 0, 0)]

@app.route('/')
def upload_form():
    return render_template('upload.html')

@app.route('/', methods=['POST'])
def upload_video():
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    filename = secure_filename(file.filename)
    lst = [filename]
    name , extension = os.path.splitext(lst[0])
    p = os.path.join('data/video/afterDetection', filename)
    # print("exteeeeeeeeeeeeeeention",extension)
    # global id , part
    id = request.form['id']
    part = request.form['part']
    # k = list()
    # k.append(id)
    # k.append(part)
    t = os.path.join(app.config['UPLOAD_FOLDER'], 'partid.txt')
    with open(t,'w') as f:
        f.writelines('{}\n{}\n'.format(id,part))

    if file.filename == '':
        flash('No image selected for uploading')
        return redirect(request.url)
    elif extension in ['.png','.jpg','.jpeg']:

          subprocess.run(
              ['python', 'detect.py', '--weights', './checkpoints/yolov4-416', '--size', '416', '--model', 'yolov4',
               '--images', os.path.join(app.config['UPLOAD_FOLDER'], filename), '--output', p, '--crop', '--count'])

    else:
        filename = secure_filename(file.filename)
        # nwli l file name nzidha l id wel part w bead ne5ou menha heka lkol
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # print('upload_video filename: ' + filename)
        flash('Video successfully uploaded and displayed below')
        print("hneeeeeeeeeeeeee",filename)

        subprocess.run(['python', 'detect_video.py', '--weights', './checkpoints/yolov4-416', '--size', '416', '--model', 'yolov4','--video', os.path.join(app.config['UPLOAD_FOLDER'], filename), '--output', p, '--crop', '--count'])
        # subprocess.run(
        #     ['python', 'detect.py', '--weights', './checkpoints/yolov4-416', '--size', '416', '--model', 'yolov4',
        #      '--images', os.path.join(app.config['UPLOAD_FOLDER'], filename), '--output', p, '--crop', '--count'])
        print("awed affichiih belehi 5ali nraa :",filename)
        return render_template('upload.html', filename=filename)

@app.route('/display/<filename>')
def display_video(filename):
    # print('display_video filename: ' + filename)
    # hnee nml detection : nkolou hez l video men ghadi w hanou andek l path c deja #
    print("choud be heeeeeeeeree",filename)
    return redirect(url_for('data/video/afterDetection/', filename=filename), code=301)

    # return redirect(url_for('./data/video/afterDetection', filename=filename), code=301)

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


"""
Linear layer with fused activation with PyTorch autodiff support.
"""

from typing import Optional, Tuple

import torch
from torch import Tensor
from torch import nn
from triton import cdiv

from .act_kernels import act_func_backward_kernel
from .linear_kernels import linear_forward_kernel
from .types import Context, Device

class LinearAutoGrad(torch.autograd.Function):
    """
    Autodiff for linear layer.
    """
    @staticmethod
    def forward(
        ctx: Context,
        input: Tensor,
        weight: Tensor,
        bias: Optional[Tensor] = None,
        act_func: Optional[str] = None,
        ) -> Tensor:
        """
        Linearly transforms the input using weights, optionally adding bias
        and fusing an activation function.

        Args:
            input: Input to transform.
                Must be of shape [..., in_feat_dim].
            weight: Weights input is transformed by.
                Must be of shape [in_feat_dim, out_feat_dim].
            bias: Optional additive bias vector, with None for no bias.
                If provided, must be of shape [out_feat_dim].
            act_func: Name of activation function to apply, with None for identity.
                Options are 'sigmoid', 'tanh', 'relu', 'gelu', and 'silu'.

        Returns:
            Input linearly transformed, potentially with added biased and
            fused activation.
        """
        assert weight.ndim == 2, \
            f'Weights must be 2D, received shape {weight.shape}'
        assert bias is None or bias.ndim == 1, \
            f'Bias must be 1D, received shape {bias.shape}'

        assert input.shape[-1] == weight.shape[0], \
            f'Incompatible input ({input.shape}) and weights ({weight.shape}) shape'
        assert bias is None or weight.shape[1] == bias.shape[0], \
            f'Incompatible weights ({weight.shape}) and bias ({bias.shape}) shape'

        flattened_input = input.flatten(0, -2)
        batch_dim, in_feat_dim = flattened_input.shape
        _, out_feat_dim = weight.shape

        requires_grad = (input.requires_grad or
                         weight.requires_grad or
                         (bias is not None and bias.requires_grad))
        save_pre_act = requires_grad and act_func is not None

        output = torch.empty((batch_dim, out_feat_dim),
                             device=input.device,
                             dtype=input.dtype)
        pre_act = torch.empty_like(output) if save_pre_act else output

        # Launches a 1D grid, where each program outputs blocks of
        # BLOCK_SIZE_BATCH rows and BLOCK_SIZE_OUT_FEAT columns.
        grid = lambda META: (cdiv(batch_dim, META['BLOCK_SIZE_BATCH']) *
                             cdiv(out_feat_dim, META['BLOCK_SIZE_OUT_FEAT']),)
        linear_forward_kernel[grid](flattened_input, weight,
                                    input if bias is None else bias,
                                    pre_act, output,
                                    batch_dim, in_feat_dim, out_feat_dim,
                                    *flattened_input.stride(), *weight.stride(),
                                    *pre_act.stride(), *output.stride(),
                                    add_bias=bias is not None, act_func=act_func,
                                    save_pre_act=save_pre_act)

        ctx.act_func = act_func
        ctx.bias_requires_grad = False if bias is None else bias.requires_grad
        if requires_grad:
            ctx.save_for_backward(input, pre_act if save_pre_act else None, weight)

        return output.view(*input.shape[:-1], out_feat_dim)

    @staticmethod
    def backward(
        ctx: Context,
        output_grad: Tensor,
        ) -> Tuple[Optional[Tensor], ...]:
        """
        Calculates the input gradient of the linear layer.

        Args:
            ctx: Context containing stored variables.
            output_grad: Output gradients.
                Must be the same shape as the output.

        Returns:
            Input gradient of the linear layer.
        """
        input, pre_act, weight = ctx.saved_tensors

        output_grad = output_grad.flatten(0, -2)
        flattened_input = input.flatten(0, -2)

        batch_dim, _ = flattened_input.shape
        _, out_feat_dim = weight.shape

        if ctx.act_func is None:
            pre_act_grad = output_grad

        else:
            size = batch_dim * out_feat_dim
            pre_act_grad = torch.empty(size, dtype=pre_act.dtype,
                                       device=pre_act.device)

            # Launches 1D grid where each program operates over
            # BLOCK_SIZE elements.
            grid = lambda META: (cdiv(size, META['BLOCK_SIZE']),)
            act_func_backward_kernel[grid](output_grad, pre_act, pre_act_grad,
                                           size, ctx.act_func)

            pre_act_grad = pre_act_grad.view_as(pre_act)

        # Using PyTorch's matmul, but linear_forward_kernel
        # could have also been used.
        input_grad = pre_act_grad @ weight.T if input.requires_grad else None
        weight_grad = (flattened_input.T @ pre_act_grad
                       if weight.requires_grad else None)
        bias_grad = pre_act_grad.sum(dim=0) if ctx.bias_requires_grad else None

        # Pads output with None because a gradient is necessary for
        # all input arguments.
        return (input_grad.view_as(input) if input_grad is not None else None,
                weight_grad, bias_grad, None)

class Linear(nn.Linear):
    """
    Linearly transforms the input using weights, optionally adding bias
    and fusing an activation function.
    See also base class.

    Note: Unlike PyTorch's linear layer, the weight matrix in this module is
    of shape [in_features, out_features] instead of [out_features, in_features].
    This may cause unexpected issues when manipulating the weights (e.g., porting
    parameters, initializing them, and so forth).

    Args:
        in_features: Number of input features.
        out_features: Number of output features.
        bias: Flag for additive bias.
        act_func: Name of activation function to apply, with None for identity.
            Options are 'sigmoid', 'tanh', 'relu', 'gelu', and 'silu'.
        device: Device to use. Only CUDA is supported.
        dtype: Dtype of layer. Only float32 is supported.

    Raises:
        RuntimeError: 1. A device other than CUDA was passed.
                      2. A dtype other than float32 was passed.
    """
    def __init__(
        self,
        in_features: int,
        out_features: int,
        bias: bool = True,
        act_func: Optional[str] = None,
        device: Device = 'cuda',
        dtype: torch.dtype = torch.float32,
        ) -> None:
        if 'cuda' not in str(device):
            raise RuntimeError('Linear layer only supports CUDA devices.')

        if dtype is not torch.float32:
            raise RuntimeError('Linear layer only supports float32 dtype.')

        super().__init__(in_features, out_features, bias, device, dtype)
        self.weight = nn.Parameter(self.weight.T.contiguous())
        self.act_func = act_func

    def forward(self, input: Tensor) -> Tensor:
        return LinearAutoGrad.apply(input, self.weight, self.bias,
                                    self.act_func)


"""
Perform teardown and integration logic after executing "constructive" Terraform
subcommands (e.g. `init`, `plan`, and `apply`).
"""

from typing import List

import json

from accounts.models import Group
from cbhooks.models import TerraformStateFile, TerraformPlanHook
from infrastructure.models import Environment, Server
from jobs.models import Job
from orders.models import BlueprintOrderItem
from resources.models import Resource
from utilities.logger import ThreadLogger
from common.methods import set_progress
from c2_wrapper import create_custom_field

logger = ThreadLogger(__name__)

# These are the names of Terraform resources associated with servers/VMs in the
# main Terraform Providers which have corresponding CloudBolt Resource
# Technology support. Used below in `_parse_state_file_for_server_ids()` for
# finding servers in a state file.
TERRAFORM_VM_TYPES = [
    "google_compute_instance",
    "azurerm_virtual_machine",
    "aws_instance",
    "vsphere_virtual_machine",
    "openstack_compute_instance_v2",
    "clc_server",
    "nutanix_virtual_machine",
]

def post_provision(
        hook: TerraformPlanHook,
        job: Job,
        resource: Resource,
        state_file_obj: TerraformStateFile,
        group: Group,
        **kwargs,
) -> str:
    """
    `post_provision` runs after `apply`, after a Terraform Plan action has
    provisioned one or more Resources.

    This function adds any servers provisioned by Terraform as "Server" objects
    in CloudBolt, allowing for management in this product.

    Note: This function _must_ return a `str. Any additional side-effects can
        occur during this function execution, but changing the return type will
        cause Terraform execution to break.

    Args:
        hook (TerraformPlanHook): The "Terraform Plan" Action that's called from
            a Blueprint.
        job (Job): Async "Job" object that's associated with running this `hook`.
        resource (Resource): "Resource" object that Terraform will populate /
            provision to.
        state_file_obj (TerraformStateFile): File model object for the generated
            Terraform state file.out
        group (Group): "Group" that the original Blueprint was ordered under.

    Returns:
        str: Output to be displayed on the Job "Details" page.
    """
    servers: List[Server] = get_or_create_server_records_from_state_file(
        state_file_obj=state_file_obj, resource=resource, group=group,
        job=job
    )

    # Write the Outputs of the TF plan to the Resource
    write_outputs(resource, state_file_obj)

    # Save the Blueprint deploy job to the server for job record
    blueprint_job = job.parent_job
    for server in servers:
        blueprint_job.server_set.add(server)

    return (
        f"Created resource '{resource}' with " f"{len(servers)} servers from terraform"
    )

def write_outputs(
        resource: Resource, state_file_obj: TerraformStateFile
) -> None:
    """
    Write all TF plan outputs to the Resource as parameters
    """
    state_file_content = state_file_obj.content_json
    try:
        tf_outputs = state_file_content["outputs"]
    except KeyError:
        set_progress("Outputs not set on TF plan. Continuing")
        return None
    for key in tf_outputs.keys():
        value = tf_outputs[key]["value"]
        tf_type = tf_outputs[key]["type"]
        try:
            description = tf_outputs[key]["description"]
        except:
            description = ""
        try:
            sensitive = tf_outputs[key]["sensitive"]
        except:
            sensitive = None
        logger.info(f'Custom Field: {key}, Value: {value}, Type: {type}, '
                    f'description: {description}, sensitive: {sensitive}')
        cb_type = get_cloudbolt_type(tf_type, sensitive)

        if not cb_type:
            try:
                # If cb_type can't be determined attempt to json.dumps
                value = json.dumps(value)
                cb_type = "STR"
            except:
                logger.warning(f"TF output type does not match supported "
                               f"output types. Type: {tf_type}, Key: {key}")
                continue

        if sensitive:
            # If Sensitive want to store as a string password value
            value = str(value)
        field_name = f'tf_output_{key}'
        cf = create_custom_field(field_name, key, cb_type, show_on_servers=True,
                                 description=description)
        resource.set_value_for_custom_field(field_name, value)
    return None

def get_cloudbolt_type(tf_type, sensitive):
    cb_type = ""
    if sensitive:
        cb_type = "PWD"
    elif tf_type == "string":
        cb_type = "STR"
    elif tf_type == "number":
        cb_type = "INT"
    elif tf_type == "bool":
        cb_type = "BOOL"
    return cb_type

def get_or_create_server_records_from_state_file(
        state_file_obj: TerraformStateFile, resource: Resource, group: Group,
        job: Job
) -> List[Server]:
    """
    Get or create Server object instances from server's unique UUIDs parsed out of
    the Terraform state file from this action.
    """

    server_ids = _parse_state_file_for_server_ids(state_file_obj, resource,
                                                  job)
    logger.info(
        f"Will create or update records for {len(server_ids)} servers in CloudBolt."
    )
    env = Environment.objects.get(name="Unassigned")
    servers = []

    for svr_id in server_ids:
        tech_dict = None
        if type(svr_id) == dict:
            logger.info(f'svr_id: {svr_id}')
            tech_dict = svr_id["tech_dict"]
            rh = svr_id["rh"]
            logger.info(f'tech_dict: {tech_dict}')
            env = svr_id["env"]
            svr_id = svr_id["id"]
        if svr_id:
            # Server manager does not have the create_or_update method,
            # so we do this manually.
            try:
                server = Server.objects.get(resource_handler_svr_id=svr_id)
                server.resource = resource
                server.group = group
                server.owner = resource.owner
                server.environment = env
                server.save()
                logger.info(f"Found existing server record: '{server}'")
            except Server.DoesNotExist:
                logger.info(
                    f"Creating new server with resource_handler_svr_id "
                    f"'{svr_id}', resource '{resource}', group '{group}', "
                    f"owner '{resource.owner}', and "
                    f"environment '{env}'"
                )
                server = Server(
                    hostname=svr_id,
                    resource_handler_svr_id=svr_id,
                    resource=resource,
                    group=group,
                    owner=resource.owner,
                    environment=env,
                )
                server.save()
                # We have to have already saved the new server record before this
                # will effectively be added as a custom field value, then
                # we have to save again to apply that relationship.
                server.created_by_terraform = True
                server.save()

            if tech_dict:
                server.resource_handler = rh
                server.save()
                try:
                    rh.cast().update_tech_specific_server_details(server,
                                                                  tech_dict)
                    server.refresh_info()
                except Exception as err:
                    logger.warning(f'Unable to directly sync server, verify '
                                   f'that the chosen region/vpc has been '
                                   f'imported to CloudBolt. Error: {err}')
            servers.append(server)

    return servers

def _parse_state_file_for_server_ids(state_file_obj: TerraformStateFile,
                                     resource, job) -> List[int]:
    """
    Read through the JSON dict of the state file getting resource ids if they
    are expected to be servers.

    Args:
        state_file_obj (cbhooks.TerraformStateFile)
    """
    server_ids = []

    logger.info(
        f"Parsing the JSON from the state file "
        f"'{state_file_obj.module_file.name}' to "
        f"search for servers that can be represented in CloudBolt."
    )

    state_dict = state_file_obj.content_json
    if not state_dict:
        return []

    # Terraform pushes out versions of their state file syntax, and we are only
    # able to support version 3 (will support 4 later, too)
    version = int(state_dict.get("version"))

    # Parse modules.
    # The JSON is slightly different depending on whether the plan contains modules
    modules = state_dict.get("modules")
    if modules:
        resources = []
        for module in modules:
            resources_dict = module.get("resources")
            for resource_name, attrs in resources_dict.items():
                resources.append(attrs)
    else:
        # Parse the resources directly.
        resources = state_dict.get("resources", [])

    for resource_dict in resources:
        # Expected format (version 3):
        # resource_dict = {
        #     'type': 'aws_instance',
        #     'primary': {
        #          'id': 'i-08204873902849032'
        #      }
        # }
        if resource_dict.get("type") in TERRAFORM_VM_TYPES:
            if resource_dict.get("mode") == "managed":
                logger.info(
                    f"Found a terraform resource of type '{resource_dict.get('type')}'."
                )
                if version == 3:
                    vm_id = resource_dict.get("primary", {}).get("id")
                    if vm_id:
                        server_ids.append(vm_id)
                else:
                    logger.warning(
                        f"Detected that the state file's version is "
                        f"{version} and CloudBolt currently only supports"
                        f"version 3."
                    )
                    if version == 4:
                        # We shouldn't be able to get to this step because Terraform
                        # variable - action input parsing should fail first,
                        # but we have left this code here for future support.
                        instances = resource_dict.get("instances")
                        for instance in instances:
                            vm_id = instance.get("attributes").get("id")
                            tech_dict = None
                            resource_type = resource_dict.get("type")
                            supported_types = [
                                "aws_instance", "vsphere_virtual_machine"
                            ]
                            if resource_type in supported_types:
                                tech_dict, rh, env = get_tech_dict(
                                    instance,
                                    vm_id,
                                    job,
                                    resource_type
                                )
                            if tech_dict:
                                vm_id = {
                                    "id": vm_id,
                                    "tech_dict": tech_dict,
                                    "rh": rh,
                                    "env": env
                                }
                            server_ids.append(vm_id)

    return server_ids

def get_tech_dict(instance, vm_id, job, resource_type):
    env = get_environment_from_job(job)
    if resource_type == "aws_instance":
        return get_aws_tech_dict(instance, env, vm_id)
    if resource_type == "vsphere_virtual_machine":
        return get_vmware_tech_dict(instance, env, vm_id)

def get_environment_from_job(job):
    params = json.loads(job.order_item._encrypted_arguments)["context"]
    bpoi_id = params["blueprint_order_item"]
    service_item_id = params["service_item_id"]
    bpoi = BlueprintOrderItem.objects.get(id=bpoi_id)
    bpia = bpoi.blueprintitemarguments_set.get(service_item__id=service_item_id)
    env = bpia.environment
    return env

def get_aws_tech_dict(instance, env, vm_id):
    attributes = instance.get("attributes")
    subnet_id = attributes.get("subnet_id")
    az = attributes.get("availability_zone")
    region = az[:-1]
    try:
        vpc_id, rh = get_aws_vpc_id(env, region, subnet_id)
    except Exception as err:
        logger.warning(f'get_aws_vpc_id failed. Error: {err}')
        vpc_id = None
    if not vpc_id or not rh:
        logger.warning('VPC could not be identified for TF server, skipping '
                       'direct import')
        return "", ""
    tech_dict = {
        "ec2_region": region,
        "availability_zone": az,
        "instance_id": vm_id,
        "vpc_id": vpc_id,
        "instance_type": attributes.get("instance_type"),
    }
    return tech_dict, rh, env

def get_vmware_tech_dict(instance, env, vm_id):
    attributes = instance.get("attributes")
    tech_dict = {
        "linked_clone": attributes.get("clone")[0].get("linked_clone"),
        # cluster =
        "moid": attributes.get("moid")
    }
    rh = env.resource_handler
    return tech_dict, rh, env

def get_aws_vpc_id(env, region, subnet_id):
    rh = env.resource_handler
    wrapper = rh.cast().get_api_wrapper()
    conn = wrapper.get_boto3_resource(
        rh.serviceaccount,
        rh.servicepasswd,
        region,
        service_name='ec2'
    )
    subnet = conn.Subnet(subnet_id)
    return subnet.vpc_id, rh


"""
This file is part of nand2tetris, as taught in The Hebrew University, and
was written by Aviv Yaish. It is an extension to the specifications given
[here](https://www.nand2tetris.org) (Shimon Schocken and Noam Nisan, 2017),
as allowed by the Creative Common Attribution-NonCommercial-ShareAlike 3.0
Unported [License](https://creativecommons.org/licenses/by-nc-sa/3.0/).
"""
import typing
import os

class CodeWriter:
    """Translates VM commands into Hack assembly code."""

    def __init__(self, output_stream: typing.TextIO) -> None:
        """Initializes the CodeWriter.

        Args:
            output_stream (typing.TextIO): output stream.
        """
        # Your code goes here!
        # Note that you can write to output_stream like so:
        # output_stream.write("Hello world! \n")
        self.output_stream = output_stream
        self.segments_type_dict = {"local": "LCL", "argument": "ARG",
                                   "this": "THIS", "that": "THAT",
                                   "pointer": 3, "temp": 5}
        self._vm_file_name = ''
        self.comp_i = 0
        self.call_i = 0

        self.function_counter = 0
    def set_file_name(self, filename: str) -> None:
        """Informs the code writer that the translation of a new VM file is
        started.

        Args:
            filename (str): The name of the VM file.
        """
        # Your code goes here!
        # This function is useful when translating code that handles the
        # static segment. For example, in order to prevent collisions between two
        # .vm files which push/pop to the static segment, one can use the current
        # file's name in the assembly variable's name and thus differentiate between
        # static variables belonging to different files.
        # To avoid problems with Linux/Windows/MacOS differences with regards
        # to filenames and paths, you are advised to parse the filename in
        # the function "translate_file" in Main.py using python's os library,
        # For example, using code similar to:
        # input_filename, input_extension = os.path.splitext(os.path.basename(input_file.name))
        self._vm_file_name = filename

    def write_arithmetic(self, command: str) -> None:
        """Writes assembly code that is the translation of the given
        arithmetic command. For the commands eq, lt, gt, you should correctly
        compare between all numbers our computer supports, and we define the
        value "true" to be -1, and "false" to be 0.

        Args:
            command (str): an arithmetic command.
        """
        # Your code goes here!
        if command == "add":
            self.output_stream.write(self._binary_operation("+"))

        elif command == "sub":
            self.output_stream.write(self._binary_operation("-"))

        elif command == "neg":
            self.output_stream.write(self._unary_operation("-", "before"))

        elif command == "eq":
            self.output_stream.write(self.compare("JEQ"))

        elif command == "gt":
            self.output_stream.write(self.compare("JGT"))

        elif command == "lt":
            self.output_stream.write(self.compare("JLT"))

        elif command == "and":
            self.output_stream.write(self._binary_operation("&"))

        elif command == "or":
            self.output_stream.write(self._binary_operation("|"))

        elif command == "not":
            self.output_stream.write(self._unary_operation("!", "before"))
        elif command == "shiftleft":
            self.output_stream.write(self._unary_operation("<<", "after"))
        elif command == "shiftright":
            self.output_stream.write(self._unary_operation(">>", "after"))
        # todo >> << shift left and right

    def write_push_pop(self, command: str, segment: str, index: int) -> None:
        """Writes assembly code that is the translation of the given
        command, where command is either C_PUSH or C_POP.

        Args:
            command (str): "C_PUSH" or "C_POP".
            segment (str): the memory segment to operate on.
            index (int): the index in the memory segment.
        """
        # Your code goes here!
        # Note: each reference to "static i" appearing in the file Xxx.vm should
        # be translated to the assembly symbol "Xxx.i". In the subsequent
        # assembly process, the Hack assembler will allocate these symbolic
        # variables to the RAM, starting at address 16.
        code = ""
        if command == "C_PUSH":
            if segment == "constant":
                code += f"@{index}\nD=A\n"
            elif segment == "local" or segment == "argument" or segment == "this" or segment == "that":
                code += f"@{index}\nD=A\n@{self.segments_type_dict[segment]}\nA=M+D\nD=M\n"
            elif segment == "pointer" or segment == "temp":
                code += f"@{index}\nD=A\n@{self.segments_type_dict[segment]}\nA=A+D\nD=M\n"
            elif segment == "static":
                code += f"@{self._vm_file_name}.{index}\nD=M\n"
            code += "@SP\nA=M\nM=D\n@SP\nM=M+1\n"

        elif command == "C_POP":
            if segment == "constant":
                code += f"@{index}\nD=A\n"
            elif segment == "local" or segment == "argument" or segment == "this" or segment == "that":
                code += f"@{self.segments_type_dict[segment]}\nD=M\n@{index}\nD=D+A\n"
            elif segment == "pointer" or segment == "temp":
                code += f"@{index}\nD=A\n@{self.segments_type_dict[segment]}\nA=D+A\nD=A\n"
            elif segment == "static":
                code += f"@{self._vm_file_name}.{index}\nD=A\n"

            code += f"@R13\nM=D\n@SP\nM=M-1\nA=M\nD=M\n@R13\nA=M\nM=D\n"
        self.output_stream.write(code)

    def write_label(self, label: str) -> None:
        """Writes assembly code that affects the label command.
        Let "Xxx.foo" be a function within the file Xxx.vm. The handling of
        each "label bar" command within "Xxx.foo" generates and injects the symbol
        "Xxx.foo$bar" into the assembly code stream.
        When translating "goto bar" and "if-goto bar" commands within "foo",
        the label "Xxx.foo$bar" must be used instead of "bar".

        Args:
            label (str): the label to write.
        """
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        code = f"({label})\n"
        self.output_stream.write(code)

    def write_goto(self, label: str) -> None:
        """Writes assembly code that affects the goto command.

        Args:
            label (str): the label to go to.
        """
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        code = f"@{label}\n0;JMP\n"
        self.output_stream.write(code)

    def write_if(self, label: str) -> None:
        """Writes assembly code that affects the if-goto command.

        Args:
            label (str): the label to go to.
        """
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        code = f"@SP\nM=M-1\nA=M\nD=M\n@{label}\nD;JNE\n"
        self.output_stream.write(code)

    def write_function(self, function_name: str, n_vars: int) -> None:
        """Writes assembly code that affects the function command.
        The handling of each "function Xxx.foo" command within the file Xxx.vm
        generates and injects a symbol "Xxx.foo" into the assembly code stream,
        that labels the entry-point to the function's code.
        In the subsequent assembly process, the assembler translates this
        symbol into the physical address where the function code starts.

        Args:
            function_name (str): the name of the function.
            n_vars (int): the number of local variables of the function.
        """
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        # The pseudo-code of "function function_name n_vars" is:
        # (function_name)       // injects a function entry label into the code
        # repeat n_vars times:  // n_vars = number of local variables
        #   push constant 0     // initializes the local variables to 0
        self.write_label(function_name)
        for i in range(n_vars):
            self.write_push_pop("C_PUSH", "constant", 0)

    def write_call(self, function_name: str, n_args: int) -> None:
        """Writes assembly code that affects the call command.
        Let "Xxx.foo" be a function within the file Xxx.vm.
        The handling of each "call" command within Xxx.foo's code generates and
        injects a symbol "Xxx.foo$ret.i" into the assembly code stream, where
        "i" is a running integer (one such symbol is generated for each "call"
        command within "Xxx.foo").
        This symbol is used to mark the return address within the caller's
        code. In the subsequent assembly process, the assembler translates this
        symbol into the physical memory address of the command immediately
        following the "call" command.

        Args:
            function_name (str): the name of the function to call.
            n_args (int): the number of arguments of the function.
        """
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        # The pseudo-code of "call function_name n_args" is:
        # push return_address   // generates a label and pushes it to the stack
        # push LCL              // saves LCL of the caller
        # push ARG              // saves ARG of the caller
        # push THIS             // saves THIS of the caller
        # push THAT             // saves THAT of the caller
        # ARG = SP-5-n_args     // repositions ARG
        # LCL = SP              // repositions LCL
        # goto function_name    // transfers control to the callee
        # (return_address)      // injects the return address label into the code
        self.call_i += 1
        return_address = f"return_{function_name}{self.call_i}"
        self.output_stream.write(f"@{return_address}\nD=A\n@SP\nA=M\nM=D\n@SP\nM=M+1\n")
        for segment in ["LCL", "ARG", "THIS", "THAT"]:
            self.output_stream.write(f"@{segment}\nD=M\n@SP\nA=M\nM=D\n@SP\nM=M+1\n")
        # ARG = SP-5-n_args
        self.output_stream.write(f"@{n_args}\nD=A\n@SP\nD=M-D\n@5\nD=D-A\n@ARG\nM=D\n")
        # LCL = SP
        self.output_stream.write(f"@SP\nD=M\n@LCL\nM=D\n")
        self.write_goto(function_name)
        self.write_label(f"return_{function_name}{self.call_i}")

    def write_return(self) -> None:
        """Writes assembly code that affects the return command."""
        # This is irrelevant for project 7,
        # you will implement this in project 8!
        # The pseudo-code of "return" is:
        # frame = LCL                   // frame is a temporary variable
        # return_address = *(frame-5)   // puts the return address in a temp var
        # *ARG = pop()                  // repositions the return value for the caller
        # SP = ARG + 1                  // repositions SP for the caller
        # THAT = *(frame-1)             // restores THAT for the caller
        # THIS = *(frame-2)             // restores THIS for the caller
        # ARG = *(frame-3)              // restores ARG for the caller
        # LCL = *(frame-4)              // restores LCL for the caller
        # goto return_address           // go to the return address
        self.output_stream.write("@LCL\nD=M\n@13\nM=D\n")
        self.output_stream.write("@13\nD=M\n@5\nD=D-A\nA=D\nD=M\n@14\nM=D\n")
        self.output_stream.write(
            "@SP\nA=M-1\nD=M\n@ARG\nA=M\nM=D\n@SP\nM=M-1\n")
        self.output_stream.write("@ARG\nD=M+1\n@SP\nM=D\n")
        for i, segment in enumerate(["THAT", "THIS", "ARG", "LCL"]):
            self.output_stream.write(
                f"@13\nD=M\n@{i + 1}\nA=D-A\nD=M\n@{segment}\nM=D\n")
        self.output_stream.write("@14\nA=M\n0;JMP\n")

    def compare(self, command):
        self.comp_i += 1
        stack_to_d = f"@SP\n" \
               f"M=M-1\n" \
               f"A=M\n" \
               f"D=M\n" \

        code = stack_to_d + f"@R13\nM=D\n"
        code += f"@YPOS{self.comp_i}\nD;JGT\n"
        code += stack_to_d +  f"@YNEGXPOS{self.comp_i}\nD;JGT\n"
        code += f"(CHECK{self.comp_i})\n@R13\nD=D-M\n" \
                f"@TRUE{self.comp_i}\nD;{command}\n" \
                f"@FALSE{self.comp_i}\n0;JMP\n"
        code+= f"(YPOS{self.comp_i})\n" \
               f"@SP\n" \
               f"M=M-1\n" \
               f"A=M\n" \
               f"D=M\n" \
               f"@YPOSXNEG{self.comp_i}\nD;JLT\n" \
               f"@CHECK{self.comp_i}\n0;JMP\n" \
               f"(YNEGXPOS{self.comp_i})\n" \
               f"@R13\nM=-1\n" \
               f"@CHECK{self.comp_i}\n0;JMP\n" \
               f"(YPOSXNEG{self.comp_i})\nD=-1\n" \
               f"@CHECK{self.comp_i}\n0;JMP\n" \
               f"(FALSE{self.comp_i})\n" \
               f"@SP\n" \
               f"A=M\n" \
               f"M=0\n" \
               f"@END{self.comp_i}\n0;JMP\n" \
               f"(TRUE{self.comp_i})\n" \
               f"@SP\n" \
               f"A=M\n" \
               f"M=-1\n" \
               f"@END{self.comp_i}\n0;JMP\n" \
               f"(END{self.comp_i})\n@SP\nM=M+1\n"
        return code
    def _unary_operation(self, command, before_after) -> str:
        code = f"@SP\n" \
               f"M=M-1\n" \
               f"A=M\n"
        if before_after == "before":
            code += f"M={command}M\n"
        elif before_after == "after":
            code += f"M=M{command}\n"
        return code + f"@SP\n" \
                      f"M=M+1\n"

    # binary

    def _binary_operation(self, command) -> str:
        return f"@SP\n" \
               f"M=M-1\n" \
               f"A=M\n" \
               f"D=M\n" \
               f"@SP\n" \
               f"M=M-1\n" \
               f"A=M\n" \
               f"M=M{command}D\n" \
               f"@SP\n" \
               f"M=M+1\n"

    def writeBootstrap(self):
        self.output_stream.write("@256\nD=A\n@SP\nM=D\n")
        self.write_call("Sys.init",0)


from django.shortcuts import render
from django.urls import reverse #we used reverse function to use name instead of a url in urls.py
from django.core.files.storage import FileSystemStorage
from employee.models import Event,Employee,Student,Comment
from django.http import HttpResponse,HttpResponseRedirect
from django.db.models import Sum,Count
from donor.models import Donor,Donations

# Create your views here.

def edashboard(request):
    username=request.session['username']
    d=Employee.objects.get(eusername=username)
    sl=Student.objects.all().aggregate(Count('sname'))['sname__count']
    dl=Donor.objects.all().aggregate(Count('id'))['id__count']
    el=Event.objects.all().aggregate(Count('id'))['id__count']
    f=Donations.objects.all()
    funds=0

    for i in f:
        a=float(i.collectedfunds)
        funds+=a

    return render(request,'employee/index.html',{
    'd':d,'sl':sl,'dl':dl,'el':el,'f':funds,
    })

def charte(request):
    uname=request.session['username']
    ee=Employee.objects.get(eusername=uname)
    return render(request,'employee/charte.html',{
    'ee':ee,
    })

def table(request):

    return render(request,'employee/viewstudents.html')

def addevent(request):
    uname=request.session['username']
    ee=Employee.objects.get(eusername=uname)
    return render(request,'employee/addevent.html',{
    'ee':ee,
    })

def addstudent(request):
    uname=request.session['username']
    ee=Employee.objects.get(eusername=uname)
    return render(request,'employee/addstudent.html',{
    'ee':ee,
    })

def events(request):
    event=Event.objects.all()

    p=[]
    n=[]

    for i in event:
        pos=Comment.objects.filter(event_id_id=i.id,sentiment='positive').aggregate(Count('sentiment'))['sentiment__count']
        neg=Comment.objects.filter(event_id_id=i.id,sentiment='negative').aggregate(Count('sentiment'))['sentiment__count']
        p.append(pos)
        n.append(neg)

    sent=zip(p,n,event)
    return render(request,'employee/viewevents.html',{
    'event':sent,'e':event,
    })

def addeventactions(request):
            name=request.POST.get('name','NULL')
            location=request.POST.get('location','NULL')
            address=request.POST.get('address','NULL')
            description=request.POST.get('description','NULL')
            duration=request.POST.get('duration','NULL')
            category=request.POST.get('radios','NULL')
            ev_exfunds=request.POST.get('ev_exfunds','NULL')
            uploadedfileurl=''
            if request.method=='POST' and request.FILES['myfile']:
                myfile=request.FILES['myfile']
                fs=FileSystemStorage()
                filename=fs.save(myfile.name,myfile)
                uploadedfileurl=fs.url(filename)
            s=Event(evname=name,evlocation=location,evaddr=address,evdesc=description,evdur=duration,evpic_path=uploadedfileurl,evtype=category,ev_exfunds=ev_exfunds)
            s.save()
            if s.id:
                return HttpResponseRedirect(reverse('edashboard'))
            else:
                return HttpResponse('Error')

def studentreg(request):
    name=request.POST.get('name')
    email=request.POST.get('email')
    contact=request.POST.get('contact')
    address=request.POST.get('address')
    achv=request.POST.get('achv')
    vilcit=request.POST.get('vilcit')
    gender=request.POST.get('radios')
    uploadedfileurl=''
    if request.method=='POST' and request.FILES['file']:
        myfile=request.FILES['file']
        fs=FileSystemStorage()
        filename=fs.save(myfile.name,myfile)
        uploadedfileurl=fs.url(filename)

    if contact=='NULL':
        contact=0

    s=Student(sname=name,semail=email,scontact=contact,sadd=address,sprog=achv,scity=vilcit,sgender=gender,spic_path=uploadedfileurl)

    s.save()

    return HttpResponseRedirect(reverse('edashboard'))

def tables(request):
    e=Student.objects.all()
    sr=[]
    for i in range(0,len(e)):
        sr.append(i+1)

    z=zip(e,sr)
    uname=request.session['username']
    ee=Employee.objects.get(eusername=uname)
    return render(request,'employee/viewstudents.html',{
    'e':z,'ee':ee,
    })


import boto3

dynamodb_client = boto3.client('dynamodb', region_name='us-west-2', endpoint_url='http://localhost:8000')

location = 'Trinity'
sdate = '20140101'
edate = '20140201'

response = dynamodb_client.query(
    TableName='Snotel',
    KeyConditionExpression='LocationID = :LocationID and SnotelDate BETWEEN :sdate and :edate',
    ExpressionAttributeValues={
        ':LocationID': {'S': location},
        ':sdate': {'S': sdate},
        ':edate': {'S': edate}
    }
)
items = response['Items']

data = []
for i in range(len(items)):
    data_dictionary = {}
    data_dictionary['snotelDate'] = items[i]['SnotelDate']['S']
    data_dictionary['waterCurrent'] = int(items[i]['WaterCurrent']['N'])
    data_dictionary['waterMedian'] = int(items[i]['WaterCurrentAverage']['N'])
    data_dictionary['waterPctMedian'] = int(items[i]['WaterPctAverage']['N'])
    data_dictionary['snowCurrent'] = int(items[i]['SnowCurrent']['N'])
    data_dictionary['snowMedian'] = int(items[i]['SnowMedian']['N'])
    data_dictionary['snowPctMedian'] = int(items[i]['SnowPctMedian']['N'])
    data.append(data_dictionary)


from tkinter import Tk, ttk, constants, END
from logic.chain_analytics_service import chain_analytics_service

class ContractsView:
    def __init__(self, root):
        self._root = root
        self._frame = None
        self._block_id = None
        self._current_block_id = str(
            int(chain_analytics_service.get_current_block_id(), 0))
        self._intitialize()

    def pack(self):
        self._frame.pack(fill=constants.X)

    def destroy(self):
        self._frame.destroy()

    def _intitialize(self):
        self._frame = ttk.Frame(master=self._root)

        addressLabel = ttk.Label(master=self._frame, text="Contract address")
        blockLabel = ttk.Label(
            master=self._frame, text="BlockId to start from")
        self._address_hash = ttk.Entry(master=self._frame)
        self._block_id = ttk.Entry(master=self._frame)
        self._block_id.insert(END, self._current_block_id)

        button_find = ttk.Button(
            master=self._frame,
            text="Find contracts created in new block",
            command=lambda: self._contract_finder_by_block(
                str(self._block_id.get()))
        )

        button_find_contract = ttk.Button(
            master=self._frame,
            text="Add contract from address",
            command=lambda: self._contract_finder_by_address(
                self._address_hash.get())
        )

        button_database = ttk.Button(
            master=self._frame,
            text="Get everything in database",
            command=lambda: self._show_all_contracts()
        )

        addressLabel.grid(row=0, column=0)
        self._address_hash.grid(row=0, column=1)
        blockLabel.grid(row=1, column=0)
        self._block_id.grid(row=1, column=1)

        button_database.grid(row=2, column=0)
        button_find.grid(row=2, column=1)
        button_find_contract.grid(row=2, column=2)
        frame_contracts = ttk.Frame(master=self._frame)
        frame_contracts.grid(row=4)
        columns = ["Timestamp", "Name", "Transaction hash",
                   "Contract address", "Creator address"]
        self._contract_list = ttk.Treeview(
            master=frame_contracts, columns=columns, show="headings")
        self._contract_list.grid(row=1, column=0)
        self._contract_list.bind('<Button-3>', self.clipboard)
        for col in columns[0:]:
            self._contract_list.column(col, width=120)
            self._contract_list.heading(col, text=col)

    def _show_all_contracts(self):
        contracts_found = chain_analytics_service.get_contracts_in_db()
        for i in self._contract_list.get_children():
            self._contract_list.delete(i)
        for contract in contracts_found:
            self._contract_list.insert('', 'end', values=(contract.creation_timestamp, contract.name,
                                       contract.transaction_hash, contract.contract_address, contract.creator_address))

    def _contract_finder_by_block(self, block_id):
        chain_analytics_service.add_new_contract_to_db_from_block_number(
            int(block_id, 0))
        self._show_all_contracts()

    def _contract_finder_by_address(self, address):
        chain_analytics_service.add_new_contract_to_db_with_contract_address(
            address)
        self._show_all_contracts()

    def clipboard(self, event):
        tree = self._contract_list
        cur_item = tree.item(tree.focus())
        col = tree.identify_column(event.x)
        if col == '#3':
            self._frame.clipboard_clear()
            print(cur_item)
            self._frame.clipboard_append(cur_item["values"][2])
        if col == '#4':
            self._frame.clipboard_clear()
            print(cur_item)
            self._frame.clipboard_append(cur_item["values"][3])


from itertools import combinations
import sys
input = sys.stdin.readline

d = [(0,1), (1,0), (-1,0), (0,-1)]

def out_of_range(ny:int, nx:int) -> bool:
    return ny < 0 or nx < 0 or ny >= n or nx >= m

def check(s: tuple[int]):
    res = 0
    visited = [[False]*m for _ in range(n)]
    for i in s:
        y,x = i//m, i%m
        res += board[y][x]
        visited[y][x] = True
        for dy,dx in d:
            ny,nx = y+dy,x+dx
            if not out_of_range(ny,nx) and visited[ny][nx]:
                return -int(1e9)
    return res

n,m,k = map(int,input().split())
board = [list(map(int,input().split())) for _ in range(n)]
ans = []
for i in combinations(range(n*m), k):
    ans.append(check(i))

print(max(ans))


from urllib import request
import re
# https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20
# https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=20&limit=20
# https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=40&limit=20
header =  {"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
           }
url="https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=0&limit=20"
#  "rating":["9.6","50"]    #"title":"肖申克的救赎"
data=request.Request(url,headers=header)
response = request.urlopen(data).read().decode()
pat=re.compile(r'"rating":\["(.*?)","\d+"\]')
pat2=re.compile(r'"title":"(.*?")')
result=re.findall(pat,response)
result2=re.findall(pat2,response)
for i in range(0,len(result)):
    print("豆瓣排名："+str(i+1)+"\t电影名："+result2[i]+"\t豆瓣评分："+result[i])


"""
Code is partially borrowed from repository https://github.com/sbarratt/inception-score-pytorch/blob/master/inception_score.py # noqa: E501
"""

import argparse
import logging
from pathlib import Path
from typing import Dict, Iterable, Optional, Tuple, Union

import numpy as np
import torch
import torch.utils.data
import torchvision
import torchvision.datasets as dset
import torchvision.transforms as transforms
import yaml
from torch import nn
from torch.nn import functional as F
from torchvision.models.inception import inception_v3
from yaml import Loader

from ex2mcmc.utils.callbacks import Callback, CallbackRegistry

N_INCEPTION_CLASSES = 1000
MEAN_TRASFORM = [0.485, 0.456, 0.406]
STD_TRANSFORM = [0.229, 0.224, 0.225]
N_GEN_IMAGES = 100005000

@CallbackRegistry.register()
class InceptionScoreCallback(Callback):
    def __init__(
        self,
        invoke_every: int = 1,
        device: Union[str, int, torch.device] = "cuda",
        update_input: bool = True,
        dp: bool = False,
        batch_size: int = 128,
    ) -> None:
        self.device = device
        self.model = torchvision.models.inception.inception_v3(
            pretrained=True, transform_input=False
        ).to(device)
        if dp:
            self.model = nn.DataParallel(self.model)

        self.model.eval()
        self.transform = transforms.Normalize(mean=MEAN_TRASFORM, std=STD_TRANSFORM)
        self.update_input = update_input
        self.invoke_every = invoke_every
        self.batch_size = batch_size

    @torch.no_grad()
    def invoke(self, info: Dict[str, Union[float, np.ndarray]]):
        score = None
        step = info.get("step", self.cnt)
        if step % self.invoke_every == 0:
            imgs = torch.from_numpy(info["imgs"]).to(self.device)
            imgs = self.transform(imgs)
            pis = []
            for batch in torch.split(imgs, self.batch_size):
                pis_ = batch_inception(batch, self.model, resize=True).detach().cpu()
                pis.append(pis_)
            pis = torch.cat(pis, 0)
            score = (
                (pis * (torch.log(pis) - torch.log(pis.mean(0)[None, :])))
                .sum(1)
                .mean(0)
            )
            score = torch.exp(score)

            if self.update_input:
                info["inception_score"] = score
            logger = logging.getLogger()
            logger.info(f"\nIS: {score}")
        self.cnt += 1
        return score

def batch_inception(
    imgs: torch.Tensor,
    inception_model: nn.Module,
    resize: bool = False,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    device = imgs.device
    up = nn.Upsample(size=(299, 299), mode="bilinear").to(device)

    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x, -1)

    preds = get_pred(imgs)
    return preds

def get_inception_score(
    imgs: Iterable,
    inception_model: Optional[nn.Module] = None,
    gen: Optional[nn.Module] = None,
    generate_from_latents: bool = False,
    cuda: bool = True,
    batch_size: int = 32,
    resize: bool = False,
    splits: int = 1,
    device: Union[torch.device, int] = 0,
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
    """Computes the inception score of the generated images imgs
    imgs -- Torch dataset of (3xHxW) numpy images normalized in the range [-1, 1]
    cuda -- whether or not to run on GPU
    batch_size -- batch size for feeding into Inception v3
    splits -- number of splits
    """
    N = len(imgs)

    assert batch_size > 0
    assert N >= batch_size

    # Set up dataloader
    if not isinstance(imgs, torch.utils.data.Dataset):
        imgs = torch.utils.data.TensorDataset(imgs)

    dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size)

    # Load inception model
    if inception_model is None:
        inception_model = inception_v3(
            pretrained=True,
            transform_input=False,  # False
        ).to(device)
        inception_model.eval()

    up = nn.Upsample(size=(299, 299), mode="bilinear").to(device)

    def get_pred(x):
        if resize:
            x = up(x)
        x = inception_model(x)
        return F.softmax(x, -1).data.cpu()

    # Get predictions
    preds = torch.zeros((N, N_INCEPTION_CLASSES))

    for i, batch in enumerate(dataloader):
        if isinstance(batch, list):
            batch = batch[0]
        batch = batch.to(device)
        if generate_from_latents:
            batch = gen(batch)
        batch_size_i = batch.size()[0]

        preds[i * batch_size : i * batch_size + batch_size_i] = get_pred(batch)

    # Now compute the mean kl-div
    split_scores = []

    for k in range(splits):
        part = preds[k * (N // splits) : (k + 1) * (N // splits), :]
        py = torch.mean(part, 0)
        split_scores.append(
            torch.exp(
                (part * (torch.log(part) - torch.log(py[None, :])))
                .sum(1)
                .mean(0)
                # torch.mean(torch.kl_div(part, torch.log(py[None, :])).sum(1))
            )
        )

    return (
        torch.mean(torch.stack(split_scores, 0)),
        torch.std(torch.stack(split_scores, 0)),
        preds,
    )

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--gan_config", type=str)
    parser.add_argument("--device", type=int, default=0)
    args = parser.parse_args()

    device = torch.device(args.device)

    if args.gan_config:
        from ex2mcmc.models.utils import GANWrapper
        from ex2mcmc.utils.general_utils import DotConfig

        gan_config = DotConfig(
            yaml.load(Path(args.gan_config).open("r"), Loader)
        ).gan_config
        # gen, _ = load_gan(gan_config, device)
        gan = GANWrapper(gan_config, device=device, load_weights=True)
        gen = gan.gen

        n_imgs = 1000  # 1000
        imgs = gen(torch.randn(n_imgs, gen.z_dim).to(device))
        imgs = gen.inverse_transform(imgs)

        transform = transforms.Normalize(
            mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
        )
        imgs = transform(imgs)

        print("Calculating Inception Score...")
        print(
            get_inception_score(
                imgs,
                cuda=True,
                batch_size=32,
                resize=True,
                splits=1,
            )[:-1]
        )
    else:

        class IgnoreLabelDataset(torch.utils.data.Dataset):
            def __init__(self, orig):
                self.orig = orig

            def __getitem__(self, index):
                return self.orig[index][0]

            def __len__(self):
                return len(self.orig)

        cifar = dset.CIFAR10(
            root="data/",
            download=True,
            transform=transforms.Compose(
                [
                    transforms.Scale(32),
                    transforms.ToTensor(),
                    # transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
                ]
            ),
        )

        IgnoreLabelDataset(cifar)

        print("Calculating Inception Score...")
        print(
            get_inception_score(
                IgnoreLabelDataset(cifar),
                cuda=True,
                batch_size=32,
                resize=True,
                splits=10,
            )[:-1]
        )


import random
import time

t0 = 1
t1 = 100
d = 1

a = [str(x) for x in range(t0,t1 + 1, d)]# a 为列表
b = []
nn = [0]
def choice(event):
	time.sleep(1)
	rm = random.choice(a)
	a.remove(rm)#无放回抽签
	b.append(rm)

	if ((len(b)-nn[0])%10 == 0):
		b.append('\n')
		nn[0] += 1
	bstr = ', '.join(b)
#随机输出数字
	ctn = wx.TextCtrl(win,-1,str(rm),pos = (95,225),size = (240, 160),style = (wx.TE_CENTER |wx.TE_READONLY))
	font = wx.Font(100,wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
	ctn.SetFont(font)

#已输出的
	dtn = wx.TextCtrl(win,-1,bstr,pos = (95,85),size = (240, 120),style = (wx.TE_LEFT |wx.TE_READONLY))
	font = wx.Font(15,wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
	dtn.SetFont(font)

#mac
#conda install python.app
#pythonw *.py

#linux
#conda install wxpython
#python *.py

import wx
app = wx.App()
win = wx.Frame(None, title = '抽奖器',size = (450,500))

win.Show()

btn = wx.Button(win, label = '抽奖', pos = (165,45), size = (80, 25))
btn.Bind(wx.EVT_BUTTON, choice)

codes = 'ctn = wx.TextCtrl(win,-1,"",pos = (95,225),size = (240, 160),style = (wx.TE_CENTER |wx.TE_READONLY));font = wx.Font(100,wx.DECORATIVE, wx.ITALIC, wx.NORMAL);ctn.SetFont(font)'
exec(codes)

codes = 'dtn = wx.TextCtrl(win,-1,"",pos = (95,85),size = (240, 120),style = (wx.TE_LEFT |wx.TE_READONLY));font = wx.Font(15,wx.DECORATIVE, wx.ITALIC, wx.NORMAL);dtn.SetFont(font)'
exec(codes)

app.MainLoop()


#-----------------------------------------------------------------
# Working with psycopg2
#-----------------------------------------------------------------

import psycopg2
import sys
from prettytable import PrettyTable

def heading(str):
    print('-'*60)
    print("** %s:" % (str,))
    print('-'*60, '\n')

SHOW_CMD = True
def print_cmd(cmd):
    if SHOW_CMD:
        print(cmd.decode('utf-8'))

def print_table(rows, columnsArray):
    table = PrettyTable(columnsArray)
    for row in rows:
        table.add_row(row)
    print(table)
    print()

#-----------------------------------------------------------------
# US1: As a Personal User, I want to create a post so that I can share my
# experiences with friends and family.
#-----------------------------------------------------------------
def show_US1_menu():
    heading("US1 - As a Personal User, I want \
    to create a post so that I can share my experiences with friends and family")

    post_type = "picture" # hardcode post type for demonstration
    caption = "yay!" # hardcode new caption for demonstration
    posted_by = 2 # hardcode posted by user id for demonstration
    US1(post_type=post_type, caption=caption, uid=posted_by)

def US1(post_type, caption, uid):
    tmpl = '''
        INSERT INTO Posts(type, caption, uid)
        VALUES (%s, %s, %s);
        SELECT type, caption, uid
        FROM Posts;
    '''
    cmd = cur.mogrify(tmpl, (post_type, caption, uid))
    print_cmd(cmd)
    cur.execute(cmd)
    rows = cur.fetchall()

    print_table(rows, ['type','caption','uid'])

    print("\nUS1: As a Personal User, I want to create a post so that I can share my experiences with friends and family.")
    print("\nDescription: This query is supposed to insert a new post created by a user into the Posts table. We insert the post type, caption and who it was posted by. The post_id is automatically generated since it is a serial type. In this way, the query enables users to share their experiences through posts.\n")

    # ^ Don't print rows unless we do a select

if __name__ == '__main__':
    try:
        # default database and user
        db, user = 'instagram', 'isdb'
        # you may have to adjust the user
        # python a4-socnet-sraja.py a4_socnet postgres
        if len(sys.argv) >= 2:
            db = sys.argv[1]
        if len(sys.argv) >= 3:
            user = sys.argv[2]
        # by assigning to conn and cur here they become
        # global variables.  Hence they are not passed
        # into the various SQL interface functions
        conn = psycopg2.connect(database=db, user=user)
        conn.autocommit = True
        cur = conn.cursor()

        show_US1_menu() #show user story 1 menu

    except psycopg2.Error as e:
        print("Unable to open connection: %s" % (e,))


from random import randint
from subprocess import call
import sys
from hexDictionary import hexIndex

def throwTheCoins():

    hexagram = [0,0,0,0,0,0]
    for i in reversed(range(len(hexagram))):
        toss = 0
        for x in range(0,3):
            toss = toss + randint(2,3)
        hexagram[i] = toss
    return hexagram

def movement(hexagram):

    moved = False
    newHexagram = hexagram
    for i,currentLine in enumerate(hexagram,start=0):
        if currentLine == 6:
            newHexagram[i] = 7
            moved = True
        elif currentLine == 9:
            newHexagram[i] = 8
            moved = True
    if moved:
        print('\nbecomes:\n')
        return newHexagram
    else:
        return moved

def drawTheHexagram(hexagram):

    if hexagram == False:
        return

    for i,currentLine in enumerate(hexagram,start=0):
        if currentLine == 6:
            print('--x--')
        elif currentLine == 7:
            print('-----')
        elif currentLine == 8:
            print('-- --')
        elif currentLine == 9:
            print('--o--')

    lookItUp(hexagram)

def lookItUp(hexagram):

    hexCode = 0

    for i in reversed(range(len(hexagram))):
        if (hexagram[i] == 7 or hexagram[i] == 9):
            hexCode = hexCode + (2**i)
    print('#',hexIndex[hexCode]['number'],' Name: ',hexIndex[hexCode]['name'])

def main():

    call('clear')
    hexagram = throwTheCoins()
    drawTheHexagram(hexagram)
    drawTheHexagram(movement(hexagram))

main()


#Python version 3.6.0
import random as r
from collections import defaultdict
#import numpy as np
#from copy import deepcopy

class HelperFunctions():
    def __init__(self):
        pass

    def kill_ship(self,strike_area):
        self.overall_p_density = self.calculate_strategy()
        while self.open_hits:   #keeps running until all found ships are sunk
            c = self.open_hits[0]
            x , y = c
            x_axis = []
            y_axis= []
            down_list = []
            up_list = []
            r_list = []
            l_list = []

            switch = [1,1,1,1]
            for i in range(1,10): #for the remaining length of the board
                down = (x,c[1]+i)
                up = (x,c[1]-i)
                right = (c[0]+i,y)
                left = (c[0]-i, y)

                #give a contiguous area where ships might be
                #this includes the strike area and self.open_hits
                open_hits_coordinates = list(self.open_hits)
                considered_area = strike_area + open_hits_coordinates

                if down in considered_area and switch[0] ==1:
                    down_list.append(down)
                else:
                    switch[0]=0
                if up in considered_area and switch[1] ==1:
                    up_list.append(up)
                else:
                    switch[1]=0
                if right in considered_area and switch[2] ==1:
                    r_list.append(right)
                else:
                    switch[2]=0
                if left in considered_area and switch[3] ==1:
                    l_list.append(left)
                else:
                    switch[3]=0
            #I am only using these memory addresses for identification for my greedy algorithm
            #Python is not meant to manipulate the memory so i am not doing that
            memory_locations = {}
            memory_locations[hex(id(r_list))] =  r_list#(1,0)
            memory_locations[hex(id(l_list))] = l_list#(-1,0)
            memory_locations[hex(id(up_list))] = up_list#(0,-1)
            memory_locations[hex(id(down_list))] = down_list#(0,1)

            #obtain the next available square for attack
            #for all directions by removing open hits
            adjustment_set = set() #to keep track of where the open hits are
            exit_condition = 0
            while exit_condition == 0:
                exit_condition = 1
                for i in memory_locations:
                    if len(memory_locations[i]) > 0:
                        if memory_locations[i][0] in self.open_hits:
                            memory_locations[i].pop(0)
                            adjustment_set.add(i)
                            exit_condition = 0

            #find the axes with adjacent open hits
            horizontal_adj = 0
            vertical_adj = 0
            for i in adjustment_set:
                if i in [hex(id(r_list)),hex(id(l_list))]:
                    horizontal_adj = 100
                if i in [hex(id(up_list)),hex(id(down_list))]:
                    vertical_adj = 100

            #obtain the probability densities
            try:
                right_val = self.overall_p_density[r_list[0]]
            except:
                right_val = 0
            try:
                left_val = self.overall_p_density[l_list[0]]
            except:
                left_val=0
            try:
                up_val = self.overall_p_density[up_list[0]]
            except:
                up_val=0
            try:
                down_val = self.overall_p_density[down_list[0]]
            except:
                down_val = 0

            #the preferred axis has adjacent open hits
            if left_val > 0:
                left_val = left_val + horizontal_adj
            if right_val > 0:
                right_val = right_val + horizontal_adj
            if up_val > 0:
                up_val = up_val + vertical_adj
            if down_val > 0:
                down_val = down_val + vertical_adj

            #Select an axis
            if (right_val + left_val) > (up_val + down_val):
                axis=[r_list,l_list]
            elif (right_val + left_val) < (up_val + down_val):
                axis=[up_list,down_list]
            else:
                axis=r.choice([[up_list,down_list],[r_list,l_list]])
            #process the selected axis
            strike_area = self.process_axis(c,axis,strike_area)
        return strike_area

    def process_axis(self,c,axis, strike_area):
        current_hits=[c]
        visited_directions =set()
        while (len(axis[0]) + len(axis[1])) > 0:
            current_list = self.maxchoice(axis[0],axis[1])   #current_list is a reference to the original list
            if current_list == "skip":
                #probability for both directions is zero
                #return to open hits loop
                break
            visited_directions.add(hex(id(current_list)))
            attack1 = current_list.pop(0)
            self.board[attack1[0]][attack1[1]].struck =1
            self.strike_summary.append(attack1)
            strike_area.remove(attack1)

            #In the event of a hit
            if self.board[attack1[0]][attack1[1]].occupied ==1:
                current_hits.append(attack1)
                self.open_hits.append(attack1)
                #ship updating
                for i in self.ships:
                    if i.sunk==1:
                        continue
                    new_sunk = i.update(self.board)
                    if new_sunk == 1:
                        self.ships_count = self.ships_count - 1
                        for j in i.location:
                            self.board[j[0]][j[1]].shipsunk = 1
                            try:
                                current_hits.remove((j[0],j[1]))
                            except:
                                pass
                            try:
                                self.open_hits.remove((j[0],j[1]))
                            except:
                                pass
                        #empty out this direction
                        del current_list[:] #empty out original and reference list
                        #switch to opposite list
                        if hex(id(current_list)) ==hex(id(axis[0])):
                            current_list = axis[1]
                        else:
                            current_list = axis[0]
                        if len(current_hits) <2:  #back to open hits loop if another ship is not suspected
                            del current_list[:]
                        break
             #in the event of a miss
            else:
                del current_list[:]
            #recalculating strategy after every strike
            self.overall_p_density = self.calculate_strategy()
            #end of axis loop
        return strike_area

    def maxchoice(self, list1, list2):
        try:
            a = self.overall_p_density[list1[0]]
        except:
            a = 0
        try:
            b = self.overall_p_density[list2[0]]
        except:
            b=0
        if a>b:
            return list1
        if a<b:
            return list2
        if b + a == 0:
        #no hit possible so return to the open hits loop
            return "skip"
        if b == a:
            return r.choice([list1,list2])

    def minmax_ships(self):
        ship_lengths = []
        minimum_ship_length = 0
        maximum_ship_length = 0
        for i in self.ships:
            if i.sunk == 0:
                ship_lengths.append(i.length)
        if ship_lengths:
            minimum_ship_length = min(ship_lengths)
            maximum_ship_length = max(ship_lengths)
        return minimum_ship_length, maximum_ship_length, ship_lengths

    #compute strategy based on the probability density method
    def calculate_strategy(self):
        '''output: probability density'''
        min_ship_length, max_ship_length, available_ships = self.minmax_ships()
        densities = []
        for length in available_ships:
            open_slots,probability_density = self.list_possibilities(length, mode =1)
            densities.append(probability_density)
        overall_p_density = defaultdict(int)
        for i in densities:
            for k in i:
                overall_p_density[k] = overall_p_density[k] + i[k]
        return overall_p_density