# -*- coding: utf-8 -*-
# @Time    : 2020/11/11 10:59
# @Author  : zxl
# @FileName: prepare_lessr.py

import os

"""
将数据集处理为LESSR模型所需要的的输入
"""

def deal_data(inpath, out_path, max_len):

    w = open(out_path,'w')

    item_set = set()

    with open(inpath,'r') as f:
        for l in f:
            example = eval(l)
            item_set=item_set.union(set(example[1]))

            s = ','.join([str(x) for x in example[1]])

            w.write(s+'\n')

    w.close()
    return item_set

if __name__ =="__main__":

    in_dir = "/home/zxl/project/MTAM-t2/data/training_testing_data_copy_11_10/"
    out_dir = "/home/zxl/project/MTAM-t2/data/training_testing_data_lessr/"

    for filename in os.listdir(in_dir):
    # for filename in ['taobaoapp_time_item_based_unidirection']:

        in_train_test_root = in_dir+filename+'/'

        data_name  = filename[:-29]

        out_train_test_root = out_dir+data_name+'/'

        if not os.path.exists(out_train_test_root):
            os.makedirs(out_train_test_root)

        all_item_set = set()

        for train_test_file in ['train_data.txt','test_data.txt','dev_data.txt']:
        # for train_test_file in [  'dev_data.txt']:
            in_file_path = in_train_test_root+train_test_file

            out_file_path = out_train_test_root + train_test_file.split('_')[0]+'.txt'

            if 'train' in train_test_file:
                max_len = 10000000
            else:
                max_len = 20000

            single_item_set = deal_data(in_file_path,out_file_path,max_len)
            all_item_set=all_item_set.union(single_item_set)

        out_num_file = out_train_test_root+'num_items.txt'
        with open(out_num_file,'w') as w:
            w.write(str(len(all_item_set))+'\n')


import json
import shutil
from typing import Annotated
import uuid
from bson import ObjectId
from fastapi import Depends, Form, HTTPException, Query, UploadFile
from pymongo import MongoClient
from config.settings import Settings
from helpers.upload_image_helper import uploadImage
from models.movie import Movie
from models.responses.movie_response import MovieResponse

from schemas.movie_schema import movie_serializer, movies_serializer

class MovieRepository:

    def __init__(self):
        self.appSettings  = Settings()
        self.client = MongoClient(self.appSettings.mongoClient)
        self.db = self.client['theater']
        self.collection = self.db["movie"]

    def create_collection_if_not_exists(self, collection_name: str):

        if collection_name not in self.db.list_collection_names():
            self.db.create_collection(collection_name)

    def getMovieById(self, movieId:str):
        movie = self.collection.find({"_id": ObjectId(movieId)})
        return movies_serializer(movie)

    def createMovie(self,Title: Annotated[str, Form()],
        Year: Annotated[str, Form()],
        Runtime: Annotated[str, Form()],
        Genre: Annotated[str, Form()],
        Director: Annotated[str, Form()],
        Writer: Annotated[str, Form()],
        Actors: Annotated[str, Form()],
        Poster: UploadFile,
        Plot: Annotated[str, Form()],
        Language: Annotated[str, Form()],
        Type: Annotated[str, Form()]):

        self.create_collection_if_not_exists(collection_name="movie")
        uploadedImagePath = uploadImage(Poster)

        movie = Movie(
            Title=Title,Year=Year, Runtime=Runtime, Genre=Genre,Director=Director, Writer=Writer,Actors=Actors, Plot=Plot,Poster=uploadedImagePath, Language=Language, Type=Type
        )
        insertedMovie = self.collection.insert_one(dict(movie))
        return MovieResponse(movieId= str(insertedMovie.inserted_id), status ="Success")

    def searchMovieFromDB(self, title:str, year: str,):
        movies = movies_serializer(self.collection.find({"Title":title, "Year": year,}))
        return movies


# Routine to grab Lowell Instrument data from AWS
# Original version by Carles w/some additions by JiM in Fall 2021
#
# Nov 2021 - JiM added GPS file grabbing
#
# WARNING:
# This gets hungup for some reason in Spyder.  I need to run it from a command line.

import boto3
import sys
import os
import pandas as pd
import csv
import io
from io import StringIO
from matplotlib import pyplot as plt

## HARDCODES ###
scale_dep=1.0 # scale factor where originally it looked like I needed to devide by scale_dep=10.0
min_depth=15.0/scale_dep # minimum depth (meters) acceptable for a cast
mac='00-1e-c0-6c-74-f1/' # Mary Elizabeth
vessel='Mary Elizabeth'
#mac='00-1e-c0-6c-75-1d/' # Beast of Burden
# eMOLT credentials
access_key = ''
access_pwd = ''

s3_bucket_name = 'bkt-cfa'  # bucket name
path = 'aws_files/'  # path to store the data

"""Accessing the S3 buckets using boto3 client"""
s3_client = boto3.client('s3')
s3 = boto3.resource('s3',
                    aws_access_key_id=access_key,
                    aws_secret_access_key=access_pwd)

""" Getting data files from the AWS S3 bucket as denoted above """
my_bucket = s3.Bucket(s3_bucket_name)
bucket_list = []
#for file in my_bucket.objects.filter(Prefix='00-1e-c0-6c-74-f1/'):  # write the subdirectory name
for file in my_bucket.objects.filter(Prefix=mac):  # write the subdirectory name mac add
    file_name = file.key
    if (file_name.find(".csv") != -1) or (file_name.find(".gps") != -1): # JiM added gps
        bucket_list.append(file.key)
length_bucket_list = (len(bucket_list))

# l_downloaded = os.listdir(path + 'WR_54/data') + os.listdir(path + 'WR_57/data')
# bucket_list = [e for e in bucket_list if e not in l_downloaded]
#
# """ Reading the individual files from the AWS S3 buckets and putting them in dataframes """
#
ldf_pressure = []  # Initializing empty list of dataframes
ldf_temperature = []
ldf_gps =[]

for file in bucket_list:
    obj = s3.Object(s3_bucket_name, file)
    data = obj.get()['Body'].read()
    try:
        if 'Temperature' in os.path.basename(file):
            df = pd.read_csv(io.BytesIO(data), header=0, delimiter=",", low_memory=False)
            ldf_temperature.append(df)
        elif 'Pressure' in os.path.basename(file):
            df = pd.read_csv(io.BytesIO(data), header=0, delimiter=",", low_memory=False)
            ldf_pressure.append(df)
        elif 'gps' in os.path.basename(file):
            df = pd.read_csv(io.BytesIO(data), header=0, delimiter=",", low_memory=False) # need to read this differently
            ldf_gps.append(df)
    except:
        print('Not working', file)

#print(ldf_pressure, ldf_temperature,ldf_gps) # these are lists of dataframes
# merging the dataframes

filenames = [i for i in bucket_list  if 'gps' in i] # where bucket_list is 3 times as many elements as filenames
for j in range(len(ldf_gps)):
    if max(ldf_pressure[j]['Pressure (dbar)']/scale_dep)>min_depth: # only process those that were submergedmore than 2 meters
        lat=ldf_gps[j].columns[0].split(' ')[1]# picks up the "column name" of an empty dataframe read by read_csv
        lon=ldf_gps[j].columns[0].split(' ')[2]
        ldf_temperature[j]['ISO 8601 Time']=pd.to_datetime(ldf_temperature[j]['ISO 8601 Time'])
        df=ldf_temperature[j].set_index('ISO 8601 Time')
        df['depth (m)']=ldf_pressure[j]['Pressure (dbar)'].values/scale_dep
        df['lat']=lat
        df['lon']=lon
        df.to_csv('aws_files/'+filenames[j][18:-4]+'.csv') # here is where we generate the merged file
        fig=plt.figure(figsize=(8,5))
        ax = fig.add_subplot(211)
        ax.plot(df.index,df['Temperature (C)'],color='r')
        ax.set_ylim(min(df['Temperature (C)'].values),max(df['Temperature (C)'].values))
        TF=df['Temperature (C)'].values*1.8+32 # temp in farenheit
        ax.set_ylabel('degC')
        ax2=ax.twinx()
        ax2.set_ylim(min(TF),max(TF))
        ax2.plot(df.index,TF,color='r')
        ax2.set_ylabel('fahrenheit')
        #ax.xaxis.set_major_formatter(dates.DateFormatter('%M'))
        plt.title(vessel+' at '+str(lat[:-3])+'N, '+str(lon[:-3])+'W')# where we ignore the last 3 digits of lat/lon
        ax3 = fig.add_subplot(212)
        ax3.plot(df.index,-1*df['depth (m)'])
        ax3.set_ylabel('meters')
        DF=-1*df['depth (m)']/1.8288
        ax4=ax3.twinx()
        ax4.set_ylim(min(DF),max(DF))
        ax4.plot(df.index,TF,color='b')
        ax4.set_ylabel('fathoms')
        fig.autofmt_xdate()
        plt.savefig('aws_plots/'+filenames[j][18:-4]+'.png')
        #plt.close('all')


import sys

for line in sys.stdin:
    n = int(line.strip())
    if n == 0:
        break
    carne = []
    for i in range(n):
        line = input().strip().split()
        carne.append((line[0], int(line[1])))
    carne.sort(key=lambda x: x[1])
    print(" ".join([x[0] for x in carne]))


import tensorflow as tf
import numpy as np
import scipy.io as sio

