# -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 18:51:22 2022

@author: suraj
"""
import streamlit as st
from streamlit_cropper import st_cropper
import numpy as np
import cv2
from  PIL import Image, ImageEnhance
from urllib.request import urlopen
import os
import base64
import io
from io import BytesIO

Output_image = 500

def main():

    @st.cache
    def load_image(url):
        with urlopen(url) as response:
            image = np.asarray(bytearray(response.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        image = image[:, :, [2, 1, 0]] # BGR -> RGB
        return image

    image = load_image('https://raw.githubusercontent.com/rafaelgrecco/Filter-Selector/master/Images/placeholder.jpg')
    image = Image.fromarray(image)
    st.title('SnapEdit')
    st.sidebar.title('Sidebar')

    menu = ['Filters','Image Corrections','Tools', 'Information']
    op = st.sidebar.selectbox('Option', menu)
    if op=='Tools':
        st.set_option('deprecation.showfileUploaderEncoding', False)

    # Upload an image and set some options for demo purposes

        img = st.file_uploader('Upload an image', type=['jpg', 'png', 'jpeg'])

        realtime_update = st.sidebar.checkbox(label="Update in Real Time", value=True)
        box_color = st.sidebar.color_picker(label="Box Color", value='#0000FF')
        aspect_choice = st.sidebar.radio(label="Aspect Ratio", options=["1:1", "16:9", "4:3", "2:3", "Free"])
        aspect_dict = {
            "1:1": (1, 1),
            "16:9": (16, 9),
            "4:3": (4, 3),
            "2:3": (2, 3),
            "Free": None
        }
        aspect_ratio = aspect_dict[aspect_choice]

        if img:
            img = Image.open(img)
            if not realtime_update:
                st.write("Double click to save crop")
        # Get a cropped image from the frontend
            cropped_img = st_cropper(img, realtime_update=realtime_update, box_color=box_color,
                                    aspect_ratio=aspect_ratio)

        # Manipulate cropped image at will
            st.write("Preview")
            _ = cropped_img.thumbnail((150,150))
            st.image(cropped_img)

    if op == 'Filters':

        img = st.file_uploader('Upload an image', type=['jpg', 'png', 'jpeg'])

        if img is not None:
            image = Image.open(img)
            st.sidebar.text('Original Image')
            st.sidebar.image(image, width=200)

        filters = st.sidebar.radio('Filters', ['Original','Grayscale', 'Sepia', 'Blur', 'Contour', 'Sketch'])

        if filters == 'Grayscale':
            img_convert = np.array(image.convert('RGB'))
            gray_image = cv2.cvtColor(img_convert, cv2.COLOR_RGB2GRAY)
            st.image(gray_image, width=Output_image)

        elif filters == 'Sepia':
            img_convert = np.array(image.convert('RGB'))
            img_convert = cv2.cvtColor(img_convert, cv2.COLOR_RGB2BGR)
            kernel = np.array([[0.272, 0.534, 0.131],
                            [0.349, 0.686, 0.168],
                            [0.393, 0.769, 0.189]])
            sepia_image = cv2.filter2D(img_convert, -1, kernel)
            st.image(sepia_image, channels='BGR', width=Output_image)

        elif filters == 'Blur':
            img_convert = np.array(image.convert('RGB'))
            slide = st.sidebar.slider('Quantidade de Blur', 3, 81, 9, step=2)
            img_convert = cv2.cvtColor(img_convert, cv2.COLOR_RGB2BGR)
            blur_image = cv2.GaussianBlur(img_convert, (slide,slide), 0, 0)
            st.image(blur_image, channels='BGR', width=Output_image)

        elif filters == 'Contour':
            img_convert = np.array(image.convert('RGB'))
            img_convert = cv2.cvtColor(img_convert, cv2.COLOR_RGB2BGR)
            blur_image = cv2.GaussianBlur(img_convert, (11,11), 0)
            canny_image = cv2.Canny(blur_image, 100, 150)
            st.image(canny_image, width=Output_image)

        elif filters == 'Sketch':
            img_convert = np.array(image.convert('RGB'))
            gray_image = cv2.cvtColor(img_convert, cv2.COLOR_RGB2GRAY)
            inv_gray = 255 - gray_image
            blur_image = cv2.GaussianBlur(inv_gray, (25,25), 0, 0)
            sketch_image = cv2.divide(gray_image, 255 - blur_image, scale=256)
            st.image(sketch_image, width=Output_image)
        else:
            st.image(image, width=Output_image)

    if op == 'Image Corrections':

        img = st.file_uploader('Upload an image', type=['jpg', 'png', 'jpeg'])

        if img is not None:
            image = Image.open(img)
            st.sidebar.text('Original Image')
            st.sidebar.image(image, width=200)

        MImage = st.sidebar.radio('Image enhancement', ['Original', 'Contrast', 'brightness', 'Sharpness'])

        if MImage == 'Contrast':
            slide = st.sidebar.slider('Contrast', 0.0, 2.0, 1.0)
            enh = ImageEnhance.Contrast(image)
            contrast_image = enh.enhance(slide)
            st.image(contrast_image, width=Output_image)

        elif MImage == 'brightness':
            slide = st.sidebar.slider('brightness', 0.0, 5.0, 1.0)
            enh = ImageEnhance.Brightness(image)
            brightness_image = enh.enhance(slide)
            st.image(brightness_image, width=Output_image)

        elif MImage == 'Sharpness':
            slide = st.sidebar.slider('Sharpness', 0.0, 2.0, 1.0)
            enh = ImageEnhance.Sharpness(image)
            sharpness_image = enh.enhance(slide)
            st.image(sharpness_image, width=Output_image)
        else:
            st.image(image, width=Output_image)

    elif op == 'Information':
        st.subheader('Project by aditya,mayur,sachin,suraj')

if __name__ == '__main__':
    main()

hide_streamlit_style = """
            <style>
            #MainMenu {visibility: hidden;}
            footer {

    visibility: hidden;

    }
