import math
import random
from Tkinter import *
from PIL import Image, ImageTk

class ShopHolo(object):
    @staticmethod
    def init(data):
        ShopHolo.img1 = Image.open("images/shopholo1.png")
        ShopHolo.img2 = Image.open("images/shopholo2.png")
        ShopHolo.img3 = Image.open("images/shopholo3.png")
        ShopHolo.imgs = dict()
        ShopHolo.imgs[1] = ShopHolo.img1
        ShopHolo.imgs[2] = ShopHolo.img2
        ShopHolo.imgs[3] = ShopHolo.img3

        w = h = int(data.height*2/3.)
        for key in ShopHolo.imgs:
            img = ShopHolo.imgs[key]
            img = img.resize((w,h), Image.ANTIALIAS)
            ShopHolo.imgs[key] = img

    def __init__(self, image):
        PILimg = baseImg = ShopHolo.imgs[image]
        self.image = [PILimg, baseImg, ImageTk.PhotoImage(PILimg)]
        self.angle = 0
        self.angleSpeed = 2 * image
        if image == 2:
            self.angleSpeed *= -1

    def update(self):
        # rotate holo
        self.angle += self.angleSpeed
        PILimg = self.image[0]
        baseImg = self.image[1]
        PILimg = baseImg.rotate(self.angle)
        self.image = [PILimg, baseImg, ImageTk.PhotoImage(PILimg)]

    def draw(self, canvas, data):
        canvas.create_image(data.width/2.,data.height/2.,\
                                image = self.image[2])


"""

    线程同步解决方式：
        事件（event）

    event事件是线程通信机制中最简单的实现，使用一个内部的标记flag
    ，通过flag的True或False的变化来进行操作

"""

"""
    问题：
        工人和老板问题

"""

import  threading
import logging
import time

logging.basicConfig(level=logging.INFO,format="%(message)s")
root = logging.getLogger()
root.setLevel(logging.INFO)
n = 0

def boss():
    global n
    while True:
        c = logging.getLogger("c")
        c.info("{}{}".format("boss来查看杯子：", n))
        if n == 10:
            log = logging.getLogger("a")
            log.info("{}{}".format("boss:","得到10个杯子"))
            break

def worker():
    global n
    time.sleep(2)
    n += 1
    w = logging.getLogger("b")
    w.info("{}{}".format("工人生产出",n))

threading.Thread(target=boss,daemon=True).start()

while True:
    time.sleep(2)
    worker()


from iot.DB import DBSingleton
db= DBSingleton.get_instance()
db.connectDB()

from iot.models import User, Room
from iot.serializers import RoomSerializer
from rest_framework.response import  Response
from rest_framework import status
from rest_framework.decorators import APIView

class RoomViewSet(APIView):
    def get(self, request):
        rooms = Room.objects.all()
        rooms_serializer = RoomSerializer(rooms, many=True)
        return Response(rooms_serializer.data)

    def post(self, request):
        try:
            serializer = RoomSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                nRoom= Room.objects.get(Id= serializer.validated_data["Id"])
                admins= User.objects(isAdmin= True)
                print(serializer.validated_data)
                for admin in admins:
                    admin.update(add_to_set__room= nRoom.id)
                    nRoom.update(add_to_set__users= admin.id)
                return Response(serializer.data, status.HTTP_201_CREATED)

            return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
        except:
            return Response(status.HTTP_409_CONFLICT)

class RoomDetailViewSet(APIView):
    def get_object(self, Id):
        try:
            room= Room.objects.get(Id=Id)

            return room
        except Room.DoesNotExist:
            return Response(status.HTTP_404_NOT_FOUND)

    def get(self, request, Id):
        try:
            room= self.get_object(Id)
            room_serializer = RoomSerializer(room)

            return Response(room_serializer.data)
        except:
            return Response(status.HTTP_404_NOT_FOUND)

    def put(self, request, Id):
        try:
            room = self.get_object(Id)
            serializer = RoomSerializer(room, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data)

            return Response(serializer.errors, status.HTTP_400_BAD_REQUEST)
        except:
            return Response(serializer.errors, status.HTTP_403_FORBIDDEN)

    def delete(self, request, Id):
        room = self.get_object(Id)
        count= 0
        admins= []
        for user in room.users:
            if user.isAdmin == True:
                admins.append(user)
        if len(admins) == len(room.users):
            print("yes")
            for admin in admins:
                admin.update(pull__room= room.id)
            room.delete()
            return Response(status.HTTP_204_NO_CONTENT)
        else:
            return Response(status.HTTP_400_BAD_REQUEST)


import numpy as np

import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.functional import F

MTU = 1514

def session_2d_histogram(ts, sizes, path, plot=False):
    # ts_norm = map(int, ((np.array(ts) - ts[0]) / (ts[-1] - ts[0])) * MTU)
    if len(ts) == 1:
        ts_norm = np.array([0.0])
    else:
        ts_norm = ((np.array(ts) - ts[0]) / (ts[-1] - ts[0])) * MTU
    H, xedges, yedges = np.histogram2d(sizes, ts_norm, bins=(range(0, MTU + 1, 1), range(0, MTU + 1, 1)))

    if plot:
        plt.set_cmap('plasma')
        plt.pcolormesh(xedges, yedges, H)
        plt.xlim(0, MTU + 1)
        plt.ylim(0, MTU + 1)
        plt.xticks([])
        plt.yticks([])
        plt.savefig(path)
    return torch.Tensor(H.astype(np.int32)).unsqueeze(0)

class TraceDataset(torch.utils.data.IterableDataset):
    def __init__(self, flow_times, flow_packets, flow_sizes, indexes, em):
        self.flow_times = flow_times
        self.flow_packets = flow_packets
        self.flow_sizes = flow_sizes
        self.indexes = indexes
        self.em = em

    def __iter__(self):
        for idx in self.indexes:
            c = 1 if self.flow_sizes[idx + 1] > self.em else 0
            yield session_2d_histogram(self.flow_times[idx], self.flow_packets[idx], '', False), c

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

class CNNModel(nn.Module):
    def __init__(self, filters=(10, 20)):
        super().__init__()
        self.filters = filters

        self.conv1 = nn.Conv2d(1, out_channels=self.filters[0], kernel_size=5, stride=2)
        self.bn1 = nn.BatchNorm2d(filters[0])
        self.conv2 = nn.Conv2d(filters[0], out_channels=filters[1], kernel_size=5, stride=2)
        self.bn2 = nn.BatchNorm2d(filters[1])
        self.d2 = nn.Dropout(p=0.25)
        self.linear1 = nn.Linear(filters[1] * 93 * 93, 64)
        self.d3 = nn.Dropout(p=0.5)
        self.linear2 = nn.Linear(64, 1)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.bn1(x)

        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.bn2(x)

        x = self.d2(x)

        x = x.view(-1, self.filters[-1] * 93 * 93)

        x = self.linear1(x)
        x = F.relu(x)

        x = self.d3(x)

        x = self.linear2(x)

        x = F.sigmoid(x)

        return x


# Word Builder - Every Two Charater Combination of Characters. - 3N * 3N + 2 = O(N^2)
#   Palindorme chacters are allowed, but not of the same characters.
def word_builder(characters):
    combinations = [] # 1 Step

    for character in characters: # 3N Steps ? - I Not Sure of the Constant Number of Steps For Outer Loop. I understand why it's N^2.
        for position_value in characters: # 3N Steps
            if character != position_value: # 1 Step
                combinations.append(character + position_value) # 2 Steps

    return combinations # 1 Step

# Main Program
characters = ["a", "b", "c", "d"]
print("Array of Characters: %s" % characters)
print("Two Character Combinations: %s\n" % word_builder(characters))

A Common-Sense Guide to Data Structures and Algorithms/Big O/word_builder.py


from discord.ext import commands
import json

class Cog(commands.Cog, name="config"):
    def __init__(self, bot):
        self.bot = bot
        self.data = {}
        self.load_json()
        self.sections = []

    def get_config(self, section):
        if section in self.data:
            data = self.data[section]
        else:
            data = {}
        section = ConfigSection(self, section, data)
        self.sections.append(section)
        return section

    def set_data(self, section, data):
        self.data[section] = data
        self.save_json()

    def load_json(self):
        with open("config.json", "r") as f:
            self.data = json.load(f)

    def save_json(self):
        with open("config.json", "w") as f:
            json.dump(self.data, f, indent="\t")

    @commands.command()
    async def reload_config(self, ctx):
        self.load_json()
        for i in self.sections:
            i.__init__(self, i.section, self.data[i.section])
        await ctx.send("Reloaded config")

class ConfigSection:
    def __init__(self, parent, section, data):
        self.parent = parent
        self.section = section
        self.data = data

    def __getitem__(self, item):
        return self.data[item]

    def __setitem__(self, item, value):
        self.data[item] = value
        self.parent.set_data(self.section, self.data)

    def set_default(self, key, value):
        if key not in self.data:
            self.__setitem__(key, value)

async def setup(bot):
    await bot.add_cog(Cog(bot))


from flix_web_app.domainmodel.actor import Actor
from flix_web_app.domainmodel.director import Director
from flix_web_app.domainmodel.genre import Genre
from flix_web_app.domainmodel.movie import Movie
from flix_web_app.domainmodel.user import User

import pytest

from flix_web_app.home import services as home_serv
from flix_web_app.logging_in import services as log_serv
from flix_web_app.search import services as search_serv
from flix_web_app.logging_in.services import ValidationException

def test_get_movies_for_browse(populated_repo):
    movie = Movie('Picnic', 2016)
    movie.id = 1001
    populated_repo.add_movie(movie)
    movie2 = Movie('Panadol', 2011)
    movie2.id = 1002
    populated_repo.add_movie(movie2)
    movie3 = Movie('Banana', 2009)
    movie3.id = 1003
    populated_repo.add_movie(movie3)
    assert home_serv.get_movies([1001, 1002, 1003], populated_repo) == [movie, movie2, movie3]

def test_get_ids_of_movies(populated_repo):
    li = [i for i in range(1, 1001)]
    assert home_serv.get_ids_of_movies(populated_repo) == li

def test_get_movie_ids_by_x(populated_repo):
    movie = Movie('Picnic', 2016)
    movie.id = 1001
    movie.add_genre(Genre('Blarg'))
    movie.add_actor(Actor('Glue Stick'))
    movie.director = Director('George Smith')
    populated_repo.add_movie(movie)
    lis = [1001]
    assert search_serv.get_movies_ids_by_title('Picnic', populated_repo) == lis
    assert search_serv.get_movies_ids_by_actor('Glue Stick', populated_repo) == lis
    assert search_serv.get_movies_ids_by_genre('Blarg', populated_repo) == lis
    assert search_serv.get_movies_ids_by_director('George Smith', populated_repo) == lis
    assert search_serv.get_movies_ids_by_title('LOL', populated_repo) is None
    assert search_serv.get_movies_ids_by_actor('LOL', populated_repo) is None
    assert search_serv.get_movies_ids_by_genre('LOL', populated_repo) is None
    assert search_serv.get_movies_ids_by_director('LOL', populated_repo) is None

def test_get_movies_by_x(populated_repo):
    movie = Movie('Picnic', 2016)
    movie.id = 1001
    movie.add_genre(Genre('Blarg'))
    movie.add_actor(Actor('Glue Stick'))
    movie.director = Director('George Smith')
    populated_repo.add_movie(movie)
    lis = [movie]
    assert search_serv.get_movies_by_title([1001], populated_repo) == lis
    assert search_serv.get_movies_by_actor([1001], populated_repo) == lis
    assert search_serv.get_movies_by_genre([1001], populated_repo) == lis
    assert search_serv.get_movies_by_director([1001], populated_repo) == lis
    assert search_serv.get_movies_by_title([1010], populated_repo) == []
    assert search_serv.get_movies_by_actor([1010], populated_repo) == []
    assert search_serv.get_movies_by_genre([1010], populated_repo) == []
    assert search_serv.get_movies_by_director([1010], populated_repo) == []

def test_add_user(populated_repo):
    # add new user
    user = User('Hazel', '12345')
    log_serv.add_user('Hazel', '12345', populated_repo)
    assert log_serv.get_user('Hazel', populated_repo) == user
    # user doesnt exist
    with pytest.raises(log_serv.UnknownUserException):
        log_serv.get_user('Error', populated_repo)
    # username taken
    with pytest.raises(log_serv.NameNotUniqueException):
        log_serv.add_user('Hazel', '12345', populated_repo)
    # invalid password
    with pytest.raises(log_serv.ValidationException):
        log_serv.validate_user('Hazel', "123456", populated_repo)
    #valid password
    try:
        log_serv.validate_user("Hazel", "12345", populated_repo)
    except ValidationException:
        assert False


