import sys
from collections import deque

def BFS(red_tomatoes):
    queue = deque(red_tomatoes) #따로 반복 처리를 할 필요가 없게 하기 위해
    while queue:
        z,x,y = queue.popleft()
        for dz,dx,dy in [(0,1,0),(0,-1,0),(0,0,1),(0,0,-1),(1,0,0),(-1,0,0)]: #현재박스에서 전후좌우
            next_z, next_x, next_y = z + dz, x + dx, y + dy
            if 0 <= next_x < n and 0 <= next_y < m and 0 <= next_z < h and tomatoe_box[next_z][next_x][next_y] == 0: #먼저 도착하는 친구가 최단거리임!!
                    queue.append((next_z,next_x,next_y))
                    tomatoe_box[next_z][next_x][next_y] = tomatoe_box[z][x][y] + 1

if __name__ == '__main__':
    m,n,h = map(int,input().split())
    red_tomatoes = []
    tomatoe_box = [[[] for _ in range(n)] for _ in range(h)] #3차원 리스트로 토마토 박스를 생성
    green_tomatoes = []
    for height in range(h):
        for row in range(n):
            for col,t in enumerate(map(int,sys.stdin.readline().split())):
                if t == 1: #익은 토마토이면 방문해야 하므로 리스트에 추가
                    red_tomatoes.append((height,row,col))
                if t == 0:
                    green_tomatoes.append((height,row,col)) #익지 않은 토마토의 위치 기억
                tomatoe_box[height][row].append(t)

    if len(green_tomatoes) == 0: #이미 모든 토마토가 익어있음
        print(0)

    else:
        BFS(red_tomatoes)
        res = 0
        for h,r,c in green_tomatoes:
            if tomatoe_box[h][r][c] == 0: #방문하지 못한 토마토가 존재하는 경우
                print(-1)
                sys.exit()  #-1을 출력하고 종료

            res = max(res,tomatoe_box[h][r][c]) #방문한 토마토 중 최대 값을 탐
        print(res - 1)


# titanic dataset으로 LogisticRegression, DecisionTree 분류 모델 비교

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from nltk.classify.decisiontree import DecisionTreeClassifier

df = pd.read_csv("../testdata/titanic_data.csv")
df.drop(columns=['PassengerId','Name','Ticket'], inplace=True)
# print(df.describe())
# print(df.info())
# print(df.isnull().sum()) #Age 177 / Cabin(방호수) 687 / Embarked(탑승지) 2

# NULL 처리 : 평균, 0, 'N(임의의문자)' 등으로 변경
df['Age'].fillna(df.Age.mean(), inplace=True)
df['Cabin'].fillna('N', inplace=True)
df['Embarked'].fillna('N', inplace=True)
# print(df.head(2))
# print(df.isnull().sum())  #0 #0 #0

# ## 데이터 가공이 중요한겁니다.
# #Dtype: object/Sex, Cabin,Embarked 값들의 상태를 분류해서 보기
# print('Sex:',df['Sex'].value_counts()) # male:577 female:314
# print('Cabin:',df['Cabin'].value_counts())
# #Cabin 값들이 너무 복잡함으로 간략하게 정리 (원본에 영향을 주면 안됨) : 앞글자만 사용하기로 하자
# print('Embarked:',df['Embarked'].value_counts())

# Cabin데이터가공 해볼까요
df['Cabin'] = df['Cabin'].str[:1]
print(df.head(5))

print()
#성별이 생존확률에 어떤 영향을 주었나?
print(df.groupby(['Sex','Survived'])['Survived'].count())
print(233/(81+233))  #여성 생존률 74.2%
print(109/(468+109)) #남성 생존률 18.9%

#성별 생존 확률에 대한 시각화 한 번 해볼까요
# sns.barplot(x='Sex',y='Survived', data=df, ci=95) #ci:신뢰구간 95%
# plt.xlabel('Sex')
# plt.ylabel('Survived')
# plt.show()
#나이별, Pclass가 생존확률에 어떤 영향을 주었나?...

print('----------------')
#문자열(object) 데이터(범주형 데이터)를 숫자형으로 변환
from sklearn import preprocessing #전처리 너~무나 중요하다.

# print(set(df['Cabin']))

def labelFunc(datas):
    cols=['Cabin','Sex','Embarked']
    for c in cols:
        lab = preprocessing.LabelEncoder()
        lab = lab.fit(datas[c])
        datas[c] = lab.transform(datas[c])
    return datas

df = labelFunc(df)

print(df.head(3))
print(df['Cabin'].unique()) # [ 7 2 4 6 3 0 1 5 8]
print(df['Sex'].unique())  # [1 0]
print(df['Embarked'].unique()) # [3 0 2 1]

#일단 쪼개놓고 가볼까요.
print()
feature_df = df.drop(['Survived'], axis='columns')  #axis='columns'
print(feature_df.head(2))
label_df = df['Survived']
print(label_df.head(2))

x_train, x_test, y_train, y_test = train_test_split(feature_df, label_df, test_size=0.2, random_state=1)
print(x_train.shape,x_test.shape,y_train.shape, y_test.shape) #(712, 8) (179, 8) (712,) (179,) feature(특성)은 여덟게 label은 하나

print('---------우리가 하려는게 요거야------------')
#LogisticRegression, DecisionTree,RandomForest 분류 모델 비교
logmodel = LogisticRegression(solver='lbfgs', max_iter=500).fit(x_train, y_train)
# solver='lbfgs' 알고리즘의 이름을 줄여쓴것. Limited-memory Broyden–Fletcher–Goldfarb–Shanno
# max_iter 반복횟수
decmodel = DecisionTreeClassifier().fit(x_train, y_train)
rfmodel = RandomForestClassifier().fit(x_train, y_train)

logpredict = logmodel.predict(x_test)
print('LogisticRegression acc: {0:.5f}'.format(accuracy_score(y_test, logpredict)))
decpredict = decmodel.predict(x_test)
print('DecisionTree acc: {0:.5f}'.format(accuracy_score(y_test, decpredict)))
rfpredict = rfmodel.predict(x_test)
print('RandomForest acc: {0:.5f}'.format(accuracy_score(y_test, rfpredict)))


from datetime import datetime
from html import escape, unescape
from time import time
from pytz import timezone, utc

class Entry(object):
    user_tz = None

    def __init__(self, text, timestamp=None):
        """
        'text' is the entry's text. Escape it so that we can use <,&, ; etc in the journal.
        'timestamp' is the seconds since the epoch, e.g., as returned by time.time()
        """
        self.text = escape(text)
        if timestamp:
            self.timestamp = float(timestamp)
        else:
            self.timestamp = time()

    def __str__(self):
        naive_dt = datetime.fromtimestamp(self.timestamp)
        if Entry.user_tz:
            utc_dt = utc.localize(naive_dt)
            local_dt = timezone(Entry.user_tz)
            user_dt = utc_dt.astimezone(local_dt)
        else:
            user_dt = naive_dt
        return "{}

{}".format(user_dt.strftime("%c"), unescape(self.text))

    @staticmethod
    def sort_entries(entries, since=0):
        filtered_entries = entries
        if since:
            filtered_entries = filter(lambda e: e.timestamp > time() - since, entries)
        return sorted(filtered_entries, key=lambda e: e.timestamp)

    @staticmethod
    def check_attributes(obj):
        if not hasattr(obj, 'text'):
            raise TypeError("Entry object lacks a 'text' attribute")
        if not hasattr(obj, 'timestamp'):
            raise TypeError("Entry object lacks a 'timestamp' attribute")


'''
Python script to compare two items.json files to see if there are differences between all of the included entries in the "mod" items.json file. My use case is to check my mod's items.json with the main items.json to find if BSG has updated anything since I first obtained the item entries.

Input: Two items.json files.

Output: Prints the entries by item ID that are different/have changed.

Obviously you need python installed to run these scripts (Google that if you need to install it...). You might also need some dependencies, I can't remember what comes with python so try it and see if it says you need to install any.

Written by Mighty_Condor
2023-01-25
'''
import json
import os