footer:after {
    content:'made by acpceians';
    visibility: visible;
    display: block;
    position: relative;
    #background-color: red;
    padding: 5px;
    top: 2px;
}
            </style>
            """
st.markdown(hide_streamlit_style, unsafe_allow_html=True)


# Break
# the break statment is used to stop a loop

while True:
    print ("Run forever")
    break
    print ("this code is not printed")

x= 0
while True:
    print ("In loop", x)
    x=x+1
    if x == 4:
        break

#Continue
# goes back to the top of the loop and skips what is below

x =0
for num in range(11):
    if num%2==1:
        continue
    x =x+num
print (x) ##this is the sum of all the even numbers


#importing the data csv file in our python package by using Numpy package

import numpy as np
filename = 'indian-diabetes.data.csv'

raw_data = open(filename,'r')

data = np.loadtxt(raw_data,delimiter=",")

print("Numpy loadTXt:",data.shape)

raw_data.close()

print("\n\n\n")

for l in data:
    print(l)


import django
from django.conf import settings
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('blog.urls')),
]

# Images & debug configuration
if settings.DEBUG:
    import debug_toolbar

    urlpatterns = (
            [
                path(
                    "media/<path:path>/",
                    django.views.static.serve,
                    {"document_root": settings.MEDIA_ROOT, "show_indexes": True},
                ),
                path("__debug__/", include(debug_toolbar.urls)),
            ]
            + staticfiles_urlpatterns()
            + urlpatterns
    )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import sys
import re
import pandas as pd
import numpy as np
from torch.utils.data import Dataset, DataLoader
import torch
codepath = os.path.abspath(sys.path[0])
sys.path.append(codepath+'/../lib')
sys.path.append(os.getcwd())

class MovementHybridDataset(Dataset):

    # def __init__(self, feat_path, dfeat_path,
    #              egroup_path, egroup_weight_path, divider_path,
    #              itype_path, nblist_path, weight_all_path,
    #              energy_path, force_path, ind_img_path, natoms_img_path, data_num, atom_type, is_dfeat_sparse=False
    #              ):  # , natoms_path

    def __init__(self, inputs: list, data_num, atom_type, is_dfeat_sparse=False, alive_atomic_energy=False):  # , natoms_path
        """
            pm.is_dfeat_sparse is True, self.dfeat will not be generated
        """
        self.data_num = data_num
        self.atom_type_input =atom_type
        self.ntypes = len(atom_type)
        self.is_dfeat_sparse = is_dfeat_sparse
        self.alive_atomic_energy = alive_atomic_energy
        self.max_atom_nums = 0
        super(MovementHybridDataset, self).__init__()
        self.device = torch.device(
            'cuda' if torch.cuda.is_available() else 'cpu')

        self.feat, self.dfeat= [], []
        self.egroup, self.egroup_weight, self.divider =[], [], []
        self.itype, self.nblist, self.weight_all, self.ind_img = [], [], [], []
        self.energy, self.force, self.natoms_img = [], [], []
        self.atom_type = []
        self.energy_shift = []

        if self.alive_atomic_energy:
            feat_path, dfeat_path, egroup_path, egroup_weight_path, divider_path, itype_path, \
            nblist_path, weight_all_path, ind_img_path, natoms_img_path, energy_path, force_path = inputs
        else:
            feat_path, dfeat_path, itype_path, nblist_path, weight_all_path, \
            ind_img_path, natoms_img_path, energy_path, force_path = inputs

        for i in range(data_num):
            self.feat.append(np.load(feat_path[i]))

            if self.is_dfeat_sparse==False:
                self.dfeat.append(np.load(dfeat_path[i]))

            if self.alive_atomic_energy:
                self.egroup.append(np.load(egroup_path[i]))
                self.egroup_weight.append(np.load(egroup_weight_path[i]))
                self.divider.append(np.load(divider_path[i]))

            # self.natoms_sum = natoms
            # self.natoms = pd.read_csv(natoms_path)   #/fread_dfeat/NN_output/natoms_train.csv
            self.itype.append(np.load(itype_path[i]))
            self.nblist.append(np.load(nblist_path[i]))
            self.weight_all.append(np.load(weight_all_path[i]))
            self.ind_img.append(np.load(ind_img_path[i]))

            self.energy.append(np.load(energy_path[i]))
            self.force.append(np.load(force_path[i]))

            self.natoms_img.append(np.load(natoms_img_path[i]))
            self.atom_type.append(np.array(self.get_atom_type(list(self.itype[i][0:self.ind_img[i][1]]))))

            if self.atom_type[i].size == len(self.atom_type_input):
                self.energy_shift = self._get_energy_shift(self.ind_img[i], self.itype[i], self.energy[i])

        self.image_num_list = []
        atom_nums_list = []
        feature_type_list =[]
        for i in range(self.data_num):
            image_number = self.ind_img[i].shape[0] - 1
            self.image_num_list.append(image_number)
            feature_type_list.append(self.dfeat[i].shape[2])
            atom_nums_list.append(self.natoms_img[0][0][0])
        self.max_feature_nums = max(feature_type_list)
        self.max_atom_nums = max(atom_nums_list)

    def __get_data_index(self, index, image_num_list):
        t = 0
        for i, image_num in enumerate(image_num_list):
            t += image_num
            if t > index:
                break
        image_index = index - sum(image_num_list[:i])
        return i, image_index

    def __getitem__(self, index):
        # index = index + 10
        data_index, index = self.__get_data_index(index, self.image_num_list)
        ind_image = np.zeros(2)
        ind_image[0] = self.ind_img[data_index][index]
        ind_image[1] = self.ind_img[data_index][index+1]
        dic= {}

        start_index = self.ind_img[data_index][index]
        end_index = self.ind_img[data_index][index+1]

        dic = {
            'input_feat': self.feat[data_index][start_index:end_index],
            # 'input_egroup': self.egroup[data_index][start_index:end_index],
            # 'input_egroup_weight': self.egroup_weight[data_index][start_index:end_index],
            # 'input_divider': self.divider[data_index][start_index:end_index],
            'input_itype': self.itype[data_index][start_index:end_index],
            'input_nblist': self.nblist[data_index][start_index:end_index],
            'atom_type': self.atom_type[data_index],
            'input_weight_all': self.weight_all[data_index][start_index:end_index],

            'output_energy': self.energy[data_index][start_index:end_index],
            'output_force': self.force[data_index][start_index:end_index],
            'ind_image': ind_image,
            'natoms_img': self.natoms_img[data_index][index]
        }
        if self.is_dfeat_sparse==False:
            dic['input_dfeat'] = self.dfeat[data_index][start_index:end_index]
        else:
            dic['input_dfeat'] = []

        if self.alive_atomic_energy:
            dic['input_egroup'] = self.egroup[data_index][start_index:end_index]
            dic['input_egroup_weight'] = self.egroup_weight[data_index][start_index:end_index]
            dic['input_divider'] = self.divider[data_index][start_index:end_index]
        else:
            dic['input_egroup'] = []
            dic['input_egroup_weight'] = []
            dic['input_divider'] = []
        return dic

    def get_atom_type(self, atom_type_list):
        atom_type_data_input = sorted(set(atom_type_list), key=atom_type_list.index)
        return atom_type_data_input

    def __len__(self):
        return sum(self.image_num_list)

    '''
    description:
    get energy shift from first image of input
    param {*} ind_img
    param {*} itype
    param {*} energy
    param {*} atom_type_input
    return {*}
    author: wuxingxing
    '''
    def _get_energy_shift(self, ind_img, itype, energy):
        type_dict = {}
        result = []

        num_atom = ind_img[1] # get atom nums in the first image
        # atom type list of a image
        type_list = itype[0:num_atom] # get atom types of the atoms
        atomic_energy_list = energy[0:num_atom] # get Ei of the atoms

        for atom, energy in zip(type_list, atomic_energy_list):
            if atom not in type_dict:
                type_dict[atom] = [energy]
            else:
                type_dict[atom].append(energy)

        for atom in self.atom_type_input:
            if atom in type_dict.keys():
                result.append(np.mean(type_dict[atom]))

        return result

    '''
    input para:
    examplespath : npy_file_dir
    data_file_frompwmat : read train_data.csv or test_data.csv
    '''
def get_torch_data_hybrid(data_list, data_type = "final_train", alive_atomic_energy = False, atom_type = None, is_dfeat_sparse=False):
    # examplespath='./train_data/final_train'   # for example

    f_feat, f_dfeat, f_egroup, f_egroup_weight, f_divider, \
        f_itype, f_nblist, f_weight_all, ind_img, natoms_img, f_energy, f_force\
        =[], [], [], [], [], [], [], [], [], [], [], []

    for dir in data_list:
        dir = os.path.join(dir, data_type)
        f_feat.append(os.path.join(dir, 'feat_scaled.npy'))
        f_dfeat.append(os.path.join(dir, 'dfeat_scaled.npy'))

        if alive_atomic_energy:
            f_egroup.append(os.path.join(dir, 'egroup.npy'))
            f_egroup_weight.append(os.path.join(dir, 'egroup_weight.npy'))
            f_divider.append(os.path.join(dir, 'divider.npy'))

        f_itype.append(os.path.join(dir, 'itypes.npy'))
        f_nblist.append(os.path.join(dir, 'nblist.npy'))
        f_weight_all.append(os.path.join(dir, 'weight_all.npy'))
        ind_img.append(os.path.join(dir, 'ind_img.npy'))
        natoms_img.append(os.path.join(dir, 'natoms_img.npy'))

        f_energy.append(os.path.join(dir, 'engy_scaled.npy'))
        f_force.append(os.path.join(dir, 'fors_scaled.npy'))
        # f_force = os.path.join(examplespath+'/force.npy')

        if alive_atomic_energy:
            Dataset_list = [f_feat, f_dfeat, f_egroup, f_egroup_weight, f_divider,
                            f_itype, f_nblist, f_weight_all, ind_img, natoms_img, f_energy, f_force]
        else:
            Dataset_list = [f_feat, f_dfeat, f_itype, f_nblist, f_weight_all, ind_img, natoms_img, f_energy, f_force]

    torch_data = MovementHybridDataset(Dataset_list, len(data_list), atom_type, is_dfeat_sparse, alive_atomic_energy)
    # torch_data = MovementHybridDataset(f_feat, f_dfeat,
    #                              f_egroup, f_egroup_weight, f_divider,
    #                              f_itype, f_nblist, f_weight_all,
    #                              f_energy, f_force, ind_img, natoms_img, len(data_list), atom_type, is_dfeat_sparse)
    return torch_data


import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import models
from tensorflow.keras import backend as K
import horovod.tensorflow.keras as hvd
#import horovod.tensorflow as hvd_tf

import numpy as np
import argparse
import math
import time

from cifar import load_cifar
import custom_callbacks

# Horovod: initialize Horovod.
hvd.init()

parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10, help="epochs by GPU")
parser.add_argument('--batch_size', type=int, default=2048)
parser.add_argument('--learning_rate', type=float, default=0.01)

args = parser.parse_args()
batch_size = args.batch_size
epochs = args.epochs
# Horovod: modified learning rate
lr = args.learning_rate * hvd.size()

gpus = tf.config.experimental.list_physical_devices('GPU')
for gpu in gpus:
    tf.config.experimental.set_memory_growth(gpu, True)
if gpus:
    tf.config.experimental.set_visible_devices(gpus[hvd.local_rank()], 'GPU')

train_ds, test_ds = load_cifar(batch_size)

model = tf.keras.applications.resnet50.ResNet50(include_top=True, weights=None,
            input_shape=(32, 32, 3), classes=10)

opt = tf.keras.optimizers.SGD(lr)
opt = hvd.DistributedOptimizer(opt)

model.compile(loss='categorical_crossentropy',
              optimizer=opt,
              experimental_run_tf_function=False,
              metrics=['accuracy'])

time_callback = custom_callbacks.TimeHistory()
avg_cb = custom_callbacks.MetricAverageCallback()

# Horovod: broadcast initial variable states from rank 0 to all other processes.
# This is necessary to ensure consistent initialization of all workers when
# training is started with random weights or restored from a checkpoint.
callbacks = [hvd.callbacks.BroadcastGlobalVariablesCallback(0),
             time_callback,
             avg_cb]

model.fit(train_ds,
          steps_per_epoch=math.ceil(50000/batch_size),
          epochs=epochs,
          verbose=0,
          callbacks=callbacks
          )

if hvd.rank() == 0:
    times = avg_cb.reduced_time
# tentative code version SA-MIRI Lab8
    print("TIME: ", times)
    print("Average time: ", sum(times)/len(times))
    print("Average time without epoch 1: ", sum(times[1:])/len(times[1:]))


from contextlib import redirect_stdout
from re import compile
import locale

locale.setlocale(locale.LC_ALL, "pt_Br.UTF-8")

lista = []
conjunto = {}

with open("tweets.in", encoding="utf-8") as f:
    tweets = [line.strip() for line in f.readlines()]
    tweets.sort()

regex = compile(r"RT (@\w+): .*https://.*")

for i in tweets:
	for result in regex.findall(i):
		lista.append(result)

conjunto = set(lista)
conjunto = sorted(conjunto, key = locale.strxfrm)

with open("tweets.out", "w", encoding="utf-8") as f:
    with redirect_stdout(f):
        print("\n".join(conjunto))


from anytree import Node, RenderTree
from pickpack import pickpack

title = 'Please choose your favorite fruit: '
options = [
    { 'name': 'Apples', 'grow_on': 'trees' },
    { 'name': 'Oranges', 'grow_on': 'trees' },
    { 'name': 'Strawberries', 'grow_on': 'vines' },
    { 'name': 'Grapes', 'grow_on': 'vines' },
]

def get_description_for_display(option):
    # format the option data for display
    return Node('{0} (grow on {1})'.format(option.get('name'), option.get('grow_on')))

option, index = pickpack(options, title, indicator='=>', options_map_func=get_description_for_display)
print(option, index)


import pandas as pd

def split_train():
    full_train = pd.read_csv('../data/full_train.csv', delimiter=',', header=0)
    tenth_train_rows = len(full_train) // 10
    tenth_train = full_train.iloc[:tenth_train_rows, :]
    tenth_train.to_csv('../data/tenth_train.csv', index=False)

def split_test():
    full_test = pd.read_csv('../data/full_test.csv', delimiter=',', header=0)
    tenth_test_rows = len(full_test) // 10
    tenth_test = full_test.iloc[:tenth_test_rows, :]
    tenth_test.to_csv('../data/tenth_test.csv', index=False)

def main():
    split_train()
    split_test()

if __name__ == '__main__':
    main()


#Elabore um programa que faça a leitura de vários números inteiros, até que se digite um número negativo. O programa tem
# que retornar o maior e o menor número lido

maior = 0

while True:
    num = int(input('Digite um número: '))
    if num < 0:
        break
    else:
        if num > maior:
            maior = num
print(f'O maior número digitado foi {maior}')


"""
the key is full binary tree
it must be 2^n - 1

1 cannot (1 can)
2 cannot
4 cannot

divided into 3 parts
1 root
left 2^i - 1
right 2^j - 1

ah no..
5 can, so not 2^n - 1
2*n - 1???