from random import random

import neopixel
import board
from models.objectbox_models import Led as LedModel

class LedStick:
    def __init__(self, tag_id, database):
        # init NeoPixel class with params
        # self.pins = [board.D21, board.D18, board.D12, board.MOSI]
        self.tag_id = tag_id
        self.db_id = database.led.put(LedModel())
        self.led_object = database.led.get(self.db_id)
        self.red = 0
        self.green = 0
        self.blue = 0
        self.led_count = 36

        self.led_stick = neopixel.NeoPixel(pin=board.D12, n=self.led_count, brightness=1, pixel_order=neopixel.GRB)

    def updateColorFromPosition(self, r, g, b):
        # set color for
        self.red = self.normalize_range(int(r))
        self.green = self.normalize_range(int(g))
        self.blue = self.normalize_range(int(b))

    @staticmethod
    def normalize_range(value):
        return min(max(value, 0), 255)

    def saveColorToDatabase(self, database):
        # update color in every led database object
        for led in database.led.get_all():
            led.setColor(self.red, self.green, self.blue)
            database.led.put(led)

    def setColorFromDatabase(self, database):
        rgb = database.led.get(self.db_id).getColor()
        self.led_stick.fill((rgb['red'], rgb['green'], rgb['blue']))
        self.led_stick.show()
        print("red: ", rgb['red'], "green: ", rgb['green'], "blue: ", rgb['blue'], "ID: ", self.db_id)


import datetime
import json
import time
from collections import Counter, OrderedDict
from operator import itemgetter

from .database.collection import db

class Items():
    def __init__(self):
        # item_lst = db['all_items']
        collection = db['item_ids']
        self.item_lst = collection.find_one({}, {'_id': 0})

    def pro_items(self, match_data):
        item_lst = []
        sd = []
        data = match_data
        black_lst = ['ward_sentry', 'ward_observer', 'clarity', 'tpscroll',
                     'enchanted_mango', 'smoke_of_deceit', 'tango', 'faerie_fire', 'tome_of_knowledge', 'healing_salve', None]
        item_lst = [item['key']
                    for x in data for item in x['final_items'] if item not in black_lst]
        counter = dict(Counter(item_lst))
        sd = dict(sorted(counter.items(),
                         key=itemgetter(1), reverse=True))
        return sd

    def get_item_name(self, item_id):
        if not item_id:
            return
        data = self.item_lst
        item = [item['name']
                for item in data['items'] if item_id == item['id']]
        return item[0]

    def get_item_id(self, item_name):
        data = self.item_lst
        return [item['id'] for item in data['items'] if item_name == item['name']][0]

    def convert_time(self, lst):
        for item in lst:
            if item['time'] > 0:
                item['time'] = str(datetime.timedelta(
                    seconds=item['time']))
            else:
                item['time'] = 0
        return lst

    def get_most_recent_items(self, arr, l,  p):
        done = set()
        output = []
        for j in range(l):
            if l == 6:
                item_str = 'item_'+str(j)
            else:
                item_str = 'backpack_'+str(j)
            item = self.get_item_name(p[item_str])
            for purchase in arr:
                if purchase['key'] == item and purchase['key'] not in done:
                    if len(output) < 10:
                        done.add(purchase['key'])
                        output.append(
                            {'key': item, 'time': purchase['time'], 'id': self.get_item_id(
                                purchase['key'])})
        return self.convert_time(sort_dict(output))

    def remove_buildup_items(self, starting_items):
        item_lst = ['bracer', 'null_talisman', 'wraith_band',
                    'ring_of_basilius', 'buckler', 'headress', 'magic_wand']
        build_up = [{'key': 'magic_wand', 'items': [
            'branches', 'branches', 'magic_stick']},
            {'key': 'wraith_band', 'items': ['circlet', 'slippers']},
            {'key': 'null_talisman', 'items': ['circlet', 'mantle']},
            {'key': 'bracer', 'items': ['circlet', 'gauntlets']},
            {'key': 'ring_of_basilius', 'items': ['sobi_mask']},
            {'key': 'buckler', 'items': ['ring_of_protection']},
            {'key': 'headdress', 'items': ['ring_of_regen']}]
        for item in starting_items:
            item_idx = find_index(build_up, item['key'])
            if not item_idx:
                continue
            items = build_up[item_idx]['items']
            for buildup_item in items:
                matching_idx = find_index(starting_items, buildup_item)
                if matching_idx:
                    del starting_items[matching_idx]
        return starting_items

    def bots(self, purchase_log, purchase):
        bots_recipes = {'recipe_travel_boots': 'travel_boots',
                        'recipe_travel_boots_2': 'travel_boots_2'}
        search_key = self.extract_key(purchase, bots_recipes)
        # print(purchase_log)
        for dic in purchase_log[::-1]:
            if dic['key'] == search_key[0] and search_key[0] is not None:
                bots_time = dic['time']
                if search_key[1] == 1:
                    bots_time = int(bots_time) - 60
                else:
                    bots_time = int(bots_time) + 60
                bots_entry = {'time': bots_time,
                              'key': search_key[2]}
                purchase_log.append(bots_entry)
        return purchase_log

    def extract_key(self, purchase, bots_recipes):
        search_key = None
        nxt = 0
        boots = None
        for key in list(purchase.keys())[::-1]:
            if key in bots_recipes.keys():
                try:
                    search_key = list(purchase)[list(purchase).index(key)+1]
                    nxt = 1
                except:
                    search_key = list(purchase)[list(purchase).index(key)-1]
                    nxt = -1
                boots = bots_recipes[key]
                if purchase[key] > 1:
                    search_key = list(purchase.keys())[-1]
                    nxt = -1
                    boots = 'travel_boots_2'
        return (search_key, nxt, boots)

    def item_charges(self, starting_items):
        max_charges = 1
        temp = []
        for i, item in enumerate(starting_items):
            temp.append(item)
            if item['key'] == 'tango':
                max_charges = 3
            if 'charges' in item:
                for _ in range(1, round(item['charges']/max_charges)):
                    temp.insert(i, {'key': item['key'], 'time': item['time']})
        return temp

    def clean_items(self, starting_items):
        starting_items = self.remove_buildup_items(starting_items)
        return sort_dict(self.item_charges(starting_items))

def find_index(lst, value):
    for i, dic in enumerate(lst):
        if dic['key'] == value:
            return i
    return None

def sort_dict(items):
    newlist = sorted(
        items, key=itemgetter('time'))
    return newlist


import os

data = 'marc'

if data == 'mtop':
    MODEL = 'xmod.base'
    languages = ['de', 'en', 'fr', 'th', 'es', 'hi']
    partitions = range(5)

    for language in languages:
        for partition in partitions:
            print(language, partition)
            train_path = f"mtop_partitioned/train/{language}/{partition}.jsonl"
            valid_path = f"mtop_partitioned/eval/{language}/eval.jsonl"
            # test_path = f"mtop_partitioned/test/{language}/test.jsonl"
            dest_dir = f"mtop_partitioned/fairseq/{language}/{partition}"
            os.system(f"python preprocess_mtop.py \
                --sentencepiece-model {MODEL}/sentencepiece.bpe.model \
                --train {train_path} \
                --valid {valid_path} \
                --destdir {dest_dir}")

elif data == 'marc':
    MODEL = 'xmod.base'
    languages = ['de', 'en', 'fr', 'jp', 'zh']
    categories = ['apparel', 'home', 'musical_instruments', 'sports']

    # for language in languages:
    #     for category in categories:
    #         print(language, category)
    #         train_path = f"marc/train/{language}/{category}/train.jsonl"
    #         valid_path = f"marc/eval/{language}/eval.jsonl"
    #         # test_path = f"mtop_partitioned/test/{language}/test.jsonl"
    #         dest_dir = f"marc/fairseq/{language}/{category}"

    #         os.system(f"python ./marc/preprocess_marc.py \
    #             --sentencepiece-model {MODEL}/sentencepiece.bpe.model \
    #             --train {train_path} \
    #             --valid {valid_path} \
    #             --destdir {dest_dir}")

    # Preprocess IPT

    for language in languages:
            print(language, 'IPT')
            train_path = f"marc/train/IPT/{language}/train.jsonl"
            valid_path = f"marc/eval/{language}/eval.jsonl"
            # test_path = f"mtop_partitioned/test/{language}/test.jsonl"
            dest_dir = f"marc/fairseq/IPT/{language}"

            os.system(f"python ./marc/preprocess_marc.py \
                --sentencepiece-model {MODEL}/sentencepiece.bpe.model \
                --train {train_path} \
                --valid {valid_path} \
                --destdir {dest_dir}")


# -*- coding:utf-8 -*-
import threading;
import pdb;
import struct;
import httplib;
import json;

import xmltodict;

from Atom import Atom;

class AtomEIDetail(Atom):
  def __init__(self, item, case):
    Atom.__init__(self, item, case);
    self.case = case;
    self.group = case.group;
    self.testMng = case.group.testMng;
    self.enb = self.case.group.GetEnb('src_enb');

    self.msg = {};

    for node in item:
      ele = node.get('name');
      if ele == 'msg':
        msg = int(node.get('msg'));
        dspid = int(node.get('DspId'));
        coreid = int(node.get('CoreId'));

        self.msg[msg] = {'MsgId': msg, 'DspId' : dspid, 'CoreId' : coreid, 'Tlv' : []};

        tlvs = node.getchildren();

        for tlv in tlvs:
          tlvid = int(tlv.get('id'));
          tlvmsg = tlv.get('name');
          self.msg[msg]['Tlv'].append({'id':tlvid, 'name' : tlvmsg})

  def Run(self):
    self.enb.enb.ei.startAllDetail(self.msg);

  def clear(self):
    pass;


""" Module containing tests for certain functions"""
import random
from game_module import functions
from game_module import classes

def test_reset_location():
	""" Function to test reset_location function"""
	test_rock =  classes.Rock('./icons/rock.png', 100, -600, 48, 69, 4)

	functions.reset_location(test_rock)
	assert test_rock.height == 48
	assert test_rock.y == -48
	assert 0 < test_rock.x < 800 - test_rock.width	#800 = display width

def test_overlap():
	""" Function to test overlap function"""
	test_rock =  classes.Rock('./icons/rock.png', 100, -600, 48, 69, 4)
	player_x = 800*0.45
	player_y = 600-94
	test_player = classes.Player('./icons/basket.png', player_x, player_y, 94, 139, 0)

	#Same y, different x => Does not overlap
	test_rock.y = test_player.y
	assert not functions.overlap(test_player, test_rock)

	#Same x, different y => Does not overlap
	test_rock.x = test_player.x
	test_rock.y = 0
	assert not functions.overlap(test_player, test_rock)

	#Rock's left side overlaps with player
	test_rock.x = random.randrange(test_player.x, test_player.x + test_player.width)
	test_rock.y = random.randrange(test_player.y - test_rock.height, 600)
	assert functions.overlap(test_player, test_rock)

	#Rock overlaps entirely within player
	test_rock.x = random.randrange(test_player.x, test_player.x + test_player.width - test_rock.width)
	test_rock.y = random.randrange(test_player.y - test_rock.height, 600)
	assert functions.overlap(test_player, test_rock)

	#Rock's right side overlaps with player
	test_rock.x = random.randrange(test_player.x - test_rock.width, test_player.x + test_player.width - test_rock.width)
	test_rock.y = random.randrange(test_player.y - test_rock.height, 600)
	assert functions.overlap(test_player, test_rock)


import cv2
import cv2.aruco as aruco
import numpy as np
import os
import time
import math
import turtle
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()

def on_closing():
    if messagebox.askokcancel("Quit", "Do you want to quit?"):
        root.destroy()

t = turtle.Turtle()
t.left(90)
t.color("white")
t.setpos(-100,-100)

# Opens the inbuilt camera of laptop to capture video.
cap = cv2.VideoCapture("megamax.mp4")
i = 0

while(cap.isOpened()):
    ret, frame = cap.read()

    # This condition prevents from infinite looping
    # incase video ends.
    if ret == False:
        break

    # Save Frame by Frame into disk using imwrite method
    cv2.imwrite('Frame'+str(i)+'.jpg', frame)
    i += 1

cap.release()
cv2.destroyAllWindows()