#copyPrefabPaths is a flag to tell the script to instead copy prefab paths from an existing mod items.json to the main items.json, used in conjunction with extract_items_by_ID. If anyone else is ever using this, you probably won't want to set this to True ever...
copyPrefabPaths = False

def main():

    print("\n\n")

    items_path = getFile("Drag and drop or enter the path to the main items.json file: ")
    mod_path = getFile("Drag and drop or enter the path to the mod's items.json file: ")
    if copyPrefabPaths:
        outputDirectory = getOutputDirectory()

    file_items = open(items_path, encoding='utf-8')
    file_mod = open(mod_path, encoding='utf-8')

    items = json.load(file_items)
    mod_items = json.load(file_mod)

    difference = []

    if copyPrefabPaths:

        for mod_item in mod_items:
            items[mod_item]["_props"]["Prefab"]["path"] = mod_items[mod_item]["_props"]["Prefab"]["path"]

        try:
            outputFile = open(outputDirectory + "\\output.json", "w", encoding='utf-8')
            json.dump(items, outputFile, ensure_ascii=False, indent=4)
        except: error("There was an error trying to write the output folder/file", 1)

    else:

        for item in mod_items:
            if ( mod_items[item] == items[item] ):
                continue
            else:
                difference.append(item)

        print(difference, "\n\n")

    input("Press any key to exit")

def error(errorString, fatal) :

    print("\n\n" + errorString, "\n\n")
    if (fatal):
        input("Press any key to exit")
        exit()
    else:
        input("Press any key to continue, or exit manually by closing the window or CTRL+C now.")

def getFile(prompt):

    directory = input(prompt)

    try: directory = directory.replace('"', '')
    except: error("There was an error fixing the directory path", 1)

    print("\n\nDirectory: ", directory, "\n\n")

    try: os.path.isfile(directory)
    except: error("There was an error finding that file", 1)

    print("File found!\n\n")

    return directory

def getOutputDirectory():

    outputDirectory = input("Drag and drop or enter the path to the folder where you want the output .json: ")

    try: outputDirectory = outputDirectory.replace('"', '')
    except: error("There was an error fixing the directory path", 1)

    print("\n\nDirectory: ", outputDirectory, "\n\n")

    try: os.chdir(outputDirectory)
    except: error("There was an error navigating to that directory", 1)

    print("Directory found!\n\n")

    return outputDirectory

if __name__ == '__main__': main()


import os
import sys
from django.core.management.utils import get_random_secret_key

# Use everything from settings.local, write a minimal template if it does not
# exist and alert user.
try:
    from .local import *
except ImportError:
    sys.stderr.write(
        "Could not find dceu2019/src/dceu2019/settings/local.py, creating a "
        "default one. Please customize it with your SECRET_KEY, DATABASES etc. "
        "and start again.\n"
    )
    default = (
        """# Using development settings, replace in production!\n"""
        """from .dev import *  # noqa\n"""
        """\n"""
        """SECRET_KEY = "{secret_key}"\n"""
        """DATABASES = {{\n"""
        """    "default": {{\n"""
        """        "ENGINE": "django.db.backends.sqlite3",\n"""
        """        "NAME": str(BASE_DIR.parent.parent / "db.sqlite3"),\n"""
        """    }}\n"""
        """}}\n"""
    ).format(
        secret_key=get_random_secret_key()
    )
    f = open(os.path.join(os.path.dirname(__file__), "local.py"), "w")
    f.write(
        default
    )
    sys.exit(1)


# 이전에 일반항을 잘못 생각해서 새로 짠 코드

import sys
from itertools import permutations
sys.stdin = open('input1.txt')

N, F = map(int, input().split())

pascal = []
numbers = list(range(1, N+1))

A = Q = 1
for r in range(N):
    if r == 0 or r == N-1:
        pascal.append(1)
    else:
        A *= (N-r)
        Q *= r
        pascal.append(int(A/Q))

perms = permutations(numbers)
for p in perms:
    tmp = 0
    for i in range(N):
        tmp += p[i]*pascal[i]
    if tmp == F:
        print(*p)
        break


import os
import time
import shutil
import bottle

# TODO handle logging

class webserver(bottle.Bottle):

    def __init__(self, host, port, soundboard):
        self.soundboard = soundboard
        self.host = host
        self.port = port
        self._app = bottle.Bottle()
        bottle.TEMPLATE_PATH.append('./html/templates')
        self.setup_routes()

    def setup_routes(self):
        # static files
        self._app.route("/assets/js/<filepath:re:.*\.js>",
                        callback=lambda filepath:bottle.static_file(filepath, root="html/js"))
        self._app.route("/assets/css/<filepath:re:.*\.(css|map)>",
                        callback=lambda filepath:bottle.static_file(filepath, root="html/css"))
        self._app.route("/assets/img/<filepath:re:.*\.(jpg|png|gif|ico|svg)>",
                         callback=lambda filepath:bottle.static_file(filepath, root="html/img"))
        self._app.route("/assets/font/<filepath:re:.*\.(eot|otf|svg|ttf|woff|woff2?)>",
                        callback=lambda filepath:bottle.static_file(filepath, root="html/font"))

        self._app.route('/', callback=self.index)
        self._app.route('/upload', method="GET", callback=self.upload)
        self._app.route('/upload', method="POST", callback=self.upload)
        self._app.route('/api/threads', method="GET", callback=self.api_threads)
        self._app.route('/api/samples/list', method="GET", callback=self.api_get_samples)
        self._app.route('/api/samples/play/<name>', method="GET", callback=self.api_play_sample)
        self._app.route('/api/tones/play/square/<freq>', method="GET", callback=self.api_tone_square)

    def webserver_thread(self):
        self._app.run(host=self.host, port=self.port, debug=True)

    def index(self):
        return bottle.jinja2_template('index.tpl', samples=self.get_samples())

    def upload(self):
        if bottle.request.method == "GET":
            return bottle.jinja2_template("upload.tpl")
        if bottle.request.method == "POST":
            uploaded_file = bottle.request.files.get('sampleUpload')
            if not uploaded_file:
                return bottle.jinja2_template("upload.tpl")

            if os.path.splitext(uploaded_file.filename)[1].lower() not in ('.flac', '.wav', '.mp3', '.ogg'): # TODO config
                return bottle.jinja2_template("upload.tpl", alert={"type": "alert-danger",
                    "msg": f"Filetype {os.path.splitext(uploaded_file.filename)[1].lower()} is not supported.\
                    Supported file types are wav, mp3, ogg and flac"})

            if os.path.exists(os.path.join(self.soundboard.config['sample_path'], uploaded_file.filename)):
                 return bottle.jinja2_template("upload.tpl", alert={"type": "alert-danger",
                    "msg": f"There is already a sample called {uploaded_file.filename}, please choose a different name."})

            temp_file = str(time.time()).split(".")[0] + os.path.splitext(uploaded_file.filename)[1]
            temp_path = os.path.join("cache/", temp_file) #todo config
            uploaded_file.save(temp_path)

            if os.path.getsize(temp_path) >= 3145728: # TODO config
                return bottle.jinja2_template("upload.tpl", alert={"type": "alert-danger",
                    "msg": f"{os.path.basename(uploaded_file.filename)} is too big! Max allowed size is 3MiB"})

            shutil.move(temp_path, os.path.join(self.soundboard.config['sample_path'], uploaded_file.filename.replace(" ", "_")))
            return bottle.jinja2_template("upload.tpl", alert={"type": "alert-success",
                    "msg": f"Upload successful!"})

    def get_samples(self):
        samples = []
        for sample in sorted(os.listdir(self.soundboard.config['sample_path'])):
            if not os.path.isdir(os.path.join(self.soundboard.config['sample_path'], sample)):
                samples.append({"name": os.path.splitext(sample)[0],
                                "ext": os.path.splitext(sample)[-1],
                                "path": os.path.join(self.soundboard.config['sample_path'], sample),
                                "size": os.path.getsize(os.path.join(self.soundboard.config['sample_path'], sample))})
        return samples

    # API
    def api_threads(self):
        return {"response": "OK", "threads":[str(t) for t in self.soundboard.threads]}

    def api_get_samples(self):
        return {"response": "OK", "samples": self.get_samples()}

    def api_play_sample(self, name):
        samples = self.get_samples()

        for sample in samples:
            if name in sample['name']:
                self.soundboard.samplePlayer.play_sample(sample['path'])
                return {"response": "OK"}

        return {"response": "FAIL", "MSG": f"Couldn't find {name}"}

    def api_tone_square(self, freq):
        self.soundboard.toneGenerator.toneQueue.put({"type": "square", "freq": freq, "duration": 1.0})
        return {"response": "OK"}