"""

# Definition for a binary tree node.
from typing import List, Optional

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

class Solution:
    def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
        if n%2==0:
            return None

        def build(start, end):
            if start == end:
                return TreeNode()

            res = []
            for idx in range(start+1, end, 2):
                lefts = build(start, idx-1)
                rights = build(idx+1, end)

                for left in lefts:
                    for right in rights:
                        res.append(TreeNode(0,left,right))
            return res
        return build(1,n)


import numpy as np
import sys

data = []
for line in sys.stdin:
    if line:
        parts = line.split(' ')
        for part in parts:
            k, v = part.split('=')
            if k == 'val_aer':
                data.append(float(v))

print('samples %d' % len(data))
print('mean %f' % np.mean(data))
print('std %f' % np.std(data))
print('min %f' % np.min(data))
print('max %f' % np.max(data))


#Raj Shah
#CIST-005B-72148

#This program take an input of hours and pay rate, and computes the total amount owed
#calculating for overtime past 40 hours at a 1.5x rate to inputted rate. It checks for a
#valid numeric input, and catches if a value is negative when not possible.

import random

def print_state(company, hours, rate, doc_num, gross):
    if(gross == -1):
        print("Invalid number of hours or pay rate.")
    else:
        print("\n\nCompany: {} \nhours: {} \nRate: ${:.2f} \n**********************************************\nYour "
              "document number is: {} \nYour {} gross pay is ${:.2f} dollars.".format(company, hours_float, rate_float, doc_num, company, gross))
    return 0

valid_hours = False
valid_rate = False
doc_num = random.randint(1000, 2000)
company = input("Enter your company name: ")
while(valid_hours == False):
    valid_hours = True
    hours = input("Enter the hours: ")
    try:
        hours_float = float(hours.strip())
    except ValueError:
        print("Error, please enter numeric input")
        valid_hours = False
while(valid_rate == False):
    valid_rate = True
    rate = input("Enter the rate: ")
    try:
        rate_float = float(rate.strip())
    except ValueError:
        print("Error, please enter numeric input")
        valid_rate = False

if(hours_float > 0 and hours_float <= 40 and rate_float >= 0):
    total_pay = hours_float * rate_float
elif (hours_float > 40 and rate_float >= 0):
    total_pay = (40 * rate_float) + ((hours_float - 40) * rate_float * 1.5)
else:
    total_pay = -1
print_state(company, hours_float, rate_float, doc_num, total_pay)
'''
Enter your company name: Apple
Enter the hours: 45
Enter the rate: 10

Company: Apple
hours: 45.0
Rate: $10.00
**********************************************
Your document number is: 1527
Your Apple gross pay is $475.00 dollars.

Enter your company name: Google
Enter the hours: Twenty
Error, please enter numeric input
Enter the hours: 20
Enter the rate: fourteen
Error, please enter numeric input
Enter the rate: 14

Company: Google
hours: 20.0
Rate: $14.00
**********************************************
Your document number is: 1315
Your Google gross pay is $280.00 dollars.

Enter your company name: Sony
Enter the hours: 100
Enter the rate: twelve
Error, please enter numeric input
Enter the rate: -12
Invalid number of hours or pay rate.
'''


import itertools
from collections import UserDict
from operator import itemgetter
from typing import Dict, Iterator, List, Set, Tuple, TypeVar, Union, cast

from pyproj import Proj, Transformer
from shapely.geometry import MultiLineString, MultiPolygon, Polygon
from shapely.geometry.base import BaseGeometry
from shapely.geometry.collection import GeometryCollection
from shapely.ops import polygonize, transform, unary_union

from ....utils.cache import cached_property
from ....utils.geometry import reorient
from .. import Overpass
from ..core import Relation

class RelationsDict(UserDict):
    def __missing__(self, key):
        value = self[key] = list()
        return value

    def include(self, chunk: BaseGeometry, role: str):
        if isinstance(chunk, MultiLineString):
            for c in chunk.geoms:
                self[role].append(c)
        else:
            self[role].append(chunk)

T = TypeVar("T", bound="Boundary")

class Boundary(Relation):
    """A class to parse boundary=* relations.

    boundary=* relations are used for grouping boundaries and marking
    enclaves/exclaves.

    Reference: https://wiki.openstreetmap.org/wiki/Relation:boundary

    Tags:
      - type (boundary)
      - boundary (administrative)
      - land_area (administrative)
      - name
      - admin_level

    Relation members:
      - outer 1+
      - inner 0+
      - admin_center 0-1
      - label 0-1
      - subarea 0+
    """

    def __init__(self, json):
        super().__init__(json)

        self.known_chunks = RelationsDict()
        self.parent: Overpass = json["_parent"]

        self.parsed_keys = cast(
            Dict[int, Dict[str, Union[int, str]]],
            dict(
                (elt["ref"], elt)
                for elt in self.parent.all_members[self.json["id_"]]
            ),
        )

        self._build_geometry_parts()
        if len(self.known_chunks) > 0:
            self._make_geometry(self.known_chunks)

    def simplify(
        self: T,
        resolution: float,
        bounds: Union[None, Tuple[float, float, float, float]] = None,
    ) -> T:
        if bounds is None:
            bounds = self.parent.bounds
        b0, b1, b2, b3 = bounds

        def simplify_shape(shape_: BaseGeometry) -> BaseGeometry:
            proj = Proj(
                proj="aea",  # equivalent projection
                lat_1=b1,
                lat_2=b3,
                lat_0=(b1 + b3) / 2,
                lon_0=(b0 + b2) / 2,
            )

            forward = Transformer.from_proj(
                Proj("EPSG:4326"), proj, always_xy=True
            )
            backward = Transformer.from_proj(
                proj, Proj("EPSG:4326"), always_xy=True
            )
            return transform(
                backward.transform,
                transform(forward.transform, shape_).simplify(resolution),
            )

        rel_dict = RelationsDict()
        for role, shapes in self.known_chunks.items():
            for elt in shapes:
                rel_dict.include(simplify_shape(elt), role)

        self._make_geometry(rel_dict)
        return self

    def _make_geometry(self, parts: RelationsDict):
        outer: List[Polygon] = list(polygonize((unary_union(parts["outer"]))))
        inner: List[Polygon] = list(polygonize((unary_union(parts["inner"]))))

        if len(outer) == 0:
            return GeometryCollection()

        if len(outer) > 1:
            list_ = [
                Polygon(o, holes=list(i for i in inner if o.contains(i)))
                for o in outer
            ]
            shape = MultiPolygon(list_)

        else:
            shape = Polygon(outer[0], inner)

        self.shape = reorient(shape)
        self.json["geometry"] = self.shape

    def intersections(self) -> Iterator[Tuple[int, Set[int]]]:
        all_sets: Dict[int, Set[int]] = dict(
            (key, set(e["ref"] for e in list_))
            for key, list_ in self.parent.all_members.items()
        )
        key_i = self.json["id_"]
        set_i = all_sets[key_i]
        for key_j, set_j in all_sets.items():
            if key_i == key_j:
                continue
            intersection = set_i.intersection(set_j)
            if len(intersection) > 0:
                yield key_j, intersection

    @cached_property
    def neighbours(self) -> Set[int]:
        return set(key for key, _value in self.intersections())

    def include(self, elements: Set[int]) -> None:
        for role, it in itertools.groupby(
            (self.parsed_keys[key] for key in elements), key=itemgetter("role")
        ):
            elts = list(
                elt["geometry"] for elt in it if elt["geometry"] is not None
            )
            if len(elts) > 0:
                chunk = unary_union(elts)
                self.known_chunks.include(chunk, role)

    def _build_geometry_parts(self) -> BaseGeometry:
        all_: Set[int] = set(self.parsed_keys.keys())

        for _id, intersection in self.intersections():
            self.include(intersection)
            all_ -= intersection

        self.include(all_)

# Forcing the inheritance for proper registration
class Land_Area(Boundary):
    pass


# importing the modules that will be needed in the project
import pygame
import random

# initialising the pygame modules
pygame.init()

# creating and setting the size of the screen that is going to be used
screen_width = 1040
screen_height = 680
screen = pygame.display.set_mode((screen_width, screen_height))

# Creating the player, the enemies and the prize objects with the chosen images
player = pygame.image.load("game/player.jpg")
enemy1 = pygame.image.load("game/enemy.png")
enemy2 = pygame.image.load("game/enemy.png")
enemy3 = pygame.image.load("game/enemy.png")
prize = pygame.image.load("game/prize.jpg")

# Getting the player, enemies and prize objects' widths and heights
# To be used to detect whenever any of them are off screen or where they are on the screen
player_height = player.get_height()
player_width = player.get_width()

enemy1_height = enemy1.get_height()
enemy1_width = enemy1.get_width()

enemy2_height = enemy2.get_height()
enemy2_width = enemy2.get_width()

enemy3_height = enemy3.get_height()
enemy3_width = enemy3.get_width()

prize_height = prize.get_height()
prize_width = prize.get_width()

# Printing the height and width of the player object (i.e. the position)
print(f"This is the height of the player: {player_height}.")
print(f"This is the width of the player: {player_width}.")

# Storing the player's position in variables in order for them to be changeable
playerX = 100
playerY = 50

# Setting the enemy and prize objects start position off screen and with a random Y-position
enemy1X = screen_width
enemy1Y = random.randint(0, (screen_height - enemy1_height))

enemy2X = screen_width
enemy2Y = random.randint(0, (screen_height - enemy2_height))

enemy3X = screen_width
enemy3Y = random.randint(0, (screen_height - enemy3_height))

prizeX = screen_width
prizeY = random.randint(0, (screen_height - prize_height))

# Detecting whether arrow keys are being pressed or not
keyUp = False
keyDown = False

# Creating the while loop to continually have the game running
while 1:
    # Clearing the screen and drawing the player and enemy on the screen in the specified positions
    screen.fill(0)
    screen.blit(player, (playerX, playerY))
    screen.blit(enemy1, (enemy1X, enemy1Y))
    screen.blit(enemy2, (enemy2X, enemy2Y))
    screen.blit(enemy3, (enemy3X, enemy3Y))
    screen.blit(prize, (prizeX, prizeY))

    # Updates the screen to what is currently supposed to be on screen
    pygame.display.flip()

    # Looping through events that happen during the game
    for event in pygame.event.get():

        # Checking if the user want to quit and then quits the program if it is true
        if event.type == pygame.QUIT:
            pygame.quit()
            exit(0)

        # Checking if a key has been pressed
        if event.type == pygame.KEYDOWN:

            # Testing if a key we want has been pressed
            if event.key == pygame.K_UP:
                keyUp = True
            if event.key == pygame.K_DOWN:
                keyDown = True

        # Checking if a key is not being pressed
        if event.type == pygame.KEYUP:

            # Testing if a key we want is no longer being pressed
            if event.key == pygame.K_UP:
                keyUp = False
            if event.key == pygame.K_DOWN:
                keyDown = False

    # After the checks are completed in the for loop,
    # Checking if the keyUp or keyDown variables are true and will then move the layer object accordingly
    if keyUp:
        # Checks if the next movement will move the player off screen
        # If it doesn't the player object will move
        if playerY > 0:
            playerY -= 1

    if keyDown:
        # Checks if the next movement will move the player off screen
        # If it doesn't the player object will move
        if playerY < screen_height - player_height:
            playerY += 1

    # Adding a bounding box to the player to be used to check if the enemies collide with the player
    playerBox = pygame.Rect(player.get_rect())

    # Updating the bounding box to the player to ensure it is always around the player
    playerBox.top = playerY
    playerBox.left = playerX

    # Setting the bounding boxes for the first enemy object
    enemy1Box = pygame.Rect(enemy1.get_rect())
    enemy1Box.top = enemy1Y
    enemy1Box.left = enemy1X

    # Setting the bounding boxes for the second enemy object
    enemy2Box = pygame.Rect(enemy2.get_rect())
    enemy2Box.top = enemy2Y
    enemy2Box.left = enemy2X

    # Setting the bounding boxes for the third enemy object
    enemy3Box = pygame.Rect(enemy3.get_rect())
    enemy3Box.top = enemy3Y
    enemy3Box.left = enemy3X

    # Setting the bounding boxes for the prize object
    prizeBox = pygame.Rect(prize.get_rect())
    prizeBox.top = prizeY
    prizeBox.left = prizeX

    # Testing for collisions between the player's box and the enemies' boxes
    if playerBox.colliderect(enemy1Box):

        # Printing losing status if a collision is detected
        print("You Lose!")

        # Quit the game and closing the window
        pygame.quit()
        exit(0)

    if playerBox.colliderect(enemy2Box):

        # Printing losing status if a collision is detected
        print("You Lose!")

        # Quit the game and closing the window
        pygame.quit()
        exit(0)

    if playerBox.colliderect(enemy3Box):

        # Printing losing status if a collision is detected
        print("You Lose!")

        # Quit the game and closing the window
        pygame.quit()
        exit(0)

    # Testing for a player collision
    if playerBox.colliderect(prizeBox):

        # Printing winning status if a collision is detected
        print("You Win!")

        # Quit the game and closing the window
        pygame.quit()
        exit(0)

    # Making the first enemy object move towards the player
    enemy1X -= 0.15

    # Once the first enemy object starts going off screen,
    # the second enemy object starts moving toward the player
    if enemy1X < 0:
        enemy2X -= 0.15

    # Once the second enemy object starts going off screen,
    # the third enemy object starts moving toward the player
    if enemy2X < 0:
        enemy3X -= 0.15

    # Once the third enemy object starts going off screen,
    # the prize object starts moving toward the player
    if enemy3X < 0:
        prizeX -= 0.15

    # If the prize object goes off screen the game is over and the player loses
    if prizeX < 0:
        # Printing losing status
        print("You lose!")

        # Quiting the game and closing the window
        pygame.quit()
        exit(0)


#!/usr/bin/env python
import re
import numpy as np
import argparse

#parser = argparse.ArgumentParser(description="Read special keyword")
#parser.add_argument('-f', '--filen', help="Name of file", default=None, required=True)
#parser.add_argument('')
def read_to_dict(filen):
    dm = {}
    string = ""
    data = []
    with open(filen, 'r') as f:
        for line in f.readlines():
            line = line.strip()
            if not len(line):
                continue
            if re.match("^-", line):
                continue
            if re.match("^/", line):
                continue
            pattern = '[a-z]'
            if re.match(pattern, line):
                string = line
                continue
            line = line.split()
            if line[-1] != "/":
                data += line
            else:
                data += line[0:-1]
                dm[string] = data
                data = []
    return dm

def get_keywords_value(dm, string):
    return dm[string]

def convert_to_ndarray(data, col):
        dm[key] = np.array(data).reshape(len(dm[key])/col,col)

#filen = "interpretation_schedule.txt"

#dm=read_to_dict(filen)
#print np.array(dm["injecting"]).reshape(len(dm["injecting"])/5,5)[:,4]


#!/usr/bin/env python
import os
import pandas as pd

def get_script_dir(follow_symlinks=True):
    """https://stackoverflow.com/questions/3718657/how-to-properly-determine-current-script-directory/22881871#22881871"""
    import inspect
    import os
    import sys
    if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
        path = os.path.abspath(sys.executable)
    else:
        path = inspect.getabsfile(get_script_dir)
    if follow_symlinks:
        path = os.path.realpath(path)
    return os.path.dirname(path)