def findAruco(img, marker_size=6,total_markers=250,draw=True):
  gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  key = getattr(aruco,f'DICT_{marker_size}X{marker_size}_{total_markers}')
  arucoDict=aruco.Dictionary_get(key)
  arucoParam=aruco.DetectorParameters_create()
  bbox,ids,_=aruco.detectMarkers(gray,arucoDict,parameters=arucoParam)
  t.forward(0.35)
  if ids!=None:
    t.width(4)
    t.color("red")
  else:
    t.color("blue")
    t.width(1)
  if ids == [[15]]:
    t.right(5.625)
  if ids == [[17]]:
    t.right(2.8125)
  print(ids)
  if draw:
    aruco.drawDetectedMarkers(img,bbox)
  return bbox,ids

j = 1
arr = []
flag = 0
while i!=j:
    sonic =  'Frame'+str(j)+'.jpg'
    img = cv2.imread(sonic)
    img = cv2.resize(img,(0,0),fx=0.5,fy=0.5)
    bbox,ids = findAruco(img)
    if ids !=None and flag==0:
        t.width(2)
        t.color("black")
        t.write(ids)
        flag = flag + 1
    elif ids == None:
        flag = 0
    if ids not in arr and ids!=None and ids!=[[16]]:
        arr.append(ids)
    os.unlink(sonic)
    time.sleep(0.01)
    j = j + 1
    if cv2.waitKey(1)==113:
        break
    cv2.imshow("img",img)

cv2.destroyAllWindows()

#lis = [[id, x, y]]

lis = [[[[11]], 0, 0], [[[12]], 0, 0.35],[[[13]], 0, 0.7],[[[14]], 0, 1.050],[[[15]], 0, 1.300],[[[17]], 1.027, 1.300],[[[18]], 1.027, 1.050],[[[19]], 1.027, 0.700],[[[20]], 1.027, 0.350],[[[21]], 1.027, 0]]

#arr =[[[11]], [[12]],[[13]],[[14]],[[15]],[[17]],[[18]],[[19]],[[20]],[[21]]]

sum = 0
for i in arr:
    y = 0
    q = 0
    p =[]
    r =[]
    while y==0:
        a = lis[q][0]
        if i == a and i !=[[11]]:
            p.append(lis[q][1])
            p.append(lis[q][2])
            r.append(lis[q-1][1])
            r.append(lis[q-1][2])
            m = math.sqrt(((p[0]-r[0])**2)+((p[1]-r[1])**2))
            sum = sum + m
            print('In front of room id',i)
            print('after moving a distance', sum)
            print()
            y = 1
        elif i == lis[q][0] and i==[[11]]:
            print('In front of room id',i)
            print()
            y = 1
        else:
            q = q + 1

root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()


# You are given the list of numbers with exactly the same length and you must find
# the shortest chain of numbers to link the first number to the last, with each
# pair of adjacent numbers differing by one digit.

# You should write a function that receives a list of numbers (positive integers) and
# returns the shortest route as a list of numbers.

# Input: Numbers as a list of integers.
# Output: The shortest chain from the first to the last number as a list of integers.
# Precondition: Numbers have the same length
# ∀ x ∈ numbers : 100 ≤ x < 1000

def checkio(numbers):
    first = numbers[0]
    last = numbers[-1]

    # Check for only one element
    if first == last:
        return [first]

    # Check for first and last differing by only one digit
    if sum([i!=j for i,j in zip(str(first),str(last))]) == 1:
        return [first, last]

    # Find all list members one digit different from the first
    seconds = []
    for num in numbers:
        if sum([i!=j for i,j in zip(str(first),str(num))]) == 1:
            seconds.append(num)

    # Find chain from each second to last and choose the shortest
    best_solution = numbers
    for second in seconds:
        reduced_numbers = [second] + [num for num in numbers if num != first and num != second]
        curr_solution = checkio(reduced_numbers)
        if len(curr_solution) <= len(best_solution):
            best_solution = curr_solution

    return [first] + best_solution

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert checkio([123, 991, 323, 321, 329, 121, 921, 125, 999]) == [123, 121, 921, 991, 999], "First"
    assert checkio([111, 222, 333, 444, 555, 666, 121, 727, 127, 777]) == [111, 121, 127, 727, 777], "Second"
    assert checkio([456, 455, 454, 356, 656, 654]) == [456, 454, 654], "Third, [456, 656, 654] is correct too"


#!/usr/bin/env python

from config import *
import util
import ai_data

def get_weight(L,color):
    k=0
    for i in range(5):
        if L[i]==color:
            k+=pow(2,i)
        elif L[i]!=none:
            return 0
    return ai_data.weight[k]

def get_line_value(L,color):
    v=0
    for i in range(5):
        v+=get_weight(L[i:i+5],color)
    return v

def get_color_value(fcboard,x,y,color):
    fcboard[x][y]=color
    v=0
    for L in util.get_fclists(fcboard,x,y):
        v+=get_line_value(L,color)
    fcboard[x][y]=none
    return v

def get_value(fcboard,x,y):
    if fcboard[x][y]!=none:
        return -1
    return get_color_value(fcboard,x,y,white)+get_color_value(fcboard,x,y,black)

def get_move(fcboard):
    m,mx,my=0,-1,-1
    for x in range(XCOUNTS):
        for y in range(YCOUNTS):
            tm=get_value(fcboard,x,y)
            if tm>=m:
                m,mx,my=tm,x,y
    return mx,my


import numpy as np
import torch

def cg_solve(f_Ax, b, x_0=None, cg_iters=10, residual_tol=1e-10, callback=None, verbose=False):
    """
    Goal: Solve Ax=b equivalent to minimizing f(x) = 1/2 x^T A x - x^T b
    Assumption: A is PSD, no damping term is used here (must be damped externally in f_Ax)
    Verbose mode works only with numpy
    """

    if type(b) == torch.Tensor:
        x = torch.zeros(b.shape[0]) if x_0 is None else x_0
        x = x.to(b.device)
        if b.dtype == torch.float16:
            x = x.half()
        r = b - f_Ax(x)
        p = r.clone()
    elif type(b) == np.ndarray:
        x = np.zeros_like(b) if x_0 is None else x_0
        r = b - f_Ax(x)
        p = r.copy()
    else:
        print("Type error in cg")

    fmtstr = "%10i %10.3g %10.3g %10.3g"
    titlestr = "%10s %10s %10s %10s"
    if verbose: print(titlestr % ("iter", "residual norm", "soln norm", "obj fn"))

    for i in range(cg_iters):
        if callback is not None:
            callback(x)
        if verbose:
            obj_fn = 0.5*x.dot(f_Ax(x)) - 0.5*b.dot(x)
            norm_x = torch.norm(x) if type(x) == torch.Tensor else np.linalg.norm(x)
            print(fmtstr % (i, r.dot(r), norm_x, obj_fn))

        rdotr = r.dot(r)
        Ap = f_Ax(p)
        alpha = rdotr/(p.dot(Ap))
        x = x + alpha * p
        r = r - alpha * Ap
        newrdotr = r.dot(r)
        beta = newrdotr/rdotr
        p = r + beta * p

        if newrdotr < residual_tol:
            # Early CG termination because the residual is small
            break

    if callback is not None:
        callback(x)
    if verbose:
        obj_fn = 0.5*x.dot(f_Ax(x)) - 0.5*b.dot(x)
        norm_x = torch.norm(x) if type(x) == torch.Tensor else np.linalg.norm(x)
        print(fmtstr % (i, r.dot(r), norm_x, obj_fn))
    return x


# -*- coding: utf-8 -*-
# @Author  : Junru_Lu
# @File    : util.py
# @Software: PyCharm
# @Environment : Python 3.6+
# @Reference : https://github.com/likejazz/Siamese-LSTM

# 基础包
from keras import backend as K
from keras.layers import Layer
from keras.preprocessing.sequence import pad_sequences
import numpy as np
import itertools

'''
本配置文件提供了一系列预定义函数
'''

# ------------------自定义函数------------------ #

def text_to_word_list(flag, text):  # 文本分词
    text = str(text)
    text = text.lower()

    if flag == 'cn':
        pass
    else:
        # 英文文本下的文本清理规则
        import re
        text = re.sub(r"[^A-Za-z0-9^,!.\/'+-=]", " ", text)
        text = re.sub(r"what's", "what is ", text)
        text = re.sub(r"\'s", " ", text)
        text = re.sub(r"\'ve", " have ", text)
        text = re.sub(r"can't", "cannot ", text)
        text = re.sub(r"n't", " not ", text)
        text = re.sub(r"i'm", "i am ", text)
        text = re.sub(r"\'re", " are ", text)
        text = re.sub(r"\'d", " would ", text)
        text = re.sub(r"\'ll", " will ", text)
        text = re.sub(r",", " ", text)
        text = re.sub(r"\.", " ", text)
        text = re.sub(r"!", " ! ", text)
        text = re.sub(r"\/", " ", text)
        text = re.sub(r"\^", " ^ ", text)
        text = re.sub(r"\+", " + ", text)
        text = re.sub(r"\-", " - ", text)
        text = re.sub(r"\=", " = ", text)
        text = re.sub(r"'", " ", text)
        text = re.sub(r"(\d+)(k)", r"\g<1>000", text)
        text = re.sub(r":", " : ", text)
        text = re.sub(r" e g ", " eg ", text)
        text = re.sub(r" b g ", " bg ", text)
        text = re.sub(r" u s ", " american ", text)
        text = re.sub(r"\0s", "0", text)
        text = re.sub(r" 9 11 ", "911", text)
        text = re.sub(r"e - mail", "email", text)
        text = re.sub(r"j k", "jk", text)
        text = re.sub(r"\s{2,}", " ", text)

    text = text.split()

    return text

def make_w2v_embeddings(flag, word2vec, df, embedding_dim):  # 将词转化为词向量
    vocabs = {}  # 词序号
    vocabs_cnt = 0  # 词个数计数器

    vocabs_not_w2v = {}  # 无法用词向量表示的词
    vocabs_not_w2v_cnt = 0  # 无法用词向量表示的词个数计数器

    # 停用词
    # stops = set(open('data/stopwords.txt').read().strip().split('\n'))

    for index, row in df.iterrows():
        # 打印处理进度
        if index != 0 and index % 1000 == 0:
            print(str(index) + " sentences embedded.")

        for question in ['question1', 'question2']:
            q2n = []  # q2n -> question to numbers representation
            words = text_to_word_list(flag, row[question])

            for word in words:
                # if word in stops:  # 去停用词
                    # continue
                if word not in word2vec and word not in vocabs_not_w2v:  # OOV的词放入不能用词向量表示的字典中，value为1
                    vocabs_not_w2v_cnt += 1
                    vocabs_not_w2v[word] = 1
                if word not in vocabs:  # 非OOV词，提取出对应的id
                    vocabs_cnt += 1
                    vocabs[word] = vocabs_cnt
                    q2n.append(vocabs_cnt)
                else:
                    q2n.append(vocabs[word])
            df.at[index, question + '_n'] = q2n

    embeddings = 1 * np.random.randn(len(vocabs) + 1, embedding_dim)  # 随机初始化一个形状为[全部词个数，词向量维度]的矩阵
    '''
    词1 [a1, a2, a3, ..., a60]
    词2 [b1, b2, b3, ..., b60]
    词3 [c1, c2, c3, ..., c60]
    '''
    embeddings[0] = 0  # 第一行用0填充，因为不存在index为0的词

    for index in vocabs:
        vocab_word = vocabs[index]
        if vocab_word in word2vec:
            embeddings[vocab_word] = word2vec[vocab_word]
    del word2vec

    return df, embeddings

def split_and_zero_padding(df, max_seq_length):  # 调整tokens长度

    # 训练集矩阵转换成字典
    X = {'left': df['question1_n'], 'right': df['question2_n']}

    # 调整到规定长度
    for dataset, side in itertools.product([X], ['left', 'right']):
        dataset[side] = pad_sequences(dataset[side], padding='pre', truncating='post', maxlen=max_seq_length)

    return dataset

class ManDist(Layer):  # 封装成keras层的曼哈顿距离计算

    # 初始化ManDist层，此时不需要任何参数输入
    def __init__(self, **kwargs):
        self.result = None
        super(ManDist, self).__init__(**kwargs)

    # 自动建立ManDist层
    def build(self, input_shape):
        super(ManDist, self).build(input_shape)

    # 计算曼哈顿距离
    def call(self, x, **kwargs):
        self.result = K.exp(-K.sum(K.abs(x[0] - x[1]), axis=1, keepdims=True))
        return self.result

    # 返回结果
    def compute_output_shape(self, input_shape):
        return K.int_shape(self.result)


import helpers
from timing import timeit

extra = "_demo"
extra = ""
data = helpers.get_data(__file__, extra=extra)

player1, player2 = helpers.get_records(data)

player1 = [int(_) for _ in player1[1:]]
player2 = [int(_) for _ in player2[1:]]