# -*- coding: utf-8 -*-
import os
import maya.cmds as mc

def get_same_base_name_textures():
    wrong_files = list()
    files = mc.ls(type="file")
    if not files:
        return
    texture_names = [mc.getAttr("%s.computedFileTextureNamePattern" % f) for f in files]
    if not texture_names:
        return
    texture_names = list(set(texture_names))
    base_names = [os.path.basename(texture_name) for texture_name in texture_names]
    repeat_base_names = list()
    for base_name in base_names:
        num = base_names.count(base_name)
        if num > 1:
            repeat_base_names.append(base_name)
    if not repeat_base_names:
        return
    repeat_base_names = list(set(repeat_base_names))
    same_base_name_files = list()
    for base_name in repeat_base_names:
        temp_list = list()
        for texture_name in texture_names:
            if os.path.basename(texture_name) == base_name:
                temp_list.append(texture_name)
        same_base_name_files.append(temp_list)
    for i in same_base_name_files:
        if len(list(set(i))) != 1:
            wrong_files.extend(i)
    return wrong_files


'''
Step 4 - Reporting

Author: Oliver
Date: 2022, March

'''
import pandas as pd
import numpy as np
from sklearn import metrics
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
import json
import os

from diagnostics import model_predictions

# initialization
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)-15s %(message)s")
logger = logging.getLogger()

config = {}
def init():
    global config
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    with open('config.json','r') as f:
         config = json.load(f)
    logger.info(f"Current working dir: {os.getcwd()}")
    logger.info(f"Config dictionary: {config}")

# Exception handling

###############Load config.json and get path variables
config = {}
def init():
    global config
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    logger.info(f"Current working dir: {os.getcwd()}")
    with open('config.json','r') as f:
         config = json.load(f)

def plot_confusion_matrix(save_pth: str, act: np.array, preds: np.array, ):
    '''
    Plot/save a confusion matrix.
    '''
    # plot
    cm = confusion_matrix(act, preds)
    fig = plt.figure()

    ax = fig.add_subplot(111)
    cax = ax.matshow(cm)
    fig.colorbar(cax)
    labels = ['False', 'True']
    ax.set_xticklabels([''] + labels)
    ax.set_yticklabels([''] + labels)
    plt.title('Confusion matrix')
    plt.xlabel('Predicted')
    plt.ylabel('Actual')
    plt.savefig(save_pth)

def reporting(model_pth: str, data_pth: str, plot_pth: str):
    '''
    Create a confusion matrix based on a dataset stored in data_path. Plot saved in model_path.
    '''
    #calculate a confusion matrix using the test data and the deployed model
    #write the confusion matrix to the workspace
    df = pd.read_csv(data_pth)
    preds, act = model_predictions(model_pth, df)
    plot_confusion_matrix(plot_pth, act, preds)
    logger.info(f"Predictions: {preds}, Actuals: {act}")

if __name__ == '__main__':
    try:
        init()
        reporting(
            os.path.join(config['prod_deployment_path'], config['model']),
            os.path.join(config['test_data_path'], config['test_data']),
            os.path.join(config['output_model_path'], config['confusionmatrix'])
        )
    except Exception as err:
        print(f"Reporting Main Error: {err}")


# -*- coding: utf-8 -*-
"""
Created on Sat Jan 26 11:04:25 2019

@author: LENOVO
"""

import numpy as np

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

n = int(input())

allparts = []
for i in range(n):
    allparts.append(input())
input()  # *****
for i in range(n):
    allparts.append(input())

# Loop over all possible pairs, selecting in order of max value

tfidf = TfidfVectorizer(stop_words='english').fit_transform(allparts)
pairwise_similarity = cosine_similarity(tfidf, tfidf)

crosscorr = pairwise_similarity[n:, :n]
pairvals = [0] * n
for i in range(n):
    idx = np.argmax(crosscorr, axis=None)
    print(idx)
    multi_idx = np.unravel_index(idx, crosscorr.shape)
    pairvals[multi_idx[0]] = multi_idx[1]
    crosscorr[multi_idx[0], :] = np.ones(n) * -1
    crosscorr[:, multi_idx[1]] = np.ones(n) * -1

for v in pairvals:
    print(v+1)


import sys
import json
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from webob import Response
from ryu.app.wsgi import ControllerBase, WSGIApplication, route
from ryu.lib import dpid as dpid_lib
from ryu.topology.api import get_switch, get_link, get_host
import logging

LOG = logging.getLogger('ryu.controller.controller')

fcapf_controller_instance = 'fcapf_network_controller'

class FCAPFNetworkController(app_manager.RyuApp):
    OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
    _CONTEXTS = {'wsgi': WSGIApplication}

    def __init__(self, *args, **kwargs):
        super(FCAPFNetworkController, self).__init__(*args, **kwargs)
        self.mac_to_port = {}
        self.switches = {}
        wsgi = kwargs['wsgi']
        wsgi.register(ControllerRequestProcessor, {fcapf_controller_instance: self})

    @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
    def switch_features_handler(self, ev):
        datapath = ev.msg.datapath
        self.switches[datapath.id] = datapath
        self.mac_to_port.setdefault(datapath.id, {})