## Files list
directory = get_script_dir()
files = list(filter(lambda x: x.endswith('.csv'), os.listdir(directory+'/exported')))

for filename in files:
    ## Read
    table = pd.read_csv(directory + '/exported/' + filename, sep=',', header=None)
    ## Format time
    table[1] = pd.to_datetime(table[0] + ' ' + table[1])
    table.drop([0], axis='columns')
    ## Save
    table.to_csv(directory + '/transformed/' + filename, sep=';',
                    header=False, index=False,
                    date_format="%Y.%m.%d %H:%M")


from dataclasses import dataclass
from datetime import datetime
from typing import Optional, List

from opentelemetry.proto.common.v1 import common_pb2
from opentelemetry.proto.logs.v1 import logs_pb2
from opentelemetry.proto.trace.v1 import trace_pb2

@dataclass
class LogRecord:
    span_id: str
    trace_id: str
    unix_nano_ts: int
    keyvalues: dict

    def build_meta(self):
        return self.keyvalues | {
            "span_id": self.span_id,
            "trace_id": self.trace_id,
            "timestamp": datetime.fromtimestamp(self.unix_nano_ts / 1_000_000_000).strftime("%Y-%m-%d %H:%M:%S"),
        }

    def __hash__(self) -> int:
        # very stupid exclude policy
        data = [v for k, v in self.keyvalues.items() if "id" not in k.lower()]
        return hash(str(data))

    @staticmethod
    def from_proto(data: logs_pb2.LogRecord):
        return LogRecord(
            span_id=data.span_id,
            trace_id=data.trace_id,
            unix_nano_ts=data.time_unix_nano,
            keyvalues={
                attr.key: _any_value_to_str(attr.value) for attr in data.attributes
            }
        )

@dataclass
class SpanRecord:
    trace_id: str
    span_id: str
    parent_span_id: Optional[str]
    name: str
    unix_nano_start_at: int
    unix_nano_end_at: int
    logs: List[LogRecord]

    def build_meta(self):
        return {
            "span_id": self.span_id,
            "trace_id": self.trace_id,
            "timestamp": datetime.fromtimestamp(self.unix_nano_end_at / 1_000_000_000).strftime("%Y-%m-%d %H:%M:%S"),
        }

    @staticmethod
    def from_proto(data: trace_pb2.Span, logs: List[LogRecord]):
        return SpanRecord(
            trace_id=data.trace_id,
            span_id=data.span_id,
            parent_span_id=data.parent_span_id,
            name=data.name,
            unix_nano_start_at=data.start_time_unix_nano,
            unix_nano_end_at=data.end_time_unix_nano,
            logs=logs,
        )

def _any_value_to_str(any_val: common_pb2.AnyValue) -> str:
    if any_val.string_value is not None:
        return str(any_val.string_value)
    elif any_val.bool_value is not None:
        return str(any_val.bool_value)
    elif any_val.int_value is not None:
        return str(any_val.int_value)
    elif any_val.double_value is not None:
        return str(any_val.double_value)
    elif any_val.bytes_value is not None:
        return str(any_val.bytes_value)
    elif any_val.array_value is not None:
        return f'[{", ".join(list(map(_any_value_to_str, any_val.array_value.values)))}]'
    elif any_val.kvlist_value is not None:
        kvlist = []
        for kv in any_val.kvlist_value.values:
            kvlist.append(f"{kv.key}: {_any_value_to_str(kv.value)}")
        return f'{{{", ".join(kvlist)}}}'
    else:
        return "Unsupported value type"

@dataclass
class Trace:
    trace_id: str
    unix_nano_start_at: int
    unix_nano_end_at: int
    spans: List[SpanRecord]


# -*- coding: utf-8 -*-

from superjson import json
from pathlib_mate import Path
from seedinvest_monitor.devops.config import Config

config = Config()
if config.is_aws_lambda_runtime():
    config.update_from_env_var(prefix="SEEDINVEST_MONITOR_")
else:
    config.update(json.load(Path(config.CONFIG_DIR, "00-config-shared.json").abspath, verbose=False))
    config.update(json.load(Path(config.CONFIG_DIR, "01-config-dev.json").abspath, verbose=False))
    config.dump_python_json_config_file()
    config.dump_cloudformation_json_config_file()


def file_replace(file_name,old_word,new_word):
         f_read =open (file_name)
         count =0
         content=[]
         for find_word in f_read:
                  if old_word in find_word:
                           count =find_word.count(old_word)
                           find_word=find_word.replace(old_word,new_word)
                  content .append(find_word)
         decide = input("文件%s中共有%s个【%s】\n 你确定要把所有的【%s】替换为【%s】吗？\n 【YES/NO】："
                        %(file_name,count,old_word,old_word,new_word))
         if decide in ['YES','Yes','yes']:
                  f_write = open (file_name,'w')
                  f_write.writelines(content)
                  f_write.close()
         f_read.close()
file_name = input('请输入文件名：')
old_word= input('请输入需要替换的单词或是字符：')
new_word= input('请输入新的单词或是字符：')
file_replace(file_name,old_word,new_word)


#import PIL.Image
import dlib
import numpy as np
import cv2
from .faceID_models import faceID_models
import itertools
import sys
import os
import re
import multiprocessing
import shutil

face_detector = dlib.get_frontal_face_detector()

predictor_68_point_model = faceID_models.pose_predictor_model_location()
pose_predictor_68_point = dlib.shape_predictor(predictor_68_point_model)

predictor_5_point_model = faceID_models.pose_predictor_five_point_model_location()
pose_predictor_5_point = dlib.shape_predictor(predictor_5_point_model)

cnn_face_detection_model = faceID_models.cnn_face_detector_model_location()
cnn_face_detector = dlib.cnn_face_detection_model_v1(cnn_face_detection_model)

face_recognition_model = faceID_models.face_recognition_model_location()
face_encoder = dlib.face_recognition_model_v1(face_recognition_model)

def load_image_file(file):
    """
    Loads an image file (.jpg, .png, etc) into a numpy array using opencv

    :param file: image file name or file object to load
    :return: image contents as numpy array (RGB order)
    """

    return cv2.cvtColor(np.array(cv2.imread(file)), cv2.COLOR_BGR2RGB)

def imwrite(file_name,image):
    """
    Write numpy array into disk

    :param file: image file name or file object to write
    :return: None
    """

    cv2.imwrite(file_name,cv2.cvtColor(image,cv2.COLOR_RGB2BGR))

def face_distance(face_encodings, face_to_compare):
    """
    Given a list of face encodings, compare them to a known face encoding and get a euclidean distance
    for each comparison face. The distance tells you how similar the faces are.

    :param faces: List of face encodings to compare
    :param face_to_compare: A face encoding to compare against
    :return: A numpy ndarray with the distance for each face in the same order as the 'faces' array
    """
    if len(face_encodings) == 0:
        return np.empty((0))

    return np.linalg.norm(face_encodings - face_to_compare, axis=1)

def show_image_cv(screen_name,image,wait_time=0):
    '''
    Show out image

    :param screen_name: Screen name of the showing window
    :param image: Numpy array of image
    :param wait_time: Delay time of the screen
    '''
    cv2.imshow(screen_name,cv2.cvtColor(image,cv2.COLOR_RGB2BGR))
    cv2.waitKey(wait_time)

def _rect_to_css(rect):
    """
    Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order

    :param rect: a dlib 'rect' object
    :return: a plain tuple representation of the rect in (top, right, bottom, left) order
    """
    return rect.top(), rect.right(), rect.bottom(), rect.left()

def _css_to_rect(css):
    """
    Convert a tuple in (top, right, bottom, left) order to a dlib `rect` object

    :param css:  plain tuple representation of the rect in (top, right, bottom, left) order
    :return: a dlib `rect` object
    """
    return dlib.rectangle(css[3], css[0], css[1], css[2])

def _trim_css_to_bounds(css, image_shape):
    """
    Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image.

    :param css:  plain tuple representation of the rect in (top, right, bottom, left) order
    :param image_shape: numpy shape of the image array
    :return: a trimmed plain tuple representation of the rect in (top, right, bottom, left) order
    """
    return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0)

def _raw_face_locations(img, number_of_times_to_upsample=1, model="hog"):
    """
    Returns an array of bounding boxes of human faces in a image

    :param img: An image (as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :param model: Which face detection model to use. "hog" is less accurate but faster on CPUs. "cnn" is a more accurate
                  deep-learning model which is GPU/CUDA accelerated (if available). The default is "hog".
    :return: A list of dlib 'rect' objects of found face locations
    """
    if model == "cnn":
        return cnn_face_detector(img, number_of_times_to_upsample)
    else:
        return face_detector(img, number_of_times_to_upsample)

def face_locations(img, number_of_times_to_upsample=1, model="hog"):
    """
    Returns an array of bounding boxes of human faces in a image

    :param img: An image (as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :param model: Which face detection model to use. "hog" is less accurate but faster on CPUs. "cnn" is a more accurate
                  deep-learning model which is GPU/CUDA accelerated (if available). The default is "hog".
    :return: A list of tuples of found face locations in css (top, right, bottom, left) order
    """
    if model == "cnn":
        return [_trim_css_to_bounds(_rect_to_css(face.rect), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, "cnn")]
    else:
        return [_trim_css_to_bounds(_rect_to_css(face), img.shape) for face in _raw_face_locations(img, number_of_times_to_upsample, model)]

def _raw_face_locations_batched(images, number_of_times_to_upsample=1, batch_size=128):
    """
    Returns an 2d array of dlib rects of human faces in a image using the cnn face detector

    :param img: A list of images (each as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :return: A list of dlib 'rect' objects of found face locations
    """
    return cnn_face_detector(images, number_of_times_to_upsample, batch_size=batch_size)

def batch_face_locations(images, number_of_times_to_upsample=1, batch_size=128):
    """
    Returns an 2d array of bounding boxes of human faces in a image using the cnn face detector
    If you are using a GPU, this can give you much faster results since the GPU
    can process batches of images at once. If you aren't using a GPU, you don't need this function.

    :param img: A list of images (each as a numpy array)
    :param number_of_times_to_upsample: How many times to upsample the image looking for faces. Higher numbers find smaller faces.
    :param batch_size: How many images to include in each GPU processing batch.
    :return: A list of tuples of found face locations in css (top, right, bottom, left) order
    """
    def convert_cnn_detections_to_css(detections):
        return [_trim_css_to_bounds(_rect_to_css(face.rect), images[0].shape) for face in detections]

    raw_detections_batched = _raw_face_locations_batched(images, number_of_times_to_upsample, batch_size)

    return list(map(convert_cnn_detections_to_css, raw_detections_batched))