def star1(player1, player2):
    while player1 and player2:
        deal = [player1.pop(0), player2.pop(0)]
        if deal[0] > deal[1]:
            player1 += deal
        else:
            player2 += deal[-1::-1]

    winner = player1 or player2
    r = 0
    for i, v in enumerate(winner[-1::-1]):
        r += ((i+1) * v)
    return r

def playgame(p1, p2, level=0):
    # print(f"Level {level}")
    # print(f"New game {level}:\n\t{p1}\n\t{p2}")
    p1_hands, p2_hands, c = [], [], 1
    while p1 and p2:
        # print(f"P1 deck: {p1}\nP2 deck: {p2}")

        if p1 in p1_hands or p2 in p2_hands:
            # print(f"preexisting hand! {p1_hands} -- {p2_hands}")
            return 0, p1, p2

        p1_hands.append(p1.copy())
        p2_hands.append(p2.copy())

        c1, c2 = p1.pop(0), p2.pop(0)
        # print(f"Player1 plays: {c1}\nPlayer2 plays: {c2}")

        if len(p1) >= c1 and len(p2) >= c2:
            winner, x, x = playgame(p1[:c1], p2[:c2], level+1)
        else:
            if c1 > c2:
                winner = 0
            else:
                winner = 1

        # print(f"Player {winner + 1} wins round {c}\n")
        if winner == 0:
            p1 += [c1, c2]
        else:
            p2 += [c2, c1]
        c += 1

    return int(not p1), p1, p2
    if p1:
        return 0, p1, p2
    else:
        return 1, p1, p2

@timeit
def star2(p1, p2):
    winner, p1, p2 = playgame(p1, p2)
    winner = p1 or p2
    r = 0
    for i, v in enumerate(winner[-1::-1]):
        r += ((i+1) * v)
    return r

print(f"* {star1(player1.copy(), player2.copy())}")
print(f"* {star2(player1.copy(), player2.copy())}")


from django.urls import path
from .views import *
urlpatterns = [
    path('',inicio_view, name = 'inicio_view'),
    path('about/',about_view, name ='about_view'),
    path('contacto/',contacto_view, name='contacto_view'),
    path('productos/',productos_view, name='productos_view'),
    path('marcas/',marcas_view, name = 'marcas_view'),
    path('categorias/',categorias_view, name= 'categorias_view'),

    path('agregar_producto/',agregar_producto_view, name = 'agregar_producto'),
    path('agregar_marca/',agregar_marca_view, name = 'agregar_marca'),
    path('agregar_categoria/',agregar_categoria_view, name = 'agregar_categoria'),

    path('ver_producto/<int:id_prod>',ver_producto_view, name = 'ver_producto_view'),
    path('eliminar_producto/<int:id_prod>',eliminar_producto_view, name = 'eliminar_producto_view'),
    path('editar_producto/<int:id_prod>',editar_producto_view, name = 'editar_producto_view'),

    path('ver_marca/<int:id_marca>',ver_marca_view, name = 'ver_marca_view'),
    path('eliminar_marca/<int:id_marca>',eliminar_marca_view, name = 'eliminar_marca_view'),
    path('editar_marca/<int:id_marca>',editar_marca_view, name = 'editar_marca_view'),

    path('ver_categoria/<int:id_categoria>',ver_categoria_view, name = 'ver_categoria_view'),
    path('eliminar_categoria/<int:id_categoria>',eliminar_categoria_view, name = 'eliminar_categoria_view'),
    path('editar_categoria/<int:id_categoria>',editar_categoria_view, name = 'editar_categoria_view'),

    path('login/',login_view,name='login_view'),
    path('logout/',logout_view,name='logout_view'),
]


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 15:35:12 2022