with tf.variable_scope("read_data"):

	def load_data():
		'''
		Loads data from .mat file. For debugging dataset, substitute file
		and mat_contents for 'subset_depthdata.mat' and 'sub_' respectively.

		Full data:
		- 'depth_datasetNYUv2.mat', 'images', 'depths'

		Returns:
			- images [no_images = 1449,height = 480, width = 640, channels = 3]
			- depth_maps [no_images = 1449,height = 480, width = 640]

		Comments:
		'''
		mat_contents = sio.loadmat('subset_depthdata.mat')

		images = mat_contents['sub_images']
		depth_maps = mat_contents['sub_depths']

		images = np.moveaxis(images, -1, 0)
		depth_maps = np.moveaxis(depth_maps, -1, 0)

		#images = np.moveaxis(images, 1, 2)
		#depth_maps = np.moveaxis(depth_maps, 1, 2)
		# scipy.misc.imresize()

		assert images.shape[0] == depth_maps.shape[0]

		return images, depth_maps

	def split_data(images, labels):
		'''
		Splits data in three partitions: training_(images+labels),
		test_(images+labels), validation_(images+labels)

		Returns:
			- training_images
			- training_labels
			- test_images
			- test_labels
			- validation_images
			- validation_labels
		'''
		no_images = images.shape[0]
		val_or_test_partition = (no_images // 5)
		end_of_training_partition = no_images - 2* val_or_test_partition

		a = end_of_training_partition
		b = end_of_training_partition + val_or_test_partition

		[training_images, test_images, validation_images] = np.split(images, [a, b], axis = 0)

		[training_labels, test_labels, validation_labels] = np.split(labels, [a, b], axis = 0)

		return training_images, training_labels, test_images, test_labels, validation_images, validation_labels

	def generate_dataset(images, labels):
		'''
		Generates a dataset from placeholders, resizes pictures and returns
		dataset and placeholders.
		'''
		images_placeholder = tf.placeholder(images.dtype, shape = [None, 480, 640, 3])
		labels_placeholder = tf.placeholder(labels.dtype, shape = [None, 480, 640])
		batch_size_placeholder = tf.placeholder(tf.int64, ())
		dataset = tf.data.Dataset.from_tensor_slices((images_placeholder, labels_placeholder)).batch(batch_size_placeholder).repeat()

		dataset = dataset.map(_resizing_function)

		return dataset, images_placeholder, labels_placeholder, batch_size_placeholder

	def _resizing_function(image,label):
		label = label[..., np.newaxis]
		resized_image = tf.image.resize_images(image, [223, 303])
		resized_label = tf.image.resize_images(label, [55, 74])

		return resized_image,resized_label

	# Load all data
	rgb_images, depth_maps = load_data()
	training_images, training_labels, test_images, test_labels, validation_images, validation_labels = split_data(rgb_images, depth_maps)

	# Ugly-getters
	def get_data(images = training_images, labels = training_labels):
		return images, labels

	def get_validation_data(images = validation_images, labels = validation_labels):
		return images, labels

	def get_test_data(images = test_images, labels = test_labels):
		return images, labels

	'''Approach: one dataset, feed different arrays:
	'''
	dataset, images_placeholder, labels_placeholder, batch_size_placeholder = generate_dataset(training_images, training_labels)
	iterator = dataset.make_initializable_iterator()
	(image_batch, depthmap_batch) = iterator.get_next()
	batch_size = 4

	'''Approach: three datasets, re-initializable iterator
	'''
	'''Create datasets and placeholders '''
	'''training_dataset = generate_dataset(training_images, training_labels)
	test_dataset = generate_dataset(test_images, test_labels)
	validation_dataset = generate_dataset(validation_images, validation_labels)
	'''

	''' Debuggers
	call_shape = print(iterator.output_shapes)

	feed = {images_placeholder : training_images,
			labels_placeholder : training_labels,
			batch_size_placeholder : batch_size}

	with tf.Session() as sess:
		sess.run(iterator.initializer, feed_dict = feed)
		sess.run(iterator.get_next())

	'''


import math
import decimal

root5 = decimal.Decimal(5).sqrt()
phi1 = (1+root5)/2
phi2 = (1-root5)/2

n = 1
while True:
    print(n)
    print(math.floor((math.pow(phi1, n)-math.pow(phi2, n))/root5))
    n += 1


from __future__ import annotations

from typing import Callable, Optional, Sequence, TypeVar

ArgumentT = TypeVar("ArgumentT")

def find_if(
    collection: Sequence[ArgumentT], condition: Callable[[ArgumentT], bool]
) -> Optional[ArgumentT]:
    for element in collection:
        if condition(element):
            return element

    return None


# 알고리즘 수업 - 피보나치 수 1
def fibo(n):
    global cnt1
    if n == 1:
        cnt1 = n
    elif n == 2:
        cnt1 = n
    else:
        cnt1 += 1
        return fibo(n-1) + fibo(n-2)

def fibo2(n):
    global cnt2
    f = [1]*(n+1)
    if n == 1:
        cnt2 = n
        return 1
    elif n == 2:
        cnt2 = n
        return 1
    else:
        for i in range(3, n+1):
            f[i] = f[i-1] + f[i-2]
            cnt2 += 1
    return f[n]

T = int(input())
cnt1 = 2
cnt2 = 2
fibo(T)
fibo2(T)
print(cnt1, cnt2)


import sys
import time
import signal
import threading
import numpy as np
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QLabel, QApplication, QVBoxLayout, QGridLayout
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pyqtgraph as pg
sys.path.append("..")
from Modules import Module, Analyzer

class ParameterPlotter(Analyzer):
    def __init__(self, id=None, autoMove=True, standalone=False, stepMode=False):
        super().__init__(id)

        self.parameterInputs.append({"name": "input", "module": None, "sourceIndex": 0, "default": 0.0})
        self.parameterInputs.append({"name": "input", "module": None, "sourceIndex": 0, "default": 0.0})
        self.parameterInputs.append({"name": "input", "module": None, "sourceIndex": 0, "default": 0.0})
        self.parameterInputs.append({"name": "input", "module": None, "sourceIndex": 0, "default": 0.0})

        self.autoMove = autoMove
        self.standalone = standalone
        self.stepMode = stepMode
        self.standaloneT = 0
        self.updateFunction = None

        self.maxSampleTime = 60 * 5          # [s]
        self.maxTimeWidth = 5                # [s]
        self.manualControlTime = 5           # [s]
        self.x = []
        self.y = [[], [], [], []]
        self.yMin = -1.0
        self.yMax = 1.0
        self.running = False
        self.ready = False
        self.legendAdded = [False] * 4

        if self.standalone:
            def signal_handler(sig, frame):
                self.running = False
                self.widget.graphWidget.close()

            signal.signal(signal.SIGINT, signal_handler)
            threading.Thread(target=self.run, args=(self, )).start()
            while not self.running:
                time.sleep(0.1)

        else:
            self.widget = MainWindow(stepMode=self.stepMode)
            self.app = QtWidgets.QApplication(sys.argv)
            threading.Thread(target=self.app.exec_).start()
            self.widget.show()

    def stop(self):
        self.running = False
        self.widget.close()

    def run(self, ref):
        ref.app = QtWidgets.QApplication(sys.argv)
        ref.widget = MainWindow(stepMode=self.stepMode)
        ref.widget.show()

        self.running = True
        setattr(ref, "app", ref.app)
        setattr(ref, "widget", ref.widget)

        if ref.standalone:
            ref.timer = QTimer()
            ref.timer.timeout.connect(ref.standaloneUpdate)
            ref.timer.start(int(1000 / Module.framerate))

        while ref.widget.graphWidget.isVisible():
            ref.app.processEvents()
        ref.widget.close()
        ref.app.quit()

    def isRunning(self):
        return self.widget.graphWidget.isVisible()

    def isReady(self):
        return self.ready

    def update(self, t):
        if(Module.framerate == 0):
            return False
        self.ready = True
        if self.standalone:
            while not any(self.parameterInputs):
                print("waiting")
                time.sleep(0.1)
        if not super().update(t):
            return False

        if any([i["module"] for i in self.parameterInputs]):    # Check if any input is connected to module
            self.widget.setWindowTitle(f"Parameter Plotter [{self.id}]")
        else:
            self.widget.setWindowTitle(f"Parameter Plotter [{self.id}]: Unconnected")
            return True

        for i in range(len(self.widget.data_line)):
            if not self.parameterInputs[i]["module"]:
                continue

            if not self.legendAdded[i]:
                self.legendAdded[i] = True
                module = self.parameterInputs[i]
                moduleName = f"{module['module'].superClassType}.{module['module'].__module__}"
                self.widget.legend.plotItem.legend.addItem(self.widget.legendItem[i], f"{moduleName} [{module['module'].id}] (Output: {module['sourceIndex']})")

            output = self._getParameterValue(i)
            self.yMin = min(self.yMin, output)
            self.yMax = max(self.yMax, output)
            if t not in self.x:
                self.x.append(t)
            self.y[i].append(output)

            maxSamples = int(self.maxSampleTime * Module.framerate)
            if(len(self.y[i]) > maxSamples):
                self.x = self.x[-maxSamples:]
            self.y[i] = self.y[i][-len(self.x):]

            self.widget.plotItem.setYRange(self.yMin * 1.2, self.yMax * 1.2, padding=0)
            if(time.time() - self.widget.graphWidget.mouseEventTime > self.manualControlTime) and self.autoMove:
                self.widget.plotItem.setXRange(max(0, t - self.maxTimeWidth), t, padding=0)

            if(len(self.x) > 2):
                self.widget.data_line[i].setData(self.x, self.y[i])
        return True

    def standaloneUpdate(self):
        if not self.running:
            return
        self.standaloneT += 1 / Module.framerate
        if not self.isReady():      # Start time increment only when analyzer is ready
            self.standaloneT = 0
        if self.updateFunction:
            try:
                self.updateFunction(self.standaloneT)
            except Exception as e:
                self.end()
                print(e)

class MainPlotWidget(pg.PlotWidget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.mouseEventTime = 0
        self.isClicked = False

    def wheelEvent(self,event):
        super().wheelEvent(event)
        self.mouseEventTime = time.time()

    def mouseReleaseEvent(self, event):
        super().mouseReleaseEvent(event)
        self.mouseEventTime = time.time()
        self.isClicked = False

    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        self.mouseEventTime = time.time()
        self.isClicked = True

    def mouseMoveEvent(self, event):
        super().mouseMoveEvent(event)
        if self.isClicked:
            self.mouseEventTime = time.time()

class CustomLegend(pg.PlotWidget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def wheelEvent(self,event): pass
    def mouseReleaseEvent(self, event): pass
    def mousePressEvent(self, event): pass
    def mouseMoveEvent(self, event): pass

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, *args, **kwargs):
        self.plotMode = "right" if kwargs.pop("stepMode", None) else None
        super(MainWindow, self).__init__(*args, **kwargs)
        self.widget = QWidget()
        self.widget.setStyleSheet('background-color: #212124')

        self.graphWidget = MainPlotWidget()
        self.setCentralWidget(self.graphWidget)
        self.setGeometry(300, 300, 700, 500)
        self.graphWidget.setBackground('#212124')
        self.plotItem = self.graphWidget.getPlotItem()
        self.plotItem.showGrid(x=True, y=True, alpha=0.3)
        self.plotItem.getAxis('bottom').setGrid(False)             # Disable bottom axis grid, prevent bus as noted here: https://stackoverflow.com/questions/69816567/pyqtgraph-cuts-off-tick-labels-if-showgrid-is-called
        self.plotItem.showAxis('top')                              # Show top/right axis (and grid, since enabled here)
        self.plotItem.getAxis('top').setStyle(showValues=False)    # Hide tick labels on top/right
        self.plotItem.setMouseEnabled(x=True, y=False)
        self.plotItem.hideButtons()

        self.pen = [pg.mkPen(color=(0, 142, 211), width=3),
                    pg.mkPen(color=(211, 105, 0), width=3),
                    pg.mkPen(color=(211, 0, 172), width=3),
                    pg.mkPen(color=(0, 211, 18), width=3)]

        self.data_line = [self.graphWidget.plot([0, 0], [0, 0], pen=self.pen[0], stepMode=self.plotMode),
                          self.graphWidget.plot([0, 0], [0, 0], pen=self.pen[1], stepMode=self.plotMode),
                          self.graphWidget.plot([0, 0], [0, 0], pen=self.pen[2], stepMode=self.plotMode),
                          self.graphWidget.plot([0, 0], [0, 0], pen=self.pen[3], stepMode=self.plotMode)]

        self.legendItem = [pg.LegendItem(pen=self.pen[0]),
                           pg.LegendItem(pen=self.pen[1]),
                           pg.LegendItem(pen=self.pen[2]),
                           pg.LegendItem(pen=self.pen[3])]

        self.legend = CustomLegend()
        self.legend.setBackground('#212124')
        self.legend.setMouseEnabled(x=False, y=False)
        self.legend.hideButtons()
        self.legend.setMaximumHeight(45)
        self.legend.hideAxis('left')
        self.legend.hideAxis('bottom')
        self.legend.addLegend()
        self.legend.plotItem.legend.setColumnCount(2)
        self.legend.plotItem.legend.anchor((-0.05, 0.15), (0.0, 0.0))

        self.layout = QVBoxLayout()
        self.widget.setLayout(self.layout)
        self.layout.addWidget(self.graphWidget)
        self.layout.addWidget(self.legend)
        self.setCentralWidget(self.widget)

    def closeEvent(self, event):
        event.accept()

if __name__ == '__main__':
    from Modules import Coefficient, Generator, Analyzer
    Module.framerate = 60

    enable = 1.0
    freq = 1
    rep = 1
    amp = 0.5
    offset = 0.5
    phase = 0

    sine = Generator.Sine(0)
    sine.setParameterInput(0, Coefficient(1000, enable))
    sine.setParameterInput(1, Coefficient(1001, freq))
    sine.setParameterInput(2, Coefficient(1002, rep))
    sine.setParameterInput(3, Coefficient(1003, amp))
    sine.setParameterInput(4, Coefficient(1004, offset))
    sine.setParameterInput(5, Coefficient(1005, phase))

    ramp = Generator.Ramp(1)
    rect = Generator.Rect(2)
    triangle = Generator.Triangle(3)

    plotter = Analyzer.ParameterPlotter(5000, standalone=True, stepMode=False)
    plotter.setParameterInput(0, sine, 0)
    plotter.setParameterInput(1, ramp, 0)
    plotter.setParameterInput(2, rect, 0)
    plotter.setParameterInput(3, triangle, 0)

    def update(t):
        sine.update(t)
        ramp.update(t)
        rect.update(t)
        triangle.update(t)
        plotter.update(t)

    plotter.updateFunction = update
    while not plotter.isReady(): pass    # Wait until plotter is ready
    while plotter.isRunning():
        time.sleep(0.1)


#Udemy Course Work - Lottery App

#Import the random class
import random

def menu():
    """Controlling method that
    1. Ask players for numbers
    2. Calculate the lottery numbers
    3. Print out the winnings
    """
    players_numbers = get_players_numbers()
    lottery_numbers = create_lottery_numbers()
    if len(players_numbers.intersection(lottery_numbers)) == 1:
        print("Congratulations, you have won 10 Euro!!!")
    elif len(players_numbers.intersection(lottery_numbers)) == 2:
        print("Congratulations, you have won 20 Euro!!!")
    elif len(players_numbers.intersection(lottery_numbers)) == 3:
        print("Congratulations, you have won 30 Euro!!!")
    elif len(players_numbers.intersection(lottery_numbers)) == 4:
        print("Congratulations, you have won 40 Euro!!!")
    elif len(players_numbers.intersection(lottery_numbers)) == 5:
        print("Congratulations, you have won 50 Euro!!!")
    elif len(players_numbers.intersection(lottery_numbers)) == 6:
        print("Congratulations, you have won it all!!!")
    else:
        print("Sorry, you have won nothing!!!")

#Get the Lottery numbers
def get_players_numbers():
    numbers = str( raw_input("Enter the numbers separated by commas: "))
    #Now split the string into a list using the string split method
    numbers_in_list=numbers.split(",")
    #Now get a set of numbers instead of list of string by using set comprehension, same as list just returns a set.
    numbers_in_set={int(x) for x in numbers_in_list}
    #Now return a set from the invoking call
    return numbers_in_set

#Lottery calaculates 6 random nubers
def create_lottery_numbers():
    lottery_num=set()
    for x in range(6):
        lottery_num.add(random.randint(1,100)) #Prints a random number between 1 and 100
    return lottery_num

if __name__ == "__main__":
    menu()


# # 함수
# def open_account():
#     print("새로운 계좌가 생성되었습니다.")

# # open_account() # 함수 정의를 해줘야 print문이 실행됨

# def deposit(balance, money): # 입금
#     print("입금이 완료되었습니다. 잔액은 {0}원 입니다.".format(balance + money))
#     return balance + money

# def withdraw(balance, money):
#     if balance >= money: # 잔액이 출금액보다 많으면
#         print("출금이 완료되었습니다. 잔액은 {0}원 입니다.".format(balance - money))
#         return balance - money
#     else:
#         print("출금이 완료되지 않았습니다. 잔액은 {0}원 입니다.".format(balance))
#         return balance

# def withdraw_night(balance, money): # 저녁에 출금
#     commission = 100 # 수수료 100원
#     return commission, balance -money - commission

# balance = 0 # 잔액
# balance = deposit(balance, 1000)
# # balance = withdraw(balance, 500)
# commission, balance = withdraw_night(balance, 500)
# print("수수료는 {0}원이며, 잔액은 {1}원 입니다.".format(commission, balance))

# def profile(name, age, lang):
#     print("이름 : {0}, 나이 : {1}살, 언어: {2}".format(name, age, lang))

# profile("유재석", 20, "자바")

# 기본값 지정
# def profile(name, age=17, lang="파이썬"):
#     print("이름 : {0}, 나이 : {1}살, 언어: {2}".format(name, age, lang))

# profile("유재석")

# 가변 인자

# def profile(name, age, lang1, lang2, lang3, lang4, lang5):
#     print("이름 {0}, 나이 {1}".format(name, age), end=" ")
#     print(lang1, lang2, lang3, lang4, lang5)

# def profile(name, age, *language):
#     print("이름 {0}, 나이 {1}".format(name, age), end=" ")
#     for lang in language:
#         print(lang, end=" ")
#     print()

# profile("유재석", 20, "python", "java", "go", "c", "c+", "js")
# profile("김태호", 20, "python", "java", "go")

# 지역변수 : 함수 내에서만 사용 가능 호출 끝나면 사라짐, 전역변수 : 모든 공간에서 부를수 있음
gun = 10

def checkpoint(soldiers):
    global gun # 전역 공간에 있는 gun 사용 , 자주 사용안됨
    gun = gun - soldiers
    print("[함수 내] 남은총 : {0}".format(gun))

def checkpoint_ret(gun, soldiers):
    gun = gun - soldiers
    print("[함수 내] 남은총 : {0}".format(gun))
    return gun

print("전체 총 : {0}".format(gun))
# checkpoint(2)
gun = checkpoint_ret(gun, 2)
print("남은 총 : {0}".format(gun))


class TreeNode:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class Tree:
    def __init__(self):
        self.root = None

    def add_node(self, value):
        if self.root is None:
            self.root = TreeNode(value)
        else:
            self._add_node(value, self.root)

    def _add_node(self, value, node):
        if value < node.value:
            if node.left is not None:
                self._add_node(value, node.left)
            else:
                node.left = TreeNode(value)
        else:
            if node.right is not None:
                self._add_node(value, node.right)
            else:
                node.right = TreeNode(value)

    def find_min(self):
        if self.root is None:
            return None
        else:
            return self._find_min(self.root)

    def _find_min(self, node):
        if node.left is None:
            return node.value
        else:
            return self._find_min(node.left)

    def find_max(self):
        if self.root is None:
            return None
        else:
            return self._find_max(self.root)

    def _find_max(self, node):
        if node.right is None:
            return node.value
        else:
            return self._find_max(node.right)


from block.models import Block

from django.contrib.auth.models import User
from django.shortcuts import render
from django.shortcuts import redirect
from .models import Article
from .forms import ArticleForm

from comment.models import Comment
from django.views.generic import View
from django.views.generic import DeleteView
from django.views.generic import DetailView

from .paginate import paginate_queryset

def article_list(request,block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    page_no = int(request.GET.get("page_no","1"))
    all_articles = Article.objects.filter(block=block,status=0).order_by("-id")

    ###页面上需要分布的变量
    page_articles,paginate_data = paginate_queryset(all_articles,page_no)

    return render(request,"article_list.html",{"articles":page_articles,"b":block,"paginate_data":paginate_data})

ARTICLE_CNT_1PAGE = 3     ##定义每页显示多少
def article_list_v1(request,block_id):
    block_id = int(block_id)
    block = Block.objects.get(id=block_id)
    #article_objs = Article.objects.filter(block=block,status=0).order_by("-id")
    ##实现分布 需要的变更
    page_no = int(request.GET.get("page_no","1"))   ##当前页码 ，如果没有相应参数，默认给出1
    start_index = (page_no-1) * ARTICLE_CNT_1PAGE   ##当前页数据的起始索引
    end_index = page_no * ARTICLE_CNT_1PAGE         ##当前页数据的结束索引

    all_articles = Article.objects.filter(block=block,status=0).order_by("-id")
    p = Paginator(all_articles,ARTICLE_CNT_1PAGE)
    page = p.page(page_no)
    articles = page.object_list

    ###页面上需要分布的变量
    page_nums = p.num_pages  #总页数
    page_links = [i for i in range(page_no-3,page_no+4) if i>0 and i<=page_nums]  ##标页列表
    page_first = page_links[0]-1   ###标页列表最小页
    page_max = page_links[-1]-1    ###标页列表最大页
    print("page_nums.type:",type(page_nums))
    #page_next = page_max <= page_nums    ###是否有后一页
    #page_pre = page_first > 0 ###是否有前一页

    ##上边看起来像是判断对象相等，其实是django包装了，底层是判断id比对
    ##所以，也可以写成filter(block__id=block_id)
    ## fileter(block=block,status=0)  表示 where block=? and status=?
    ## 如果想表达或，需要使用Q对象,每个Q表示一个条件，用|表示或，from django.db.models import Q
    ## filter(Q(block=block)|Q(status=0)|Q(x=y))

    return render(request,"article_list.html",{"articles":articles,"b":block,"page_nums":page_nums,"page_links":page_links,"page_first":page_first,"page_max":page_max,"page_no":page_no,"page_next":page_no+1,"page_pre":page_no-1})

#基于函数实现的处理逻辑：简单快速、但是长期看面临迁移到类

def publish_article(request,b_id):
    b_id = int(b_id)
    block = Block.objects.get(id=b_id)
    if request.method=="GET":
        return render(request,"publish_article.html",{"bol":block})
    else:
        #第一种判断语句写法
        #title = request.POST["title"].strip()
        #content = request.POST["content"].strip()
        #if not title or not content:
        #    return render(request,"publish_article.html",{"bol":block,"error":"标题或内容不能为空","title":title,"content":content})
        #if len(title)>100 or len(content)>10000:
        #    return render(request,"publish_article.html",{"bol":block,"error":"标题或内容过长","title":title,"content":content})
        #else:
        #    article = Article(block=block,title=form.cleaned_data["title"],content=form.cleaned_data["content"],status=0)
        #    article.save()

        #第二种写法：把判断语句 抽出来到forms.py 里
        #form = ArticleForm(request.POST)
        #if form.is_valid():
        #    article = Article(block=block,title=form.cleaned_data["title"],content=form.cleaned_data["content"],status=0)
        #    article.save()
        #    return redirect("/article/list/%s" % b_id)
        #else:
        #    print(form.errors)
        #    return render(request,"publish_article.html",{"bol":block,"form":form})

        #第三种写法：整合,先用form.save提交form中的信息，保存在内存中
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.block = block
            article.status=0
            article.save()
            return redirect("/article/list/%s" % b_id)
        else:
            return render(request,"publish_article.html",{"bol":block,"form":form})

#基于类实现处理逻辑，相对复杂，可以使用高级的设计模式
class ArticleCreate(View):
    template_name="publish_article.html"

    def init_data(self,block_id):
        self.block_id = block_id
        self.block = Block.objects.get(id=block_id)
        #self.owner = User.objects.get(id)

    def get(self,request,block_id):
        print("request.method............:",request.method)
        self.init_data(block_id)
        return render(request,self.template_name,{"bol":self.block})

    def post(self,request,block_id):
        self.init_data(block_id)
        self.user = request.user
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.block = self.block
            article.owner = self.user
            article.status=0
            article.save()
            return redirect("/article/list/%s" % block_id)
        else:
            return render(request,"publish_article.html",{"bol":self.block,"form":form})

#####文章详情页面也使用两种方式分别实现一下
###基于函数

###2017-05-30 增加评论展示

def article_detail(request,block_id,aid):
    block_id = int(block_id)
    aid = int(aid)
    block = Block.objects.get(id=block_id)
    article = Article.objects.get(id=aid)

    ##评论内容及评论分页
    #all_comments = Comment.objects.filter(article = aid,status=0).order_by("-create_timestamp")  ###order_by ("-column_name")  表示降序
    all_comments = Comment.normal_objects.filter(article=aid).order_by("-create_timestamp")  ##增加数据管理员逻辑
    page_no = int(request.GET.get("page_no","1"))
    page_comments,paginate_data = paginate_queryset(all_comments,page_no)
    #print("all_comments..........",all_comments.size)
    #msg_cnt = message_cnt(request.user)
    print(block_id,block.name,block.manager_name)
    return render(request,"article_detail.html",{"block_id":block_id,"block_name":block.name,"art":article,"comments":page_comments,"paginate_data":paginate_data})

###基于类

class ArticleDetailView(DetailView):
    model = Article
    tempate_name = 'article_detail.html'
    context_object_name = 'article'

    def init_data(self,block_id,aid):
        self.block_id = block_id
        self.block = Block.objects.get(id=block_id)
        self.aid = aid
        self.article = Article.objects.get(id = aid)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        page_no = int(self.request.GET.get("page_no","1"))
        all_comments = Comment.objects.filter(article=context["article"],status=0)
        print("all_comments...............",all_comments)
        comments,pagination_data = paginate_queryset(all_comments,page_no,cnt_per_page=3)
        context['comments'] = comments

        return context

    def get(self,request,block_id,aid):
        print("request.method............:",request.method)
        self.init_data(block_id,aid)
        return render(request,self.template_name,{"block_id":block_id,"block_name":block.name,"art":article})

    def post(self,request,block_id):
        self.init_data(block_id,aid)
        self.user = request.user
        form = ArticleForm(request.POST)
        if form.is_valid():
            article = form.save(commit=False)
            article.block = self.block
            article.owner = self.user
            article.status=0
            article.save()
            return redirect("/article/list/%s" % block_id)
        else:
            return render(request,"article_detail.html",{"bol":self.block,"form":form})


# coding = utf-8

# 导入函数库
import datetime
import random
import numpy as np
from TextCnn_inference import inference
import tensorflow as tf
from tensorflow.contrib import learn

# pycharm not need the “/souhu_algorithm_competition"
# 参数设置
#=====================================================#
# Data loading params
tf.flags.DEFINE_float('test_sample_percentage', 0.005, 'Percentage of the training data to use for testing')
tf.flags.DEFINE_string('training_data_file', './data_bunch/cnn_non_stop_words_train_bunch.dat', 'Data for training')
tf.flags.DEFINE_string('training_data_label_file', './data_bunch/cnn_train_label_bunch.dat', 'Some infomation for training,such as label, picture list and so on')

# Model Hyperparameters
tf.flags.DEFINE_integer('embedding_size', 300, "Dimensionality of character embedding (default: 128)")
tf.flags.DEFINE_string('filter_sizes', '2,3,4', "Comma-separated filter sizes (defulat: '2,3,4')")
tf.flags.DEFINE_integer('num_filters', 128, "Number of filters per filter size (default: 128)")
tf.flags.DEFINE_float('dropout_keep_prob', 0.5, "Dropout keep probality (default: 0.5)")
tf.flags.DEFINE_integer('fc1_nodes', 50, "Number of nodes in first full connection layer (default: 50) ")
# tf.flags.DEFINE_float('moving_average_decay', 0.99, "移动平均指数")
tf.flags.DEFINE_float('learning_rate_basic', 0.9, "基础学习率")
tf.flags.DEFINE_float('learning_rate_decay', 0.96, "学习率衰减速度")

# Training parameters
tf.flags.DEFINE_integer('batch_size', 500, "Batch size (default: 64)")
tf.flags.DEFINE_integer('num_epochs', 200000, "Number of training epochs (default: 2000)")
tf.flags.DEFINE_integer("evaluate_every", 100, "Evaluate model on dev set after this many steps (default: 100)")
tf.flags.DEFINE_integer("checkpoint_every", 100, "Save model after this many steps (default: 100)")
tf.flags.DEFINE_integer("num_checkpoints", 5, "Number of checkpoints to store (default: 5)")

# Misc Parameters
tf.flags.DEFINE_boolean('allow_soft_placement', True, "Allow device soft device placement")
tf.flags.DEFINE_boolean('log_device_placement', False, "Log placement of ops on devices")

FLAGS = tf.flags.FLAGS

# Load data
from instrument import read_bunch
train_data = read_bunch(FLAGS.training_data_file)
train_label = read_bunch(FLAGS.training_data_label_file)
# validate_data = read_bunch(FLAGS.validate_data_file)

# Build vocabulary
# sequence_length = max(train_data.news_length)                        # 取句子的最大长度
sequence_length = int(np.percentile(train_data.news_length,95))        #95%分位数
vocab_processor = learn.preprocessing.VocabularyProcessor(sequence_length)
train_matrix = np.array(list(vocab_processor.fit_transform(train_data.news_words_jieba)))
# Writer vocabulary to local
vocab_path = './vocabulary'
vocab_processor.save(vocab_path)
# release memeory
del train_data

# save trained model to local with a name
model_save_path = './model/'
model_name = 'TextCnn.ckpt'

# Training
#=========================================================#
def TextCnn_train(x_array,y_label, FLAGS):
    # Split train/test set
    from sklearn.model_selection import train_test_split
    train_x, test_x, train_y, test_y = train_test_split(x_array,
                                                        y_label,
                                                        test_size=FLAGS.test_sample_percentage,
                                                        random_state=33)
    # Placeholders for input, output and dropout
    x  = tf.placeholder(tf.int32, [None, train_x.shape[1]], name='input-x')
    y_ = tf.placeholder(tf.float32, [None, len(train_y[1])], name='input-y')
    DropOut_keep_prob = tf.placeholder(tf.float32, name="dropout_keep_prob")

    # use the inference function to compute logit
    y = inference(input_tensor= x,
                  sequence_length=train_x.shape[1],
                  embedding_size=FLAGS.embedding_size,
                  vocab_size=len(vocab_processor.vocabulary_),
                  filter_sizes=list(map(int, FLAGS.filter_sizes.split(','))),
                  num_filters=FLAGS.num_filters,
                  dropout_keep_prob= DropOut_keep_prob,
                  fc1_nodes=FLAGS.fc1_nodes,
                  num_classes=len(train_y[1]))
    global_step = tf.Variable(0, trainable=False)

    # define accuracy
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # define cost function, learning rate, moving average operation and train step
    cross_entroy = -(tf.reduce_sum(y_*tf.log(tf.clip_by_value(tf.nn.softmax(y), 1e-30, 1.0)), reduction_indices=[1]))
    loss = tf.reduce_mean(cross_entroy)
    learning_rate = tf.train.exponential_decay(FLAGS.learning_rate_basic,
                                                global_step, train_x.shape[0]/FLAGS.batch_size,
                                                FLAGS.learning_rate_decay)
    train_step = tf.train.AdadeltaOptimizer(learning_rate).minimize(loss, global_step=global_step)

    # 初始化TensorFlow持久化类
    saver = tf.train.Saver()

    session_conf = tf.ConfigProto(allow_soft_placement=FLAGS.allow_soft_placement,
                                  log_device_placement=FLAGS.log_device_placement)
    with tf.Session(config=session_conf) as sess:
        tf.global_variables_initializer().run()

        # 在训练过程中不再测试模型在验证数据上的表现，验证和测试的过程将会有一个独立的程序完成
        for epoch in range(FLAGS.num_epochs):
            # 随机从训练集中抽取 batch_size 条数据参加模型训练
            shuffle_indices = np.random.permutation(np.arange(train_x.shape[1]))
            batch_indices = random.sample(list(shuffle_indices), FLAGS.batch_size)
            batch_x, batch_y = zip(*np.array(list(zip(train_x, train_y)))[batch_indices])
            print(''.center(130, '*'))
            print(batch_x)
            print(batch_y)

            # Training
            train_feed_dict = {x: batch_x, y_: batch_y, DropOut_keep_prob: FLAGS.dropout_keep_prob}
            _, step, train_loss, train_accuracy, y_value = sess.run([train_step, global_step, loss, accuracy, y], train_feed_dict)
            time_str = datetime.datetime.now().isoformat()
            print("{}: step {}, loss {:g}, acc {:g}".format(time_str, step, train_loss, train_accuracy))
            print(y_value)

            current_step = tf.train.global_step(sess, global_step)
            if current_step % 10 == 0:   # 每 FLAGS.evaluate_every 步进行验证一次
                print("\nEvaluation:")
                # data structure is tuple
                test_feed_dict = {x: tuple(test_x), y_: tuple(test_y), DropOut_keep_prob: 1.0}
                step, valid_accuracy = sess.run([global_step, accuracy], test_feed_dict)
                time_str = datetime.datetime.now().isoformat()
                print("{}: step {}, acc {:g}".format(time_str, step, valid_accuracy))
                print("")
            if current_step % FLAGS.checkpoint_every == 0:  # 每 FLAGS.checkpoint_every 保存一次模型
                path = saver.save(sess, './model/TextCnn_model.ckpt', global_step=current_step)
                print("Saved model checkpoint to {}\n".format(path))

def main(argv=None):
    TextCnn_train(train_matrix, train_label.news_pic_label_one_hot, FLAGS=FLAGS)

if __name__ == '__main__':
    main()


'''
    Just exploring the autograd package in PyTorch
    I expected that it would not work when you do multiple forward passes before backward.

    Result: PyTorch seems to be storing ALL the intermediate computations.

    This is pretty handy since it takes care of everything, but you should
    be a little careful when using it: https://pytorch.org/docs/master/notes/faq.html

    examples discussed:
      - accumulating history during training loop
      - holding on to tensors that are not needed
      - using RNNs on long sequences
'''
import torch as th
from nets import *

f = make_net([1,2,2], [th.nn.Tanh()])

f.zero_grad()
y = f(th.tensor([2.1]))
l1 = (0 - y[0] - y[1]) ** 2
l1.backward()
g1 = [p.grad.clone() for p in f.parameters()]

f.zero_grad()
y = f(th.tensor([3.1]))
l2 = (-2 - y[0] - y[1]) ** 2
l2.backward()
g2 = [p.grad.clone() for p in f.parameters()]

f.zero_grad()
y = f(th.tensor([2.1]))
l1 = (0 - y[0] - y[1]) ** 2
y = f(th.tensor([3.1]))
l2 = (-2 - y[0] - y[1]) ** 2
l = l1+l2
l.backward()
g = [p.grad.clone() for p in f.parameters()]
print(g)
print(g1)
print(g2)

# seems to work!


import argparse
import sys
from xml.etree import ElementTree

def junit_to_trs(junit_xml):
    root = ElementTree.fromstring(junit_xml)
    testcases = root.findall("./testsuite/testcase")

    if len(testcases) < 1:
        print(":test-result: ERROR convert-junit-to-trs.py")
        return 99

    has_fail = False
    has_error = False
    has_skipped = False
    for testcase in testcases:
        filename = f"{testcase.attrib['classname'].replace('.', '/')}.py"
        name = f"{filename}::{testcase.attrib['name']}"
        res = "PASS"
        for node in testcase:
            if node.tag == "failure":
                res = "FAIL"
                has_fail = True
            elif node.tag == "error":
                res = "ERROR"
                has_error = True
            elif node.tag == "skipped":
                if node.attrib.get("type") == "pytest.xfail":
                    res = "XFAIL"
                else:
                    res = "SKIP"
                    has_skipped = True
        print(f":test-result: {res} {name}")

    if has_error:
        return 99
    if has_fail:
        return 1
    if has_skipped:
        return 77
    return 0

def main():
    parser = argparse.ArgumentParser(
        description="Convert JUnit XML to Automake TRS and exit with "
        "the appropriate Automake-compatible exit code."
    )
    parser.add_argument(
        "junit_file",
        type=argparse.FileType("r", encoding="utf-8"),
        help="junit xml result file",
    )
    args = parser.parse_args()

    junit_xml = args.junit_file.read()
    sys.exit(junit_to_trs(junit_xml))

if __name__ == "__main__":
    main()


import sys
sys.path.append('.')

from amaranth.sim import Simulator, Tick

from adat.transmitter import ADATTransmitter
from adat.nrzidecoder import NRZIDecoder
from testdata import *

def test_with_samplerate(samplerate: int=48000):
    clk_freq = 50e6
    dut = ADATTransmitter()
    adat_freq = NRZIDecoder.adat_freq(samplerate)
    clockratio = clk_freq / adat_freq

    print(f"FPGA clock freq: {clk_freq}")
    print(f"ADAT clock freq: {adat_freq}")
    print(f"FPGA/ADAT freq: {clockratio}")

    sim = Simulator(dut)
    sim.add_clock(1.0/clk_freq, domain="sync")
    sim.add_clock(1.0/adat_freq, domain="adat")

    def write(addr: int, sample: int, last: bool = False, drop_valid: bool = False):
        while (yield dut.ready_out == 0):
            yield from wait(1)
        if last:
            yield dut.last_in.eq(1)
        yield dut.addr_in.eq(addr)
        yield dut.sample_in.eq(sample)
        yield dut.valid_in.eq(1)
        yield Tick("sync")
        if drop_valid:
            yield dut.valid_in.eq(0)
        if last:
            yield dut.last_in.eq(0)

    def wait(n_cycles: int):
        for _ in range(int(clockratio) * n_cycles):
            yield Tick("sync")

    def sync_process():
        yield Tick("sync")
        yield Tick("sync")
        yield dut.user_data_in.eq(0xf)
        for i in range(4):
            yield from write(i, i, drop_valid=True)
        for i in range(4):
            yield from write(4 + i, 0xc + i, i == 3, drop_valid=True)
        yield dut.user_data_in.eq(0xa)
        yield Tick("sync")
        for i in range(8):
            yield from write(i, (i + 1) << 4, i == 7)
        yield dut.user_data_in.eq(0xb)
        yield Tick("sync")
        for i in range(8):
            yield from write(i, (i + 1) << 8, i == 7)
        yield dut.user_data_in.eq(0xc)
        yield Tick("sync")
        for i in range(8):
            yield from write(i, (i + 1) << 12, i == 7)
        yield dut.user_data_in.eq(0xd)
        yield Tick("sync")
        for i in range(8):
            yield from write(i, (i + 1) << 16, i == 7)
        yield dut.user_data_in.eq(0xe)
        yield Tick("sync")
        for i in range(8):
            yield from write(i, (i + 1) << 20, i == 7, drop_valid=True)
        yield from wait(900)

    def adat_process():
        nrzi = []
        i = 0
        while i < 1800:
            yield Tick("adat")
            out = yield dut.adat_out
            nrzi.append(out)
            i += 1

        # skip initial zeros
        nrzi = nrzi[nrzi.index(1):]
        signal = decode_nrzi(nrzi)
        decoded = adat_decode(signal)
        print(decoded)
        user_bits = [decoded[frame][0] for frame in range(7)]
        assert user_bits == [0x0, 0xf, 0xa, 0xb, 0xc, 0xd, 0xe],                                            print_assert_failure(user_bits)
        assert decoded[0][1:] == [0, 0, 0, 0, 0, 0, 0, 0],                                                  print_assert_failure(decoded[0][1:])
        assert decoded[1][1:] == [0, 1, 2, 3, 0xc, 0xd, 0xe, 0xf],                                          print_assert_failure(decoded[1][1:])
        assert decoded[2][1:] == [0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80],                          print_assert_failure(decoded[2][1:])
        assert decoded[3][1:] == [0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x800],                  print_assert_failure(decoded[3][1:])
        assert decoded[4][1:] == [0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0x6000, 0x7000, 0x8000],          print_assert_failure(decoded[4][1:])
        assert decoded[5][1:] == [0x10000, 0x20000, 0x30000, 0x40000, 0x50000, 0x60000, 0x70000, 0x80000],  print_assert_failure(decoded[5][1:])

    sim.add_sync_process(sync_process, domain="sync")
    sim.add_sync_process(adat_process, domain="adat")

    with sim.write_vcd(f'transmitter-smoke-test-{str(samplerate)}.vcd'):
        sim.run()

if __name__ == "__main__":
    test_with_samplerate(48000)


#출처: '으뜸 머신러닝' kNN 모델을 통한 이미지의 노이즈 제거 구현
import matplotlib.pyplot as plt
import numpy as np
from skimage.io import imread
from skimage.transform import resize

url = 'https://github.com/dknife/ML/raw/main/data/Proj1/40/'
imgR, imgC, channel = 24, 24, 3
images = []

for i in range(40):
  file = url+ 'img{0:02d}.jpg'.format(i+1)
  img = imread(file)
  img = resize(img, (imgR, imgC, 3))
  #print(img.shape)
  images.append(img)

def plot_images(nRow, nCol, img):
  fig = plt.figure()
  fig, ax = plt.subplots(nRow, nCol, figsize = (nCol, nRow))
  for i in range(nRow):
    for j in range(nCol):
      if nRow <= 1: axis = ax[j]
      else : axis = ax[i, j]
      axis.get_xaxis().set_visible(False)
      axis.get_yaxis().set_visible(False)
      axis.imshow(img[i*nCol+j])

x = np.array(images[:30])
x_test = np.array(images[30:])
plot_images(3, 10, x)
plot_images(1, 10, x_test)

x_noise = x+ np.random.randn(len(x), imgR, imgC, channel)*0.1
x_noise = np.clip(x_noise, 0, 1)
x_test_noise = x_test+ np.random.randn(len(x_test), imgR, imgC, channel)*0.1
x_test_noise = np.clip(x_test_noise, 0, 1)
plot_images(3, 10, x_noise)
plot_images(1, 10, x_test_noise)

#input -> (0,1) , output -> (0, 255)
x_noise_flat = x_noise.reshape(-1, imgR*imgC*channel)
x_flat = np.array(x.reshape(-1, imgR*imgC*channel)*255, dtype = np.uint)
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(x_noise_flat, x_flat)
denoised_result = knn.predict(x_noise_flat)
denoised_result = denoised_result.reshape(-1, imgR, imgC, channel)
plot_images(3, 10, denoised_result) #images' each pixels are classified by knn model. Outputs are the labels(pixels' classes) of the noised images.

##New images are added by simply creating more noised images from the same 40 images. (for training and testing)
n_augmentation = 100 #add x100 more
x_noise_aug = x+np.random.rand(len(x), imgR, imgC, channel)*0.2
y_label = np.array(x*255, dtype = np.uint) #maybe images can't be perfectly retrieved (without noises) because dtype = np.unit forces some float vals to same int vals (classification inprecise)
y = y_label

print(x_noise.shape)
for i in range(n_augmentation):
  noisy_data = x+np.random.randn(len(x), imgR, imgC, channel) * 0.2
  x_noise_aug = np.append(x_noise_aug, noisy_data, axis = 0)
  y = np.append(y, y_label, axis = 0)

x_noise_aug = np.clip(x_noise_aug, 0, 1)
print(x_noise_aug.shape, y.shape)

plot_images(1, 10, x_noise_aug[0:300:30]) #index 0~300 by step 30 (10 elements sliced)
x_noise_aug_flattened = x_noise_aug.reshape(-1, imgR*imgC*channel)
y_flattened = y.reshape(-1, imgR*imgC*channel)
knn.fit(x_noise_aug_flattened, y_flattened)
denoised_result = knn.predict(x_noise_flat) #test the model with x_noise_flat created before (created when no image was augmented)
denoised_result = denoised_result.reshape(-1, imgR, imgC, channel)
plot_images(3, 10, x_noise)
plot_images(3, 10, denoised_result)

rndidx = np.random.randint(0, 20)
data = x[rndidx:rndidx+10] + np.random.randn(10, imgR, imgC, channel)*.4
data = np.clip(data, 0, 1)
data_flat = data.reshape(-1, imgR*imgC*channel)
denoised = knn.predict(data_flat)
denoised = denoised.reshape(-1, imgR, imgC, channel)
denoised = np.clip(denoised, 0, 255)

plot_images(1, 10, data)
plot_images(1, 10, denoised)

denoised = knn.predict(x_test_noise.reshape(-1, imgR*imgC*channel))
denoised = denoised.reshape(-1, imgR, imgC, channel)

plot_images(1, 10, x_test_noise)
plot_images(1, 10, denoised)
#overfitting problem -> because new labels were generated just by copying 30 training data labels over and over (x100 times)
#way to solve this problem is to augment new labels by actually modifying labels(rotation, shifting...)

from keras.preprocessing.image import ImageDataGenerator
image_generator = ImageDataGenerator(
    rotation_range = 360,
    zoom_range = 0.1,
    shear_range = 0.1,
    width_shift_range = 0.1,
    height_shift_range = 0.1,
    horizontal_flip = True,
    vertical_flip = True
) #keras class iterator for generating newly augmented images

y_aug = x.reshape(-1, imgR, imgC, channel)
print(y_aug.shape)
it = image_generator.flow(y_aug) #iterator for ImageDataGenerator() class object
nData = y_aug.shape[0]

x_aug = y_aug +np.random.randn(nData, imgR, imgC, channel)*0.1
n_augmentation = 500 #augmentation by x500
for _ in range(n_augmentation):
  new_y = it.next() #iterator usage
  new_x = new_y + np.random.randn(nData, imgR, imgC, channel)*0.1
  y_aug = np.append(y_aug, new_y, axis = 0)
  x_aug = np.append(x_aug, new_x, axis = 0)#append newly generated y,x row-wise

y_aug = np.array(y_aug*255, dtype = np.uint)
y_aug = y_aug.reshape(-1, imgR, imgC, channel)
x_aug = x_aug.reshape(-1, imgR, imgC, channel)
y_aug = np.clip(y_aug, 0, 255)
x_aug = np.clip(x_aug, 0, 1)
plot_images(3, 10, y_aug[30:])

#Now, train the newly generated images with KNN model
x_aug_flat = x_aug.reshape(-1, imgR*imgC*channel)
y_aug_flat = y_aug.reshape(-1, imgR*imgC*channel)
knn.fit(x_aug_flat, y_aug_flat)
denoised = knn.predict(x_test_noise.reshape(-1, imgR*imgC*channel))
denoised = denoised.reshape(-1, imgR, imgC, channel)
plot_images(1, 10, x_test_noise)
plot_images(1, 10, denoised)

images = it.next() #load 30 images generated by ImageDataGenerator()'s iterator method
testX = images + np.random.randn(nData, imgR, imgC, channel)* 0.4
testX = np.clip(testX, 0, 1)
denoised = knn.predict(testX.reshape(-1, imgR*imgC*channel))
denoised = denoised.reshape(-1, imgR, imgC, channel)

plot_images(1, 10, testX)
plot_images(1, 10, denoised)


class Solution:
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """

        if len(numbers) == 2:
            return [1, 2]

        left, right = 0, len(numbers) - 1

        while left < right:
            sum = numbers[left] + numbers[right]
            if sum == target:
                return [left + 1, right + 1]
            elif target > sum:
                left += 1
            else:
                right -= 1

if __name__ == '__main__':
    r = Solution().twoSum([2, 7, 11, 15], 9)
    print(r)

167. Two Sum II - Input array is sorted.py


from datetime import datetime
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'espa.espa.settings')

import django

django.setup()

from espa.espa.models import Project
from espa.espa.processors.AnaptyxiBudgetAnalysis import convertAmountStringToInteger
from espa.espa.scrapers.anaptyxi.ΑnaptyxiScraper import ratioToBudgetForEachPrefecture, prefectures, prefectureCodeToNUTSCodeMapping

'''
Prints a list of budget per municipality.
'''
def municipalityAnalysis():
    prefectureSums = {}

    for code in prefectures.keys():
        prefectureSums[code] = {}
        for i in range(1996, 2016):  # we magically know that project years are in this range
            prefectureSums[code][i] = 0

    totalBudgetSum = 0  # for checking
    countOfProjects = 0
    ignoredBecauseOfDateBudgetSum = 0

    for project in Project.objects.all():
        countOfProjects += 1
        prefTotalWeight = 0
        projectBudget = convertAmountStringToInteger(project.budget)
        totalBudgetSum += projectBudget
        if project.startDate == "-":
            ignoredBecauseOfDateBudgetSum += projectBudget
            continue
        for prefecture in project.prefecturesOwning.all():
            if prefecture.code != "14":
                prefTotalWeight += ratioToBudgetForEachPrefecture[prefecture.code]

        localPrefectureSum = 0
        for prefecture in project.prefecturesOwning.all():
            if prefecture.code != "14":
                currentPrefWeight = ratioToBudgetForEachPrefecture[prefecture.code] / prefTotalWeight
                currentPrefectureAllocation = projectBudget * currentPrefWeight
                projectYear = datetime.strptime(project.startDate, "%d/%m/%Y").year
                prefectureSums[prefecture.code][projectYear] += currentPrefectureAllocation
                localPrefectureSum += currentPrefectureAllocation
        if abs(localPrefectureSum - projectBudget) > 1:
            print("project %s has prefectures %s but the budget does not equal the allocation (%d vs %d)"
                  % (project, project.prefecturesOwning.all(), projectBudget, localPrefectureSum))
    print(totalBudgetSum)
    valuesSum = 0
    for yearValue in prefectureSums.values():
        for value in yearValue.values():
            valuesSum += value
    prettyPrintBudgets(prefectureSums)
    print(valuesSum)
    print(totalBudgetSum - valuesSum)
    print("ignored because of date sum up to %d " % ignoredBecauseOfDateBudgetSum)

def prettyPrintBudgets(budgets):
    # Prints csv with AreaCode, Year, Value
    print('"AreaCode","Year","Value"')
    for areaCode, yearValues in budgets.items():
        nutsValue = prefectureCodeToNUTSCodeMapping[areaCode]
        for year, value in yearValues.items():
            print('"%s","%d","%d"' % (nutsValue, year, value))


from math import pi
print("Aqui podra calcular el area de un circulo por su radio o diamentro ")
radio_or_diametro = int(input("Ingrese una 1 si es radio o 2 si es diametro:" ))
if radio_or_diametro==1:
    radio = int(input("Ingresa el radio del circulo: "))
    print("El area del circiulo  por medio del radio es:")
    area = pi * radio ** 2
    print(area)

if radio_or_diametro==2:
    diametro = int(input("Ingresa el diametro del circulo: "))
    print("El area del circiulo  por medio del diameatro es: ")
    area =(1/4)* pi * diametro ** 2
    print(area)


import tkinter as tk
import requests
import datetime

def get_covid_data():
    api = "https://disease.sh/v3/covid-19/all"
    json_data = requests.get(api).json()
    total_cases = str(json_data['cases'])
    total_deaths = str(json_data['deaths'])
    today_cases = str(json_data['todayCases'])
    today_deaths = str(json_data['todayDeaths'])
    today_recovered = str(json_data['todayRecovered'])
    updated_at = json_data['updated']
    date = datetime.datetime.fromtimestamp(updated_at/1e3)
    label.config(text="Total Cases: " + total_cases + "\nTotal Deaths: " + total_deaths + "\nToday's Cases: " + today_cases + "\nToday's Deaths: " + today_deaths + "\nRecovered: " + today_recovered)
    label2.config(text = date)
canvas = tk.Tk()
canvas.geometry("400x400")
canvas.title("Covid-19 Tracker")

f = ("poppins", 20, "bold")
button = tk.Button(canvas, text="Get Data", font=f, command=get_covid_data)
button.pack(pady=20)

label =tk.Label(canvas, text="Covid-19 Tracker", font=f)
label.pack(pady=20)

label2 = tk.Label(canvas, font=8)
label2.pack()
get_covid_data()
canvas.mainloop()


# encoding:utf-8

import json
import os
import re
import time
import numpy as np

# 配置文件路径
eid_path = '../../Twitter/json/'						# 源文件路径
label_path_read = '../../Twitter/'					# 标签路径
label_path_write = '../label/'
event_path = '../event_text/'					    # 分词处理后的保存路径
time_path = '../event_time/'
index_path = '../event_index/'
word2vec_path_read = '../../../word2vector/'			# 词向量读取路径
word2vec_path_write = '../word2vec/'
embedding_size = 300

def get_file_name(file_path):						# 获取file_path路径下的文件名
	for root, dirs, files in os.walk(file_path):
		return files

def get_time(date):
	dt_time = time.strptime(date, '%a %b %d %H:%M:%S %z %Y')
	dt_sec = time.mktime(dt_time)
	return dt_sec

def fenci(eid_path, label_path_read, label_path_write, event_path):
	char = '[+\.\!\/_,-?\[\]@*&""\'‘’”“$%„{}^()#]'	# 要过滤符号列表

	labels = {}

	fl = open(label_path_write + 'labels.json', 'w')		# 输出标签文件
	# fl = open(label_path + 'labels.txt', 'w')
	with open(label_path_read + 'label.txt', 'r') as lf:
		lines = lf.readlines()
		for line in lines:
			m = line.split()						# m[:2]为每个子事件的'eid'和'label'
			m = m[:2]
			eid = m[0].split(':')[1]
			label = m[1].split(':')[1]
			if int(label) == 0:						# 两类问题的第一类：否
				labels[eid] = [1, 0]
			else:
				labels[eid] = [0, 1]				# 两类问题的第一类：是
			# fl.write(eid + ' ' + label + '\n')	# 输出格式'eid label'
	json.dump(labels, fl)
	fl.close()

	list_eid = get_file_name(eid_path)				# 文件名列表
	for eid in list_eid:
		fe = open(event_path + eid + '.txt', 'w', encoding='utf8')		# 将每个event的分词结果输出
		ft = open(time_path + eid + '.txt', 'w')

		with open(eid_path + eid, 'r') as f:
			data = json.load(f)						# data的类型为 'list'
			n = len(data)
			t0 = get_time(data[0]['created_at'])

			for item in data:

				t = get_time(item['created_at'])
				ft.write(str(int(t-t0)))

				text = re.sub(char, '', item['text']).split()			# 过滤'text'里的符号并分词
				for s in text:
					if s[0:4] == 'http':			# 过滤掉'http'开头的网址
						text.remove(s)
				for token in text:
					fe.write(token + ' ')

				n -= 1
				if n > 0:
					fe.write('\n')
					ft.write('\n')
		fe.close()
		ft.close()

def build_embeddings(word2vec_path_read, word2vec_path_write):
	words_embeddings = {}
	with open(word2vec_path_read + 'Google_IJCAI2016_w2v.txt', 'r') as files:
		lines = files.readlines()
		for line in lines:
			l = line.split()
			word = l[0]
			value = l[1:]
			words_embeddings[word] = value

	with open(word2vec_path_write + 'Google_IJCAI2016_w2v.json', 'w') as fj:
		json.dump(words_embeddings, fj)

	print('word-vector build succeed...')

# 数据预处理，返回处理后的输入数据
def get_embeddings(time_path, index_path, embedding_size):
	with open(word2vec_path_write + 'Google_IJCAI2016_w2v.json', 'r') as fj:
		vector = json.load(fj)

	files = get_file_name(event_path)                   # 获取当前目录下的所有文件名和文件数
	num_event = len(files)

	for i in range(num_event):
		eid = files[i].split('.')[0]
		ft = open(time_path + eid + '.txt', 'r')
		time_lines = ft.readlines()
		with open(event_path + files[i], 'r', encoding='utf8') as event:
			lines = event.readlines()
			length = len(lines)                                 # 计算每个事件的评论数
			vec = np.zeros((length, embedding_size+1), dtype=np.float32)     # 初始化事件矩阵

			for j in range(length):
				vec[j, 0] = int(time_lines[j])
				sents = lines[j].split()
				for word in sents:
					if vector.__contains__(word):
						vec[j, 1: ] = vec[j, 1: ] + np.array(vector[word], dtype=np.float32)     # 对每条评论的各词向量求均值
				if len(sents) == 0:
					vec[j, 1: ] = vec[j, 1: ]
				else:
					vec[j, 1: ] = vec[j, 1: ] / len(sents)
			ft.close()
			with open(index_path + files[i], 'w', encoding='utf8') as fi:
				for k in range(length):
					for n in range(embedding_size+1):
						fi.write(str(vec[k, n]))
						if n < embedding_size:
							fi.write(' ')
					if k < length-1:
						fi.write('\n')

if __name__ == '__main__':
	fenci(eid_path, label_path_read, label_path_write, event_path)
	build_embeddings(word2vec_path_read, word2vec_path_write)
	get_embeddings(time_path, index_path, embedding_size)


from __future__ import annotations

import logging
import sys

# logging.basicConfig(level=100)

class InheritLogger:
    lvl = logging.DEBUG
    lgr: logging.Logger = logging.getLogger("mrp")
    h = logging.StreamHandler(sys.stdout)

    h.setLevel(lvl)
    lgr.addHandler(h)
    lgr.setLevel(lvl)

    @classmethod
    def set_logger_by_name(cls, lgr_name):
        """To overwrite the deafult logger"""
        cls.lgr = logging.getLogger(lgr_name)

    @classmethod
    def set_lgr_level(cls, lvl: int):
        for h in cls.lgr.handlers:
            h.setLevel(lvl)

        cls.lgr.setLevel(lvl)


from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PainterWidget import PainterWidget
import numpy as np
import time
import requests
import json

server_addr = "the_addr/predict/"

class PredictionProcessor(QObject):
    predicted = pyqtSignal(list)
    finished = pyqtSignal()

    @pyqtSlot()
    def run(self, array:np.ndarray):
        try:
            req_dict = {"array":array.tolist()}
            req = requests.post(server_addr, data=json.dumps(req_dict))
            response = req.json()

            if response["Error"]:
                ret = [False, response["Message"]]
            else:
                ret = [True, response["Prediction"]]
        except:
            ret = [False, "Error occurred!"]

        self.predicted.emit(ret)
        self.finished.emit()

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.setWindowTitle("Number Recognizer")
        self.setFixedSize(400, 460)

        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)

        self.vertical_layout = QVBoxLayout()
        self.vertical_layout.setAlignment(Qt.AlignHCenter)
        self.central_widget.setLayout(self.vertical_layout)

        self.painter_widget = PainterWidget()
        self.vertical_layout.addWidget(self.painter_widget)

        self.label = QLabel()
        self.label.setText("Type any number above")
        self.label.setStyleSheet(f"font-size: 20px;padding:15px")
        self.vertical_layout.addWidget(self.label)
        self.label.setAlignment(Qt.AlignBottom)

        self.btns_layout = QHBoxLayout()
        self.vertical_layout.addLayout(self.btns_layout)

        self.predict_btn = QPushButton()
        self.predict_btn.setFixedSize(120,50)
        self.predict_btn.setText("Predict")
        self.predict_btn.setStyleSheet(f"font-size: 16px")
        self.btns_layout.addWidget(self.predict_btn)

        self.clear_btn = QPushButton()
        self.clear_btn.setFixedSize(120,50)
        self.clear_btn.setText("Clear")
        self.clear_btn.setStyleSheet(f"font-size: 16px")
        self.btns_layout.addWidget(self.clear_btn)

        self.predict_btn.clicked.connect(self.recognizer_clicked)
        self.clear_btn.clicked.connect(self.clear_clicked)

    def recognizer_clicked(self):
        self.predict_btn.setEnabled(False)
        self.label.setText("Waiting ...")
        self.label.repaint()
        get_req = self.painter_widget.get_img()

        if not get_req[0]:
            self.label.setText(get_req[1])
            self.label.repaint()
            self.predict_btn.setEnabled(True)
        else:
            img_array = get_req[1]

            self.predict_obj = PredictionProcessor()
            self.prediction_thread = QThread()

            self.predict_obj.predicted.connect(self.image_predicted)
            self.predict_obj.moveToThread(self.prediction_thread)
            self.predict_obj.finished.connect(self.prediction_thread.quit)
            self.prediction_thread.started.connect(lambda: self.predict_obj.run(img_array))
            self.prediction_thread.start()

    def image_predicted(self, ret):
        if not ret[0]:
            text = ret[1]
        else:
            text = f"The number is {ret[1]}"

        self.label.setText(text)
        self.label.repaint()
        self.predict_btn.setEnabled(True)

    def clear_clicked(self):
        self.painter_widget.clear_board()

if __name__ == '__main__':
    import sys
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


from typing import TYPE_CHECKING

from paul_plans.defensive_building import DefensiveBuilding, DefensePosition
from sc2.ids.unit_typeid import UnitTypeId
from sharpy.plans import BuildOrder, Step, StepBuildGas
from sharpy.plans.acts import ActBuilding
from sharpy.plans.acts.zerg import ZergUnit, AutoOverLord
from sharpy.plans.require import UnitExists, RequiredAll
from sharpy.plans.tactics import PlanDistributeWorkers

if TYPE_CHECKING:
    from sharpy.knowledges import Knowledge

class RoachRushResponse(BuildOrder):
    """Respond to a Roach Rush."""

    def __init__(self):
        """Create plan for build order."""
        self.drones = ZergUnit(UnitTypeId.DRONE, to_count=0)
        self.lings = ZergUnit(UnitTypeId.ZERGLING, to_count=999)
        self.queens = ZergUnit(UnitTypeId.QUEEN, to_count=3)
        self.roaches = ZergUnit(UnitTypeId.ROACH, to_count=100, priority=True)
        self.ravagers = ZergUnit(UnitTypeId.RAVAGER, to_count=0)
        self.defense_spines = DefensiveBuilding(
            unit_type=UnitTypeId.SPINECRAWLER, position_type=DefensePosition.Entrance, to_base_index=1, to_count=3
        )
        self.gas = StepBuildGas(to_count=3)

        unit_building = BuildOrder(
            [
                Step(None, self.drones, skip_until=self.should_build_drones),
                Step(UnitExists(UnitTypeId.SPAWNINGPOOL), self.defense_spines),
                Step(
                    RequiredAll([UnitExists(UnitTypeId.ROACHWARREN), UnitExists(UnitTypeId.ROACH)]),
                    self.ravagers,
                    skip_until=self.should_build_ravagers,
                ),
                Step(UnitExists(UnitTypeId.ROACHWARREN), self.roaches),
                Step(
                    RequiredAll(
                        [
                            UnitExists(UnitTypeId.SPAWNINGPOOL),
                            UnitExists(
                                UnitTypeId.ROACHWARREN,
                                include_pending=True,
                                include_not_ready=True,
                                include_killed=True,
                            ),
                        ]
                    ),
                    self.lings,
                ),
                Step(UnitExists(UnitTypeId.SPAWNINGPOOL), self.queens),
                Step(UnitExists(UnitTypeId.SPAWNINGPOOL), self.lings),
            ]
        )

        buildings: BuildOrder = BuildOrder(
            [
                Step(None, ActBuilding(UnitTypeId.SPAWNINGPOOL, to_count=1)),
                Step(UnitExists(UnitTypeId.SPAWNINGPOOL), ActBuilding(UnitTypeId.ROACHWARREN, to_count=1)),
                Step(None, self.gas, skip_until=self.should_build_gas),
            ]
        )

        super().__init__(buildings, unit_building)

    def should_build_drones(self, knowledge):
        """Determine if we need to build drones."""
        if self.cache.own(UnitTypeId.DRONE).amount >= 16 + self.get_count(UnitTypeId.EXTRACTOR) * 3:
            return False
        if not self.knowledge.game_analyzer.our_power.is_enough_for(
            self.knowledge.enemy_units_manager.enemy_total_power
        ):
            return False
        self.drones.to_count = 16 + self.get_count(UnitTypeId.EXTRACTOR) * 3
        return True

    def should_build_gas(self, knowledge):
        if (
            self.knowledge.game_analyzer.our_power.is_enough_for(self.knowledge.enemy_units_manager.enemy_total_power)
            and self.cache.own(UnitTypeId.DRONE).amount >= 16 * self.get_count(UnitTypeId.EXTRACTOR) * 3
        ):
            self.gas.to_count = min(3, self.get_count(UnitTypeId.EXTRACTOR) + 1)
            return True
        return False

    def should_build_ravagers(self, knowledge):
        if self.cache.own(UnitTypeId.ROACH).amount >= 10:
            self.ravagers.to_count = self.cache.own(UnitTypeId.ROACH).amount // 2
            return True
        return False


import webbrowser

# HTML 수정 함수
def write(name, desc):
  Element(name).element.innerText = desc

# 하단 버튼 링크 연결 함수
def button(*args):
  link = "https://www.instagram.com/hong__seoeun/" # https:// 꼭 붙여야 연결됩니다!
  webbrowser.open(link)

# 배경 색깔 설정 함수
def background(color):
  for i in range(0, 2):
    write("g" + str(i), color[i])

def information(info):
  key = list(info.keys())
  for i in range(0, 4):
    write("a" + str(i), key[i])
    write("b" + str(i), info[key[i]])

# 배경 색깔 설정
colors = ["#FFFFFF", "#6799FF"]
background(colors)

# 이름과 설명, 버튼에 들어갈 글 설정
write("name", "홍서은")
write("description", "안녕, 만나서 반가워")
write("button", "instagram")

# 상세설명에 들어갈 제목과 글 설정
informations = {
  "사는 곳": "경주",
  "나이": "16살",
  "취미1": "독서",
  "취미2": "베이킹"
}
information(informations)


from django.shortcuts import render , get_object_or_404
from .models import Post , Category

def show_category(request,hierarchy= None):
    category_slug = hierarchy.split('/')
    parent = None
    root = Category.objects.all()
    for slug in category_slug[:-1]:
        parent = root.get(parent=parent, slug = slug)

    try:
        instance = Category.objects.get(parent=parent,slug=category_slug[-1])
    except:
        instance = get_object_or_404(Post, slug = category_slug[-1])
        return render(request, "post_detail.html", {'instance':instance})
    else:
        return render(request, 'categories.html', {'instance':instance})

def post_detail(request,slug=None):
    instance = get_object_or_404(Post,slug=slug)
    return render(request,"post_detail.html",{ 'instance':instance})

def post_list(request,slug=None):
    posts = Post.objects.all()
    return render(request,"post_list.html",{ 'posts':posts})


"""
.. _ref_fields_container:

FieldsContainer
===============
Contains classes associated with the DPF FieldsContainer.
"""
from ansys import dpf
from ansys.dpf.core.collection import Collection
from ansys.dpf.core import errors as dpf_errors
from ansys.dpf.core import field

class FieldsContainer(Collection):
    """Represents a fields container, which contains fields belonging to a common result.

    A fields container is a set of fields ordered by labels and IDs. Each field
    of the fields container has an ID for each label defining the given fields
    container. These IDs allow splitting the fields on any criteria.

    The most common fields container has the label ``"time"`` with IDs
    corresponding to time sets. The label ``"complex"``, which is
    used in a harmonic analysis for example, allows real parts (``id=0``)
    to be separated from imaginary parts (``id=1``).

    For more information, see the `Fields container and fields
    <https://dpf.docs.pyansys.com/user_guide/fields_container.html#ref-user-guide-fields-container>
    `_ documentation section.

    Parameters
    ----------
    fields_container : ansys.grpc.dpf.collection_pb2.Collection, ctypes.c_void_p,
    FieldsContainer, optional
        Fields container created from either a collection message or by copying an existing
        fields container. The default is "None``.
    server : ansys.dpf.core.server, optional
        Server with the channel connected to the remote or local instance.
        The default is ``None``, in which case an attempt is made to use the
        global server.

    Examples
    --------
    Extract a displacement fields container from a transient result file.

    >>> from ansys.dpf import core as dpf
    >>> from ansys.dpf.core import examples
    >>> transient = examples.download_transient_result()
    >>> model = dpf.Model(transient)
    >>> disp = model.results.displacement()
    >>> disp.inputs.time_scoping.connect([1,5])
    >>> fields_container = disp.outputs.fields_container()
    >>> field_set_5 =fields_container.get_fields_by_time_complex_ids(5)
    >>> #print(fields_container)

    Create a fields container from scratch.

    >>> from ansys.dpf import core as dpf
    >>> fc= dpf.FieldsContainer()
    >>> fc.labels =['time','complex']
    >>> for i in range(0,20): #real fields
    ...     mscop = {"time":i+1,"complex":0}
    ...     fc.add_field(mscop,dpf.Field(nentities=i+10))
    >>> for i in range(0,20): #imaginary fields
    ...     mscop = {"time":i+1,"complex":1}
    ...     fc.add_field(mscop,dpf.Field(nentities=i+10))

    """

    def __init__(self, fields_container=None, server=None):
        super().__init__(collection=fields_container, server=server)
        if self._internal_obj is None:
            if self._server.has_client():
                self._internal_obj = self._api.collection_of_field_new_on_client(
                    self._server.client
                )
            else:
                self._internal_obj = self._api.collection_of_field_new()

        self._component_index = None  # component index
        self._component_info = None  # for norm/max/min

    def create_subtype(self, obj_by_copy):
        return field.Field(field=obj_by_copy, server=self._server)

    def get_fields_by_time_complex_ids(self, timeid=None, complexid=None):
        """Retrieve fields at a requested time ID or complex ID.

        Parameters
        ----------
        timeid : int, optional
            Time ID or frequency ID, which is the one-based index of the
            result set.
        complexid : int, optional
            Complex ID, where ``1`` is for imaginary and ``0`` is for real.

        Returns
        -------
        fields : list[Field]
            Fields corresponding to the request.

        Examples
        --------
        Extract the fifth time set of a transient analysis.

        >>> from ansys.dpf import core as dpf
        >>> from ansys.dpf.core import examples
        >>> transient = examples.download_transient_result()
        >>> model = dpf.Model(transient)
        >>> len(model.metadata.time_freq_support.time_frequencies)
        35
        >>> disp = model.results.displacement()
        >>> disp.inputs.time_scoping.connect([1,5])
        >>> fields_container = disp.outputs.fields_container()
        >>> field_set_5 =fields_container.get_fields_by_time_complex_ids(5)

        """
        label_space = self.__time_complex_label_space__(timeid, complexid)
        return super()._get_entries(label_space)

    def get_field_by_time_complex_ids(self, timeid=None, complexid=None):
        """Retrieve a field at a requested time ID or complex ID.

        An exception is raised if the number of fields matching the request is
        greater than one.

        Parameters
        ----------
        timeid : int, optional
            Time ID or frequency ID, which is the one-based index of the
            result set.
        complexid : int, optional
            Complex ID, where ``1`` is for imaginary and ``0`` is for real.

        Returns
        -------
        fields : Field
            Field corresponding to the request

        Examples
        --------
        Extract the fifth time set of a transient analysis.

        >>> from ansys.dpf import core as dpf
        >>> from ansys.dpf.core import examples
        >>> transient = examples.download_transient_result()
        >>> model = dpf.Model(transient)
        >>> len(model.metadata.time_freq_support.time_frequencies)
        35
        >>> disp = model.results.displacement()
        >>> disp.inputs.time_scoping.connect([1,5])
        >>> fields_container = disp.outputs.fields_container()
        >>> field_set_5 =fields_container.get_fields_by_time_complex_ids(5)

        """
        label_space = self.__time_complex_label_space__(timeid, complexid)
        return super()._get_entry(label_space)

    def __time_complex_label_space__(self, timeid=None, complexid=None):
        label_space = {}
        if timeid is not None:
            label_space["time"] = timeid
        if complexid is not None:
            label_space["complex"] = complexid
        return label_space

    def get_fields(self, label_space):
        """Retrieve the fields at a requested index or label space.

        Parameters
        ----------
        label_space : dict[str,int]
            Scoping of the requested fields. For example,
            ``{"time": 1, "complex": 0}``.

        Returns
        -------
        fields : list[Field]
            Fields corresponding to the request.

        Examples
        --------
        >>> from ansys.dpf import core as dpf
        >>> fc= dpf.FieldsContainer()
        >>> fc.labels =['time','complex']
        >>> #real fields
        >>> for i in range(0,20):
        ...     mscop = {"time":i+1,"complex":0}
        ...     fc.add_field(mscop,dpf.Field(nentities=i+10))
        >>> #imaginary fields
        >>> for i in range(0,20):
        ...     mscop = {"time":i+1,"complex":1}
        ...     fc.add_field(mscop,dpf.Field(nentities=i+10))

        >>> fields = fc.get_fields({"time":2})
        >>> # imaginary and real fields of time 2
        >>> len(fields)
        2

        """

        return super()._get_entries(label_space)

    def get_field(self, label_space_or_index):
        """Retrieves the field at a requested index or label space.

        An exception is raised if the number of fields matching the request is
        greater than one.

        Parameters
        ----------
        label_space_or_index : dict[str,int], int
            Scoping of the requested fields. For example,
            ``{"time": 1, "complex": 0}`` or the index of the field.

        Returns
        -------
        field : Field
            Field corresponding to the request.

        Examples
        --------
        >>> from ansys.dpf import core as dpf
        >>> fc = dpf.fields_container_factory.over_time_freq_fields_container(
        ...     [dpf.Field(nentities=10)]
        ... )
        >>> field = fc.get_field({"time":1})

        """
        return super()._get_entry(label_space_or_index)

    def get_field_by_time_id(self, timeid=None):
        """Retrieves the complex field at a requested time.

        Parameters
        ----------
        timeid: int, optional
            Time ID, which is the one-based index of the result set.

        Returns
        -------
        fields : Field
            Fields corresponding to the request.
        """
        if not self.has_label("time"):
            raise dpf_errors.DpfValueError("The fields container is not based on time scoping.")

        if self.has_label("complex"):
            label_space = self.__time_complex_label_space__(timeid, 0)
        else:
            label_space = self.__time_complex_label_space__(timeid)

        return super()._get_entry(label_space)

    def get_imaginary_fields(self, timeid=None):
        """Retrieve the complex fields at a requested time.

        Parameters
        ----------
        timeid: int, optional
            Time ID, which is the one-based index of the result set.

        Returns
        -------
        fields : list[Field]
            Fields corresponding to the request.
        """
        if not self.has_label("complex") or not self.has_label("time"):
            raise dpf_errors.DpfValueError(
                "The fields container is not based on time and complex scoping."
            )

        label_space = self.__time_complex_label_space__(timeid, 1)

        return super()._get_entries(label_space)

    def get_imaginary_field(self, timeid=None):
        """Retrieve the complex field at a requested time.

        Parameters
        ----------
        timeid: int, optional
            Time ID, which is the one-based index of the result set.

        Returns
        -------
        fields : Field
            Field corresponding to the request.
        """
        if not self.has_label("complex") or not self.has_label("time"):
            raise dpf_errors.DpfValueError(
                "The fields container is not based on time and complex scoping."
            )

        label_space = self.__time_complex_label_space__(timeid, 1)

        return super()._get_entry(label_space)

    def __getitem__(self, key):
        """Retrieve the field at a requested index.

        Parameters
        ----------
        key : int
            Index.

        Returns
        -------
        field : Field
            Field corresponding to the request.
        """
        return super().__getitem__(key)

    def add_field(self, label_space, field):
        """Add or update a field at a requested label space.

        Parameters
        ----------
        label_space : dict[str,int]
            Label space of the requested field. For example,
            {"time":1, "complex":0}.
        field : Field
            DPF field to add or update.

        Examples
        --------
        >>> from ansys.dpf import core as dpf
        >>> fc= dpf.FieldsContainer()
        >>> fc.labels =['time','complex']
        >>> for i in range(0,20): #real fields
        ...     mscop = {"time":i+1,"complex":0}
        ...     fc.add_field(mscop,dpf.Field(nentities=i+10))
        >>> for i in range(0,20): #imaginary fields
        ...     mscop = {"time":i+1,"complex":1}
        ...     fc.add_field(mscop,dpf.Field(nentities=i+10))

        """
        super()._add_entry(label_space, field)

    def add_field_by_time_id(self, field, timeid=1):
        """Add or update a field at a requested time ID.

        Parameters
        ----------
        field : Field
            DPF field to add or update.
        timeid: int, optional
            Time ID for the requested time set. The default is ``1``.

        """
        labels = self.labels
        if not self.has_label("time") and (
            len(self.labels) == 0 or (len(self.labels) == 1 and self.has_label("complex"))
        ):
            self.add_label("time")
        if len(self.labels) == 1:
            super()._add_entry({"time": timeid}, field)
        elif self.has_label("time") and self.has_label("complex") and len(labels) == 2:
            super()._add_entry({"time": timeid, "complex": 0}, field)
        else:
            raise dpf_errors.DpfValueError(
                "The fields container is not only based on time scoping."
            )

    def add_imaginary_field(self, field, timeid=1):
        """Add or update an imaginary field at a requested time ID.

        Parameters
        ----------
        field : Field
            DPF field to add or update.
        timeid: int, optional
            Time ID for the requested time set. The default is ``1``.
        """
        if not self.has_label("time") and (
            len(self.labels) == 0 or (len(self.labels) == 1 and self.has_label("complex"))
        ):
            self.add_label("time")
        if not self.has_label("complex") and len(self.labels) == 1 and self.has_label("time"):
            self.add_label("complex")
        if self.has_label("time") and self.has_label("complex") and len(self.labels) == 2:
            super()._add_entry({"time": timeid, "complex": 1}, field)
        else:
            raise dpf_errors.DpfValueError(
                "The fields container is not only based on time scoping."
            )

    def select_component(self, index):
        """Select fields containing only the component index.

        Fields can be selected only by component index as multiple fields may
        contain a different number of components.

        Parameters
        ----------
        index : int
            Index of the component.

        Returns
        -------
        fields : FieldsContainer
            Fields container with one component selected in each field.

        Examples
        --------
        Select using a component index.

        >>> from ansys.dpf import core as dpf
        >>> from ansys.dpf.core import examples
        >>> transient = examples.download_transient_result()
        >>> model = dpf.Model(transient)
        >>> disp = model.results.displacement()
        >>> disp.inputs.time_scoping.connect([1,5])
        >>> fields_container = disp.outputs.fields_container()
        >>> disp_x_fields = fields_container.select_component(0)
        >>> my_field = disp_x_fields[0]

        """
        comp_select = dpf.core.Operator("component_selector_fc")
        comp_select.connect(0, self)
        comp_select.connect(1, index)
        return comp_select.outputs.fields_container.get_data()

    @property
    def time_freq_support(self):
        """Time frequency support."""
        return self._get_time_freq_support()

    @time_freq_support.setter
    def time_freq_support(self, value):
        return super()._set_time_freq_support(value)

    def deep_copy(self, server=None):
        """Create a deep copy of the fields container's data (and its fields) on a given server.

        This method is useful for passing data from one server instance to another.

        Parameters
        ----------
        server : ansys.dpf.core.server, optional
            Server with the channel connected to the remote or local instance.
            The default is ``None``, in which case an attempt is made to use the
            global server.

        Returns
        -------
        fields_container_copy : FieldsContainer

        Examples
        --------
        >>> from ansys.dpf import core as dpf
        >>> from ansys.dpf.core import examples
        >>> transient = examples.download_transient_result()
        >>> model = dpf.Model(transient)
        >>> disp = model.results.displacement()
        >>> disp.inputs.time_scoping.connect([1,5])
        >>> fields_container = disp.outputs.fields_container()
        >>> other_server = dpf.start_local_server(as_global=False)
        >>> deep_copy = fields_container.deep_copy(server=other_server)

        """
        fc = FieldsContainer(server=server)
        fc.labels = self.labels
        for i, f in enumerate(self):
            fc.add_field(self.get_label_space(i), f.deep_copy(server))
        try:
            fc.time_freq_support = self.time_freq_support.deep_copy(server)
        except:
            pass
        return fc

    def get_time_scoping(self):
        """Retrieves the time scoping containing the time sets.

        Returns
        -------
        scoping: Scoping
            Scoping containing the time set IDs available in the fields container.
        """
        return self.get_label_scoping("time")

    def animate(self, save_as=None, deform_by=None, scale_factor=1.0, **kwargs):
        """Creates an animation based on the Fields contained in the FieldsContainer.

        This method creates a movie or a gif based on the time ids of a FieldsContainer.
        For kwargs see pyvista.Plotter.open_movie/add_text/show.

        Parameters
        ----------
        save_as : Path of file to save the animation to. Defaults to None. Can be of any format
            supported by pyvista.Plotter.write_frame (.gif, .mp4, ...).
        deform_by : FieldsContainer, Result, Operator, optional
            Used to deform the plotted mesh. Must return a FieldsContainer of the same length as
            self, containing 3D vector Fields of distances.
            Defaults to None, which takes self if possible. Set as False to force static animation.
        scale_factor : float, list, optional
            Scale factor to apply when warping the mesh. Defaults to 1.0. Can be a list to make
            scaling frequency-dependent.
        """
        from ansys.dpf.core.animator import Animator

        # Create a workflow defining the result to render at each step of the animation
        wf = dpf.core.Workflow()
        # First define the workflow index input
        forward_index = dpf.core.operators.utility.forward()
        wf.set_input_name("loop_over", forward_index.inputs.any)
        # Define the field extraction using the fields_container and indices
        extract_field_op = dpf.core.operators.utility.extract_field(self)
        to_render = extract_field_op.outputs.field
        n_components = self[0].component_count
        if n_components > 1:
            norm_op = dpf.core.operators.math.norm(extract_field_op.outputs.field)
            to_render = norm_op.outputs.field

        loop_over = self.get_time_scoping()
        frequencies = self.time_freq_support.time_frequencies
        if frequencies is None:
            raise ValueError("The fields_container has no time_frequencies.")

        # TODO /!\ We should be using a mechanical::time_selector, however it is not wrapped.

        wf.set_input_name("indices", extract_field_op.inputs.indices)  # Have to do it this way
        wf.connect("indices", forward_index)  # Otherwise not accepted
        # Add the operators to the workflow
        wf.add_operators([extract_field_op, forward_index])

        deform = True
        # Define whether to deform and what with
        if deform_by is not False:
            if deform_by is None or isinstance(deform_by, bool):
                # By default, set deform_by as self if nodal 3D vector field
                if self[0].location == dpf.core.common.locations.nodal and n_components == 3:
                    deform_by = self
                else:
                    deform = False
            if deform_by and not isinstance(deform_by, dpf.core.FieldsContainer):
                deform_by = deform_by.eval()
                if len(deform_by) != len(self):
                    raise ValueError(
                        "'deform_by' argument must result in a FieldsContainer "
                        "of same length as the animated one "
                        f"(len(deform_by.eval())={len(deform_by)} "
                        f"!= len(self)={len(self)})."
                    )
        else:
            deform = False

        if deform:
            scale_factor_fc = dpf.core.animator.scale_factor_to_fc(scale_factor, deform_by)
            scale_factor_invert = dpf.core.operators.math.invert_fc(scale_factor_fc)
            # Extraction of the field of interest based on index
            # time_selector = dpf.core.Operator("mechanical::time_selector")
            extract_field_op_2 = dpf.core.operators.utility.extract_field(deform_by)
            wf.set_input_name("indices", extract_field_op_2.inputs.indices)
            wf.connect("indices", forward_index)  # Otherwise not accepted
            # Scaling of the field based on scale_factor and index
            extract_scale_factor_op = dpf.core.operators.utility.extract_field(scale_factor_invert)
            wf.set_input_name("indices", extract_scale_factor_op.inputs.indices)
            wf.connect("indices", forward_index)  # Otherwise not accepted

            divide_op = dpf.core.operators.math.component_wise_divide(
                extract_field_op_2.outputs.field, extract_scale_factor_op.outputs.field
            )
            wf.set_output_name("deform_by", divide_op.outputs.field)
        else:
            scale_factor = None
        wf.set_output_name("to_render", to_render)
        wf.progress_bar = False

        loop_over_field = dpf.core.fields_factory.field_from_array(
            frequencies.data[loop_over.ids - 1]
        )
        loop_over_field.scoping.ids = loop_over.ids
        loop_over_field.unit = frequencies.unit

        # Initiate the Animator
        anim = Animator(workflow=wf, **kwargs)

        kwargs.setdefault("freq_kwargs", {"font_size": 12, "fmt": ".3e"})

        return anim.animate(
            loop_over=loop_over_field,
            save_as=save_as,
            scale_factor=scale_factor,
            **kwargs,
        )

    def __add__(self, fields_b):
        """Add two fields or two fields containers.

        Returns
        -------
        add : operators.math.add_fc
        """
        from ansys.dpf.core import dpf_operator
        from ansys.dpf.core import operators

        if hasattr(operators, "math") and hasattr(operators.math, "add_fc"):
            op = operators.math.add_fc(self, fields_b, server=self._server)
        else:
            op = dpf_operator.Operator("add_fc", server=self._server)
            op.connect(0, self)
            op.connect(1, fields_b)
        return op

    def __sub__(self, fields_b):
        """Subtract two fields or two fields containers.

        Returns
        -------
        minus : operators.math.minus_fc
        """
        from ansys.dpf.core import dpf_operator
        from ansys.dpf.core import operators

        if hasattr(operators, "math") and hasattr(operators.math, "minus_fc"):
            op = operators.math.minus_fc(server=self._server)
        else:
            op = dpf_operator.Operator("minus_fc", server=self._server)
        op.connect(0, self)
        op.connect(1, fields_b)
        return op

    def __pow__(self, value):
        if value != 2:
            raise ValueError('DPF only the value is "2" supported')
        from ansys.dpf.core import dpf_operator
        from ansys.dpf.core import operators

        if hasattr(operators, "math") and hasattr(operators.math, "sqr_fc"):
            op = operators.math.sqr_fc(server=self._server)
        else:
            op = dpf_operator.Operator("sqr_fc", server=self._server)
        op.connect(0, self)
        op.connect(1, value)
        return op

    def __mul__(self, value):
        """Multiply two fields or two fields containers.

        Returns
        -------
        mul : operators.math.generalized_inner_product_fc
        """
        from ansys.dpf.core import dpf_operator
        from ansys.dpf.core import operators

        if hasattr(operators, "math") and hasattr(operators.math, "generalized_inner_product_fc"):
            op = operators.math.generalized_inner_product_fc(server=self._server)
        else:
            op = dpf_operator.Operator("generalized_inner_product_fc", server=self._server)
        op.connect(0, self)
        op.connect(1, value)
        return op