class ControllerRequestProcessor(ControllerBase):
    def __init__(self, req, link, data, **config):
        super(ControllerRequestProcessor, self).__init__(req, link, data, **config)
        self.fcapf_network_controller = data[fcapf_controller_instance]

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/flowtable/addflows', methods=['PUT'])
    def add_flows(self, req, **kwargs):
        try:
            entries = req.json if req.body else {}
            for entry in entries:
                dpid = entry['dpid']
                payload = entry['payload']
                self._set_flow_table(dpid, payload)
            status = 200
        except ValueError:
            LOG.error("Wrong input!!")
            status = 400
        except:
            status = 400
        return Response(status=status)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/flowtable/addflow/{dpid}', methods=['PUT'], requirements={'dpid': dpid_lib.DPID_PATTERN})
    def add_flow(self, req, **kwargs):
        try:
            entry = req.json if req.body else {}
            self._set_flow_table(kwargs['dpid'], entry)
            status = 200
        except ValueError:
            LOG.error("Wrong input!!")
            status = 400
        except:
            status = 400
        return Response(status=status)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/flowtable/delflows', methods=['PUT'])
    def del_flows(self, req, **kwargs):
        try:
            entries = req.json if req.body else {}
            for entry in entries:
                dpid = entry['dpid']
                payload = entry['payload']
                self._delete_flow_table(dpid, payload)
            status = 200
        except ValueError:
            LOG.error("Wrong input!!")
            status = 400
        except:
            status = 400
        return Response(status=status)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/flowtable/delflow/{dpid}', methods=['PUT'], requirements={'dpid': dpid_lib.DPID_PATTERN})
    def del_flow(self, req, **kwargs):
        try:
            entry = req.json if req.body else {}
            self._delete_flow_table(kwargs['dpid'], entry)
            status = 200
        except ValueError:
            LOG.error("Wrong input!!")
            status = 400
        except:
            status = 400
        return Response(status=status)

    def _set_flow_table(self, dpid_str, entry):
        try:
            dpid = dpid_lib.str_to_dpid(dpid_str)
            contr_inst = self.fcapf_network_controller
            if dpid not in contr_inst.mac_to_port:
                return Response(status=404)
            datapath = contr_inst.switches.get(dpid)
            dl_type=entry['dltype']
            action = entry['action']
            if action == 'normal':
                action = ofproto_v1_3.OFPP_NORMAL

            ip_src = entry['ipsrc']
            ip_dest = entry['ipdest']
            if datapath is not None:
                parser = datapath.ofproto_parser
                # from known device to new device
                actions = [parser.OFPActionOutput(action)]
                if dl_type == "ip":
                    port = entry['inport']
                    match = parser.OFPMatch(in_port=port, ipv4_src=ip_src,
                        ipv4_dst=ip_dest, eth_type=0x0800)
                elif dl_type == "arp":
                    match = parser.OFPMatch(arp_spa=ip_src,
                        arp_tpa=ip_dest, eth_type=0x0806)
                else:
                    LOG.error("Wrong input!!")
                self._add_flow(datapath, 1, match, actions)
            else:
                LOG.error("Datapath not found!!")
        except:
            LOG.error("Unexpected error in _set_flow_table:", sys.exc_info()[0])
            raise

    def _delete_flow_table(self, dpid_str, entry):
        try:
            dpid = dpid_lib.str_to_dpid(dpid_str)
            contr_inst = self.fcapf_network_controller
            if dpid not in contr_inst.mac_to_port:
                return Response(status=404)
            datapath = contr_inst.switches.get(dpid)
            dl_type=entry['dltype']
            ip_src = entry['ipsrc']
            ip_dest = entry['ipdest']
            if datapath is not None:
                parser = datapath.ofproto_parser
                # from known device to new device
                if dl_type == "ip":
                    port = entry['inport']
                    match = parser.OFPMatch(in_port=port, ipv4_src=ip_src,
                        ipv4_dst=ip_dest, eth_type=0x0800)
                elif dl_type == "arp":
                    match = parser.OFPMatch(arp_spa=ip_src,
                        arp_tpa=ip_dest, eth_type=0x0806)
                else:
                    LOG.error("Wrong input!!")
                self._del_flow(datapath, match)
            else:
                LOG.error("Datapath not found!!")
        except:
            LOG.error("Unexpected error in _delete_flow_table:", sys.exc_info()[0])
            raise

    def _add_flow(self, datapath, priority, match, actions, buffer_id=None):
        try:
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser

            inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
                                                 actions)]
            if buffer_id:
                # mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                #                         priority=priority, match=match,
                #                         instructions=inst, idle_timeout=300)
                mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,
                                        priority=priority, match=match,
                                        instructions=inst)
            else:
                # mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                #                         match=match, instructions=inst, idle_timeout=300)
                mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
                                        match=match, instructions=inst)
            datapath.send_msg(mod)
        except:
            LOG.error("Unexpected error in _add_flow:", sys.exc_info()[0])
            raise

    def _del_flow(self, datapath, match):
        try:
            ofproto = datapath.ofproto
            parser = datapath.ofproto_parser
            mod = parser.OFPFlowMod( datapath, command=ofproto.OFPFC_DELETE,
                out_port=ofproto.OFPP_ANY, out_group=ofproto.OFPG_ANY,
                priority=1, match=match)
            datapath.send_msg(mod)
        except:
            LOG.error("Unexpected error in _del_flow:", sys.exc_info()[0])
            raise

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/switches', methods=['GET'])
    def list_switches(self, req, **kwargs):
        return self._switches(req, **kwargs)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/switches/{dpid}', methods=['GET'], requirements={'dpid': dpid_lib.DPID_PATTERN})
    def get_switch(self, req, **kwargs):
        return self._switches(req, **kwargs)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/links', methods=['GET'])
    def list_links(self, req, **kwargs):
        return self._links(req, **kwargs)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/links/{dpid}', methods=['GET'], requirements={'dpid': dpid_lib.DPID_PATTERN})
    def get_links(self, req, **kwargs):
        return self._links(req, **kwargs)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/hosts', methods=['GET'])
    def list_hosts(self, req, **kwargs):
        return self._hosts(req, **kwargs)

    @route('fcapfnetworkcontroller', '/fcapfnetworkcontroller/topology/hosts/{dpid}', methods=['GET'], requirements={'dpid': dpid_lib.DPID_PATTERN})
    def get_hosts(self, req, **kwargs):
        return self._hosts(req, **kwargs)

    def _switches(self, req, **kwargs):
        try:
            dpid = None
            if 'dpid' in kwargs:
                dpid = dpid_lib.str_to_dpid(kwargs['dpid'])
            switches = get_switch(self.fcapf_network_controller, dpid)
            body = json.dumps([switch.to_dict() for switch in switches])
        except:
            LOG.error("Unexpected error in _links:", sys.exc_info()[0])
        return Response(content_type='application/json', body=body)

    def _links(self, req, **kwargs):
        try:
            dpid = None
            if 'dpid' in kwargs:
                dpid = dpid_lib.str_to_dpid(kwargs['dpid'])
            links = get_link(self.fcapf_network_controller, dpid)
            # customlinks = [link.to_dict() for link in links]
            # body = json.dumps([self._preciselink(link) for link in customlinks])
            body = json.dumps([link.to_dict() for link in links])
        except:
            LOG.error("Unexpected error in _links:", sys.exc_info()[0])
        return Response(content_type='application/json', body=body)

    def _hosts(self, req, **kwargs):
        try:
            dpid = None
            if 'dpid' in kwargs:
                dpid = dpid_lib.str_to_dpid(kwargs['dpid'])
            hosts = get_host(self.fcapf_network_controller, dpid)
            body = json.dumps([host.to_dict() for host in hosts])
        except:
            LOG.error("Unexpected error in _links:", sys.exc_info()[0])
        return Response(content_type='application/json', body=body)

    def _preciselink(self, link):
        try:
            plink={
                'src':{
                    'port_no': link['src']['port_no'],
                    'dpid': link['src']['dpid']
                },
                'dst':{
                    'port_no': link['dst']['port_no'],
                    'dpid': link['dst']['dpid']
                }
            }
        except:
            LOG.error("Unexpected error in _links:", sys.exc_info()[0])
        return plink


import tkinter as tk
from tkinter import filedialog
import pandas as pd
import graphviz
from sklearn import tree
import matplotlib.pyplot as plt
import decisionTree