@author: antoine
"""

import numpy as np
import pandas as pd

from corrector import *
from data_structurs import SeqManager, Appertures, TimeStruct

from astropy.time import Time

class Occult(Corrector):
    def __init__(self, seq = None, flatSeq = None, biasSeq = None, darkSeq = None):

        if seq != None:
            super().__init__(SeqManager(seq), flatSeq, biasSeq, darkSeq)
            print(self.getHeader())
            self.key = str(input("ENTER THE KEY OF A TIME REF WITH | SEPARATOR IF NEEDED (exemple JD | jd or DATE-OBS | isot. Refere to Time.FORMATS from astropy.time): "))
            self.format = self.key.split("|")[-1].replace(' ', '')
            self.key =  self.key.split("|")[0].replace(' ', '')

        self.appertures = []
        self.refStars = []
        self.objectOfInterst = []
        self.results = []

    def start(self, r, ri, re, center = False, correct = False):

        print("SELECT STAR OF INTERREST")
        self.selectAp(r, self.objectOfInterst)
        print("SELECT REFERENCES STARS")
        self.selectAp(r, self.refStars)
        self.objectOfInterst = Utils.centred(self.objectOfInterst, self.getImg().getData(), r)
        fig,ax = plt.subplots(1)

        for i in range(len(self)):

            img = self.getImg(i)
            dat = img.getReducedData()

            ax.clear()

            ax.imshow(dat, cmap='Greys', vmin = np.median(dat[dat>0])*0.5, vmax = np.median(dat[dat>0]) / 0.5)

            nexRefStar = Utils.centred(self.refStars, dat, r)
            dr = self.driftByCenter(nexRefStar)
            self.refStars = nexRefStar

            if center:
                self.objectOfInterst = Utils.centred(self.objectOfInterst, dat, r)
            else:
                self.objectOfInterst = self.objectOfInterst - dr

            for j in self.refStars:
                c = Circle(j, radius = r, fill=False)
                ax.add_patch(c)
                c = Circle(j, radius = ri, fill=False)
                ax.add_patch(c)
                c = Circle(j, radius = re, fill=False)
                ax.add_patch(c)

            for j in self.objectOfInterst:
                c = Circle(j, radius = r, fill=False)
                ax.add_patch(c)
                c = Circle(j, radius = ri, fill=False)
                ax.add_patch(c)
                c = Circle(j, radius = re, fill=False)
                ax.add_patch(c)

            plt.pause(0.01)

            stars = np.concatenate((self.refStars, self.objectOfInterst))
            self.appertures.append(Appertures(stars, r = r, ri = ri, re = re))
            self.results.append(self.appertures[-1].Photom(self.getImg(i), self.key, self.format))

            print("image: ", i, '\n', self.appertures[-1].Photom(img, self.key, self.format))

    def driftByCenter(self, newPos):
        newPos = np.array(newPos)
        return np.mean(np.array(self.refStars) - newPos, axis = 0)

    def selectAp(self, r, s):
        fig = plt.figure()
        ax = fig.add_subplot(111)
        isClose = [False]
        img = self.getData()

        ax.imshow(img, cmap='Greys', vmin = np.nanmedian(img)*0.5, vmax = np.nanmedian(img)/0.5)

        plt.connect('button_press_event', lambda event: Utils.getPosFromImage(event, s, isClose))
        plt.show(block=False)

        while not isClose[0]:
            plt.pause(0.01)

    def phot(self):
        stars = []
        for res in self.results:
            star = []
            for i in range(len(res)):
                star.append(res[i][7])

            stars.append(star)
        return np.asarray(stars)

    def starsPhot(self):

        stars = []
        for res in self.results:
            star = []
            for i in range(len(self.refStars)):
                star.append(res[len(self.objectOfInterst) + i][7])
            stars.append(star)
        return np.asarray(stars)

    def astPhot(self):

        asts = []
        for res in self.results:
            ast = []
            for i in range(len(self.objectOfInterst)):
                ast.append(res[i][7])

            asts.append(ast)
        return np.asarray(asts)

    def extractTime(self):

        # x = np.zeros((len(self)))
        # for i in range(len(self)):
        #     x[i] = self.getImg(i).getTime(self.key)
        # return x

        x = []
        for i in range(len(self.results)):
            t = Time(self.results[i][0][4], format = 'jd', precision = 9)
            x.append(TimeStruct(t.jd1, t.jd2))
        return np.asarray(x)

    # def timeFormat(self, tArr, forma):
    #     newArr = []
    #     for i in tArr.to_value(forma):
    #         if forma == 'hms':
    #             newArr = tArr.to_value('isot').split('T')[-1]
    #         else:
    #             newArr = tArr.to_value(forma)
    #     return newArr

    def timeFormat(self, tArr, forma):
        newArr = np.zeros(tArr.shape, dtype= object)
        for j in range(tArr.shape[0]):
            if forma == 'hms':
                newArr[j] = Time(tArr[j].jd1, tArr[j].jd2, format = 'jd', precision = 9).to_value('isot').split('T')[-1]
            else:
                newArr[j] = Time(tArr[j].jd1, tArr[j].jd2, format = 'jd', precision = 9).to_value(forma)

        return newArr

    def plot(self, yRange = None, binning = 1, astsSelection = None, starsSelection = None, inMag = False, forma = 'jd', xtick = None):

        if starsSelection is not None and (isinstance(starsSelection, int) or isinstance(starsSelection, float)):
            starsSelection = [starsSelection]

        if astsSelection is not None and (isinstance(astsSelection, int) or isinstance(astsSelection, float)):
            astsSelection = [astsSelection]

        plt.figure()
        if inMag:
            stars = -2.5*np.log10(Utils.binn(binning, self.phot()))
        else:
            stars = Utils.binn(binning, self.phot())
        print(stars.shape)

        x = Utils.binn(binning, self.extractTime())
        x = self.timeFormat(x, forma)

        for i in range(stars.shape[1]):
            if i < len(self.refStars):
                if starsSelection is not None:
                    if i in starsSelection:
                        plt.scatter(x, stars[:, i], label = 'star ' + str(i))
                else:
                    plt.scatter(x, stars[:, i], label = 'star ' + str(i))
            else:
                if astsSelection is not None:
                    if i in  astsSelection:
                        plt.scatter(x, stars[:, i], label = 'occulted ' + str(i))
                else:
                    plt.scatter(x, stars[:, i], label = 'occulted ' + str(i))

        if inMag:
            plt.gca().invert_yaxis()

        if xtick != None:
           plt.xticks(np.linspace(plt.xlim()[0], plt.xlim()[-1], xtick))

        if yRange != None:
            plt.ylim(yRange)

        plt.legend()
        plt.show()

    def plotDif(self, refS = 0, ast = -1, yRange = None, binning = 1, resc = True, forma = 'jd', xtick = None, inMag = True):
        if inMag:
            print("result in Mag")
            asts = -2.5*np.log10(Utils.binn(binning, self.astPhot()))
            stars = -2.5*np.log10(Utils.binn(binning, self.starsPhot()))
        else:
            print("result in ADU")
            asts = Utils.binn(binning, self.astPhot())
            stars = Utils.binn(binning, self.starsPhot())

        x = Utils.binn(binning, self.extractTime())
        x = self.timeFormat(x, forma)

        if ast == -1:
            plt.figure()
            for i in range(asts.shape[1]):
                plt.scatter(x, asts[:,i] - stars[:, refS], label='ast - s' + str(refS+1), linewidths=1, marker='x')
        else:
            plt.figure()
            plt.scatter(x, asts[:,ast] - stars[:, refS], label='ast - s' + str(refS+1), linewidths=1, marker='x')

        of = np.zeros(stars.shape[1])
        if resc:
            of = Utils.rescalMulti((asts.T  - stars[:, refS]).T, (stars.T - stars[:, refS]).T)

        for j in range(stars.shape[1]):
            if j != refS:
                plt.scatter(x, (stars[:,j] - stars[:, refS]) + of[j], label='s' + str(j+1) +' - s' + str(refS+1), linewidths=1, marker='x')

        plt.legend()
        if yRange != None:
            plt.ylim(yRange)

        if xtick != None:
            plt.xticks(np.linspace(plt.xlim()[0], plt.xlim()[-1], xtick))

        if inMag:
            plt.gca().invert_yaxis()

        plt.show()

    def toAOTACsv(self, pName, forma = 'jd'):

        if len(self.results) == 0:
            print('empty result list')
            return

        x = Utils.binn(1, self.extractTime())
        # x = Time(x, format = 'jd', precision = 9)
        x = self.timeFormat(x, forma)

        header = ["FrameNo", "Time (UT)"]

        for i in range(len(self.results[0])):
            header.append("Signal ("+ str(i+1) + ")")
            header.append("Background ("+ str(i+1) +")")

        resultats = []
        for i, res in enumerate(self.results):
            resultat = [i,x[i]]

            for re in res:
                resultat.append(re[3])
                resultat.append(re[-2])

            resultats.append(resultat)

        df = pd.DataFrame(resultats, columns= header)
        df.to_csv(pName, index=False)

    def toCsv(self, path):

        header = self.buildCsvHeader()

        csv = []
        for table in self.results:
            csvRow = np.zeros(( len(table) * len(table[0]) ), dtype = object)
            for i, row in enumerate(table):
                if i < len(self.objectOfInterst):
                    csvRow[len(table)-1-i] = 1
                else:
                    csvRow[len(table)-1-i] = 0

                for j in range(len(row)-1):
                    if j == 0 or j == 1:
                        csvRow[(j+1)*len(table) + i] = row[1+j].value
                    # elif j == 3:
                    #     csvRow[(j+1)*len(table) + i] = row[1+j]
                    else:
                        csvRow[(j+1)*len(table) + i] = row[1+j]
            csv.append(csvRow)

        df = pd.DataFrame(csv, columns= header)
        df.to_csv(path, index=False)

        return df

    def buildCsvHeader(self):

        NOfAp = len(self.results[0])
        NbOfRowElements = len(self.results[0][0])
        header = [0]*NOfAp*NbOfRowElements

        for i in range(NOfAp):
            header[i] = 'isOcullt (' + str(i+1) + ')'

        for i in range(NbOfRowElements-1):
            for j in range(NOfAp):
                if i == 0:
                    header[NOfAp + i*NOfAp + j] = "xcenter (" + str(j+1) + ')'
                elif i == 1:
                    header[NOfAp + i*NOfAp + j] = "ycenter (" + str(j+1) + ')'
                elif i == 2:
                    header[NOfAp + i*NOfAp + j] = "aperture_sum (" + str(j+1) + ')'
                elif i == 3:
                    header[NOfAp + i*NOfAp + j] = "Time (" + str(j+1) + ')'
                elif i == 4:
                    header[NOfAp + i*NOfAp + j] = "annulus_median (" + str(j+1) + ')'
                elif i == 5:
                    header[NOfAp + i*NOfAp + j] = "aper_bkg (" + str(j+1) + ')'
                elif i == 6:
                    header[NOfAp + i*NOfAp + j] = "aper_sum_bkgsub (" + str(j+1) + ')'

        return header

    def readCsv(self, path):
       data = pd.read_csv(path)

       header = data.columns.values
       qTableHeader = ['id','xcenter','ycenter','aperture_sum','Time','annulus_median','aper_bkg','aper_sum_bkgsub']

       NofAp = len([i for i in header if 'isOcullt' in i])
       Nast = len([i for i in data.iloc[0,:NofAp] if i == 1])

       self.results = []

       for i in range(data.shape[0]):
           qTArr = np.zeros((NofAp, len(qTableHeader)), dtype = object)

           for row in range(qTArr.shape[0]):
               for col in range(qTArr.shape[1]):

                   if col == 0:
                       qTArr[row, col] = row + 1
                   else:
                       qTArr[row, col] = data.iloc[i, col*NofAp+row]

                   # elif col == 1:
                   #     qTArr[col, row] = data.iloc[i, NofAp+row]
                   # elif col == 2:
                   #     qTArr[col, row] = data.iloc[i, 2*NofAp+row]
                   # elif col == 3:
                   #     qTArr[col, row] = data.iloc[i, 3*NofAp+row]
           self.results.append(QTable(qTArr, names = qTableHeader))

if __name__ == '__main__':

    import glob
    # ----------------ex occult-----------------
    path = 'C:\\Users\\antoine\\OneDrive\\Documents\\PHD\\lightcurve\\entrainement\\Adorea\\reduced\\target-c1\\'
    path = 'C:\\Users\\antoi\\OneDrive\\Documents\\PHD\\lightcurve\\entrainement\\22-04-12PST3c/'
    res = 'C:\\Users\\antoi\\OneDrive\\Documents\\PHD\\lightcurve\\entrainement\\PST3c\\res\\'
    seq = glob.glob(path + "*1999*.fit*")

    # bias = glob.glob(path + "*bias*.fit*")
    # dark = glob.glob(path + "*dark*.fit*")

    occult = Occult(seq)
    r = 3
    occult.start(r, r*1.5, r*2, False)


import pickle
from fastfeature.plotting.plotter import cool_plotting
from fastsklearnfeature.candidates.CandidateFeature import CandidateFeature
from fastsklearnfeature.candidates.RawFeature import RawFeature
from typing import List, Dict, Any
import numpy as np

#file = "/tmp/chart.p"
#file = '/home/felix/phd/fastfeature_logs/charts/chart_all_23_11.p'
#file = '/home/felix/phd/fastfeature_logs/charts/chart_all_fold20_no_hyper_opt_32min.p'
#file = '/home/felix/phd/fastfeature_logs/charts/chart_all_sorted_by_complexity_fold20_hyper_opt_1045min.p'

#heart
#file = '/home/felix/phd/fastfeature_logs/newest_28_11/chart_hyper_10_all.p'
#my_range = (0.72, 0.88)
# heart also raw features
file = '/home/felix/phd/fastfeatures/results/cluster_good_cv_fixed_group/all_data.p'
my_range = (0.50, 0.88)

#diabetes
#file = '/home/felix/phd/fastfeatures/results/diabetes/chart.p'
#my_range = (0.72, 0.78)

all_data = pickle.load(open(file, "rb"))

names = [str(r['candidate']) for r in all_data]
scores = [r['score'] for r in all_data]
runtimes = [r['time'] for r in all_data]
candidates: List[CandidateFeature] = [r['candidate'] for r in all_data]

group_by_transformation = {}
for i in range(len(candidates)):
    c = candidates[i]
    if not isinstance(c, RawFeature):
        if not c.transformation.name in group_by_transformation:
            group_by_transformation[c.transformation.name] = []
        group_by_transformation[c.transformation.name].append(scores[i])

keys = []
avg_score = []
for k,v in group_by_transformation.items():
    keys.append(k)
    avg_score.append(np.mean(v))
    print(k + ': mean ' + str(np.mean(v)) + " max " + str(np.max(v)))


import tensorflow as tf

def create(filepath, batch_size=1, repeat=False, buffsize=1000):
  def _parse(record):
    keys_to_features = {
      'uid': tf.FixedLenFeature([], tf.string),
      'audio/data': tf.VarLenFeature(tf.float32),
      'audio/shape': tf.VarLenFeature(tf.int64),
      'text': tf.VarLenFeature(tf.int64)
    }
    features = tf.parse_single_example(
      record,
      features=keys_to_features
    )
    audio = features['audio/data'].values
    shape = features['audio/shape'].values
    audio = tf.reshape(audio, shape)
    audio = tf.contrib.layers.dense_to_sparse(audio)
    text = features['text']
    return audio, text, shape[0], features['uid']

  dataset = tf.data.TFRecordDataset(filepath).map(_parse).batch(batch_size=batch_size)
  if buffsize > 0:
    dataset = dataset.shuffle(buffer_size=buffsize)
  if repeat:
    dataset = dataset.repeat()
  iterator = dataset.make_initializable_iterator()
  return tuple(list(iterator.get_next()) + [iterator.initializer])


from pathlib import Path
import csv
import re
import db
import os

conexao = db.connect()

local_path = os.path.dirname(os.path.abspath(__file__)) + "/bd_files"

def lista_arquivos_csv():
    arquivos_csv = []
    for p, _, files in os.walk(os.path.abspath(local_path)):
        for file in files:
            if re.search('.csv$', file):
                arquivos_csv.append(os.path.join(p, file))

    return arquivos_csv

def ler_arquivo_csv(arquivo):
    with open(arquivo, newline='') as csvFile:
        linhas = csv.reader(csvFile, delimiter=',')
        for idx, linha in enumerate(linhas):
            if re.search('departamentos', arquivo):
                if idx != 0:
                    #cod,nome
                    colunas = '"cod", "nome"'
                    cursor = conexao.cursor()
                    valores = (linha[0], linha[1])
                    db.inserir(cursor, "departamentos", colunas, valores)

            elif re.search('disciplinas', arquivo):
                #cod,nome,cod_depto
                if idx != 0:
                    colunas = '"cod", "nome", "cod_depto"'
                    cursor = conexao.cursor()
                    valores = (linha[0], linha[1], linha[2])
                    db.inserir(cursor, "disciplinas", colunas, valores)

            elif re.search('turmas', arquivo):
               #turma,periodo,professor,horario,vagas_ocupadas,total_vagas,local,cod_disciplina,cod_depto
                if idx != 0:
                    colunas = '"turma", "periodo", "professor", "horario", "vagas_ocupadas", "total_vagas", "local", "cod_disciplina", "cod_depto"'
                    cursor = conexao.cursor()
                    valores = (linha[0], linha[1], linha[2], linha[3], linha[4], linha[5], linha[6], linha[7], linha[8])
                    db.inserir(cursor, "turmas", colunas, valores)

if __name__ == "__main__":

    arquivos_csv = lista_arquivos_csv()

    for arquivo in arquivos_csv:
        ler_arquivo_csv(arquivo)

    conexao.commit()
    db.close(conexao.cursor(), conexao)


"""
题目描述:
输入一个链表，反转链表后，输出新链表的表头。
解决思路：
第一种：遍历后输出到一个数组，新建链表，插入数组栈弹出的值
第二种：用多个指针，分别指向当前结点和前一个结点
"""

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

# 第一种
# class Solution:
#     # 返回ListNode
#     def ReverseList(self, pHead):
#         array = []
#         head = pHead
#         while head:
#             array.append(head.val)
#             head = head.next
#         if len(array) == 0:
#             return None
#         node = ListNode(array.pop())
#         while len(array) > 0:
#             tmp = ListNode(array.pop())
#             head = node
#             while head.next:
#                 head = head.next
#             head.next = tmp
#         return node

# 第二种
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if pHead==None or pHead.next==None:
            return pHead
        pre = None
        cur = pHead
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

node = ListNode(1)
for i in range(2, 11):
    tmp = ListNode(i)
    head = node
    while head.next:
        head = head.next
    head.next = tmp

S = Solution()
tmp = node
while tmp:
    print(tmp.val)
    tmp = tmp.next
node = S.ReverseList(node)
while node:
    print(node.val)
    node = node.next


import sqlite3
import os

# #
# 本模块用来对路径为 "path_db" 数据库进行简单操作，一般步骤如下
# 1. 实例化DbManger，查看该数据库包含的所有表。可对数据库进行：
#       查看已有表，表的列； 新建表，重命名表，备份表，删除列。
# 2. 实例化TableManger，可对表进行：
#       查看列，查看行和id，显示并返回行，行的查找； 插入新行，删除行，修改行。
#  注意：所有表内部数据以隐藏的列 "id" 进行传递，id列会自动生成。
# #

__Author__ = "J"

class DbManager:
    def __init__(self, path_db):
        self.conn = sqlite3.connect(path_db)
        self.c = self.conn.cursor()
        self.__tables = self.getAllTables()

    def __del__(self):
        try:
            self.c.close()
            self.conn.close()
            print("The database closed.")
        except:
            print("关闭数据库异常!!!")

    def createNewTable(self, table_name, columns):
        # columns是一个tuple或者list数据
        if table_name not in self.__tables:
            sql = "CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" % table_name + (",%s text"*len(columns)) % columns + ")"
            self.c.execute(sql)
            self.__tables = self.getAllTables()
        else:
            print("The table %r has already existed!" % table_name)

    def dropTable(self, table_name):
        if table_name in self.__tables:
            sql = "DROP TABLE IF EXISTS %s" % table_name
            self.c.execute(sql)
            self.__tables = self.getAllTables()
        else:
            print("There is no table named %r" % table_name)

    def renameTable(self, old_table_name, new_table_name):
        if old_table_name in self.__tables and new_table_name not in self.__tables:
            sql = "ALTER TABLE %s RENAME TO %s" % (old_table_name, new_table_name)
            self.c.execute(sql)
            self.conn.commit()
        elif old_table_name not in self.__tables:
            print("There is no table named %r", old_table_name)
        else:
            print("The new name %r has already existed in this database" % new_table_name)

    def backupTable(self, original_table_name, new_table_name=None):
        # 将表复制到同一个数据库，每行的id不会发生变化
        if original_table_name in self.__tables:
            if new_table_name == None:
                new_table_name = original_table_name + "_backup"
            while new_table_name in self.__tables:
                new_table_name = new_table_name + "_副本"
            print(new_table_name)

            columns = self.getTableColumns(original_table_name)
            sql1 = "CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" % new_table_name + (",%s text"*len(columns)) % columns + ")"
            sql2 = "INSERT INTO %s" % new_table_name + " SELECT * FROM %s" % original_table_name
            self.c.execute(sql1)
            self.c.execute(sql2)
            self.conn.commit()
        else:
            print("There is no table named %s", original_table_name)

    def copyTableToOtherDb(self, table_name, path_other_database, Reorder=False):
        # Reorder为True，将表重新整理，移除空余的id，并复制到新的数据库中。例如原表有id为(1, 2, 4)，新的表中id为(1, 2, 3)
        table_names = []
        other_db_conn = sqlite3.connect(path_other_database)
        other_db_cursor = other_db_conn.cursor()
        other_db_cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        temp = other_db_cursor.fetchall()
        for table in temp:
            table_names.append(table[0])
        if table_name in table_names:
            print("A table named %s has already exsited in database %s" % (table_name, os.path.basename(path_other_database)))
            return table_name
        columns = self.getTableColumns(table_name)
        self.c.execute("SELECT * FROM %s" % table_name)
        datas = self.c.fetchall()
        sql1 = "CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" % table_name + (",%s text" * len(columns)) % columns + ")"
        other_db_cursor.execute(sql1)
        for data in datas:
            if Reorder:
                sql2 = "INSERT INTO %s(" % table_name + (((",%s"*len(columns)).strip(',')) % columns) + ") VALUES(" + (",?"*len(columns)).strip(',') + ")"
                other_db_cursor.execute(sql2, tuple(data[1:]))
            else:
                sql2 = "INSERT INTO %s " % table_name + "VALUES(" + (",?"*len(data)).strip(',') + ")"
                other_db_cursor.execute(sql2, tuple(data))
        other_db_conn.commit()
        return table_name

    def deleteTableColumns(self, table_name, *columns_to_del, Reorder=False):
        # Reorder为True，将表重新整理，移除空余的id，。例如原表有id为(1, 2, 4)，新的表中id为(1, 2, 3)
        columns_original = list(self.getTableColumns(table_name))
        temp_table = "temp_table"
        for column in columns_to_del:
            if column not in columns_original:
                print("Columns need to be deleted are not in table %s, the table is not modified!" % table_name)
                return
            else:
                columns_original.pop(columns_original.index(column))
        new_columns = tuple(columns_original)
        sql1 = "CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" % temp_table + (",%s text" * len(new_columns)) % new_columns + ")"
        if Reorder:
            sql2 = "INSERT INTO %s(" % temp_table + ((",%s"*len(new_columns)) % new_columns).strip(",") + ")" + " SELECT " + ((",%s"*len(new_columns)) % new_columns).strip(",") + " FROM %s" % table_name
        else:
            sql2 = "INSERT INTO %s" % temp_table + " SELECT id" + (",%s"*len(new_columns)) % new_columns + " FROM %s" % table_name
        self.c.execute(sql1)
        self.c.execute(sql2)
        self.conn.commit()
        self.dropTable(table_name)
        self.renameTable(temp_table, table_name)

    def addTableColumns(self, table_name, *columns_to_add):
        columns_original = self.getTableColumns(table_name)
        for column in columns_to_add:
            if column in columns_original:
                print("Columns need to be add have already existed in table %s, the table is not modified!" % table_name)
                return
        for column in columns_to_add:
            self.c.execute("ALTER TABLE %s ADD COLUMN %s text" % (table_name, column))
        self.conn.commit()

    def renameTableColumns(self, table_name, **columns_to_rename):
        columns_original = list(self.getTableColumns(table_name))
        for k, v in columns_to_rename.items():
            if k not in columns_original:
                print("Columns need to be renamed are not in table %s, the table is not modified!" % table_name)
                return
            else:
                columns_original[columns_original.index(k)] = v
        new_columns = tuple(columns_original)
        temp_table = "temp_table"
        sql1 = "CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" % temp_table + (",%s text" * len(new_columns)) % new_columns + ")"
        sql2 = "INSERT INTO %s" % temp_table + " SELECT * FROM %s" % table_name
        self.c.execute(sql1)
        self.c.execute(sql2)
        self.c.execute("DROP TABLE IF EXISTS %s" % table_name)
        self.c.execute("ALTER TABLE %s RENAME TO %s" % (temp_table, table_name))
        self.conn.commit()

    # ###################### 以下所有为查询数据相关函数 ######################
    def getAllTables(self):
        table_names = []
        self.c.execute("SELECT name FROM sqlite_master WHERE type='table'")
        temp = self.c.fetchall()
        for table in temp:
            table_names.append(table[0])
        table_names = tuple(table_names)
        return table_names

    def getTableColumns(self, table_name):
        # 获取表中列的名字
        self.c.execute("PRAGMA table_info(%s)" % table_name)
        temp = self.c.fetchall()
        columns = []
        for i in temp:
            columns.append(i[1])
        columns = tuple(columns)
        return columns[1:]

    def execSQL(self, sql):
        self.c.execute(sql)
        return self.c.fetchall()

class TableManager:
    def __init__(self, table_name, path_db, columns4init=('如果不是创建新表，不需要填写该参数',)):
        # 修改表内容后自动保存
        self.auto_commit = True
        self.table = table_name
        self.columns = columns4init

        self.conn = sqlite3.connect(path_db)
        self.c = self.conn.cursor()
        sql = ("CREATE TABLE IF NOT EXISTS %s(id integer PRIMARY KEY AUTOINCREMENT" + ",%s text" * len(self.columns) + ")") % ((self.table,) + self.columns)
        self.c.execute(sql)
        self.columns = self._getColumns()

    def __del__(self):
        try:
            self.c.close()
            self.conn.close()
        except:
            print("Fatal Error: The database: %s can't be closed!!!" % self.table)

    def appendLine(self, **columns):
        # 表末尾添加一条新行
        col = []
        val = []
        for k, v in columns.items():
            col.append(k)
            val.append(v)
        sql = "INSERT INTO %s(" % self.table + ((",%s" * len(col)) % tuple(col)).strip(',') + ") VALUES(" + (",?" * len(col)).strip(',') + ")"
        self.c.execute(sql, tuple(val))
        if self.auto_commit:
            self.conn.commit()

    def deleteLine(self, id):
        # 删除id对应的某一行
        self.c.execute("DELETE FROM %s WHERE id=?" % self.table, (str(id),))
        if self.auto_commit:
            self.conn.commit()

    def _deleteLines(self, ids):
        # 删除tuple内所有id对应的行
        for id in ids:
            self.c.execute("DELETE FROM %s WHERE id=?" % self.table, (str(id),))
        if self.auto_commit:
            self.conn.commit()

    def modifyLine(self, id, **columns):
        for k, v in columns.items():
            self.c.execute("UPDATE %s SET %s=? WHERE id=?" % (self.table, str(k)), (str(v), str(id)))
        if self.auto_commit:
            self.conn.commit()

    def commitData(self):
        # 手动提交数据
        self.conn.commit()

    def rollbackData(self):
        # 手动回滚数据操作
        self.conn.rollback()

    #  ###################### 以下所有为查询数据相关函数 ######################

    def _getColumns(self):
        # 获取表中列的名字
        self.c.execute("PRAGMA table_info(%s)" % self.table)
        temp = self.c.fetchall()
        columns = []
        for i in temp:
            columns.append(i[1])
        columns = tuple(columns)
        return columns[1:]

    def getColumns(self):
        return self.columns

    def countLines(self):
        sql = "SELECT count(*) FROM %s" % self.table
        self.c.execute(sql)
        result = self.c.fetchone()
        return result[0]

    def getAllId(self, orderby=None, desc=False):
        # 返回所有行id，例如(1, 2, 3, 4, ...)
        # 按column对所有id进行升序排列，当desc为True时，降序排列
        ids = []
        if orderby is None or orderby not in self.columns:
            sql = 'SELECT id FROM %s' % self.table
        else:
            if desc:
                sql = 'SELECT id FROM %s ORDER BY %s DESC' % (self.table, orderby)
            else:
                sql = 'SELECT id FROM %s ORDER BY %s' % (self.table, orderby)
        self.c.execute(sql)
        result = self.c.fetchall()
        for i in result:
            ids.append(i[0])
        ids = tuple(ids)
        return ids

    def displayBriefData(self, id, *columns):
        if len(columns) == 0:
            columns = (self.columns[0],)
        sql = "SELECT " + (("%s,"*len(columns)) % columns).strip(',') + " FROM %s WHERE id=?" % self.table
        self.c.execute(sql, (str(id),))
        line = self.c.fetchone()
        return line

    def displayBriefDatas(self, ids, *columns):
        lines = []
        for id in ids:
            lines.append(self.displayBriefData(id, *columns))
        lines = tuple(lines)
        return lines

    def displayDetailedData(self, id):
        if id not in self.getAllId():
            return
        self.c.execute("SELECT * FROM %s WHERE id=?" % self.table, (str(id), ))
        line = self.c.fetchone()
        # return line[1:]
        temp_cols = list(self.columns)
        temp_cols.insert(0, "id")
        return dict(zip(temp_cols, line))

    def searchDataByKey(self, **column):
        # 模糊匹配，返回id，例如参数为title="bug"，结果返回(1, 2, 3,...)
        ids = []
        key = []
        var = []
        mix = []
        if len(column) == 0:
            print("没有进行匹配，请输入至少1个列名及对应关键字")
            return ()
        for k, v in column.items():
            key.append(str(k))
            var.append(str(v))
            mix.append('%'+str(v)+'%')
        # 把key中的每项依次间隔插入到mix中，比如[1,3,5]插入到[2,4,6]后得到[1,2,3,4,5,6]
        for n in range(len(key)):
            mix.insert(n*2, key[n])
        sql = "SELECT id FROM %s WHERE " % self.table + "%s LIKE %r" % tuple(mix[:2]) + " AND %s LIKE %r" * (len(key) - 1) % tuple(mix[2:])
        self.c.execute(sql)
        result = self.c.fetchall()
        for item in result:
            ids.append(item[0])
        '''
        # 打印各个列表关键字匹配的结果
        dict_ids = {}
        for k, v in column.items():
            ids.clear()
            sql = "SELECT id FROM %s WHERE %s LIKE %r" % (self.__table_name, str(k), '%'+str(v)+'%')
            self.c.execute(sql)
            result = self.c.fetchall()
            for item in result:
                ids.append(item[0])
            dict_ids[k] = tuple(ids)
        print(dict_ids)
        '''
        ids = tuple(ids)
        return ids

    def searchDataInTable(self, keyword, *exclude):
        ids = set()
        target_cols = tuple(col for col in self.columns if col not in exclude)
        for col in target_cols:
            sql = 'SELECT id FROM %s WHERE ' % self.table + "%s LIKE %r" % (col, '%'+keyword + '%')
            self.c.execute(sql)
            result = self.c.fetchall()
            for item in result:
                ids.add(item[0])
        return tuple(ids)

if __name__ == '__main__':
    import re
    import time

    # 多表模糊匹配查询速度测试
    time_mark = time.time()
    t_vers = {
        'V01': TableManager('t_V01', './libfiles/soft.db'),
        'V02': TableManager('t_V02', './libfiles/soft.db'),
        'V03V04': TableManager('t_V03V04', './libfiles/soft.db'),
        'V05': TableManager('t_V05', './libfiles/soft.db'),
        'T05': TableManager('t_T05', './libfiles/soft.db')
    }

    string = '华 麦 邵 阀门'
    ret_data = {'itemsNum': 0, 'items': {}}
    keywords = re.split(r'\s+', string)
    key = 0
    for soft_type in t_vers:
        ids_for_each_keys = []

        for keyword in keywords:
            ids_for_each_keys.append(t_vers[soft_type].searchDataInTable(keyword, 'path'))
        ids = ids_for_each_keys[0]
        for i in range(1, len(ids_for_each_keys)):
            ids = tuple(id for id in ids if id in ids_for_each_keys[i])
        ret_data['itemsNum'] += len(ids)
        for soft_id in ids:
            ret_data['items'][key] = t_vers[soft_type].displayDetailedData(soft_id)
            key += 1
    print(ret_data)
    print('一共耗时: ', time.time() - time_mark)


# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 16:52:22 2020

@author: Kokkinos
"""