def _raw_face_landmarks(face_image, face_locations=None, model="large"):
    if face_locations is None:
        face_locations = _raw_face_locations(face_image)
    else:
        face_locations = [_css_to_rect(face_location) for face_location in face_locations]

    pose_predictor = pose_predictor_68_point

    if model == "small":
        pose_predictor = pose_predictor_5_point

    return [pose_predictor(face_image, face_location) for face_location in face_locations]

def face_encodings(face_image, known_face_locations=None, num_jitters=1):
    """
    Given an image, return the 128-dimension face encoding for each face in the image.

    :param face_image: The image that contains one or more faces
    :param known_face_locations: Optional - the bounding boxes of each face if you already know them.
    :param num_jitters: How many times to re-sample the face when calculating encoding. Higher is more accurate, but slower (i.e. 100 is 100x slower)
    :return: A list of 128-dimensional face encodings (one for each face in the image)
    """
    raw_landmarks = _raw_face_landmarks(face_image, known_face_locations, model="large")
    return [np.array(face_encoder.compute_face_descriptor(face_image, raw_landmark_set, num_jitters)) for raw_landmark_set in raw_landmarks]

def compare_faces(known_face_encodings, face_encoding_to_check, tolerance=0.6):
    """
    Compare a list of face encodings against a candidate encoding to see if they match.

    :param known_face_encodings: A list of known face encodings
    :param face_encoding_to_check: A single face encoding to compare against the list
    :param tolerance: How much distance between faces to consider it a match. Lower is more strict. 0.6 is typical best performance.
    :return: A list of True/False values indicating which known_face_encodings match the face encoding to check
    """

    return list(face_distance(known_face_encodings, face_encoding_to_check) <= tolerance)

#######################################################################################################################################
def image_files_in_folder(folder):
    return [os.path.join(folder, f) for f in os.listdir(folder) if re.match(r'.*\.(jpg|jpeg|png|JPG)', f, flags=re.I)]

def test_image(target_encodings,image_to_check, model,output_folder):
    '''
    Given an unknown image, compare the face appear in it with sample encodings

    :param target_encodings: encodings extracted from sample image
    :param image_to_check: image path that needs to be check
    :param model: face detection model, either 'hog' or 'cnn'
    :param output_folder: output folder of images that has target_encodings in

    '''
    unknown_image = load_image_file(image_to_check)

    unknown_image_locations = face_locations(unknown_image,model=model)
    test_encodings = face_encodings(unknown_image,unknown_image_locations)

    for idx,test_encoding in enumerate(test_encodings):
        compare_results = compare_faces(target_encodings,test_encoding,0.6)
        print (compare_results)
        if any(compare_results):
            shutil.copyfile(image_to_check, os.path.join(output_folder,os.path.basename(image_to_check)))

def process_images_in_process_pool(target_encodings,images_to_check, number_of_cpus, model,output_folder):
    if number_of_cpus == -1:
        processes = None
    else:
        processes = number_of_cpus

    # macOS will crash due to a bug in libdispatch if you don't use 'forkserver'
    context = multiprocessing
    if "forkserver" in multiprocessing.get_all_start_methods():
        context = multiprocessing.get_context("forkserver")

    pool = context.Pool(processes=processes)

    function_parameters = zip(
        itertools.repeat(target_encodings),
        images_to_check,
        itertools.repeat(model),
        itertools.repeat(output_folder)
    )

    pool.starmap(test_image, function_parameters)

def find_ID(sample,input,output_folder,cpus, model):
    '''
    find the images that has at lease one ID that appear in sample image

    :param sample: sample image path
    :param input: folder contains testing images
    :param cpus: number of cpus that you want to use
    :param model: face detection model, either 'hog' or 'cnn'

    '''
    # Multi-core processing only supported on Python 3.4 or greater
    if (sys.version_info < (3, 4)) and cpus != 1:
        click.echo("WARNING: Multi-processing support requires Python 3.4 or greater. Falling back to single-threaded processing!")
        cpus = 1

    if not (os.path.exists(input) or os.path.exists(sample)):
        click.echo("ERROR: " + input + " is not found")
        sys.exit(1)

    if not os.path.exists(output_folder):
        os.mkdir(output_folder)

    try:
        image_sample = load_image_file(sample)
        target_locations = face_locations(image_sample,model=model)
        target_encodings = face_encodings(image_sample,target_locations)
        print (target_encodings)
        print(len(target_encodings)," faces are found in sample image")

    except:
        print("Cannot encode from the sample image")
        quit()

    if os.path.isdir(input):
        if cpus == 1:
            [test_image(target_encodings,image_file, model,output_folder) for image_file in image_files_in_folder(input)]
        else:
            process_images_in_process_pool(target_encodings,image_files_in_folder(input), cpus, model,output_folder)
    else:
        test_image(target_encodings,image_to_check, model,output_folder)


from sklearn.metrics import mean_squared_error,accuracy_score,auc,f1_score
import torch
import numpy as np

def rmse(y_true,y_pred):
    if isinstance(y_true,torch.Tensor):
        return ((y_pred-ytrue)**2).mean().pow(0.5).item()
    elif isinstance(y_true,np.ndarray):
        return mean_squared_error(y_true,y_pred,squared=False)

def accuracy(y_true,y_pred,reduction=True):
    if isinstance(y_true,torch.Tensor):
        y_pred = torch.argmax(y_true,dim=-1)
        if reduction:
            return y_pred.eq(y_true.view_as(preds)).mean().item()
        else:
            return y_pred.eq(y_true.view_as(preds)).sum().item()

    elif isinstance(y_true,np.ndarray):
        y_pred = np.argmax(y_pred,axis=-1)
        if reduction:
            return accuracy_score(y_true,y_pred)
        else:
            return accuracy_score(y_true,y_pred,normalize=False)

class f1(object):
    def __init__(self,average='macro'):
        self.average=average
    def __call__(self,y_true,y_pred):
        if isinstance(y_true,torch.Tensor):
            preds = y_pred.cpu().detach().numpy()
            truths = y_true.cpu().detach().numpy()

        elif isinstance(y_true,list):
            preds = np.array(y_preds)
            truths = np.array(y_true)
        else:
            preds = y_pred
            truths = y_true
        preds = np.argmax(preds,axis=1)
        return f1_score(truths,preds,average = self.average)
    @property
    def __name__(self):
        return self.__class__.__name__

_metrics = {'accuracy':accuracy,'f1_score':f1,'rmse':rmse}

def get_metric(name=''):

    if name not in _metrics:
        raise ValueError('Metric should be either accuracy,f1_score and rmse')
    return _metrics[name]


from elasticmagic.cluster import MAX_RESULT_WINDOW

from . import AsyncSearchQueryWrapper
from ...pagination.flask import BasePagination

class AsyncPagination(BasePagination):
    """Helper class to provide compatibility with Flask-SQLAlchemy paginator.
    """

    @classmethod
    async def create(
            cls, query, page=1, per_page=10, max_items=MAX_RESULT_WINDOW
    ):
        self = cls()
        self.original_query = query
        self.query = AsyncSearchQueryWrapper(query, max_items=max_items)
        self.page = page if page > 0 else 1
        self.per_page = per_page
        self.max_items = max_items
        self.offset = (self.page - 1) * self.per_page
        self.items = await self.query[self.offset:self.offset + self.per_page]
        self.total = (await self.query.get_result()).total
        return self

    async def prev(self):
        return await self.create(
            self.original_query, **self._prev_page_params()
        )

    async def next(self):
        return await self.create(
            self.original_query, **self._next_page_params()
        )


#!/usr/bin/env python3
# script fetches FMI Open data and imports it to DB
from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running

from db_setup import *
from cleaner import *
import configparser
from configurator import *
import os.path

tiff_dir_base = config.get("locations","wms_data_dir")
api_key = config.get( "settings","fmi_api_key")

# set logger
logger = set_logger( "fmi_open" )

from datetime import datetime,timedelta
import os
from urllib.request import urlopen,urlparse

from xml.etree import ElementTree
gml_namespace = "http://www.opengis.net/gml/3.2"

# sections in config file must match with layer names
wfs_layers = {
    'fmi_radar_single_dbz':
    'http://opendata.fmi.fi/wfs?request=GetFeature&storedquery_id=fmi::radar::single::dbz',
    'fmi_radar_single_vrad':
    'http://opendata.fmi.fi/wfs?request=GetFeature&storedquery_id=fmi::radar::single::vrad',
    'fmi_radar_single_etop_20':
    'http://opendata.fmi.fi/wfs?request=GetFeature&storedquery_id=fmi::radar::single::etop_20',
    'fmi_radar_single_hclass':
    'http://opendata.fmi.fi/wfs?request=GetFeature&storedquery_id=fmi::radar::single::hclass'

}

config_dataset_names,config_sections = get_sections_from_config()

def update():
    add_datasets = []
    return_datasets = []
    logger.debug( "Start updating of DB" )
    for layer in wfs_layers:
        if not layer in config_dataset_names:
            continue
        else:
            logger.debug( "Found layer %s from config" % layer )
            section = config_sections[config_dataset_names.index(layer)]
        # check that tiff directory exists
        tiff_dir = "%s/%s" % (tiff_dir_base,layer)
        if not os.path.exists(tiff_dir):
            logger.debug( "GeoTIFF directory does not exist. Create it." )
            os.makedirs(tiff_dir)
        # get WFS to get WMS urls
        try:
            wfs_url = wfs_layers[layer].replace("{key}",api_key)
            response = urlopen( wfs_url )
            logger.debug( "Data from url %s fetched" % wfs_url )
        # ignore network related problems
        except:
            logger.error( "Network error occurred while fetching url %s" % wfs_url )
            continue
        logger.debug( "Parse WFS response for layer %s" % layer )
        wfs_response = ElementTree.fromstring(response.read())
        file_references = wfs_response.findall('.//{%s}fileReference' % gml_namespace)
        for ref in file_references:
            url = ref.text
            query = urlparse(url).query
            query = query.split("&")
            for q in query:
                if q[0:4].lower()=="time":
                    time_value = q.split("=")[-1]
                elif q[0:3].lower()=="srs":
                    projdef = q.split("=")[-1]
                elif q[0:4].lower()=="bbox":
                    bbox = q.split("=")[-1]
                elif q[0:6].lower()=="layers":
                    radar_name = q.split("=")[-1]
                elif q[0:9].lower()=="elevation":
                    radar_elevation = q.split("=")[-1]
            timestamp = datetime.strptime(time_value,\
                    "%Y-%m-%dT%H:%M:%SZ")
            # search if dataset already exists
            if (radar_name.split("_")[0] != "Radar:kesalahti") :
                continue
            if (layer!='fmi_radar_single_etop_20' and float(radar_elevation) > 0.5) :
                continue
            output_filename = tiff_dir + "/" + radar_name.replace("Radar:","")+ time_value.replace(":","")\
                .replace("-","") + "_"+radar_elevation+ ".tif"
            # skip file fetching if it already exists
            if os.path.isfile(output_filename):
                continue
            # save file to disk
            try:
                response = urlopen( url )
                logger.debug( "Fetched data from url %s" % url )
            # ignore network related problems
            except:
                logger.error( "Network error or invalid api-key occurred while fetching url %s" % url )
                continue
            f = open(output_filename,"wb")
            f.write( response.read() )
            f.close()
            # import dataset to db
            logger.info( "Add new dataset: %s:%s to DB." % (layer,str(timestamp)) )
            add_datasets.append(
                RadarDataset(
                    name = layer,
                    timestamp = timestamp,
                    geotiff_path = output_filename,
                    projdef = projdef,
                    bbox_original = bbox,
                    dataset_type = config.get(section,"dataset_type"),
                    unit = config.get(section,"unit"),
                    style = config.get(section,"style"),
                    title = config.get(section,"title")
                )
            )
            return_datasets.append({"name": layer,
                                    "timestamp": timestamp })
    # finally add new datasets to DB
    if (len(add_datasets)>0):
        session.add_all(add_datasets)
        session.commit()
    logger.info ( "Added %i results." % len(add_datasets) )
    logger.debug( "Updating of DB finished" )
    session.close()
    return return_datasets