class DecisionTreeGUI:

    def __init__(self):
        self.dt = None
        self.window = tk.Tk()
        self.window.title("Decision Tree GUI")

        self.csv_file_label = tk.Label(self.window, text="CSV File:")
        self.csv_file_label.pack()
        self.csv_file_entry = tk.Entry(self.window)
        self.csv_file_entry.pack()

        self.browse_button = tk.Button(self.window, text="Browse", command=self.browse_csv_file)
        self.browse_button.pack()

        self.train_button = tk.Button(self.window, text="Train", command=self.train)
        self.train_button.pack()

        self.data_to_predict_label = tk.Label(self.window, text="Data to Predict:")
        self.data_to_predict_label.pack()
        self.data_to_predict_entry = tk.Entry(self.window)
        self.data_to_predict_entry.pack()

        self.predict_button = tk.Button(self.window, text="Predict", command=self.predict)
        self.predict_button.pack()

        self.generate_pdf_button = tk.Button(self.window, text="Generate PDF", command=self.generate_pdf)
        self.generate_pdf_button.pack()

        self.window.mainloop()

    def browse_csv_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("CSV Files", "*.csv")])
        if file_path:
            self.csv_file_entry.delete(0, tk.END)
            self.csv_file_entry.insert(tk.END, file_path)

    def train(self):
        csv_file_path = self.csv_file_entry.get()

        if csv_file_path:
            dataset = pd.read_csv(csv_file_path)
            print(dataset)
            self.dt = decisionTree.DecisionTree(dataset)
            self.dt.train()

            print("Training completed.")
        else:
            print("Please select a CSV file.")

    def predict(self):
        data_to_predict = self.data_to_predict_entry.get()
        if data_to_predict:
            data_to_predict = eval(data_to_predict)  # Convert string to list
            predicted_output = self.dt.predict(data_to_predict)
            print("Predicted output: ", predicted_output)
        else:
            print("Please enter the data to predict.")

    def generate_pdf(self):
        if hasattr(self, 'dt'):
            tree.plot_tree(self.dt.dtc)
            plt.show()
            dot_data = tree.export_graphviz(self.dt.dtc, out_file=None,
                                            feature_names=self.dt.df_encoded.columns[:-1],
                                            class_names=self.dt.label_encoder.classes_,
                                            filled=True, rounded=True)
            graph = graphviz.Source(dot_data)
            graph.render("mytree1")
            print("PDF generated.")
        else:
            print("Please train the model first.")


from app import app, db, mail
from app.models import User, Post

from app.forms import LoginForm, RegistrationForm, UpdateForm, RequestResetForm, ResetPasswordForm, BookMassageForm
from flask import render_template, url_for, redirect,jsonify, flash, request
from flask_login import login_user,logout_user,  current_user, login_required
from werkzeug.urls import url_parse
import secrets
from PIL import Image
import os
from flask_mail import Message

@app.route("/terms")
def terms():
    return render_template("terms.html",title="Terms Page")

@app.route('/')
@app.route('/home')
def home():
	"""
	if current_user.is_authenticated:
		user= {
		'username': User.query.get(current_user.get_id()).lastname,
		'career': "Developer"
		}
	else:
		user = {
		"username": "Sample User",
		"career": "Sample Career"
		}

	posts = Post.query.order_by(Post.timestamp).all()
	print(posts)
	"""

	return render_template('home.html', title="Home Page")

@app.route('/login', methods=['GET', 'POST'])
def login():

	if current_user.is_authenticated:
		return redirect(url_for("home"))

	form = LoginForm()

	if form.validate_on_submit():
		user = User.query.filter_by(email = form.email.data).first()

		if user == None or not user.check_password(form.password.data):
			flash("Invalid credentials")
			return redirect(url_for('login'))
		login_user(user, remember = form.remember_me.data)

		#Ensures redirect to desired page after login verification
		next_page = request.args.get('next')

		if not next_page or url_parse(next_page).netloc != '':
			next_page = url_for('home')

		return redirect(next_page)

	return render_template('login.html', title="Login Page", form=form)

@app.route('/logout')
@login_required
def logout():
	logout_user()
	return redirect(url_for('login'))

@app.route('/admin', methods=['POST', 'GET'])
@login_required
def admin():

	if not current_user.is_authenticated :
		return redirect(url_for("login"))

	user_id = current_user.get_id()
	user = User.query.get(user_id)

	if user.email != app.config['ADMINISTRATOR_MAIL']:
		return redirect(url_for("home"))

	flash("Welcome Administrator!")

	return render_template("admin.html", title="Admin Page")

@app.route('/registration', methods=['GET', 'POST'])
def registration():
	if current_user.is_authenticated:
		return redirect(url_for('home'))

	form = RegistrationForm()

	if form.validate_on_submit():
		user = User(firstname=form.firstname.data, lastname=form.lastname.data, email=form.email.data, phone_number= form.phone_number.data)
		user.set_password(form.password.data)
		print(user.email)

		db.session.add(user)
		db.session.commit()
		flash('Registration successful.')

		return redirect(url_for('login'))

	return render_template("registration.html", title="Registration Page", form = form)

@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html'), 404

@app.errorhandler(500)
def internal_error(error):
    db.session.rollback()
    return render_template('500.html'), 500

#Save profile picture logic
def save_picture(form_picture):
	random_hex = secrets.token_hex(8)
	_, f_ext = os.path.splitext(form_picture.filename)
	picture_fn = random_hex + f_ext
	picture_path = os.path.join(app.root_path, 'static/profile_images', picture_fn)

	#Resize Image
	output_size = (250, 250)
	i = Image.open(form_picture)
	i.thumbnail(output_size)
	i.save(picture_path)
	return picture_fn

@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
	if not current_user.is_authenticated:
		return redirect(url_for("login"))

	form = UpdateForm()

	if form.validate_on_submit():

		if form.picture.data:
			#flash("Picture Data Available!!")
			picture_file = save_picture(form.picture.data)
			current_user.image_pic = picture_file

		current_user.firstname = form.firstname.data
		current_user.lastname = form.lastname.data
		current_user.email = form.email.data
		current_user.phone_number = form.phone_number.data
		db.session.commit()

		flash("Profile updated!")
		return redirect(url_for('profile'))
	elif request.method == 'GET':

		form.firstname.data = current_user.firstname
		form.lastname.data = current_user.lastname
		form.phone_number.data = current_user.phone_number
		form.email.data = current_user.email
		print(form.picture.data)

	posts = Post.query.filter_by(user_id= current_user.get_id()).all()
	image = url_for('static', filename='profile_images/'+ current_user.image_pic)

	return render_template("profile.html", title='Profile Page', posts=posts, image=image, form=form)

@app.route('/about', methods=['GET', 'POST'])
def about():
	return render_template('about.html', title='About Page')

@app.route('/contact', methods=['GET', 'POST'])
def contact():
	return render_template('contact.html', title='Contact Page')

def send_reset_email(user):
	token = user.get_reset_token()
	msg = Message('Password Reset Request', sender='artmanafrica.com', recipients=[user.email])
	msg.body = f'''To reset your password, visit the following link: {url_for('reset_token', token=token, _external=True)}
	If you did not make this request then simply ignore this message and no changes will be made.
	'''
	mail.send(msg)

@app.route('/reset_password', methods=['GET', 'POST'])
def reset_request():
	if current_user.is_authenticated:
		return redirect(url_for('home'))
	form = RequestResetForm()
	if form.validate_on_submit():
		user = User.query.filter_by(email=form.email.data).first()
		send_reset_email(user)
		flash('Check your email for instructions to reset your password.')
		return redirect(url_for('login'))
	return render_template('reset_request.html',title='Reset Password', form=form)

@app.route('/reset_password/<token>', methods=['GET', 'POST'])
def reset_token(token):
	if current_user.is_authenticated:
		return redirect(url_for('home'))
	user = User.verify_token(token)
	if user is None:
		flash('This is an expired or invalid token.')
		return redirect(url_for('reset_request'))
	form = ResetPasswordForm()
	if form.validate_on_submit():
		user.set_password(form.password.data)
		db.session.commit()
		flash('Password updated successfully.')
		return redirect(url_for('login'))
	return render_template('reset_token.html', form=form, title='Reset Password ')

@app.route('/swedish', methods=['GET', 'POST'])
@login_required
def swedish():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('swedish.html', form=form, title= "Swedish Massage")

@app.route('/sports', methods=['GET', 'POST'])
@login_required
def sports():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('sports.html', form=form, title= "Sports Massage")

@app.route('/deep_tissue', methods=['GET', 'POST'])
@login_required
def deep_tissue():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('deep_tissue.html', form=form, title= "Deep Tissue Massage")

@app.route('/reflexology', methods=['GET', 'POST'])
@login_required
def reflexology():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('reflexology.html', form=form, title= "Reflexology Massage")