"""Example program to show how to read a multi-channel time series from LSL."""
import numpy as np
import scipy.io as sio
from pylsl import StreamInlet, resolve_stream
from tkinter import *

from graphics import Graphics

class data_rec(Graphics):

    def __init__(self):

        Graphics.__init__(self)

        with open("visual_cues.txt") as f:
            content = f.readlines()
            content = [line.rstrip('\n') for line in content]

        self.Fs = int(content[0]) # Sampling Frequency
        self.Rdur = int(content[1]) # Rest visual cue duration
        self.IMdur = int(content[2]) # Imaginary Movement visual cue duration
        self.Prdur = int(content[3])

        del content[0:4]
        self.content = np.array(content)

        self.vcN = len(self.content) # number of visual cues
        idxs = np.where(self.content == 'REST')
        self.RN = len(idxs[0]) # number of REST visual cues
        idxs = np.where(self.content == 'PREPARE')
        self.PRN = len(idxs[0])
        self.IMN = len(self.content) - self.RN - self.PRN # number of Imaginary Movements visual cues
        self.recdur = self.RN * self.Rdur * self.Fs + self.IMN * self.IMdur * self.Fs + self.PRN * self.Prdur * self.Fs # duration of the recording

    def begin_stream(self):

        print("looking for an EEG stream...")
        self.streams = resolve_stream('type', 'EEG')

        # create a new inlet to read from the stream
        self.inlet = StreamInlet(self.streams[0])

    def record_loop(self):

        cSTR = 0
        cVC = 0
        cdur = 0
        dur = self.Prdur
        buffer = []

        while cSTR < self.recdur:

            sample, timestamp = self.inlet.pull_sample()
            buffer += [sample,]

            if cdur % (dur * self.Fs) == 0:

                if self.content[cVC] == 'REST':
                    print("REST")
                    self.delete_all()
                    cdur = 0
                    dur = self.Rdur
                    cVC = cVC+1

                elif self.content[cVC] == 'LEFT':
                    print("LEFT")
                    self.left_arrow()
                    cdur = 0
                    dur = self.IMdur
                    cVC = cVC+1

                elif self.content[cVC] == 'RIGHT':
                    print("RIGHT")
                    self.right_arrow()
                    cdur = 0
                    dur = self.IMdur
                    cVC = cVC+1

                elif self.content[cVC]=='PREPARE':
                    self.Concentration_Cross()
                    cdur = 0
                    dur = self.Prdur
                    cVC = cVC+1

            cSTR = cSTR + 1
            cdur = cdur + 1

        return buffer

    def save_recording(self, buffer):

        LABELS = []
        trig = []
        offset = self.IMdur * self.Fs
        IM_interval = 2* self.IMdur * self.Fs

        idxs=np.where(self.content=='REST')
        self.content = np.delete(self.content,idxs)
        idxs=np.where(self.content=='PREPARE')
        self.content = np.delete(self.content,idxs)

        for i, visual_cue in enumerate(self.content):

            if visual_cue == 'LEFT':
                LABELS += [1,]
                trig += [offset + i * IM_interval,]
            else:
                LABELS += [2,]
                trig += [offset + i * IM_interval,]

        trig = np.array(trig)
        LABELS = np.array(LABELS)
        buffer = np.array(buffer)

        # create matlab files
        sio.savemat('trig.mat', {'trig':trig})
        sio.savemat('rec.mat', {'rec':buffer})
        sio.savemat('LABELS.mat', {'LABELS':LABELS})