if __name__ == '__main__':
    update()
    # delete old
    for layer in wfs_layers:
        if not layer in config_dataset_names:
            continue
        else:
            section = config_sections[config_dataset_names.index(layer)]
            clean_up(config.get(section,"name"),
                     int( config.get(section,"cleanup_time") ))


import csv
import requests
import random
import json
import pymysql
import time
from lxml import etree
allResult = []
# 从json文件当中获取当前的数据条数以及总数据
# with open('小说.json','r',encoding='utf-8') as file:
# with open('小说test.json','r',encoding='utf-8') as file:
#     # jsonDic = json.load(file)
#     count = jsonDic['count']
#     allResult = jsonDic['data']
db = pymysql.connect('localhost', 'root', 'root', 'python', 8889)
cursor = db.cursor()
count = 0
for i in range(1, 600):
    url = "https://api.hongdouyuedu.com/honor/category/info?category=%E5%A5%B3%E9%A2%91%3B%E7%8E%B0%E4%BB%A3%E8%A8%80%E6%83%85%3B%E6%80%BB%E8%A3%81%E8%B1%AA%E9%97%A8&channel=oppo&device_name=PDPM00&identifier=&physic_size=6.56&platform=wwa1&plattype=aphone&scale_screen=2400_1080&ts=1598649593222&uuid=FF91EABB42C32DD1CBC71BCE6A528208&version=2.5.9&virtual=0&sig=b221f5e56806176a35b9d433da5014bc"
    parameter = {"page_index": i}
    headers = {
        "User-Agent": "okhttp/3.12.1",
        "Host": "api.hongdouyuedu.com",
        "Connection": "Keep-Alive",
        "Accept-Encoding": "identity",
    }
    response = requests.get(url, headers=headers, params=parameter)
    print(response.text)
    content = response.json()["data"]["data"]
    for book in content:
        print()
        print("开始爬取下一本小说")
        book_name = book["name"]
        print(book_name)
        author_name = book["author_name"]
        print(author_name)
        tags = book["label_name"]
        print(tags)
        categories = book["category_name"]
        print(categories)
        intro = book["described"]
        print(intro)
        words_num = book["words_total"]
        popularity = book["views_total"]
        print(book_name + " 小说爬取完毕")

        # 分享链接
        # share_url = secondary_content["data"]["share_url"]
        share_url = "空"

        dic = {
            '书名': book_name,
            '作者名': author_name,
            '标签': tags,
            '可选分类': categories,
            '简介': intro,
            '字数': words_num,
            '人气数': popularity,
            '分享链接': share_url
        }

        count += 1
        allResult.append(dic)
        # 写入json文件，"红豆小说1000本总裁文.json"
        data = {'data': allResult, 'count': count}
        with open('小说.json', 'w', encoding='utf-8') as file:
            # 直接存入json
            json.dump(data, file, ensure_ascii=False, indent=4)

        count += 1
        # 写入csv文件，"红豆小说1000本总裁文.csv"
        header = ['书名', '作者名', '标签', '可选分类', '简介', '字数', '人气数', '分享链接']
        with open('小说.csv', 'a', encoding='utf-8-sig', newline='') as file:
            huo = csv.DictWriter(file, header)
            if count == 1:
                huo.writeheader()
            huo.writerow(dic)

        # 写入数据库表
        sql = "INSERT INTO xiaoshuo (book_name, author_name, tags, categories, intro, words_num, popularity, share_url) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s');" % (
            book_name, author_name, tags, categories, intro, words_num, popularity, share_url)
        cursor.execute(sql)
        # 数据库提交操作
        db.commit()

# 从json文件当中获取当前的数据条数以及总数据
# with open('小说.json','r',encoding='utf-8') as file:
# with open('小说test.json','r',encoding='utf-8') as file:
#     # jsonDic = json.load(file)
#     count = jsonDic['count']
#     allResult = jsonDic['data']

# 关闭数据库
db.close()


print(cv2.TERM_CRITERIA_EPS, cv2.TERM_CRITERIA_MAX_ITER)

# Vector for 3D points
threedpoints = []

# Vector for 2D points
twodpoints = []

#  3D points real world coordinates
objectp3d = np.zeros((1, CHECKERBOARD[0]
                      * CHECKERBOARD[1],
                      3), np.float32)
objectp3d[0, :, :2] = np.mgrid[0:CHECKERBOARD[0],
                               0:CHECKERBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None


# -*- coding:utf8 -*-

from __future__ import print_function
import os
import numpy as np
import pandas as pd
import codecs
from keras.datasets import imdb
from config import Config

class Data_Loader(object):

    def __init__(self):
        print('Loading data...')

    def load_from_file(self, config, mode='train'):

        if mode == 'train':
            path = config.train_path
        else:
            path = config.test_path

        neg_path = path + 'neg/'
        pos_path = path + 'pos/'

        neg_list = os.listdir(neg_path)
        pos_list = os.listdir(pos_path)

        data = []
        label = []

        print("Load neg...")
        for neg in neg_list:
            with codecs.open(neg_path + neg) as fp:
                text = fp.read()
                data.append(text.strip())
                label.append(0)

        print("neg data is", len(data))
        # print("example of neg:\n", data[0])

        print("Loading pos...")
        for pos in pos_list:
            with codecs.open(pos_path + pos) as fp:
                text = fp.read()
                data.append(text.strip())
                label.append(1)

        print("all data is", len(data))
        # print("example of pos:\n", data[-1])

        return data, label

    def load(self, config):
        """Load data

        :param config:
        :return: the data of imdb
        """
        (X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=config.max_features)
        print(len(X_train), 'train sequences')
        print(len(X_test), 'test sequences')
        print('x_train set\' shape', np.shape(X_train))
        print('y_train set\' shape', np.shape(y_train))
        print('x_test set\' shape', np.shape(X_test))
        print('y_test set\' shape', np.shape(y_test))

        return X_train, y_train, X_test, y_test

    def stat(self):
        """Statistic data

        :return: None
        """
        print('statistic...')
        config = Config()
        X_train, y_train, X_test, y_test = self.load(config)
        len_num = []
        for X in X_train+X_test:
            len_num.append(len(X))
        print('max len num is', max(len_num))
        len_num = pd.Series(len_num)
        print('len num count is\n', len_num.value_counts())

    def show_example(self):
        print('show example...')
        config = Config(word_vocb_path='./data/imdb.vocab')
        index_word = config.get_index_word()
        X_train, _, _, _ = self.load(config)
        print(X_train[0])
        new_text = []
        for index in X_train[0]:
            new_text.append(index_word[index].strip())
        print(' '.join(new_text))

    def test(self):
        config = Config()
        X_train, y_train, X_test, y_test = self.load(config)
        print(X_train[0])
        print(y_train[0])

if __name__ == '__main__':
    data_loader = Data_Loader()
    data_loader.show_example()
    # data_loader.stat()


import itertools

list = ['0001','0011','0101','1011','1101','0111']

new_list = [int(binary , 2) for binary in list]

new_list.sort()

print(new_list)

sum= sum(new_list)

print(sum)

combination = itertools.combinations(new_list,2)

last = None

for combo in combination:
    last = combo
    print(combo)

if last != None:
    print(last[0])
    print(last[1])

# jo minus krane wala concpt hai vo karna hai like 2 array lekar ek mai sab add karke ek ek elemnt se subtract karna hai and phir itertools lagana hai


import sys
sys.stdin = open("res/input_swea_d6_1263.txt")
T = int(input())

INF = 999999999

for tc in range(1, T+1):
    line = input()
    line = line.split(" ")
    N = int(line[0])
    arr = [[0 for i in range(N)] for j in range(N)]

    for i in range(0, N):
        for j in range(0, N):
            arr[i][j] = int(line[1+i*N+j])
            if arr[i][j] ==0 and i is not j:
                arr[i][j] = INF

    for k in range(0, N):
        for i in range(0, N):
            if i is k : continue
            for j in range(0, N):
                if (j is k) or (i is j): continue
                candidate = arr[i][k] + arr[k][j]
                if arr[i][j] > candidate: arr[i][j] = candidate

    min_cc = INF

    for i in range(N):
        cc = 0
        for j in range(N):
            cc+= arr[i][j]
        min_cc = min(min_cc, cc)

    print("#{} {}".format(tc, min_cc))


import pandas as pd
import random
import numpy as np
import matplotlib.pyplot as plt

def throw_two_dice():
    die = [1,2,3,4,5,6]
    die_1 = random.choices(die)
    die_2 = random.choices(die)
    dice = [die_1[0], die_2[0]]
    total = np.sum(dice)

    return total

n_times = 1000000
outcomes = []
for i in range(n_times):
    outcomes.append(throw_two_dice())

data = pd.DataFrame({'outcome': outcomes})
data = data.groupby(['outcome']).agg(n=('outcome', 'count')).reset_index()
data['probability'] = data['n'] / 1000000
data.plot(x='outcome', y='probability', kind='bar')


import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.patches import Rectangle

'''
0 -- up
1 -- right
2 -- down
3 -- left
'''
def get_motion_direction(x, epsilon):
	if np.random.uniform(0,1) > epsilon:
		return x
	return np.random.randint(0, 4)

def is_wall(x, y):
	if x == 0 or x == 49:
		return True
	if y == 0 or y == 24:
		return True
	if x == 25 or x == 26:
		if y != 12:
			return True
	return False

def is_goal(x, y):
	if x == 48 and y == 12:
		return True
	return False

def reward(x, y, hit_wall):
	if is_goal(x, y):
		return 100
	if hit_wall:
		return -1
	return 0

def transition(x, y, dir, epsilon):
	# add arbitrariness
	dir = get_motion_direction(dir, epsilon)

	xf = x
	yf = y
	if dir == 0:
		yf += 1
	elif dir == 1:
		xf += 1
	elif dir == 2:
		yf -= 1
	else:
		xf -= 1
	return (xf, yf)

def get_next_state(qsa_grid, x, y, epsilon):
	dir = np.argmax(qsa_grid[x][y])
	xf, yf = transition(x, y, dir, epsilon)
	hit_wall = False
	if is_wall(xf, yf):
		hit_wall = True
		xf, yf = x, y
	r = reward(xf, yf, hit_wall)
	return (xf, yf, r, dir)

def initialise_qsa_grid():
	qsa_grid = np.zeros((50, 25, 4))
	for x in range(50):
		for y in range(25):
			for a in range(4):
				qsa_grid[x][y][a] = 1
	return qsa_grid

def get_start_state():
	x = 0
	y = 0
	while (is_wall(x, y) or is_goal(x, y)):
		x = np.random.randint(0, 50)
		y = np.random.randint(0, 25)
	return (x, y)

def run_one_episode(qsa_grid, learning_rate, epsilon, episode_length):
	discount_factor = 0.99
	x, y = get_start_state()
	reward_per_episode = 0
	for ep_len in range(episode_length):
		xf, yf, r, action = get_next_state(qsa_grid, x, y, epsilon)
		qsa_grid[x][y][action] += learning_rate*(r + discount_factor*np.max(qsa_grid[xf][yf]) - qsa_grid[x][y][action])
		reward_per_episode += r
		x, y = xf, yf
		if is_goal(xf, yf):
			break
	return qsa_grid, reward_per_episode

def q_learning(learning_rate, epsilon, episodes = 4000, episode_length = 1000):
	qsa_grid = initialise_qsa_grid()
	reward_per_episode = []
	for eps in range(episodes):
		qsa_grid, r = run_one_episode(qsa_grid, learning_rate, epsilon, episode_length)
		reward_per_episode.append(r)

	val_grid = np.zeros((50, 25))
	action_grid = np.zeros((50, 25))
	for x in range(qsa_grid.shape[0]):
		for y in range(qsa_grid.shape[1]):
			if is_wall(x, y) or is_goal(x, y):
				action_grid[x][y] = -1
			else:
				action_grid[x][y] = np.argmax(qsa_grid[x][y])
				val_grid[x][y] = np.max(qsa_grid[x][y])
	return (val_grid, action_grid, reward_per_episode)

def show_heatmap(arr):
	ax = sns.heatmap(arr.T, cmap='gray', linewidth=0.1)
	ax.invert_yaxis()
	ax.add_patch(Rectangle((48, 12), 1, 1, fill=False, edgecolor='red', lw=2))
	ax.add_patch(Rectangle((0, 0), 1, 25))
	ax.add_patch(Rectangle((0, 24), 50, 1))
	ax.add_patch(Rectangle((49, 0), 1, 25))
	ax.add_patch(Rectangle((0, 0), 50, 1))
	ax.add_patch(Rectangle((25, 0), 2, 12))
	ax.add_patch(Rectangle((25, 13), 2, 12))
	plt.show()

def plot_reward(r):
	y = [i for i in range(len(r))]
	plt.plot(y, r)
	plt.ylabel('Reward')
	plt.xlabel('Episodes')
	plt.show()

def plot_reward_avg(r):
	r = [np.sum(r[10*i:10*(i+1)])/10 for i in range(len(r)//10)]
	y = [10*i for i in range(len(r))]
	plt.plot(y, r)
	plt.ylabel('Reward')
	plt.xlabel('Episodes')
	plt.show()

def action_indicator_diag(arr):
	x = np.arange(0.5, 50.5, 1)
	y = np.arange(0.5, 25.5, 1)

	X, Y = np.meshgrid(x, y)
	u = np.zeros((25, 50))
	v = np.zeros((25, 50))

	for i in range(50):
		for j in range(25):
			if (arr[i][j] == 0):
				v[j][i] = 1
			elif (arr[i][j] == 1):
				u[j][i] = 1
			elif (arr[i][j] == 2):
				v[j][i] = -1
			else:
				u[j][i] = -1

	# creating plot
	# fig, ax = plt.subplots(figsize =fsize)
	fig, ax = plt.subplots()
	ax.quiver(X, Y, u, v, angles='xy', pivot='mid')

	major_ticks_x = np.arange(0, 50, 1)
	#minor_ticks_x = np.arange(0, 49, 1)
	major_ticks_y = np.arange(0, 25, 1)
	#minor_ticks_y = np.arange(0, 24, 1)

	ax.axis([0, 50, 0, 25])
	ax.set_xticks(major_ticks_x)
	ax.set_yticks(major_ticks_y)
	ax.add_patch(Rectangle((0, 0), 1, 25))
	ax.add_patch(Rectangle((0, 24), 50, 1))
	ax.add_patch(Rectangle((49, 0), 1, 25))
	ax.add_patch(Rectangle((0, 0), 50, 1))
	ax.add_patch(Rectangle((25, 0), 2, 12))
	ax.add_patch(Rectangle((25, 13), 2, 12))
	ax.add_patch(Rectangle((48, 12), 1, 1, color = 'red', alpha = 0.3))

	ax.grid(True)
	plt.minorticks_on
	ax.set_axisbelow(True)

	plt.show()

def part_b():
	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.05)
	show_heatmap(val_grid)
	action_indicator_diag(action_grid)

def part_c():
	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.005)
	show_heatmap(val_grid)
	action_indicator_diag(action_grid)

	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.05)
	show_heatmap(val_grid)
	action_indicator_diag(action_grid)

	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.5)
	show_heatmap(val_grid)
	action_indicator_diag(action_grid)