@app.route('/shiatsu', methods=['GET', 'POST'])
@login_required
def shiatsu():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('shiatsu.html', form=form, title= "Shiatsu Massage")

@app.route('/thai', methods=['GET', 'POST'])
@login_required
def thai():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('thai.html', form=form, title= "Thai Massage")

@app.route('/prenatal', methods=['GET', 'POST'])
@login_required
def prenatal():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('prenatal.html', form=form, title= "Prenatal Massage")

@app.route('/couples', methods=['GET', 'POST'])
@login_required
def couples():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('couples.html', form=form, title= "Couples Massage")

@app.route('/chair', methods=['GET', 'POST'])
@login_required
def chair():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('chair.html', form=form, title= "Chair Massage")

@app.route('/stone', methods=['GET', 'POST'])
@login_required
def stone():
	if not current_user.is_authenticated:
		return redirect(url_for('login'))
	form = BookMassageForm()
	if form.validate_on_submit() and current_user.is_authenticated:
		massage = form.massage.data
		scheduled_on = form.scheduled_on.data
		user_id = current_user.id
		booking = Post(massage=massage, scheduled_on=scheduled_on, user_id= user_id)

		db.session.add(booking)
		db.session.commit()
		flash(f"{massage} booked on {scheduled_on}.")

	return render_template('stone.html', form=form, title= "Hot Stone Massage")


from tkinter import *
from tkinter import filedialog as fd
import os
from PIL import Image

root=Tk()
root.geometry("450x500")
root.title("Image Converter")

def png():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.png")

def jpg():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.jpg")

def jpeg():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.jpeg")

def gif():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.gif")

def webp():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.webp")

def tiff():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.tiff")

def pdf():
    filename=fd.askopenfilename()
    file_path = filename.split("/")
    file = file_path.pop(-1)
    Image.open(filename).save(f"{'/'.join(file_path)}/{file.split('.')[0]}.pdf")

Label_1=Label(root,text="Find your format and convert!", width=50, font=("bold",15))
Label_1.place(x=-50,y=50)

Button(root,text="PNG", width=20, height=2, bg="brown",fg="white",command=png).place(x=150,y=100)
Button(root,text="JPG", width=20, height=2, bg="brown",fg="white", command=jpg).place(x=150,y=150)
Button(root,text="JPEG", width=20, height=2, bg="brown",fg="white", command=jpeg).place(x=150,y=200)
Button(root,text="GIF", width=20, height=2, bg="brown",fg="white", command=gif).place(x=150,y=250)
Button(root,text="WEBP", width=20, height=2, bg="brown",fg="white", command=webp).place(x=150,y=300)
Button(root,text="TIFF", width=20, height=2, bg="brown",fg="white", command=tiff).place(x=150,y=350)
Button(root,text="PDF", width=20, height=2, bg="brown",fg="white", command=pdf).place(x=150,y=400)

root.mainloop()


import streamlit as st
import langchain_helper as lch
import textwrap

st.title('Youtube Assistant')

with st.sidebar:
    with st.form(key = "my_form"):
        youtube_url = st.sidebar.text_area(
            label = "What is youtube url of your desired video?",
            max_chars = 50
        )
        query = st.sidebar.text_area(
            label = 'Ask me about the video?',
            max_chars = 50,
            key = 'query'

        )

        submit_button = st.form_submit_button(label = 'submit')

if query and youtube_url:
    db = lch.create_vector_db_from_youtube_url(youtube_url)
    response, docs = lch.get_response_from_query(db, query)
    st.subheader("Answer:")
    st.text(textwrap.fill(response, width = 80))


from genericpath import getsize
from PIL import Image
import numpy as np
import os
from Compress_fuc import *
# input:threshold1 and threshold2
# function:compute the trigger frame
# output:return the index of picture needed to be sent
def cachetriggerframe(path,threshold1,threshold2):
    trigger_frame_index=[]
    for i in range(1498):
        a=i+1
        b=a+1
        path1=os.path.join(path + str(a) + '.png' )
        path2=os.path.join(path + str(b) + '.png' )
        img1=Image.open(path1,'r').convert('L')
        img2=Image.open(path2,'r').convert('L')

        mats1 = np.array(img1)
        mats2 = np.array(img2)
        differ=mats2-mats1
        mask=differ>35
        sum=np.sum(mask!=0)
        # Image.fromarray(differ).show() #查看帧差图像
        if sum > threshold2:
            trigger_frame_index.append(b)
            # img2.show()
    return trigger_frame_index

# print("The index of frames needed to be trigger:",trigger_frame_index)
# for i in trigger_frame:
    # info=[]
    # info=Compress_Alth(path,i)
    # print(info)


import ctypes, pygame, random, sys

from Grid import Grid
from Ship import Ship
from Cell import Cell