rec = data_rec()
rec.begin_stream()
buffer = rec.record_loop()
rec.save_recording(buffer)


import os
import sys
from pathlib import Path

sys.path.insert(0, '../')
from script_generator import *

DATASET = ["sift10M"]
SEARCH_L = [""]
TYPE = ["distributed"]
NUM_SHARD = ["1", "2", "4", "8", "16"]

gen = ScriptGenerator(f"num_shard.sh")

gen.options = {"DATASET": DATASET, "SEARCH_L": SEARCH_L, "TYPE": TYPE, "NUM_SHARD": NUM_SHARD}

experiments, scripts = gen.generate()

for i, (exp, sc) in enumerate(zip(experiments, scripts)):
    SCRIPT_DIR = f"/root/git/guitar/workload/script-generator/scripts/distributed/"
    Path(SCRIPT_DIR).mkdir(parents=True, exist_ok=True)

    file_name = f"{exp['DATASET']}_{exp['SEARCH_L']}_{exp['TYPE']}_{exp['NUM_SHARD']}.sh"
    filepath = os.path.join(SCRIPT_DIR, file_name)
    print(filepath)

    with open(filepath, "w") as f:
        f.write(sc)

print(f"generated {len(experiments)} experiment scripts")


import sys
sys.stdin = open('bj6593.txt','r')

dh=[0,0,0,0,1,-1]
dx=[1,0,-1,0,0,0]
dy=[0,1,0,-1,0,0]

def IS(h,y,x):
    return -1<h<L and -1<y<R and -1<x<C

while True:
    L,R,C=map(int,input().split())
    if not L+R+C:break
    Arr=[]
    Map=[[[0]*C for _ in range(R)]for __ in range(L)]
    for l in range(L):
        A=[]
        for r in range(R):
            a=input()
            if 'S' in a:S=(l,r,a.index('S'),0)
            A.append(a)
        input()
        Arr.append(A)
    Que=[S]
    Result=0
    while Que and not Result:
        Q=[]
        for q in Que:
            for d in range(6):
                nH=q[0]+dh[d]
                nY=q[1]+dy[d]
                nX=q[2]+dx[d]
                cnt=q[3]+1
                if IS(nH,nY,nX) and (Arr[nH][nY][nX]=='.' or Arr[nH][nY][nX]=='E') and not Map[nH][nY][nX]:
                    if Arr[nH][nY][nX]=='E':Result=cnt
                    Map[nH][nY][nX]=1
                    Q.append((nH,nY,nX,cnt))
        Que=Q
    if Result:print('Escaped in %d minute(s).'%Result)
    else:print('Trapped!')


# ---------------------- PROBLEM 33 (RANDOM) ----------------------------------#
# Write a function called selectionSort which accepts an array return the sorted array
# in ascending order.

# Sample input: [5, 3, 4, 1, 2]
# Sample output: [1, 2, 3, 4, 5]

# ----------------METHOD 01---------------------#
# COMPLEXITY = TIME: O(n^2), SPACE: O(1)
def selectionSort(arr):
	for i in range(len(arr)):
		min_idx = i
		for j in range(i+1, len(arr)):
			if arr[min_idx] > arr[j]:
				min_idx =  j
		arr[min_idx], arr[i] = arr[i], arr[min_idx]
	return arr
# ----------------METHOD 01---------------------#


from omega import *
from euclid import *
from cyclops import *
import csv
import struct
import sys

# Path to the directory that will store the binary versions of the pose files.
poseBinaryCachePath = "./"

# Decimation used by the text -> binary pose file converter
poseDecimation = 10

# Position bias used by pose text->binary data converter. Used to convert i.e.
# from UTM coodrdinates to a local reference frame.
poseTranslation = [ 1371377, 435670, 0 ]

# Root scene node for dive objects. By default this is a node attached to the scene
# root, but user can set it to something else
diveSceneRoot = SceneNode.create("diveRoot")

# Stores the currently active dive
activeDive = None

#------------------------------------------------------------------------------
# Load GLSL shaders used to render dive point clouds
shaderPath = "icecloud/shaders/";

pointsSectionProgram = ProgramAsset()
pointsSectionProgram.name = "points-section"
pointsSectionProgram.vertexShaderName = shaderPath + "sonarPoint.vert"
pointsSectionProgram.fragmentShaderName = shaderPath + "sonarPoint.frag"
pointsSectionProgram.geometryShaderName = shaderPath + "sonarPoint.geom"
pointsSectionProgram.geometryOutVertices = 4
pointsSectionProgram.geometryInput = PrimitiveType.Points
pointsSectionProgram.geometryOutput = PrimitiveType.TriangleStrip
getSceneManager().addProgram(pointsSectionProgram)

pointsActiveProgram = ProgramAsset()
pointsActiveProgram.name = "points-active"
pointsActiveProgram.vertexShaderName = shaderPath + "sonarPoint-active.vert"
pointsActiveProgram.fragmentShaderName = shaderPath + "sonarPoint.frag"
pointsActiveProgram.geometryShaderName = shaderPath + "sonarPoint.geom"
pointsActiveProgram.geometryOutVertices = 4
pointsActiveProgram.geometryInput = PrimitiveType.Points
pointsActiveProgram.geometryOutput = PrimitiveType.TriangleStrip
getSceneManager().addProgram(pointsActiveProgram)

pointScale = Uniform.create('pointScale', UniformType.Float, 1)
fieldMin = Uniform.create('unif_FieldMin', UniformType.Float, 1)
fieldMax = Uniform.create('unif_FieldMax', UniformType.Float, 1)

w1 = Uniform.create('unif_W1', UniformType.Float, 1)
w2 = Uniform.create('unif_W2', UniformType.Float, 1)
w3 = Uniform.create('unif_W3', UniformType.Float, 1)
w4 = Uniform.create('unif_W4', UniformType.Float, 1)

fieldMin.setFloat(10)
fieldMax.setFloat(50.0)
pointScale.setFloat(0.1)

w1.setFloat(1)
w2.setFloat(0)
w3.setFloat(0)
w4.setFloat(0)

# These variables store the bounds of the three attributes associated with each dive.
attribMinBound = Vector3(sys.float_info.max,sys.float_info.max, sys.float_info.max)
attribMaxBound = Vector3(-sys.float_info.max,-sys.float_info.max, -sys.float_info.max)

minAttrib = Uniform.create('unif_AttribMinBound', UniformType.Vector3f, 1)
maxAttrib = Uniform.create('unif_AttribMaxBound', UniformType.Vector3f, 1)

#-------------------------------------------------------------------------------
# This is the program used to display pose data
poseBasicProgram = ProgramAsset()
poseBasicProgram.name = "pose-basic"
poseBasicProgram.vertexShaderName = shaderPath + "posePoint.vert"
poseBasicProgram.fragmentShaderName = shaderPath +  "posePoint.frag"
poseBasicProgram.geometryShaderName = shaderPath + "posePoint.geom"
poseBasicProgram.geometryOutVertices = 4
poseBasicProgram.geometryInput = PrimitiveType.Points
poseBasicProgram.geometryOutput = PrimitiveType.TriangleStrip
getSceneManager().addProgram(poseBasicProgram)

#-------------------------------------------------------------------------------
# Read telemetry CSV and generate binary file
def generatePoseFile(infilename, outfilename):
    f = open(infilename) # input file
    reader = csv.reader(f, delimiter="\t")

    file = open(outfilename, 'wb') # output file

    curRow = 0
    for row in reader:
        row = row[0].split(" ")
        # timestamp orientation pose
        # timestamp (s) is time since 00:00, 1970 Jan 01
        # orientation (rad) is [pitch, roll, yaw]
        # pose (m) is [UTM North, UTM East, Depth from 2008 Dec 10 lake level]
        if( curRow > 4 and curRow % poseDecimation == 0):
            timestamp = 0;
            fields = [0,0,0,0,0,0,0];
            curField = 0;
            for col in row:
                if( len(col) > 0 ):
                    fields[curField] = col;
                    curField += 1;

            # shift fields to x, y, z, rx, ry, rz, timestamp
            x =  float(fields[4]) - float(poseTranslation[0])
            y =  float(fields[5]) - float(poseTranslation[1])
            z =  float(fields[6]) - float(poseTranslation[2])

            fields[4] = x;
            fields[5] = -z;
            fields[6] = y;

            dataBytes = struct.pack('ddddddd', float(fields[4]), float(fields[5]), float(fields[6]), float(fields[1]), float(fields[2]), float(fields[3]), float(fields[0]) )
            file.write(dataBytes)
        curRow += 1
    f.close()
    file.close()


# All the imports
import time

import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keyboard_layout_us import KeyboardLayoutUS
from adafruit_hid.mouse import Mouse

from adafruit_macropad import MacroPad

from rainbowio import colorwheel
import displayio
import terminalio
from adafruit_display_text import bitmap_label as label
from adafruit_displayio_layout.layouts.grid_layout import GridLayout

import board
from adafruit_seesaw import seesaw, rotaryio, digitalio, neopixel

# set up rotary breakouts using the built-in STEMMA QT connector on a microcontroller

i2c = board.STEMMA_I2C()

qt_enc1 = seesaw.Seesaw(i2c, addr=0x36)
qt_enc2 = seesaw.Seesaw(i2c, addr=0x38)

qt_enc1.pin_mode(24, qt_enc1.INPUT_PULLUP)
button1 = digitalio.DigitalIO(qt_enc1, 24)
button_held1 = False

qt_enc2.pin_mode(24, qt_enc2.INPUT_PULLUP)
button2 = digitalio.DigitalIO(qt_enc2, 24)
button_held2 = False

encoder1 = rotaryio.IncrementalEncoder(qt_enc1)
last_position1 = None

encoder2 = rotaryio.IncrementalEncoder(qt_enc2)
last_position2 = None