def part_d():
	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.05)
	plot_reward(reward_per_episode)
	plot_reward_avg(reward_per_episode)

	np.random.seed(1)
	val_grid, action_grid, reward_per_episode = q_learning(0.25, 0.5)
	plot_reward(reward_per_episode)
	plot_reward_avg(reward_per_episode)

part_b()
part_c()
part_d()


quantity = int(input())

for i in range (quantity):
	numero1, numero2 = [i for i in input().split()]
	vetor1 = list(numero1)
	vetor2 = list(numero2)
	vetor1.reverse()
	vetor2.reverse()
	encaixa = True
	if len(vetor1)>= len(vetor2) :
		for j in range(len(vetor2)):
			if vetor2[j] != vetor1[j]:
				encaixa = False
	else:
		encaixa = False
	if encaixa :
		print("encaixa")
	else:
		print("nao encaixa")


#!/usr/bin/env python
import rospy
import roslib
roslib.load_manifest('rospytro')
import pytro.ltraj
import numpy as np

class PathSolver:

  def __init__(self):
    rospy.init_node('traj_test', anonymous=True)
    A = np.eye(2)
    B = np.eye(2)
    self.lt = pytro.ltraj.LTraj2DAvoid(A,B,5)
    self.lt.setInitialState([2.0,3.0])
    self.lt.setTerminalState([8.0,4.0])
    self.lt.add2NormStageCost(np.zeros((2,2)),np.eye(2),Nc=11)
    self.lt.addStatic2DObst(2.5,3.5,1.5,4.5)
    self.lt.addStatic2DObst(5.5,6.5,3.5,7.5)
    # or solve by PuLP default built-in solver
    self.lt.solveByBranchBound()
    self.lt.plotTraj2D()

if __name__=="__main__":
    lt = PathSolver()


import glob
import re
import jieba
from collections import defaultdict

jieba.enable_paddle()
jieba.initialize()

def convert_to_halfwidth(line):
    line = line.translate(str.maketrans("".join([chr(i) for i in range(ord('！'), ord('～') + 1)]), "".join([chr(i) for i in range(ord('!'), ord('~') + 1)]))).strip()
    line = line.translate(str.maketrans("《》、。“”", "(),.\"\"")).strip()
    return line

ch_radio_fnames = glob.glob("../datasets/man_ch_news_txt/ch_radio/cr??????", recursive=True)
p_daily_fnames = glob.glob("../datasets/man_ch_news_txt/p_daily/pd????", recursive=True)
xinhua_fnames = glob.glob("../datasets/man_ch_news_txt/xinhua/xh????_?", recursive=True)

with open("../extracted/raw_ch_radio_sents.txt", "w") as ch_radio_sents_f:
    for ch_radio_fname in ch_radio_fnames:
        with open(ch_radio_fname, encoding='gb18030') as ch_radio_f:
            while True:
                line = ch_radio_f.readline()
                if len(line) == 0:
                    break
                if line[:4] == "<HL>" and line[-5:] == "</HL>":
                    line = line[4:-5]
                    line = convert_to_halfwidth(line.strip())
                    line = " ".join(jieba.cut(line, use_paddle=True))
                    ch_radio_sents_f.write(line + '\n')
                    # tokens = jieba.cut(line[4:-5], use_paddle=True)
                    # for token in tokens:
                    #     w2i[token] += 1
                elif line.strip() == "<TEXT>":
                    sents = []
                    while True:
                        line = ch_radio_f.readline().strip()
                        if line.strip() == "</TEXT>":
                            break
                        if line != "<p>":
                            print("unexpected line that is not <p>")
                            print(line)
                            input("Press enter")
                        line = ch_radio_f.readline().strip()
                        for line_1 in re.split(r'[!?.]', line):
                            line_1 = convert_to_halfwidth(line_1.strip())
                            sents.append(line_1)

                    sents.pop()
                    for sent in sents:
                        sent = sent.translate(str.maketrans('', '', '#"\'%-`~()[]<>.,·¡™=§*?_/\\@&—;:'))
                        sent = " ".join(jieba.cut(sent, use_paddle=True))
                        if len(sent.strip()) == 0:
                            continue
                        ch_radio_sents_f.write(sent + '\n')
        print(f'Done with {ch_radio_fname}')

with open("../extracted/raw_p_daily_sents.txt", "w") as p_daily_sents_f:
    for p_daily_fname in p_daily_fnames:
        print(p_daily_fname)
        with open(p_daily_fname, encoding='gb18030') as p_daily_f:
            while True:
                line = p_daily_f.readline()
                if len(line) == 0:
                    break
                if line[:4] == "<HL>" and line[-5:] == "</HL>":
                    line = line[4:-5]
                elif line[0] == '<':
                    continue
                for line_1 in re.split(r'[.!?]', line):
                    line_1 = convert_to_halfwidth(line_1.strip())
                    line_1 = line_1.translate(str.maketrans('', '', '#"\'%-`~()[]<>.,·¡™=§*?_/\\@&—;:'))
                    if len(line_1.strip()) == 0:
                        continue
                    line_1 = " ".join(jieba.cut(line_1, use_paddle=True))
                    if len(line_1.strip()) == 0:
                        continue
                    p_daily_sents_f.write(line_1 + '\n')
        print(f'Done with {p_daily_fname}')

with open("../extracted/raw_xinhua_sents.txt", "w") as xinhua_sents_f:
    for xinhua_fname in xinhua_fnames:
        with open(xinhua_fname, encoding='gb18030') as xinhua_f:
            while True:
                line = xinhua_f.readline()
                if len(line) == 0:
                    break
                line = convert_to_halfwidth(line.strip())
                if line[:10] == "<headline>" and line[-11:] == "</headline>":
                    line = convert_to_halfwidth(line[10:-11].strip())
                elif line[:3] == "<s>" and line[-4:] == "</s>":
                    line = convert_to_halfwidth(line[3:-4].strip())
                else:
                    continue
                for line_1 in re.split(r'[.!?]', line):
                    line_1 = convert_to_halfwidth(line_1.strip())
                    if len(line_1.strip()) == 0:
                        continue
                    line_1 = line_1.translate(str.maketrans('', '', '#"\'%-`~()[]<>.,·¡™=§*?_/\\@&—;:'))
                    line_1 = " ".join(jieba.cut(line_1, use_paddle=True))
                    if line_1 == "完":
                        continue
                    if len(line_1.strip()) == 0:
                        continue
                    xinhua_sents_f.write(line_1 + '\n')
        print(f'Done with {xinhua_fname}')


#
# @lc app=leetcode id=367 lang=python3
#
# [367] Valid Perfect Square
#

# @lc code=start
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        l = 1
        r = 1<<31
        while(l <= r):
            m = (l+r)//2
            msq = m*m
            if( msq< num):
                l = m + 1
            elif (msq == num):
                return True
            else:
                r = m - 1
        return False

# @lc code=end


import tkinter as tk
import tkinter.font as tkFont
from time import strftime
import datetime as dd