class Game:

    def __init__(self): # Constructor for the "Game" class

        # file paths for the ship images
        carrier_file_path = r"Utils\carrier.png"
        battleship_file_path = r"Utils\battleship.png"
        cruiser_file_path = r"Utils\cruiser.png"
        submarine_file_path = r"Utils\submarine.png"
        destroyer_file_path = r"Utils\destroyer.png"

        # instantiate a grid object
        self.grid = Grid()

        carrier = Ship(5,self.grid.screen,self.grid.cell_width,self.grid.window_border_thickness,carrier_file_path)
        battleship = Ship(4,self.grid.screen,self.grid.cell_width,self.grid.window_border_thickness,battleship_file_path)
        cruiser = Ship(3,self.grid.screen,self.grid.cell_width,self.grid.window_border_thickness,cruiser_file_path)
        submarine = Ship(3,self.grid.screen,self.grid.cell_width,self.grid.window_border_thickness,submarine_file_path)
        destroyer = Ship(2,self.grid.screen,self.grid.cell_width,self.grid.window_border_thickness,destroyer_file_path)

        self.ships = [carrier,battleship,cruiser,submarine,destroyer]

    def config(self): # Initial game set up, what you would do when playing battleship in real life

        self.grid.draw_board() # Draw the board

        player_ship_locations = [] # friendly (left board) ship locations
        for ship in self.ships:
            current_ship = ship.draw_player_ships(player_ship_locations)
            for cell in current_ship:
                player_ship_locations.append(cell)

        opponent_ship_locations = [] # enemy (right board) ship locations
        for ship in self.ships:
            current_ship = ship.generate_opponent_ship_locations(opponent_ship_locations)
            for cell in current_ship:
                opponent_ship_locations.append(cell)

        pygame.display.flip()

        return player_ship_locations,opponent_ship_locations # return both values, 0 = friendly, 1 = enemy

    def calculate_probability(self):
        for col in range(self.grid.cols):
            for row in range(self.grid.rows):
                cell = Cell(col,row,self.grid.screen,self.grid.cell_width,self.grid.grid_border_thickness,self.grid.window_border_thickness,self.grid.window_width,False)
                b_value = col*25 # probability function goes here
                color = (0,0,b_value)
                cell.update_cell_color(color)
        pygame.display.flip()

    def player_move(self,opponent_ship_locations,player_moves): # the program user takes his turn

        # 0,0 on opponents board, the upperleft hand corner of the grid, where the two grid lines intersect
        # described as a percentage of the total width and hieght

        origin = (
            ((self.grid.window_width/2) + (self.grid.window_border_thickness))/ self.grid.window_width, # x %
            ((self.grid.window_border_thickness))/ self.grid.window_height # y %
            )

        # The percent of the total width (x) and height (y) that the width of one cell takes up
        cell_width_percent_vectors = (
            (self.grid.cell_width/self.grid.window_width), # x %
            (self.grid.cell_width/self.grid.window_height) # y %
        )

        opponent_board_cell_percents = [] # Will stoe pixel ranges, x & y, for each cell EX: [[x_min, x_max],[y_min,y_max]]
        opponent_board_cell_index = [] # Will store the coordinates of the corresponding cell EX: [1,2]

        # Make all of the grid ranges
        for col in range(self.grid.cols):
            for row in range(self.grid.rows):

                x_min = (cell_width_percent_vectors[0]*col) + origin[0]
                x_max = (cell_width_percent_vectors[0]*col) + origin[0]+cell_width_percent_vectors[0]

                y_min = (cell_width_percent_vectors[1]*row) + origin[1]
                y_max = (cell_width_percent_vectors[1]*row)+origin[1]+cell_width_percent_vectors[1]

                opponent_board_cell_percents.append([[x_min,x_max],[y_min,y_max]])
                opponent_board_cell_index.append([col,row])

        # Here is the bulk of the logic concerning actually executing a player move

        unique_move = False # Assume that the move will be a repeat move
        while not unique_move:

            clicked = False
            while not clicked: # While the user has not moved

                valid_move = False
                while not valid_move: # A valid move is a move in the opponent's grid

                    for event in pygame.event.get(): # Allow the user to quit if they want
                        if event.type == pygame.QUIT:
                            sys.exit()

                    player_move = [pygame.mouse.get_pos()[0]/self.grid.window_width,pygame.mouse.get_pos()[1]/self.grid.window_height] # as a percentage of the pygame window

                    if pygame.mouse.get_pressed()[0]: # if the left mouse button is pressed
                        clicked = True
                        while pygame.mouse.get_pressed()[0] != 0: # prevent multiple executions
                            pygame.event.get()
                            continue

                        x_min = opponent_board_cell_percents[0][0][0]
                        x_max = opponent_board_cell_percents[-1][0][1]

                        y_min = opponent_board_cell_percents[0][1][0]
                        y_max = opponent_board_cell_percents[-1][1][1]

                        if (x_min <= player_move[0] <= x_max) and (y_min <= player_move[1] <= y_max): # If the move is in the opponent's grid, it is a valid move
                            valid_move = True

            # get the cell to update
            for cell_range in opponent_board_cell_percents:

                x_min = cell_range[0][0]
                x_max = cell_range[0][1]

                y_min = cell_range[1][0]
                y_max = cell_range[1][1]

                if x_min <= player_move[0] <= x_max and y_min <= player_move[1] <= y_max:
                    i = opponent_board_cell_percents.index(cell_range)
                    x = opponent_board_cell_index[i][0]
                    y = opponent_board_cell_index[i][1]

            if [x,y] in player_moves: # If the player has already selected that cell
                unique_move = False
                pop_up_window_title = "Repeat Move"
                pop_up_window_message = "You already moved there"
                ctypes.windll.user32.MessageBoxW(0, pop_up_window_message, pop_up_window_title, 1)

            elif [x,y] not in player_moves:
                unique_move = True

        cell = Cell(x,y,self.grid.screen,self.grid.cell_width,self.grid.grid_border_thickness,self.grid.window_border_thickness,self.grid.window_width,False)

        x = cell.x
        y = cell.y

        if [x,y] in opponent_ship_locations: # If there is a ship there
            cell.is_hit()
            is_hit = True
        elif [x,y] not in opponent_ship_locations: # If there is NOT a ship there
            cell.is_miss()
            is_hit = False

        pygame.display.flip()

        return is_hit,[x,y] # return the status of the ship (hit or not) and the cell coordinates

    def opponent_move(self,player_ship_locations,opponent_moves): # opponent's move

        unique_move = False # assume a non unique move

        while not unique_move:
            x = random.randint(0,9)
            y = random.randint(0,9)
            if [x,y] not in opponent_moves:
                unique_move = True

        cell = Cell(x,y,self.grid.screen,self.grid.cell_width,self.grid.grid_border_thickness,self.grid.window_border_thickness,self.grid.window_width,True)

        if [cell.x,cell.y] in player_ship_locations:
            cell.is_hit()
            is_hit = True
        elif [cell.x,cell.y] not in player_ship_locations:
            cell.is_miss()
            is_hit = False

        return is_hit,[x,y] # return the status of the ship (hit or not) and the cell coordinates


import os
import logging
import random

from .utils import (
    run_command,
    DennisException,
    format_release_branch_name,
    format_release_pr_name
)
from .task import Task

_log = logging.getLogger(__name__)

RELEASE_TYPES = ['major', 'minor', 'hotfix']
ALLOWED_BRANCHES = {
    'major': ['develop'],
    'minor': ['develop'],
    'hotfix': ['master']
}
PR_DESCRIPTION = (
    '![]({})'
    '\n\n'
    'We’re on our way to a much simpler release process. This release branch'
    ' is therefore minimal. I’m not making any changes here. It’s still fine'
    ' for you to make some last-minute tweaks, but remember – soon that chance'
    ' is going away, because release branches will no longer be a thing.'
    '\n\n'
    'Here’s my advice though. Make sure your code is ready to go by the time'
    ' you merge it to develop. Soon there will be no other way!'
    '\n\n'
    'Yours sincerely,'
    '\nDennis (Bot)'
)

class PrepareTask(Task):
    """
        Steps taken:

        - Create new branch with new tag
        - Execute the release script release.sh
        - Commit changes and Push
        - Create PR into master

    """

    release_script_path = None
    release_script_name = 'release'

    def __init__(
        self, branch=None, **kwargs
    ):
        super().__init__(**kwargs)

        # Validate the source branch being used for the new release branch
        # is one of the expected branches for this release type
        if not branch == 'develop':
            ALLOWED_BRANCHES['hotfix'].append(branch)
        if branch not in ALLOWED_BRANCHES[self.version_type]:
            message = (
                'With a release type "{}" you are not allowed'
                ' to branch off "{}". The branches you can use are: {}.'
                ' If you are creating a hotfix, you may use master or any'
                ' non-develop branch'.format(
                    self.release_type,
                    branch,
                    ALLOWED_BRANCHES[self.release_type]
                )
            )
            _log.error(message)
            raise DennisException(message)

        self.branch = branch

        self.release_script_path = os.path.join(
            self.repo.working_dir, self.release_script_name
        )

    def run(self):
        if self.release:
            _log.warn(
                'This release seems to be already ongoing, continuing'
                ' to cover any missed steps'
            )

        # Release branch name
        if self.release:
            release_branch_name = self.release.name
        else:
            release_branch_name = format_release_branch_name(
                self.version_type
            )

        # If local branch exists
        if (
            not self.release and
            self._does_local_branch_exist(release_branch_name)
        ):
            _log.warn(
                'Found local branch with the same'
                ' name {}, deleting that stuff'.format(
                    release_branch_name
                )
            )
            self.repo.delete_head(release_branch_name, '-D')

        # Checkout the source branch
        _log.info('Checking out and pulling source branch: {}'.format(
            self.branch))
        self._checkout_and_pull(self.branch)

        # Create release branch
        if not (self.release and self.release.branch):
            _log.info('Creating new branch for {} release'.format(
                self.version_type
            ))
            release_branch = self.repo.create_head(release_branch_name)
        else:
            release_branch = self.release.branch

        # Checkout release branch
        _log.info('Checking out release branch: {}'.format(
            release_branch_name))
        self._checkout(release_branch_name)

        # Run the release script
        if not self.release:
            if os.path.isfile(self.release_script_path):
                _log.info('Running {} script inside {}'.format(
                    self.release_script_name, self.repo_name
                ))
                output, success, return_code = run_command(
                    [
                        self.release_script_path,
                        self.last_version
                    ],
                    cwd=self.repo.working_dir
                )
                if not success:
                    raise DennisException(
                        'Failed to run release script {} with code {}'
                        ' and output {}'.format(
                            self.release_script_path, return_code, output
                        )
                    )
            else:
                _log.warn(
                    'No release script ({}) was found'
                    ' in the project root'.format(
                        self.release_script_name))

        if not self.release:
            # Commit changes
            self._commit_all('Initial Release Commit')

            # Push upstream
            _log.info('Pushing new release branch upstream')
            self._push()

            # Setting upstream for convenience
            self.repo.remotes.origin.fetch()
            refs = [
                r
                for r in self.repo.remotes.origin.refs
                if r.name == 'origin/{}'.format(release_branch_name)
            ]
            if any(refs):
                release_branch.set_tracking_branch(
                    refs[0]
                )

        # Create pull request
        if not (self.release and self.release.pr):
            release_pr_description = PR_DESCRIPTION.format(random.choice([
                'https://media.giphy.com/media/3o6Ztn3DaJ41FDHVwA/giphy.gif',
                'https://media.giphy.com/media/l0HlFwETpLZyast9u/giphy.gif',
                'https://media.giphy.com/media/l0HlTP1jCtsx1Xl4s/giphy.gif',
                'https://media.giphy.com/media/l0HlIT8WBMsYENnG0/giphy.gif',
                'https://media.giphy.com/media/l0HlHnIwSCFBq2ySQ/giphy.gif',
                'https://media.giphy.com/media/3o6Zt51xm4FZJcBy7e/giphy.gif',
                'https://media.giphy.com/media/3o6ZtmFYFy93Lg1LwI/giphy.gif',
                'https://media.giphy.com/media/eK3GNqMBif63C/giphy.gif',
                'https://media.giphy.com/media/d1FKUVRyHv9Sgy64/giphy.gif',
            ]))
            release_pr = self.github_repo.create_pull(
                format_release_pr_name(self.version_type),
                release_pr_description, 'master',
                self.repo.active_branch.name
            )
        else:
            release_pr = self.release.pr

        # Done
        _log.info(
            'All done. You may now proceed to the required QA testing'
            ' and, when happy, come back to dennis and hit "dennis release"'
            '\n\n'
            'Find the PR @ {}'.format(
                release_pr.html_url
            )
        )

    def _does_local_branch_exist(self, name):
        return len([head for head in self.repo.heads if head.name == name]) > 0