pixel1 = neopixel.NeoPixel(qt_enc1, 6, 1)
pixel1.brightness = 0.2
pixel1.fill(0xFF0000)

pixel2 = neopixel.NeoPixel(qt_enc2, 6, 1)
pixel2.brightness = 0.2
pixel2.fill(0x00FF00)

last_position1 = -encoder1.position
last_position2 = -encoder2.position

# set up macropad
macropad = MacroPad()
macropad.pixels.brightness = 0.5

last_position = macropad.encoder

# create keyboard

keyboard = Keyboard(usb_hid.devices)
keyboard_layout = KeyboardLayoutUS(keyboard)

# shortcut titles and colours

shortcuts_list = ["focus", "top", "front","right",
                  "zoom", "l cut", "cam", "shear",
                  "sel+-", "tbd", "tbd", "tbd",
                  "xray", "apply", "tbd", "tbd",]
pixel_colours = [ 0x0000FF, 0x00FF00, 0xFF0000,
                  0xFF7F50, 0xDFFF00, 0xE74C3C,
                  0xE74C3C, 0xE74C3C, 0xE74C3C,
                  0xE74C3C, 0xE74C3C, 0x6495ED,]
button_keycodes = [[Keycode.KEYPAD_SEVEN], [Keycode.KEYPAD_ONE], [Keycode.KEYPAD_THREE],
                   [Keycode.CONTROL, Keycode.R], [Keycode.KEYPAD_ZERO], [Keycode.KEYPAD_THREE],
                   [Keycode.KEYPAD_SEVEN], [Keycode.KEYPAD_ONE], [Keycode.KEYPAD_THREE],
                   [Keycode.CONTROL, Keycode.A], [Keycode.KEYPAD_ONE], [Keycode.KEYPAD_THREE],]

# create display as grid
main_group = displayio.Group()
macropad.display.show(main_group)
title = label.Label(
    y=4,
    font=terminalio.FONT,
    color=0x0,
    text="      SHORTCUTS      ",
    background_color=0xFFFFFF,
)
layout = GridLayout(x=0, y=10, width=128, height=54, grid_size=(4, 4), cell_padding=1)
labels = []
for shortcut in shortcuts_list:
    labels.append(label.Label(terminalio.FONT, text=str(shortcut)))

for index in range(16):
    x = index % 4
    y = index // 4
    layout.add_content(labels[index], grid_position=(x, y), cell_size=(1, 1))

main_group.append(title)
main_group.append(layout)

while True:

    # handle key presses
    for pixel in range(12):
        macropad.pixels[pixel] = pixel_colours[pixel]

    key_event = macropad.keys.events.get()

    if key_event and key_event.pressed:
        if len(button_keycodes[key_event.key_number]) > 1:
            keyboard.press(
                button_keycodes[key_event.key_number][0],
                button_keycodes[key_event.key_number][1],
            )
            time.sleep(0.09)
            keyboard.release(
                button_keycodes[key_event.key_number][0],
                button_keycodes[key_event.key_number][1],
            )
        else:
            keyboard.press(button_keycodes[key_event.key_number][0])
            time.sleep(0.09)
            keyboard.release(button_keycodes[key_event.key_number][0])
    # read macropad encoder

    position = macropad.encoder
    position_change = last_position - position

    if position_change != 0:
        modulo_position = position % 3
        if modulo_position == 0:
            keyboard.press(Keycode.ONE)
            time.sleep(0.09)
            keyboard.release(Keycode.ONE)
        elif modulo_position == 1:
            keyboard.press(Keycode.TWO)
            time.sleep(0.09)
            keyboard.release(Keycode.TWO)
        elif modulo_position == 2:
            keyboard.press(Keycode.THREE)
            time.sleep(0.09)
            keyboard.release(Keycode.THREE)

    last_position = position

    # use macropad encoder button

    macropad.encoder_switch_debounced.update()
    if macropad.encoder_switch_debounced.pressed:
        keyboard.press(Keycode.O)
    if macropad.encoder_switch_debounced.released:
        keyboard.release(Keycode.O)

    # read frirst encoder change and do a thing

    position1 = -encoder1.position
    position_change1 = last_position1 - position1

    if position_change1 > 0:
        for _ in range(position_change1):
            keyboard.press(Keycode.KEYPAD_PLUS)
            time.sleep(0.09)
            keyboard.release(Keycode.KEYPAD_PLUS)

    elif position_change1 < 0:
        for _ in range(-position_change1):
            keyboard.press(Keycode.KEYPAD_MINUS)
            time.sleep(0.09)
            keyboard.release(Keycode.KEYPAD_MINUS)

    last_position1 = position1

    # press encoder 1

    if not button1.value and not button_held1:
        button_held1 = True
        pixel1.brightness = 0.5
        keyboard.press(Keycode.KEYPAD_PERIOD)

    if button1.value and button_held1:
        button_held1 = False
        pixel1.brightness = 0.1
        keyboard.release(Keycode.KEYPAD_PERIOD)

    # read second encoder change and do a thing

    position2 = -encoder2.position
    position_change2 = last_position2 - position2

    if position_change2 > 0:
        for _ in range(position_change2):
            keyboard.press(Keycode.CONTROL, Keycode.KEYPAD_PLUS)
            time.sleep(0.09)
            keyboard.release(Keycode.CONTROL, Keycode.KEYPAD_PLUS)

    elif position_change2 < 0:
        for _ in range(-position_change2):
            keyboard.press(Keycode.CONTROL, Keycode.KEYPAD_MINUS)
            time.sleep(0.09)
            keyboard.release(Keycode.CONTROL, Keycode.KEYPAD_MINUS)

    last_position2 = position2

    # handle encoder 2 button

    if not button2.value and not button_held2:
        button_held2 = True
        pixel2.brightness = 0.5
        keyboard.press(Keycode.SHIFT, Keycode.Z)

    if button2.value and button_held2:
        button_held2 = False
        pixel2.brightness = 0.1
        keyboard.release(Keycode.SHIFT, Keycode.Z)


import sys
import os
import fileinput
import re
import time
#this program is replace the break.pl file that instructor provide. And same fuctaion which is convert the format for DB_load
def makeReviewIndex(fileName,fileName1):
    tempFile=open(fileName1,'w+')
    file=open(fileName,'r')
    for line in fileinput.input(fileName):
            c=line.split(',')
            tempFile.write(str(c[0])+"\n")
            stringList = c[1:]
            stringList = ",".join(stringList)
            tempFile.write(str(stringList))
    tempFile.write("\n")
    tempFile.close()
    file.close()

def makeIndex(fileName,fileName1):
    tempFile=open(fileName1,'w+')
    file=open(fileName,'r')
    for line in fileinput.input(fileName):
        c=line.split(',')
        for i in c:
            if '\n' in i:
                tempFile.write(str(i))
            else:
                tempFile.write(str(i)+'\n')
    tempFile.close()
    file.close()

start_time = time.time()
makeReviewIndex("reviews.txt","reviewIdx.txt")
makeIndex("pterms.txt","ptermIdx.txt")
makeIndex("rterms.txt","rtermIdx.txt")
makeIndex("scores.txt","scoreIdx.txt")
print("Your file is formated for db_load!")
print("It cost %s seconds" % (time.time() - start_time))


from random import randint
import random
from time import sleep
import time
from scapy.layers import dhcp
from scapy.layers.dhcp import DHCP, BOOTP
from scapy.layers.inet import IP, UDP
from scapy.layers.l2 import Ether, ARP
from scapy.sendrecv import sniff, sendp
from scapy.all import get_if_hwaddr
from scapy.all import conf
from scapy.layers.dns import DNS, DNSQR, DNSRR

from scapy.all import *
import time

ip_address ="196.0.0.12"
server_id = "196.0.0.11"
mac_address = get_if_hwaddr(conf.iface)

def handle_dhcp(pkt):
    global ip_address, server_id
    if DHCP in pkt and pkt[DHCP].options[0][1] == 2: # DHCP Offer
        ip_address = pkt[BOOTP].yiaddr
        server_id = pkt[DHCP].options[2][1]
        request = Ether(src=mac_address, dst="ff:ff:ff:ff:ff:ff") / \
            IP(src=ip_address, dst="255.255.255.255") / \
            UDP(sport=68, dport=67) / \
            BOOTP(op=1, chaddr=mac_address) / \
            DHCP(options=[("message-type", "request"),
                           ("server_id", server_id),
                           ("requested_addr", ip_address),
                           "end"])

        # Send DHCP Request
        sendp(request,iface=conf.iface)

        # Sniff DHCP ACK with a filter applied
        sniffed_pkt = sniff(filter="udp and (port 67 or 68)", timeout=3)
       # and (src host " + server_id + " and dst host " + mac_address + ")", timeout=3)

        # Call handle_dhcp(pkt) function explicitly if a DHCP ACK message is sniffed
        if sniffed_pkt and DHCP in sniffed_pkt[0] and sniffed_pkt[0][DHCP].options[0][1] == 5:
            handle_dhcp(sniffed_pkt[0])
        # Print DHCP ACK options
        print("DHCP ACK received:")
        print(f"  IP address: {sniffed_pkt[0][BOOTP].yiaddr}")
        print(f"  Subnet mask: {sniffed_pkt[0][DHCP].options[1][1]}")
        print(f"  Default gateway: {sniffed_pkt[0][DHCP].options[3][1]}")
        print(f"  DNS server: {sniffed_pkt[0][DHCP].options[5][1]}")
        return sniffed_pkt[0][BOOTP].yiaddr

def dhco_request():
    global ip_address, server_id
    discover = Ether(src=mac_address, dst="ff:ff:ff:ff:ff:ff") / \
                    IP(src="0.0.0.0", dst="255.255.255.255") / \
                    UDP(sport=68, dport=67) / \
                    BOOTP(op=1, chaddr=mac_address) / \
                    DHCP(options=[("message-type", "discover"),
                                   ("broadcast_flag", ""),
                                   ("requested_addr", "0.0.0.0"), # Set the requested IP address to 0.0.0.0
                                   "end"])
    sendp(discover, iface=conf.iface)
    sniffed_pkt = sniff(filter="udp and (port 67 or 68)", timeout=4)
    if sniffed_pkt:
           handle_dhcp(sniffed_pkt[0])

def DNS_PKT(client_ip):
    dns_server_ip = "5.29.14.36"
    # Get the domain name from the user
    domain_name = input("Enter a domain name: ").encode()
    # Create the DNS query packet
    dns_query = DNSQR(qname=domain_name)
    dns_pkt = Ether() / IP(dst=dns_server_ip) / UDP(sport=9999, dport=53) / DNS(rd=1, qd=dns_query)

    # Send the DNS query packet and sniff for the response
    sendp(dns_pkt, iface=conf.iface)
    response = sniff(filter="udp and port 9999", timeout=5)

    # Check if the domain name is in the DNS response
    if response and response[0].haslayer(DNSRR):
        ip_address = response[0][DNSRR].rdata

        print(f"The IP address of {domain_name.decode('utf-8')} is {ip_address}")
    else:
        print(f"The IP address of {domain_name.decode('utf-8')} is not here")

def main():
    global ip_address, server_id
    user_input = input("Enter 1 to start sending DHCP discovery messages, 2 to ask for domain, or 0 to stop: ")
    while user_input == "1":
        ip_address= dhco_request()
        user_input = input("press 1 to send dns request or 0 to leave ")
        if user_input == "0":
            break
        DNS_PKT(ip_address)
        user_input = input("press 1 for send a dhcp request or 0 to leave ")
        if user_input == "0":
            break
    user_input = input("press 2 to send dns request or 0 to leave ")
    while user_input == "2":
        DNS_PKT(ip_address)

if __name__ == "__main__":
    main()


import os
import warnings
from PIL import Image
import numpy as np
from sklearn.externals import joblib
from test_model.config import *

def tes1t1_data(file_path):
    img = Image.open(file_path)
    data = img.getdata()
    data = np.matrix(data) / 255
    data1 = data.tolist()
    data2 = []
    for i in data1:
        data2.extend(i)
    return [data2]

def together_path(dir_list):           # 遍历一个文件夹的所有函数
    all_file_path = []
    for i in dir_list:
        file_list = os.listdir('./{0}'.format(i))
        for j in file_list:
            file_path = '{0}/{1}'.format(i, j)
            all_file_path.append(file_path)
    return all_file_path

def reconginize_img(img_path):
    warnings.filterwarnings("ignore")
    m = tes1t1_data(img_path)
    svc_3 = joblib.load(model_path_3)
    a = svc_3.predict(m)
    print(a)

if __name__ == '__main__':
    img_path_list = together_path(img_path)
    for file_path in img_path_list:
        reconginize_img(file_path)