class App:
    def __init__(self, root):
        #setting title
        root.title("clock")
        #setting window size
        width=1000
        height=580
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
        root.geometry(alignstr)
        root.resizable(width=False, height=False)

        def time():
            string = strftime('%H:%M:%S %p')
            lbl.config(text=string)
            lbl.after(1000, time)

        date = dd.datetime.now()

        GLabel_70=tk.Label(root)
        GLabel_70["activeforeground"] = "#542121"
        #GLabel_70["anchor"] = "nw"
        ft = tkFont.Font(family='Times',size=15)
        GLabel_70["font"] = ft
        GLabel_70["fg"] = "#333333"
        GLabel_70["justify"] = "center"
        GLabel_70["text"] = "Current Time and Date"
        GLabel_70.place(x=80,y=20)

        lbl = tk.Label(root, font=('calibri', 40, 'bold'),background='purple',foreground='white')

        lbl.place(x=80,y=60)
        time()
        lbl1 = tk.Label(root, text=f"{date:%A, %B %d, %Y}",font=('calibri', 20, 'bold'),background='black',foreground='white')

        lbl1.place(x=80,y=120)

        GLabel_70=tk.Label(root)
        GLabel_70["activeforeground"] = "#542121"
        #GLabel_70["anchor"] = "nw"
        ft = tkFont.Font(family='Times',size=15)
        GLabel_70["font"] = ft
        GLabel_70["fg"] = "#333333"
        GLabel_70["justify"] = "center"
        GLabel_70["text"] = "Previos Date"
        GLabel_70.place(x=80,y=180)

        GLabel_70=tk.Label(root)
        GLabel_70["activeforeground"] = "#542121"
        #GLabel_70["anchor"] = "nw"
        ft = tkFont.Font(family='Times',size=15)
        GLabel_70["font"] = ft
        GLabel_70["fg"] = "#333333"
        GLabel_70["justify"] = "center"
        GLabel_70["text"] = "Office Opening Time"
        GLabel_70.place(x=700,y=20)

        lbl2 = tk.Label(root, text="09:15 AM",font=('calibri', 20, 'bold'),background='black',foreground='white')

        lbl2.place(x=700,y=80)

        GLabel_70=tk.Label(root)
        GLabel_70["activeforeground"] = "#542121"
        #GLabel_70["anchor"] = "nw"
        ft = tkFont.Font(family='Times',size=15)
        GLabel_70["font"] = ft
        GLabel_70["fg"] = "#333333"
        GLabel_70["justify"] = "center"
        GLabel_70["text"] = "Office Closing Time"
        GLabel_70.place(x=700,y=150)

        lbl3 = tk.Label(root, text="15:30 PM",font=('calibri', 20, 'bold'),background='black',foreground='white')

        lbl3.place(x=700,y=210)

        GButton_235=tk.Button(root)
        GButton_235["bg"] = "red"
        ft = tkFont.Font(family='Times',size=10)
        GButton_235["font"] = ft
        GButton_235["fg"] = "#000000"
        GButton_235["justify"] = "center"
        GButton_235["text"] = "Quit"
        GButton_235.place(x=80,y=550,width=70,height=25)
        GButton_235["command"] = self.GButton_235_command

        GButton_125=tk.Button(root)
        GButton_125["bg"] = "Green"
        ft = tkFont.Font(family='Times',size=10)
        GButton_125["font"] = ft
        GButton_125["fg"] = "#000000"
        GButton_125["justify"] = "center"
        GButton_125["text"] = "Last Date"
        GButton_125.place(x=700,y=550,width=70,height=25)
        GButton_125["command"] = self.GButton_125_command

        #root.Listbox = Listbox(width=50, height=10, highlightthickness=0, font=('Andalus', 12, 'bold'),
        #                     selectmode=SINGLE, bg='#044f19', fg='#65eb8a', selectbackground='#aed6b9',
         #                    selectforeground='#68786d', selectborderwidth=3, activestyle=NONE)
        #root.Listbox.place(x=460,y=450,width=111,height=30)
        #root.Listbox.grid(row=0, column=1, padx=(20, 0), pady=(20, 0), sticky="nsew")

    def GButton_235_command(self):
        quit()

    def GButton_125_command(self):
        date = dd.datetime.now()
        import datetime as dt
        date = dt.datetime.now()
        a=f"{date:%A, %B %d, %Y}"
        print(a)
        print(date)
        Previous_Date = date - dt.timedelta(days=1)
        print (Previous_Date)

        lbl4 = tk.Label(root, text=Previous_Date,font=('calibri', 20, 'bold'),background='black',foreground='white')

        lbl4.place(x=80,y=210)

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()


#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=C0301,C0103,R0914,R0903

"""
WMArchive command line tool
"""
from __future__ import print_function
__author__ = "Valentin Kuznetsov"

# system modules
import os
import sys
import pwd
if  sys.version_info < (2, 6):
    raise Exception("WMArchive requires python 2.6 or greater")

WMArchive_CLIENT = 'wma-client/1.1::python/%s.%s' % sys.version_info[:2]

import re
import time
import json
import urllib
import urllib2
import httplib
import cookielib
from   optparse import OptionParser

# define exit codes according to Linux sysexists.h
EX_OK           = 0  # successful termination
EX__BASE        = 64 # base value for error messages
EX_USAGE        = 64 # command line usage error
EX_DATAERR      = 65 # data format error
EX_NOINPUT      = 66 # cannot open input
EX_NOUSER       = 67 # addressee unknown
EX_NOHOST       = 68 # host name unknown
EX_UNAVAILABLE  = 69 # service unavailable
EX_SOFTWARE     = 70 # internal software error
EX_OSERR        = 71 # system error (e.g., can't fork)
EX_OSFILE       = 72 # critical OS file missing
EX_CANTCREAT    = 73 # can't create (user) output file
EX_IOERR        = 74 # input/output error
EX_TEMPFAIL     = 75 # temp failure; user is invited to retry
EX_PROTOCOL     = 76 # remote error in protocol
EX_NOPERM       = 77 # permission denied
EX_CONFIG       = 78 # configuration error

class HTTPSClientAuthHandler(urllib2.HTTPSHandler):
    """
    Simple HTTPS client authentication class based on provided
    key/ca information
    """
    def __init__(self, key=None, cert=None, level=0):
        if  level > 1:
            urllib2.HTTPSHandler.__init__(self, debuglevel=1)
        else:
            urllib2.HTTPSHandler.__init__(self)
        self.key = key
        self.cert = cert

    def https_open(self, req):
        """Open request method"""
        #Rather than pass in a reference to a connection class, we pass in
        # a reference to a function which, for all intents and purposes,
        # will behave as a constructor
        return self.do_open(self.get_connection, req)

    def get_connection(self, host, timeout=300):
        """Connection method"""
        if  self.key:
            return httplib.HTTPSConnection(host, key_file=self.key,
                                                cert_file=self.cert)
        return httplib.HTTPSConnection(host)

def x509():
    "Helper function to get x509 either from env or tmp file"
    proxy = os.environ.get('X509_USER_PROXY', '')
    if  not proxy:
        proxy = '/tmp/x509up_u%s' % pwd.getpwuid( os.getuid() ).pw_uid
        if  not os.path.isfile(proxy):
            return ''
    return proxy

def check_glidein():
    "Check glideine environment and exit if it is set"
    glidein = os.environ.get('GLIDEIN_CMSSite', '')
    if  glidein:
        msg = "ERROR: das_client is running from GLIDEIN environment, it is prohibited"
        print(msg)
        sys.exit(EX__BASE)

def check_auth(key):
    "Check if user runs das_client with key/cert and warn users to switch"
    if  not key:
        msg  = "WARNING: das_client is running without user credentials/X509 proxy, create proxy via 'voms-proxy-init -voms cms -rfc'"
        print(msg, file=sys.stderr)

def fullpath(path):
    "Expand path to full path"
    if  path and path[0] == '~':
        path = path.replace('~', '')
        path = path[1:] if path[0] == '/' else path
        path = os.path.join(os.environ['HOME'], path)
    return path

class WMArchiveOptionParser:
    """
    WMArchive cache client option parser
    """
    def __init__(self):
        usage  = "Usage: %prog [options]\n"
        usage += "For more help please visit https://github.com/dmwm/WMArchive/wiki"
        self.parser = OptionParser(usage=usage)
        self.parser.add_option("--verbose", action="store", type="int",
            default=0, dest="verbose", help="verbosity level")
        self.parser.add_option("--spec", action="store", type="string",
            default="query.json", dest="spec",
            help="specify query spec file, defalt query.json")
        host = 'https://vocms013.cern.ch'
        msg  = "host name of WMArchive server, default is %s" % host
        self.parser.add_option("--host", action="store", type="string",
                       default=host, dest="host", help=msg)
        msg  = 'specify private key file name, default $X509_USER_PROXY'
        self.parser.add_option("--key", action="store", type="string",
                               default=x509(), dest="ckey", help=msg)
        msg  = 'specify private certificate file name, default $X509_USER_PROXY'
        self.parser.add_option("--cert", action="store", type="string",
                               default=x509(), dest="cert", help=msg)
    def get_opt(self):
        """
        Returns parse list of options
        """
        return self.parser.parse_args()

def get_data(host, spec_file, ckey, cert, verbose=0):
    """Contact WMArchive server and retrieve data for given spec"""
    try:
        query = json.load(open(spec_file))
    except Exception as exp:
        msg = 'Unable to open spec JSON file'
        print(msg)
        print(str(exp))
        sys.exit(EX_DATAERR)
    if  'spec' not in query or 'fields' not in query:
        print('The input query JSON file must contain a "spec" and "fields"')
        print('The "spec" represents a dict of conditions or list of wmaids')
        print('    Examples: "spec":{"lfn":"bla.root", "timerange":[YYYYMMDD,YYYYMMDD]}')
        print('              "spec":[wmaid1, wmaid2]')
        print('The "fields" provides list of keys to look-up')
        print('    Examples: "fields":["wmaid", "lfn"]')
        sys.exit(EX_NOINPUT)
    path = '/wmarchive/data'
    pat  = re.compile('http[s]{0,1}://')
    if  not pat.match(host):
        msg = 'Invalid hostname: %s' % host
        print(msg)
        sys.exit(EX_UNAVAILABLE)
    url = host + path
    data = json.dumps(query)
    client = '%s (%s)' % (WMArchive_CLIENT, os.environ.get('USER', ''))
    headers = {"Accept": "application/json", "User-Agent": client, "Content-type":"application/json"}
    req  = urllib2.Request(url=url, data=data, headers=headers)
    ckey = fullpath(ckey)
    cert = fullpath(cert)
    http_hdlr  = HTTPSClientAuthHandler(ckey, cert, verbose)
    proxy_handler  = urllib2.ProxyHandler({})
    cookie_jar     = cookielib.CookieJar()
    cookie_handler = urllib2.HTTPCookieProcessor(cookie_jar)
    opener = urllib2.build_opener(http_hdlr, proxy_handler, cookie_handler)
    fdesc = opener.open(req)
    response = json.load(fdesc)
    fdesc.close()
    return response

def main():
    """Main function"""
    optmgr  = WMArchiveOptionParser()
    opts, _ = optmgr.get_opt()
    data = get_data(opts.host, opts.spec, opts.ckey, opts.cert, opts.verbose)
    print(json.dumps(data))

#
# main
#
if __name__ == '__main__':
    main()


from typing import Union, List

from simpleperf_utils import AdbHelper

def get_logcat_for_aut(aut: str, adb: AdbHelper) -> Union[str, None]:
    status, pid = adb.run_and_return_output(['shell', 'pidof', aut])
    if not status:
        print("failed to get pid")
        return None
    print(pid)
    status, logcat_str = adb.run_and_return_output(
        ['shell', 'logcat', '-d', '--pid=' + str(pid)], True, True)
    if not status:
        print("something went wrong with logcat!")
        return None
    return logcat_str

def filter_logcat_str_for_tags(logcat: List[str], tags: Union[str, List[str]]) -> List[str]:
    if isinstance(tags, str):
        def filter_fun(line):
            return tags in line
    elif isinstance(tags, List):
        def filter_fun(line):
            return any(tag in line for tag in tags)
    else:
        raise TypeError(f'Unknown type for tags: {type(tags)}')

    return list(filter(filter_fun, logcat))

def split_logcat(logcat: str, latest_first: bool = True) -> List[str]:
    log_list = logcat.split('\n')
    if latest_first:
        log_list.reverse()
    return log_list