import cv2
import numpy as np

img = cv2.imread('star.jpg',0)
ret,thresh = cv2.threshold(img, 127, 255, 0)
image, contours, hierarchy = cv2.findContours(thresh, 1, 2)

# Moments
cnt = contours[0]
M = cv2.moments(cnt)

print('M:')
print(M)

# centroid
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])

print('centroid:(' + str(cx) + ',' + str(cy)+')')

# Contour Area
area = cv2.contourArea(cnt)

print('area:' + str(area))

# Contour Perimeter
perimeter = cv2.arcLength(cnt, True)

print('perimeter:' + str(perimeter))

# Contour Approximation
epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)

print('approx:' + str(approx))

# Convex Hull
hull = cv2.convexHull(cnt)

print('hull:' + str(hull))

# Checking Convexity
k = cv2.isContourConvex(cnt)

print('k:' + str(k))

# Straight Bounding Rectangle
x,y,w,h = cv2.boundingRect(cnt)
img = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)

cv2.imwrite('straight_rectangle.png', img)

# Rotated Rectangle
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
im = cv2.drawContours(img, [box], 0, (0, 0, 255), 2)

cv2.imwrite('rotated_rectangle.png', im)

# Minimum Enclosing Circle
(x, y), radius = cv2.minEnclosingCircle(cnt)
center = (int(x), int(y))
radius = int(radius)
img = cv2.circle(img, center, radius, (0, 255, 0), 2)

# Fitting an Ellipse
ellipse = cv2.fitEllipse(cnt)
im = cv2.ellipse(im, ellipse, (0, 255, 0), 2)

# Fitting a Line
rows, cols = img.shape[:2]
[vx, vy, x, y] = cv2.fitLine(cnt, cv2.DIST_L2, 0, 0.01, 0.01)
lefty = int((-x*vy/vx) + y)
righty = int(((cols-x)*vy/vx)+y)
img = cv2.line(img, (cols-1, righty), (0, lefty), (0, 255, 0), 2)


# Create the item dictionary:
import numpy as np
import numpy
import random
import copy
from numpy import array
from deap import base, creator, tools, algorithms

###  Multi-objective Optimization Problem  ###

IND_INIT_SIZE = 5

MAX_WEIGHT = 2000 # kg
MAX_SIZE = 1500 # m**3

r = array([[213, 508,  22],  # 1st arg : weight / 2nd arg : size / 3rd arg : value
       [594, 354,  50],
       [275, 787,  43],
       [652, 218,  46],
       [728, 183,  43],
       [856, 308,  33],
       [727, 482,  45],
       [762, 683,  26],
       [707, 450,  19],
       [909, 309,  45],
       [979, 247,  42],
       [259, 705,  42],
       [260, 543,  14],
       [899, 825,  17],
       [446, 360,  35],
       [491, 818,  47],
       [647, 404,  17],
       [604, 623,  32],
       [900, 840,  45],
       [374, 127,  33]] )

NBR_ITEMS = r.shape[0]
IND_INIT_SIZE=20

items = {}
# Create random items and store them in the items' dictionary.
for i in range(NBR_ITEMS):
    items[i] = ( r[i][0] , r[i][1] , r[i][2] )

creator.create("Fitness", base.Fitness, weights=(-1.0, 1.0 ))  # Note here <- I used only two weights!  (at first, I tried weights=(-1.0 , -1.0, 1.0)) but it crashes. With deap, you cannot do such a thing.

creator.create("Individual", set, fitness=creator.Fitness)

toolbox = base.Toolbox()

# Attribute generator
toolbox.register("attr_item", random.randrange, NBR_ITEMS)

# Structure initializers
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_item, n=IND_INIT_SIZE) #
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

def evaluation(individual):
    weight = 0.0
    size =0.0
    value = 0.0

    # Maximize or Minimize Conditions
    for item in individual:
        weight += items[item][0]  # It must be minimized.
        size += items[item][1]  # It must be minimized.
        value += items[item][2]  # It must be maximized.

    # Limit Conditions
    if weight > MAX_WEIGHT or size > MAX_SIZE:
        return 10000, 0

    if value == 0:
        value = 0.0000001

    MinFitess_score = weight + size   # NOTE : Minimize weight, size
    MaxFitenss_score = value  # NOTE : Maximize weight, size

    return MinFitess_score , MaxFitenss_score,

def cxSet(ind1, ind2):
    """Apply a crossover operation on input sets. The first child is the
    intersection of the two sets, the second child is the difference of the
    two sets.
    """
    temp = set(ind1)  # Used in order to keep type
    ind1 &= ind2  # Intersection (inplace)
    ind2 ^= temp  # Symmetric Difference (inplace)
    return ind1, ind2

def mutSet(individual):
    """Mutation that pops or add an element."""
    if random.random() < 0.5:
        if len(individual) > 0:  # We cannot pop from an empty set
            individual.remove(random.choice(sorted(tuple(individual))))
    else:
        individual.add(random.randrange(NBR_ITEMS))
    return individual,  # NOTE comma(,) , if there's no comma, an error occurs.

toolbox.register("mate", cxSet)
toolbox.register("mutate", mutSet)
toolbox.register("select", tools.selNSGA2) # NSGA-2 applies to multi-objective problems such as knapsack problem
toolbox.register("evaluate", evaluation)

def main():
    ngen = 300  # a number of generation  < adjustable value >

    pop = toolbox.population(n= 300)
    hof = tools.ParetoFront() # a ParetoFront may be used to retrieve the best non dominated individuals of the evolution
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean, axis=0)
    stats.register("std", numpy.std, axis=0)
    stats.register("min", numpy.min, axis=0)
    stats.register("max", numpy.max, axis=0)

    algorithms.eaSimple(pop, toolbox, 0.7, 0.2, ngen=ngen, stats=stats, halloffame=hof, verbose=True)

    return hof, pop

if __name__ == "__main__":
    hof, pop = main()

    print(hof)