from datetime import datetime, timedelta
import json
import threading
import logging
from enum import Enum
from const import CONST
from main import send_post
import pykka
import ledPWM

'''
on: time_h=19 photoresistor=50
time_h=18 photoresistor=20 -> nothing
time_h=20 photoresistor=60 -> nothing
time_h=21 photoresistor=40 -> switch on
time_h=3 photoresistor=60 -> ???

off: time_h=6 photoresistor=70
time_h=4 photoresistor=60 -> nothing
time_h=5 photoresistor=75 -> switch off
or
time_h=6 photoresistor=60 -> switch off
'''
# no need for a lock because everything here is single thread

logger = logging.getLogger(__name__)
action = Enum('action', 'turn_on turn_off energy_saving car_detected')
error = Enum('error', 'generic')
C = CONST()

class Lamp(pykka.ThreadingActor):
    def __init__(self, lamp_id, lamp_number, pin, area, pr_proxy, us_proxy_1, us_proxy_2, lamp_policy_on=None,
                 lamp_policy_off=None, lamp_energy=None):
        super(Lamp, self).__init__()
        self.lamp_id = lamp_id
        self.lamp_number = lamp_number
        self.pin = pin
        self.area = area
        self.pr_proxy = pr_proxy
        self.us_proxy_1 = us_proxy_1
        self.us_proxy_2 = us_proxy_2
        self.lamp_policy_on = lamp_policy_on
        self.lamp_policy_off = lamp_policy_off
        self.lamp_energy = lamp_energy
        self.timer_on = threading.Timer(0, None)
        self.timer_energy_on_1 = threading.Timer(0, None)
        self.timer_energy_on_2 = threading.Timer(0, None)
        self.start_energy = threading.Timer(0, None)
        self.timer_energy_timeout = threading.Timer(0, None)
        self.my_proxy = None
        self.start_time_on = None
        self.start_time_energy_on = None
        self.timeout_on_off = 0
        self.timeout_energy = 0
        self.on = False
        self.debug = False
        self.old_intensity = 0
        ledPWM.set_led_intensity(self.pin, 0)
        self.update_schedules()

    def set_self_proxy(self, lamp_proxy):
        self.my_proxy = lamp_proxy

    def update_schedules(self):
        self.timeout_on_off = self.get_delta(self.lamp_policy_on.time_h, self.lamp_policy_on.time_m, 0,
                                             self.lamp_policy_off.time_h, self.lamp_policy_off.time_m, 0)
        self.timeout_energy = self.get_delta(self.lamp_energy.time_h_on, self.lamp_energy.time_m_on, 0,
                                             self.lamp_energy.time_h_off, self.lamp_energy.time_m_off, 0)

    def start_schedule_on(self):
        wait_t = self.get_wait(self.lamp_policy_on.time_h, self.lamp_policy_on.time_m, 0,
                               self.lamp_policy_off.time_h, self.lamp_policy_off.time_m, 0)
        logger.debug("wait = {0}".format(wait_t))
        self.timer_on.cancel()
        self.timer_on = threading.Timer(wait_t, self.pr_proxy.add_actor, [self.my_proxy])
        self.timer_on.start()
        self.start_time_on = datetime.today() + timedelta(seconds=wait_t)

    def start_schedule_energy_on(self):
        wait_t = self.get_wait(self.lamp_energy.time_h_on, self.lamp_energy.time_m_on, 0,
                               self.lamp_energy.time_h_off, self.lamp_energy.time_m_off, 0)
        self.timer_energy_on_1.cancel()
        self.timer_energy_on_1 = threading.Timer(wait_t, self.us_proxy_1.add_actor, [self.my_proxy])
        self.timer_energy_on_1.start()
        self.timer_energy_on_2.cancel()
        self.timer_energy_on_2 = threading.Timer(wait_t, self.us_proxy_2.add_actor, [self.my_proxy])
        self.timer_energy_on_2.start()
        self.start_energy.cancel()
        self.start_energy = threading.Timer(wait_t, self.set_to_energy)
        self.start_energy.start()
        self.start_time_energy_on = datetime.today() + timedelta(seconds=wait_t)

    def update_light(self, current_photoresistor):
        if not self.debug:
            url = C.SERVER_URL + C.CHANGE_LIGHT
            if self.is_in_schedule():
                if self.on and current_photoresistor > self.lamp_policy_off.photoresistor:
                    self.timer_energy_timeout.cancel()
                    ledPWM.set_led_intensity(self.pin, 0)
                    logger.info("lamp off")
                    self.on = False
                    post_fields = self.create_post_fields(action.turn_off.value, 0, current_photoresistor)
                    send_post(url, post_fields)
                elif not self.on and current_photoresistor < self.lamp_policy_on.photoresistor:
                    if self.is_energy_saving_time():
                        ledPWM.set_led_intensity(self.pin, self.lamp_energy.intensity)
                        logger.info("lamp energy")
                        self.on = True
                        post_fields = self.create_post_fields(action.energy_saving.value, self.lamp_energy.intensity,
                                                              current_photoresistor)
                        send_post(url, post_fields)
                    else:
                        ledPWM.set_led_intensity(self.pin, self.lamp_policy_on.intensity)
                        logger.info("lamp on")
                        self.on = True
                        post_fields = self.create_post_fields(action.turn_on.value, self.lamp_policy_on.intensity,
                                                              current_photoresistor)
                        send_post(url, post_fields)
            else:
                logger.info("schedule is over, see you tomorrow")
                ledPWM.set_led_intensity(self.pin, 0)
                logger.info("lamp off")
                self.on = False
                self.pr_proxy.remove_actor(self.my_proxy)
                post_fields = self.create_post_fields(action.turn_off.value, 0, current_photoresistor)
                send_post(url, post_fields)
                self.start_schedule_on()

    def ultrasonic_notify(self, us_timeout, wait_time, right_lane, notified=False):
        logger.info("[{0}]Received an ultrasonic notify".format(self.lamp_id))
        if not self.debug:
            if self.is_in_schedule() and self.is_energy_saving_time():
                if self.on:
                    # If the lamp is off because of the photoresistor, even if there is a car the lamp stay off
                    self.timer_energy_timeout.cancel()
                    if right_lane:
                        position = self.lamp_id
                    else:
                        position = self.lamp_number - self.lamp_id
                    # If this is the last lamp and we were not notified, we notify the nearest rpi
                    if position == self.lamp_number and not notified:
                        from main import notify_nearby
                        threading.Timer(wait_time * position, notify_nearby, [right_lane]).start()
                    threading.Timer(wait_time * position, self.car_detected).start()
                    logger.info("[{0}]There is a car! Lamp full power".format(self.lamp_id))
                    self.timer_energy_timeout.cancel()
                    self.timer_energy_timeout = threading.Timer(us_timeout + wait_time * position, self.set_to_energy)
                    self.timer_energy_timeout.start()
            else:
                self.timer_energy_timeout.cancel()
                logger.info("schedule is over, see you tomorrow")
                self.us_proxy_1.remove_actor(self.my_proxy)
                self.us_proxy_2.remove_actor(self.my_proxy)
                self.start_schedule_energy_on()

    def force_on(self, new_intensity):
        if not self.debug:
            self.debug = True
            self.old_intensity = ledPWM.get_led_intensity(self.pin)
        ledPWM.set_led_intensity(self.pin, new_intensity)

    def force_off(self):
        if not self.debug:
            self.debug = True
            self.old_intensity = ledPWM.get_led_intensity(self.pin)
        ledPWM.set_led_intensity(self.pin, 0)

    def stop_debug(self):
        if self.debug:
            self.debug = False
            ledPWM.set_led_intensity(self.pin, self.old_intensity)

    def car_detected(self):
        ledPWM.set_led_intensity(self.pin, self.lamp_policy_on.intensity)
        logger.info("{0} Car detected".format(ledPWM.get_led_intensity(self.pin)))
        url = C.SERVER_URL + C.CHANGE_LIGHT
        post_fields = self.create_post_fields(action.car_detected.value, self.lamp_policy_on.intensity)
        send_post(url, post_fields)

    def set_to_energy(self):
        ledPWM.set_led_intensity(self.pin, self.lamp_energy.intensity)
        logger.info("{0} Set to energy".format(ledPWM.get_led_intensity(self.pin)))
        url = C.SERVER_URL + C.CHANGE_LIGHT
        post_fields = self.create_post_fields(action.energy_saving.value, self.lamp_energy.intensity)
        send_post(url, post_fields)

    def create_post_fields(self, this_action, intensity, photoresistor=-1, timestamp=0):
        return {'area': self.area, 'action': this_action, 'intensity': intensity, 'photoresistor': photoresistor,
                'timestamp': timestamp}

    def to_json(self):
        return json.dumps([self.lamp_id, self.lamp_policy_on, self.lamp_policy_off, self.lamp_energy],
                          default=lambda o: o.__dict__, indent=4)

    @staticmethod
    def get_delta(start_h, start_m, start_s, end_h, end_m, end_s):
        today = datetime.today()
        start = today.replace(hour=start_h, minute=start_m, second=start_s)
        end = today.replace(hour=end_h, minute=end_m, second=end_s)
        if (end - start).total_seconds() < 1:
            end = end + timedelta(days=1)
        return (end - start).total_seconds()

    @staticmethod
    def get_wait(start_h, start_m, start_s, end_h, end_m, end_s):
        today = datetime.today()
        start = today.replace(hour=start_h, minute=start_m, second=start_s)
        end = today.replace(hour=end_h, minute=end_m, second=end_s)
        if (end - start).total_seconds() < 1:
            end = end + timedelta(days=1)
        if (end - start).total_seconds() > 24*60*60:
            start = start + timedelta(days=1)
        if (today - end).total_seconds() > 1:
            start = start + timedelta(days=1)
        tomorrow = today + timedelta(days=1)
        if (start - tomorrow).total_seconds() < 1 < (end - tomorrow).total_seconds():
            today = today + timedelta(days=1)
        return (start - today).total_seconds()

    def is_in_schedule(self):
        now = datetime.today()
        logger.info("now = {0}".format(now))
        logger.info("start time = {0}".format(self.start_time_on))
        elapsed = (now - self.start_time_on).total_seconds()
        logger.info("elapsed {0} seconds, timeout is {1}".format(elapsed, self.timeout_on_off))
        return elapsed < self.timeout_on_off

    def is_energy_saving_time(self):
        now = datetime.today()
        elapsed = (now - self.start_time_energy_on).total_seconds()
        logger.debug("Are we in energy saving? " + str(0 < elapsed < self.timeout_energy))
        return 0 < elapsed < self.timeout_energy


import torch
import numpy as np
from torch.utils.data import DataLoader
import pandas as pd
from sklearn.model_selection import train_test_split
from keras.datasets import mnist
from torch.autograd import Variable
import matplotlib.pyplot as plt
import torch.nn as nn
import warnings
warnings.filterwarnings("ignore")

(x_train,y_train),(x_test,y_test)=mnist.load_data()
print(y_test.shape)
x_train=x_train/255
x_test=x_test/255
x_train=np.array(x_train,dtype='f')
x_test=np.array(x_test,dtype='f')

featureTrain=torch.from_numpy(x_train)
targetTrain=torch.from_numpy(y_train).type(torch.LongTensor)

featureTest=torch.from_numpy(x_test)
targetTest=torch.from_numpy(y_test).type(torch.LongTensor)

#hyperparameters
batch_size=100
n_iters=18000 #(60.000 input // batch_size)*numberofepochs(30)
epochs=n_iters/(len(featureTrain)/batch_size)
epochs=int(epochs)

train=torch.utils.data.TensorDataset(featureTrain,targetTrain)
test=torch.utils.data.TensorDataset(featureTest,targetTest)

train_loader=DataLoader(train,batch_size=batch_size,shuffle=False)
test_loader=DataLoader(test,batch_size=batch_size,shuffle=False)

class CNNModel(nn.Module):
    def __init__(self):
        super(CNNModel, self).__init__()
        #Convolutional layer1
        self.cnn1=nn.Conv2d(in_channels=1,out_channels=16,kernel_size=5,stride=1,padding=0)
        self.relu1=nn.ReLU()
        #maxpooling
        self.maxpool1=nn.MaxPool2d(kernel_size=2)

        #Convolutional layer1
        self.cnn2=nn.Conv2d(in_channels=16,out_channels=32,kernel_size=5,stride=1,padding=0)
        self.relu2=nn.ReLU()
        #maxpooling
        self.maxpool2=nn.MaxPool2d(kernel_size=2)

        #fully connected
        self.fc1=nn.Linear(32*4*4,10)
    def forward(self,x):
        #conv1
        out=self.cnn1(x)
        out=self.relu1(out)
        out=self.maxpool1(out)

        #conv2
        #conv1
        out=self.cnn2(out)
        out=self.relu2(out)
        out=self.maxpool2(out)

        #flatten
        out=out.view(out.size(0),-1)

        out=self.fc1(out)

        return out

model=CNNModel()

#crossentropyloss
error=nn.CrossEntropyLoss()

#SGD optimizer
lr=0.02
optimizer=torch.optim.SGD(model.parameters(),lr=lr)

#CNN model training
count=0
loss_list=[]
iteration_list=[]
accuracy_list=[]
for epoch in range(epochs):
    for i, (images,labels) in enumerate(train_loader):
        train=Variable(images.view(100,1,28,28))
        labels=Variable(labels)

        optimizer.zero_grad()

        outputs=model(train)

        loss=error(outputs,labels)

        loss.backward()

        optimizer.step()

        count+=1

        if count%10==0:
             #accuracy
            correct=0
            total=0

            for images,labels in test_loader:
                test=Variable(images.view(100,1,28,28))

                outputs=model(test)
                predicted=torch.max(outputs.data,1)[1]

                total+=len(labels)
                correct+=(predicted==labels).sum()

            accuracy=100*correct/float(total)

            loss_list.append(loss.data)
            iteration_list.append(count)
            accuracy_list.append(accuracy)
        if count%10==0:
            print("iteration: {} Loss: {} Accuracy: {}%".format(count,loss.data,accuracy))

plt.figure(figsize=(25,25))
plt.plot(loss_list,c="orange")
plt.xlabel("Steps",fontsize=25)
plt.ylabel("Loss",fontsize=25)
plt.show()


class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        if len(s2) < len(s1) : return False

        left = 0
        s1Counter = defaultdict(int)
        s2Counter = defaultdict(int)

        for i in range(len(s1)):
            s1Counter[s1[i]] += 1
            s2Counter[s2[i]] += 1

        if s1Counter == s2Counter: return True

        for r in range(len(s1), len(s2)):
            s2Counter[s2[r]] += 1
            s2Counter[s2[left]] -= 1

            if s2Counter[s2[left]] == 0:
                del s2Counter[s2[left]]

            left += 1

            if s2Counter == s1Counter:
                return True

        return False


from sklearn import preprocessing
import pickle
import joblib
import nltk
import pandas as pd
from flask import Flask,request
"""
string = "infection including flu pneumonia immunization diphtheria tetanus child teething \
    infant inflammatory disease including rheumatoid arthritis ra crohn disease blood \
        clot extreme sunburn food poisoning medication including antibiotic"
        """

label_encoder = preprocessing.LabelEncoder()
stopword = nltk.corpus.stopwords.words('english')

def clean(text):
    wn = nltk.WordNetLemmatizer()
    tokens = nltk.word_tokenize(text)
    lower = [word.lower() for word in tokens]
    no_stopwords = [word for word in lower if word not in stopword]
    no_alpha = [word for word in no_stopwords if word.isalpha()]
    lemm_text = [wn.lemmatize(word) for word in no_alpha]
    return lemm_text

def vectorize(data, tfidf_vect_fit):
    X_tfidf = tfidf_vect_fit.transform(data)
    words = tfidf_vect_fit.get_feature_names()
    X_tfidf_df = pd.DataFrame(X_tfidf.toarray())
    X_tfidf_df.columns = words
    return(X_tfidf_df)

def predictions(string):

    strngs = clean(string)
    x_string = ""

    for stng in strngs:
        x_string = x_string+" "+stng

    with open('vector.pkl', 'rb') as vector:
        model_vector = pickle.load(vector)
        vector.close()

    with open('model.pickle', 'rb') as mlmodel:
        model1 = pickle.load(mlmodel)
        mlmodel.close()

    with open('labels.txt', 'rb') as resltdict:
        labels = dict(pickle.load(resltdict))

    pred = model1.predict(model_vector.transform([x_string]))

    return labels[int(pred)]

app = Flask(__name__)

@app.route('/predict', methods=['GET', 'POST'])
def model_code():
    if request.method=="POST":
        strings=request.form['str']
        return predictions(strings)

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


#!/usr/bin/python3
'''Square Module
This module demonstrates how to work with classes.

The functionality included in this module is only for
demonstration purposes.
'''

class Square:
    '''class Square
    This is a simple class to demonstrate how to work with properties
    setters, and getters. It also demonstrates how to work with private
    and public attributes
    '''
    def __init__(self, size=0):
        '''The class square implements a typical square

        The following parameters are initialised when the class
        is first initialised.

        Args:
            size (float): the length or width of the square
            '''
        self.__size = size

    @property
    def size(self):
        '''The getter functions returns the value of the size attribute

        The setter method has the following characteristics

        Args:
            newsize: the size of the square

        Returns:
            does not return anythong

        Raises:
            TypeError: if size is not of type interger
            ValueError: If size is not >= 0
        '''
        return self.__size

    @size.setter
    def size(self, newsize):
        if not isinstance(newsize, int):
            raise TypeError("size must be an interger")
        elif size < 0:
            raise ValueError("size must be >= 0")
        else:
            self.__size = newsize

    def area(self):
        '''The area method calculates the area of the square
        the parameter __size.

        Args:
            no arguments.

        Returns:
            The area of the square

        Raises:
            No exception. Expected to be always successful
        '''
        return self.__size * self.__size

    def my_print(self):
        '''Draws a square using #

        Args:
            no arguments.

        Returns:
            Nothing

        Raises:
            No exception. Expected to be always successful
        '''
        times = 0
        if self.__size == 0:
            print("")
        else:
            c = "#" * self.__size
            while times < self.__size:
                print(f"{c}")
                times += 1


from PyQt5.QtWidgets import QWidget, QLabel, QPushButton
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QGridLayout

from PyQt5.QtGui import QPixmap, QImage

import numpy as np

class Panel(QWidget):

    def __PrivateMethod(self):
        print("private method, value of")
        return

    def __init__(self):
        QWidget.__init__(self)
        self.initWidgets()
        pass

    def resizePanel(self, w , h ):
        self._width = w
        self._height = h
        self.resize(w, h)
        return

    def initWidgets(self):
        self.resizePanel(800, 600);

        # control
        self.btnOpenCamera=QPushButton(self)
        self.btnOpenCamera.setText("Open")

        self.btnCloseCamera=QPushButton(self)
        self.btnCloseCamera.setText("Close")

        self.btnStopCamera=QPushButton(self)
        self.btnStopCamera.setText("Stop")

        # img show
        self.lbl_img = QLabel(self)
        self.lbl_img1 = QLabel(self)
        self.lbl_img2 = QLabel(self)
        self.lbl_img3 = QLabel(self)

        self.lbl_img.resize(400, 300)
        self.lbl_img1.resize(400, 300)
        self.lbl_img2.resize(400, 300)
        self.lbl_img3.resize(400, 300)

        layCtl = QHBoxLayout()
        layCtl.addWidget(self.btnOpenCamera)
        layCtl.addWidget(self.btnStopCamera)
        layCtl.addWidget(self.btnCloseCamera)

        lay = QGridLayout()
        lay.addWidget(self.lbl_img, 0, 0)
        lay.addWidget(self.lbl_img1, 1, 1)
        lay.addWidget(self.lbl_img2, 1, 0)
        lay.addWidget(self.lbl_img3, 0, 1)

        mainLay = QVBoxLayout()
        mainLay.addLayout(layCtl)
        mainLay.addLayout(lay)

        self.setLayout(mainLay)

        return

    def showCvImg(self, cv_img):

        h, w, d = cv_img.shape
        qimg = QImage(cv_img.data, w, h, w*d, QImage.Format_Grayscale16)
        pix_map = QPixmap(qimg)
        pix_map = pix_map.scaled(400, 300)

        qimg1 = QImage(cv_img.data, w, h, w*d, QImage.Format_RGB888)
        pix_map1 = QPixmap(qimg1)
        pix_map1 = pix_map1.scaled(400, 300)

        self.lbl_img.setPixmap(pix_map)
        self.lbl_img1.setPixmap(pix_map1)
        pass


import boto3
import sys
import json
from pygments import highlight, lexers, formatters
from src.s3_event_config import S3EventConfig, TopicConfig, QueueConfig, LambdaConfig

class S3Events:
    def __init__(self, client):
        self.Config = {}
        self.Client = client

    def __str__(self, pretty=True):
        json_txt = json.dumps((self.Config), indent = 4)
        if pretty is True:
            json_txt = highlight(
                json_txt,
                lexers.JsonLexer(),
                formatters.TerminalFormatter()
            )
        return(json_txt)

    # Update client object
    def update_client(self, client):
        self.Client = client
        return(self)

    def get_bucket_notifications(self, bucket_name):
        self.Config = self.Client.get_bucket_notification_configuration(
            Bucket=bucket_name
        )
        self.ResponseMetadata = self.Config.pop('ResponseMetadata', None)

    # Add notification to an existing configuration
    def add_notification_config(
        self, notif_type, dest_arn, events,
        id=None, filter_prefix=None, filter_suffix=None, verbose=False
    ):
        config_params = {
            'id': id,
            'dest_arn': dest_arn,
            'events': events,
            'filter_prefix': filter_prefix,
            'filter_suffix': filter_suffix
        }

        notif_type_map = {
            'topic': TopicConfig(config_params),
            'queue': QueueConfig(config_params),
            'lambda': LambdaConfig(config_params)
        }
        if notif_type not in notif_type_map:
            raise ValueError("Invalid notif_type: {}. Valid types: [\"topic\",\"queue\",\"lambda\"]".format(notif_type))
        notif_config = notif_type_map[notif_type]

        # notif_config = TopicConfig(config_params)
        notif_config.construct_config()
        self.Config = notif_config.attach_config(self.Config)

        print("Config {} added".format(id))

    # Remove notification by Id
    def remove_notification(self, id):
        print("This method currently does nothing!")
        pass

    def put_notification(self, bucket_name):
        response = self.Client.put_bucket_notification_configuration(
            Bucket=bucket_name,
            NotificationConfiguration=self.Config
        )

        return(response)


from django.conf.urls import url
from . import views

app_name = 'food'

urlpatterns = [
    url(r'^order/$', views.order, name="order"),
    url(r'^$', views.homepage, name="home"),
    url(r'^prepare/$', views.prepare, name="prepare"),
    url(r'^success/$', views.success, name="success"),
    url(r'^business/$', views.business, name="business"),
    url(r'^orderlist/$', views.OrderList.as_view(), name="list"),
    # pk stands for primary key; as_view() means we are using generic view
    url(r'^orderdetail/(?P<pk>[0-9]+)/$', views.OrderDetail.as_view(), name="detail"),
]


from datetime import datetime
from channels.generic.websocket import AsyncJsonWebsocketConsumer
from asgiref.sync import sync_to_async
from .models import Room,Message

class ChatConsumer(AsyncJsonWebsocketConsumer):
    async def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        self.room_group_name = f'chat_{self.room_name}'
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name,
        )
        print(f'Aceitando conexão do usuário {self.scope["user"].username}')
        await self.accept()

    async def disconnect(self, code):
        await self.channel_layer.group_discard(self.room_group_name,self.channel_name)

    async def receive_json(self, content, **kwargs):
        await self.save_message(content)
        content['type'] = 'chat_message'
        content['date_added'] = datetime.isoformat(datetime.now())
        await self.channel_layer.group_send(self.room_group_name, content)

    async def chat_message(self,content):
        await self.send_json(content)

    @sync_to_async
    def save_message(self,data):
        Message.objects.create(
            user=self.scope['user'],
            content=data['message'],
            room=Room.objects.get(slug=data['room'])
        )


from flask_restplus import Api
from flask import Blueprint

from .offices import offices
from .meetings import meetings

blueprint = Blueprint('api', __name__, url_prefix='/api')

api = Api(
    blueprint,
    title='Office Data Manager',
    description='Manages and provides data about each office, meeting, and suggested changes.',
    version='1.0',
    doc='/doc'
)

api.add_namespace(offices, path='/v1/offices')
api.add_namespace(meetings, path='/v1/meetings')


#!/root/mypy/bin/python
'''find the difference of two files

test

'''

import sys

def diff(fpath1,fpath2):
    f1=open(fpath1,'r')
    f2=open(fpath2,'r')
    f1set=set(f1.readlines())
    f2set=set(f2.readlines())
    fdiff=set(f1set-f2set)
    return fdiff

if __name__ == '__main__':
    result=diff(sys.argv[1],sys.argv[2])
    print(result)


from .colors import Color
from fastapi import APIRouter, Response
from jinja2 import Template
from os import path

class SvgResponse(Response):
    media_type = "image/svg+xml"

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(media_type="image/svg+xml", *args, **kwargs)

class Markers:
    def __init__(self, min: float, max: float) -> None:
        self.min = min
        self.max = max
        template_path = path.join(path.dirname(__file__), "pin.svg")
        self.template = Template(open(template_path).read())
        self.min_color = Color(rgb=(1, 0, 0))
        self.max_color = Color(rgb=(0, 1, 0))

    def get_router(self) -> APIRouter:
        router = APIRouter()

        @router.get("/{score}", response_class=SvgResponse, status_code=200)
        def get_marker(score: float):
            factor = score / (self.max - self.min + 1)
            response = SvgResponse(
                content=self.template.render(
                    {
                        "color": self.min_color.lerp(
                            self.max_color, factor
                        ).get_css_color()
                    }
                ),
            )
            response.headers['cache-control'] = 'max-age=3600'
            return response

        return router


# -*- coding: utf-8 -*-
# python 3.x
# Filename: StrUtil.py
# 定义一个StrUtil工具类实现字符串操作相关的功能
from util.LogUtil import *

TAG = 'StrUtil'

class StrUtil:
    @staticmethod
    def capitalize(data: str):
        """
        将字符串的首字母大写，其余字母大小写不变
        :param data: data
        :return: value
        """
        if not data:
            return ""
        return data[0].upper() + data[1:]

    @staticmethod
    def decapitalize(data: str):
        """
        将字符串的首字母小写，其余字母大小写不变
        :param data: data
        :return: value
        """
        if not data:
            return ""
        return data[0].lower() + data[1:]

    @staticmethod
    def containsStr(srcStr: str, dataList: []):
        """
        判断字符串中是否包含指定列表中的数据
        :param srcStr: 源字符串
        :param dataList: 要判断的字符串列表
        :return: True 包含任意一个数据 False 一个都不包含
        """
        isContains = False
        for data in dataList:
            if data in srcStr:
                isContains = True
                break
        return isContains

    @staticmethod
    def decode(data):
        """
        将字节转为字符串
        :param data: 源字节串
        :return: 解码后到字符串
        """
        if not data:
            return ''
        try:
            return data.decode()
        except Exception as e:
            LogUtil.e(TAG, 'decode 错误信息：', e)
        try:
            return data.decode('gbk')
        except Exception as e:
            LogUtil.e(TAG, 'decode 错误信息：', e)
        return ''

if __name__ == "__main__":
    LogUtil.d(StrUtil.capitalize("thank"))
    LogUtil.d(StrUtil.decapitalize("THANK"))

    LogUtil.d(StrUtil.capitalize("t"))
    LogUtil.d(StrUtil.decapitalize("T"))

    LogUtil.d(StrUtil.capitalize(""))
    LogUtil.d(StrUtil.decapitalize(""))


import datetime
from django.shortcuts import render
from .models import Agreement, Period
import json
from django.http import HttpResponse

# Function of separation ID
# Returns a single identifier without a comma
# Returns "None", if not number or 0
def separation(set_in):
    double_comma = 0
    result = []
    set_path = ""
    for char in str(set_in):
        if char == ",":
            double_comma += 1
            if double_comma > 1:
                return None
            if set_path:
                try:
                    result.append(int(set_path))
                except ValueError:
                    return None
                set_path = ""
        elif char == "0" or char == "-":
            return None
        else:
            set_path +=char
            double_comma = 0
    try:
        result.append(int(set_path))
    except ValueError:
        return None
    return result

def home(request):
    context ={
        'page_header': 'Home page title B2B',
    }
    return render(request, 'agreement/home.html', context)

def calendar(request, country=0, negotitator=0, company=0):
    answer = dict()
    # Getting and validation ones ID
    if 'country' in request.GET:
        country = request.GET['country']
        country = separation(country)
        if country == None:
            context = {
                'mes_er':"You made a mistake when entering the country code",
            }
            return render(request, 'agreement/mistake.html', context)
    if 'negotitator' in request.GET:
        negotitator = request.GET['negotitator']
        negotitator = separation(negotitator)
        if negotitator == None:
            context = {
                'mes_er':"You made a mistake when entering the negotiator",
            }
            return render(request, 'agreement/mistake.html', context)
    if 'company' in request.GET:
        company = request.GET['company']
        company = separation(company)
        if company == None:
            context = {
                'mes_er':"You made a mistake when entering the company code",
            }
            return render(request, 'agreement/mistake.html', context)
    if not country:
        country = 0

    # Filter definition
    if country == 0:
        if negotitator == 0:
            if company == 0:
                agreements_all = Agreement.objects.all()
            else:
                agreements_all = Agreement.objects.filter\
                    (company__id__in=company)
        else:
            if company == 0:
                agreements_all = Agreement.objects.filter\
                    (negotiator__id__in=negotitator)
            else:
                agreements_all = Agreement.objects.filter\
                    (company__id__in=company, negotiator__id__in=negotitator)
    else:
        if negotitator == 0:
            if company == 0:
                agreements_all = Agreement.objects.filter\
                    (company__country__in=country)
            else:
                agreements_all = Agreement.objects.filter\
                    (company__country__in=country, company__id__in=company)
        else:
            if company == 0:
                agreements_all = Agreement.objects.filter\
                    (company__country__in=country, negotiator__id__in=\
                        negotitator)
            else:
                agreements_all = Agreement.objects.filter\
                    (company__country__in=country, company__id__in=company,\
                    negotiator__id__in=negotitator)
    if not agreements_all:
        context = {
        'mes_er': "Your sample is empty",
        }
        return render(request, 'agreement/mistake.html', context)

    for select_agreement in agreements_all:
        id_agr = int(select_agreement.id)
        select_periods = Period.objects.filter(agreement__id=id_agr)
        mas_year = 0
        mas_month = 0
        for i in range(len(select_periods)):
            mass = str(select_periods[i])
            if int(mass[11:15]) > mas_year:
                mas_year = int(mass[11:15])
            if int(mass[16:18]) > mas_month:
                mas_month = int(mass[16:18])
        year = answer.get(mas_year, 0)
        if not year:
            answer[mas_year] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        monthes = answer[mas_year]
        monthes[mas_month-1] +=1
        answer[mas_year] = monthes
    return HttpResponse(json.dumps(answer), content_type='application/json')


# pylint: skip-file
# Still work in progress
import math
from struct import pack, unpack

from bot.actions_generator import ActionsGenerator
from bot.bot import Bot
from bot.mcst.mcst_bot_game_state import MCSTBotGameState
from game_client.actions import Action, ActionCode
from utility.coordinates import Coords

def action_to_bytestring(action: Action, game_state: MCSTBotGameState):
    return pack(
        "cccccccccc",
        action.action_code.value,
        action.actor.vehicle_id,
        action.target,
        0,
        # TODO: get vehicle count
        game_state.current_player.idx,
        action.affected_vehicles,
    )

def bytestr_to_action(bytestr: bytes, game_state: MCSTBotGameState):
    unpacked = unpack("cccccccccc", bytestr)
    affected_vehicles = []
    for i in range(7, len(unpacked)):
        affected_vehicles.append(find_vehicle(game_state.vehicles, unpacked[i]))
    return Action(
        ActionCode(unpacked[0]),
        find_vehicle(game_state.vehicles, unpacked[1]),
        Coords((unpacked[2], unpacked[3], unpacked[4])),
        affected_vehicles,
    )

def get_current_player(bytestr: bytes):
    return bytestr[6]

def get_next_vehicle(bytestr: bytes):
    return (bytestr[5] + 1) % 5

def find_vehicle(vehicles, id):
    return next(
        filter(lambda vehicle: vehicle.vehicle_id == id, vehicles.values()), None
    )

class MCSTNode:
    def __init__(self, parent, action: bytes, child=None, sibling=None):
        self.parent: MCSTNode = parent
        self.child: MCSTNode = child
        self.sibling: MCSTNode = sibling
        self.am_visited = 0
        self.am_wins = 0
        self.action: bytes = action

    def children(self):
        node = self.child
        while node is not None:
            yield node
            node = node.sibling

    def have_all_children(self):
        return all((child.am_visited > 0 for child in self.children()))

    def get_new_child(self):
        # returns random children
        return next(filter(lambda child: child.am_visited == 0, self.children()))

    def get_most_valuable_child(self):
        return max(self.children(), key=lambda node: node.get_uct())

    def get_uct(self):
        result = self.am_wins / self.am_visited
        result += math.sqrt(2 * math.log(self.parent.am_visited) / self.am_visited)
        return result

class MonteCarloSearchTree:
    def __init__(self, game_state: MCSTBotGameState, bot: Bot):
        self.root: MCSTNode = MCSTNode(None, bytes())
        self.bot: Bot = bot
        self.game_state: MCSTBotGameState = game_state
        self.action_generator = ActionsGenerator(game_state)

    def selection(self) -> (MCSTNode, MCSTBotGameState):
        node = self.root
        game_state = self.game_state  # TODO: copy game_state
        while not game_state.finished and node.have_all_children():
            node = node.get_most_valuable_child()

            action = bytestr_to_action(node.action, game_state)
            game_state.update_from_action(action)  # TODO: update from action
        return node, game_state

    def expansion(self, node: MCSTNode, game_state: MCSTBotGameState):
        new_node = node.get_new_child()

        action = bytestr_to_action(node.action, game_state)
        game_state.update_from_action(action)  # TODO: update_from_action

        self.action_generator.game_state = game_state
        vehicles = game_state.current_player.ordered_vehicle_iter
        vehicle = next(vehicles)
        for i in range(get_next_vehicle(node.action)):
            vehicle = next(vehicles)

        possible_steps = self.action_generator(vehicle)  # TODO: get possible steps
        child = None
        for action in possible_steps:
            bytestr = action_to_bytestring(action)
            child = MCSTNode(new_node, bytestr, sibling=child)
        new_node.child = child
        return new_node, game_state

    def playout(self, game_state: MCSTBotGameState):
        while not game_state.finished:
            for action in self.bot.get_actions(game_state):  # TODO: change interface
                game_state.update_from_action(action)  # TODO: update from action
        return game_state.winner  # TODO: get winner

    def backpropagation(self, node: MCSTNode, winner):
        while node.parent is not None:
            node.am_visited += 1
            if (
                get_current_player(node.action) == winner
            ):  # TODO: determine which player made a move
                node.am_wins += 1


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf

from core import utils
from core import box_utils
from object_detection.builders.model_builder import _build_faster_rcnn_feature_extractor as build_faster_rcnn_feature_extractor

slim = tf.contrib.slim

def calc_oicr_loss(labels,
                   num_proposals,
                   proposals,
                   scores_0,
                   scores_1,
                   scope,
                   iou_threshold=0.5):
  """Calculates the NOD loss at refinement stage `i`.

  Args:
    labels: A [batch, num_classes] float tensor.
    num_proposals: A [batch] int tensor.
    proposals: A [batch, max_num_proposals, 4] float tensor.
    scores_0: A [batch, max_num_proposal, 1 + num_classes] float tensor,
      representing the proposal score at `k-th` refinement.
    scores_1: A [batch, max_num_proposal, 1 + num_classes] float tensor,
      representing the proposal score at `(k+1)-th` refinement.

  Returns:
    oicr_cross_entropy_loss: a scalar float tensor.
  """
  with tf.name_scope(scope):
    (batch, max_num_proposals,
     num_classes_plus_one) = utils.get_tensor_shape(scores_0)
    num_classes = num_classes_plus_one - 1

    # For each class, look for the most confident proposal.
    #   proposal_ind shape = [batch, num_classes].

    proposal_mask = tf.sequence_mask(
        num_proposals, maxlen=max_num_proposals, dtype=tf.float32)
    proposal_ind = utils.masked_argmax(
        scores_0[:, :, 1:], tf.expand_dims(proposal_mask, axis=-1), dim=1)

    # Deal with the most confident proposal per each class.
    #   Unstack the `proposal_ind`, `labels`.
    #   proposal_labels shape = [batch, max_num_proposals, num_classes].

    proposal_labels = []
    indices_0 = tf.range(batch, dtype=tf.int64)
    for indices_1, label_per_class in zip(
        tf.unstack(proposal_ind, axis=-1), tf.unstack(labels, axis=-1)):

      # Gather the most confident proposal for the class.
      #   confident_proosal shape = [batch, 4].

      indices = tf.stack([indices_0, indices_1], axis=-1)
      confident_proposal = tf.gather_nd(proposals, indices)

      # Get the Iou from all the proposals to the most confident proposal.
      #   iou shape = [batch, max_num_proposals].

      confident_proposal_tiled = tf.tile(
          tf.expand_dims(confident_proposal, axis=1), [1, max_num_proposals, 1])
      iou = box_utils.iou(
          tf.reshape(proposals, [-1, 4]),
          tf.reshape(confident_proposal_tiled, [-1, 4]))
      iou = tf.reshape(iou, [batch, max_num_proposals])

      # Filter out irrelevant predictions using image-level label.

      target = tf.to_float(tf.greater_equal(iou, iou_threshold))
      target = tf.where(label_per_class > 0, x=target, y=tf.zeros_like(target))
      proposal_labels.append(target)

    proposal_labels = tf.stack(proposal_labels, axis=-1)

    # Add background targets, and normalize the sum value to 1.0.
    #   proposal_labels shape = [batch, max_num_proposals, 1 + num_classes].

    bkg = tf.logical_not(tf.reduce_sum(proposal_labels, axis=-1) > 0)
    proposal_labels = tf.concat(
        [tf.expand_dims(tf.to_float(bkg), axis=-1), proposal_labels], axis=-1)

    proposal_labels = tf.div(
        proposal_labels, tf.reduce_sum(proposal_labels, axis=-1, keepdims=True))

    assert_op = tf.Assert(
        tf.reduce_all(
            tf.abs(tf.reduce_sum(proposal_labels, axis=-1) - 1) < 1e-6),
        ["Probabilities not sum to ONE", proposal_labels])

    # Compute the loss.

    with tf.control_dependencies([assert_op]):
      losses = tf.nn.softmax_cross_entropy_with_logits(
          labels=tf.stop_gradient(proposal_labels), logits=scores_1)
      oicr_cross_entropy_loss = tf.reduce_mean(
          utils.masked_avg(data=losses, mask=proposal_mask, dim=1))

  return oicr_cross_entropy_loss

def extract_frcnn_feature(inputs,
                          num_proposals,
                          proposals,
                          options,
                          is_training=False):
  """Extracts Fast-RCNN feature from image.

  Args:
    feature_extractor: An FRCNN feature extractor instance.
    inputs: A [batch, height, width, channels] float tensor.
    num_proposals: A [batch] int tensor.
    proposals: A [batch, max_num_proposals, 4] float tensor.
    options:
    is_training:

  Returns:
    proposal_features: A [batch, max_num_proposals, feature_dims] float
      tensor.
  """
  feature_extractor = build_faster_rcnn_feature_extractor(
      options.feature_extractor, is_training, options.inplace_batchnorm_update)

  # Extract `features_to_crop` from the original image.
  #   shape = [batch, feature_height, feature_width, feature_depth].

  preprocessed_inputs = feature_extractor.preprocess(inputs)

  (features_to_crop, _) = feature_extractor.extract_proposal_features(
      preprocessed_inputs, scope='first_stage_feature_extraction')

  if options.dropout_on_feature_map:
    features_to_crop = slim.dropout(
        features_to_crop,
        keep_prob=options.dropout_keep_prob,
        is_training=is_training)

  # Crop `flattened_proposal_features_maps`.
  #   shape = [batch*max_num_proposals, crop_size, crop_size, feature_depth].

  batch, max_num_proposals, _ = utils.get_tensor_shape(proposals)
  box_ind = tf.expand_dims(tf.range(batch), axis=-1)
  box_ind = tf.tile(box_ind, [1, max_num_proposals])

  cropped_regions = tf.image.crop_and_resize(
      features_to_crop,
      boxes=tf.reshape(proposals, [-1, 4]),
      box_ind=tf.reshape(box_ind, [-1]),
      crop_size=[options.initial_crop_size, options.initial_crop_size])

  flattened_proposal_features_maps = slim.max_pool2d(
      cropped_regions,
      [options.maxpool_kernel_size, options.maxpool_kernel_size],
      stride=options.maxpool_stride)

  # Extract `proposal_features`,
  #   shape = [batch, max_num_proposals, feature_dims].

  (box_classifier_features
  ) = feature_extractor.extract_box_classifier_features(
      flattened_proposal_features_maps, scope='second_stage_feature_extraction')

  flattened_roi_pooled_features = tf.reduce_mean(
      box_classifier_features, [1, 2], name='AvgPool')
  flattened_roi_pooled_features = slim.dropout(
      flattened_roi_pooled_features,
      keep_prob=options.dropout_keep_prob,
      is_training=is_training)

  proposal_features = tf.reshape(flattened_roi_pooled_features,
                                 [batch, max_num_proposals, -1])

  # Assign weights from pre-trained checkpoint.

  tf.train.init_from_checkpoint(
      options.checkpoint_path,
      assignment_map={"/": "first_stage_feature_extraction/"})
  tf.train.init_from_checkpoint(
      options.checkpoint_path,
      assignment_map={"/": "second_stage_feature_extraction/"})

  return proposal_features


from collections import deque

N, K = map(int, input().split(' '))

que = deque(list(range(1, N+1))) # 큐로 문제 풀이

tmp_list = []
while que :
    que.rotate(-K + 1)
    tmp_list.append(str(que.popleft()))

print("<",', '.join(tmp_list),">", sep = '')

요세푸스 문제 0.py


# encoding: utf-8
"""
通过fp-growth算法寻找购物篮数据当中的频繁项集，算法逻辑来源于：Tan, Pang-Ning, Michael Steinbach, and Vipin Kumar.
Introduction to Data Mining. 1st ed. Boston: Pearson / Addison Wesley, 2006. (pp. 363-370)

"""

# original author information
__copyright__ = 'Copyright © 2022 ERSSLE'
__license__ = 'MIT License'

from collections import defaultdict

class FPTree(object):
    """
    创建一颗FP树，算法的逻辑来源于 Tan, Pang-Ning, Michael Steinbach, and Vipin Kumar.
    Introduction to Data Mining. 1st ed. Boston: Pearson / Addison Wesley, 2006. (pp. 363-370)
    """
    def __init__(self,reverse=True):
        """
        初始化：reverse指定树生长时的排序方式，默认从高频项到低频项，也可反转（False）
        """
        self._reverse = reverse
        self._nodes_level = defaultdict(lambda: set())
        self._nodes_cluster = defaultdict(lambda: set())
        self._nodes_parent = defaultdict(lambda: None)
        self._nodes_children = defaultdict(lambda: set())
        self._nodes_count = defaultdict(lambda: 0)

        self._nodes_level['lv_0'].add(0)
        self._nodes_cluster['root'].add(0)
        self._nodes_parent[0] = None
        self._nodes_children[0] = set()
        self._nodes_count[0] = None

    @property
    def node_datas(self):
        """
        返回所含所有fp树结构信息的数据
        """
        return dict(
            nodes_level = dict(self._nodes_level),
            nodes_cluster = dict(self._nodes_cluster),
            nodes_parent = dict(self._nodes_parent),
            nodes_children = dict(self._nodes_children),
            nodes_count = dict(self._nodes_count)
        )

    def create_tree(self,node_datas):
        """
        根据结构数据直接构建fp树
        node_datas:一个字典结构数据，其形式与node_datas返回结果相同
        """
        self._nodes_level = node_datas['nodes_level']
        self._nodes_cluster = node_datas['nodes_cluster']
        self._nodes_parent = node_datas['nodes_parent']
        self._nodes_children = node_datas['nodes_children']
        self._nodes_count = node_datas['nodes_count']

    def add(self,transaction):
        """
        逐条添加
        """
        last_node = 0
        for i,item in enumerate(transaction):
            node = self._nodes_cluster[item].intersection(self._nodes_children[last_node])
            if node:
                node = list(node)[0]
                self._nodes_count[node] += 1
            else:
                node = self._next_node
                self._nodes_level['lv_%s' % (i+1)].add(node)
                self._nodes_cluster[item].add(node)
                self._nodes_parent[node] = last_node
                self._nodes_children[last_node].add(node)
                self._nodes_count[node] += 1
            last_node = node
    def adds(self,transactions,support=1):
        """
        输入数据条目，生长fp树
        transactions: 双层python链表，内嵌层每一项元素代表一条数据
        support:项的最小支持度
        """
        items = defaultdict(lambda: 0)
        for transaction in transactions:
            for item in transaction:
                assert item != 'root','数据当中不可存在root默认的根节点标识，尝试替换成其它标识后再进行'
                items[item] += 1
        items = dict((item, spt) for item, spt in items.items() if spt >= support)
        self.item_list = [k for k in items.keys()]
        self.item_list.sort(key=lambda k: items[k],reverse=self._reverse)
        self.item_list.append(None)  # 添加虚拟待检查节点，使fp全树的频繁项集查找和子图统一
        def clean_transaction(transaction):
            transaction = filter(lambda v: v in items, transaction)
            transaction_list = list(transaction)
            transaction_list.sort(key=lambda v: self.item_list[::-1].index(v), reverse=self._reverse)
            return transaction_list
        for transaction in map(clean_transaction,transactions):
            self.add(transaction)

    @property
    def _next_node(self):
        """
        返回下一个节点id号，每一个节点有一个唯一的id号,root节点id=0
        """
        return max(self._nodes_parent) + 1
    @property
    def maxdepth(self):
        """排除根节点树结构的最大深度"""
        return len(self._nodes_level) - 1
    @property
    def node_num(self):
        """排除根节点树的节点总数"""
        return len(self._nodes_parent) - 1

def find_child_tree(tree,item,node_to_item=None):
    """
    根据结尾项从源树获取子树，使子树的叶节点均含有类型相同的项
    tree: 源树
    item: 子树的叶节点类型
    node_to_item: 一个从节点到节点类型的映射字典，如果为None自动查找
    """
    nodes_cluster = tree.node_datas['nodes_cluster']
    nodes_parent = tree.node_datas['nodes_parent']
    nodes_count = tree.node_datas['nodes_count']
    if node_to_item is None:
        node_to_item = dict((v,k) for k,vs in nodes_cluster.items() for v in vs)
    leaf_nodes = nodes_cluster[item]

    child_tree = FPTree()
    new_node_datas = dict(
            nodes_level = defaultdict(lambda: set()),
            nodes_cluster = defaultdict(lambda: set()),
            nodes_parent = defaultdict(lambda: None),
            nodes_children = defaultdict(lambda: set()),
            nodes_count = defaultdict(lambda: 0)
    )
    for node in leaf_nodes:
        nodes = [node]
        while node:
            node = nodes_parent[node]
            nodes.append(node)
        for i,node in enumerate(nodes):
            new_node_datas['nodes_level']['lv_%s' % (len(nodes) - nodes.index(node)-1)].add(node)
            new_node_datas['nodes_cluster'][node_to_item[node]].add(node)
            new_node_datas['nodes_parent'][node] = nodes_parent[node]
            if node > 0:
                new_node_datas['nodes_children'][nodes_parent[node]].add(node)
                new_node_datas['nodes_count'][node] += nodes_count[nodes[0]]
            else:
                new_node_datas['nodes_count'][node] = None
    child_tree.create_tree(new_node_datas)
    child_tree._reverse = tree._reverse
    child_tree.item_list = [item for item in tree.item_list if item in child_tree._nodes_cluster]
    return child_tree

def find_counts(tree,minimum_support,node_to_item=None):
    """
    从树结构当中递归查找频繁项的统计值，即支持度。
    返回结果是一个层叠的字典
    tree: fp树
    minimum_support: 支持度
    node_to_item: 一个从节点到节点类型的映射字典，如果为None自动查找
    """
    if node_to_item is None:
        node_to_item = dict((v,k) for k,vs in tree.node_datas['nodes_cluster'].items() for v in vs)
    def get_count(tree,item):
        return sum(tree.node_datas['nodes_count'][node] for node in tree.node_datas['nodes_cluster'][item])
    def find_trees_count(tree):
        trees = []
        for item in tree.item_list[-2::-1]:
            child_tree = find_child_tree(tree,item,node_to_item)
            if get_count(tree,item) >= minimum_support:
                trees.append(child_tree)
            else:
                None
        return {tr.item_list[-1]:(
            get_count(tr,tr.item_list[-1]),
            find_trees_count(tr)
            ) for tr in trees
            }
    return find_trees_count(tree)

def find_frequent_itemsets_alpha(cnt):
    """解析find_count结果，生成频繁项集"""
    itemsets = []
    def find_itemsets(cnt,suffix=[]):
        cnts = []
        for k,vs in cnt.items():
            itemset = ([k] + suffix,vs[0])
            itemsets.append(itemset)
            cnts.append(vs[1])
            find_itemsets(vs[1],[k]+suffix)
    find_itemsets(cnt)
    return itemsets

def find_frequent_itemsets(datas,minimum_support,reverse=True):
    """
    基于给定的支持度，查找频繁项集
    datas: 双层python链表，每一项元素代表一条数据
    minimum_support: 支持度
    reverse: 指定树生长时的排序方式，默认从高频项到低频项，也可反转（False）
    """
    tree = FPTree(reverse=reverse)
    tree.adds(datas,support=minimum_support)
    node_to_item = dict((v,k) for k,vs in tree.node_datas['nodes_cluster'].items() for v in vs)
    counts = find_counts(tree,minimum_support,node_to_item)
    return find_frequent_itemsets_alpha(counts)

try:
    import networkx as nx
    import matplotlib.pyplot as plt

    def plot_fptree(tree,width_depth_rate = 1.5,add_labels=True,ax=None):
        """
        根据给定的fp树绘制成图形
        tree: 树
        add_labels: 添加节点类型与计数标签
        """
        node_datas = tree.node_datas
        node_to_item = dict((v,k) for k,vs in tree._nodes_cluster.items() for v in vs)
        depth = tree.maxdepth
        max_width = max(len(nodes)for nodes in node_datas['nodes_level'].values())
        graph = nx.Graph()
        graph_width = (max_width * width_depth_rate) / depth
        graph_depth = 1.0
        row_num = 1
        nodes_xy = {}
        nodes_labels = []
        def add_nodes(nodes,row_num = row_num):
            width = len(nodes)
            xs = [graph_width * (i+1) / (width+1) for i in range(width)]
            ys = [1 - (graph_depth * row_num) / (depth+2)] * width
            row_num += 1
            nodes_xy.update(dict((node,(x,y)) for node,x,y in zip(nodes,xs,ys) if node is not None))
            for node,x,y in zip(nodes,xs,ys):
                if node is not None:
                    txt = '%s:%s' % (node_to_item[node],node_datas['nodes_count'][node])
                    nodes_labels.append((txt,(x,y)))
            new_nodes = []
            for node in nodes:
                if node in node_datas['nodes_children']:
                    children = sorted(list(node_datas['nodes_children'][node]))
                    if children:
                        new_nodes = new_nodes + children
                    else:
                        new_nodes.append(None)
                else:
                    new_nodes.append(None)
            if set(new_nodes) == set([None]):
                return 0
            else:
                add_nodes(new_nodes,row_num)
        add_nodes([0])
        graph.add_nodes_from(nodes_xy)
        for k,vs in node_datas['nodes_children'].items():
            graph.add_edges_from((k,v) for v in vs)
        if ax is None:
            fig = plt.figure(figsize=(6*graph_width,6))
            ax = fig.add_subplot()
        nx.draw(graph,nodes_xy,with_labels=True,node_size=1000,node_color='r',ax=ax)
        if add_labels:
            for txt,xy in nodes_labels:
                _ = ax.text(xy[0],xy[1]-0.05,txt,fontdict={'fontsize':15,'color':'b'})
except ModuleNotFoundError:
    None

if __name__ == '__main__':
    datas = [
        ['a','b'],
        ['b','c','d'],
        ['a','c','d','e'],
        ['a','d','e'],
        ['a','b','c'],
        ['a','b','c','d'],
        ['a'],
        ['a','b','c'],
        ['a','b','d'],
        ['b','c','e']
    ]
    print('datas频繁项集:','\n',find_frequent_itemsets(datas,2))
    if 'plot_fptree' in dir():
        tree = FPTree()
        tree.adds(datas,2)
        plot_fptree(tree)
        plt.show()


from tkinter import *
from functools import partial
import connection
import time

def end_shift(user_id,start_time):
  global newTab
  t = time.localtime()
  date_time = time.strftime("%Y/%m/%d, %H:%M:%S",t)
  print(date_time,user_id,start_time)
  query = connection.cur.execute("UPDATE bj_clock_in SET end_time = to_timestamp('{}' , 'YYYY-MM-DD HH24:MI:SS') where job_id = '{}'  and start_time = to_timestamp('{}', 'YYYY-MM-DD HH24:MI:SS')".format(date_time,user_id, start_time))
  connection.connection.commit()
  print("Done Updated")
  newTab.destroy()

newTab = Tk()
newTab.title("User bar")
newTab.geometry("500x300")

user = connection.cur.execute("select job_id,start_time from bj_clock_in order by start_time desc ").fetchone()
user_id = user[0]
start_time = user[1]

name = connection.cur.execute("select first_name from bj_employees where job_id="+str(user_id)).fetchone()

lbl2 = Label(newTab, text = "Shift started at: ").grid(row = 0, column = 3)
lbl1 = Label(newTab, text = "Welcome,").grid(row = 0, column = 1)
lbl3 = Label(newTab, text = name).grid(row = 0, column = 2)
lbl4 = Label(newTab, text = start_time).grid(row = 0, column = 4)

end_shift = partial(end_shift,user_id,start_time)
delButton = Button(newTab,text="End shift", command=end_shift).grid(row =0,column =5)


# coding: utf-8

class FukumenzanSolver():
	def __init__(self, probrem_):
		'''

		:param probrem_: 問題の文字列のリスト（刺繍要素は、合計値の文字列）
			このクラスの中では、左からの桁位置を扱いやすくするため、逆順にしておく。数字が入る　board_もその位置に対応するように扱う。
			probrem_ ['SEND', 'MORE', 'MONEY']
			, self.probrem_['DNES', 'EROM', 'YENOM']
			, self.board_ [[v11,v12,v13,v14], [....], [v31,v32,v33,v34,v35]]
			          v11 は文字Dの数字、v12 は文字Nの数字、v13 は文字Eの数字、v14 は文字Sの数字、　　　、v32 は文字Eの数字(=v11)
		'''
		self.probrem_, self.board_ = [], []
		self.used_, self.fu_dict, self.chrs = [], {}, []
		self.NOTIN = -1
		for r, row in enumerate(probrem_):
			self.probrem_.append(list(reversed(row)))
			self.board_.append([self.NOTIN for _ in range(len(row))])

		for d in range(len(self.probrem_[-1])):
			for r in range(len(self.probrem_)):
				if d < len(self.probrem_[r]):
					c = self.probrem_[r][d]
					if c in self.fu_dict:
						self.fu_dict[c]['rd'].append((r,d))
						self.fu_dict[c]['nodes'] += 1
					else:
						self.fu_dict[c] = {'rd':[(r, d)], 'val':0, 'nodes':1}
						self.chrs.append(c)

	def get_size(self):
		return len(self.probrem_)

	def get_digit(self, row:int = -1):
		return len(self.probrem_[row])

	def is_used(self, val:int)->bool:
		return True	if val in self.used_ else False

	def get_val(self, row:int, digit:int)->int:
		if digit >= self.get_digit(row):
			return 0
		else:
			return self.board_[row][digit]

	def set_val_with_chr(self, c, val:int):
		for r, d in self.fu_dict[c]['rd']:
			self.board_[r][d] = val
		self.used_.append(val)

	def reset_val_with_chr(self, c:str):
		for r, d in self.fu_dict[c]['rd']:
			val = self.board_[r][d]
			if val != self.NOTIN:
				self.board_[r][d] = self.NOTIN
				if val in self.used_:
					self.used_.remove(val)

	def is_valid(self):
		for val in self.board_:
			if val[-1]==0:
				return False
		kuriage:int = 0
		number_targets = sum_row_number= self.get_size() - 1
		for digit in range(self.get_digit()):
			sum:int = 0
			for row in range(number_targets):
				v:int = self.get_val(row, digit)
				if  v == self.NOTIN:
					return True
				if row != number_targets:
					sum += v
			sum_digit = self.get_val(sum_row_number, digit)
			if sum_digit == self.NOTIN:
				return True
			sum += kuriage
			kuriage, sum = divmod(sum, 10)
			if sum != sum_digit:
				return False
		return (kuriage == 0)

	def solve(self):

		ret = self.dfs(0)
		if ret:
			return self.board_
		else:
			return []

	def dfs(self, idx:int)->bool:
		while  True:
			if idx >= len(self.chrs):
				return True
			elif idx < 0:
				return False

			target_c = self.chrs[idx]
			val = self.fu_dict[target_c]['val']
			if val > 9:
				self.reset_val_with_chr(target_c)
				self.fu_dict[target_c]['val'] = 0
				idx -= 1
				self.reset_val_with_chr(self.chrs[idx])
				self.fu_dict[self.chrs[idx]]['val'] += 1
			else:
				if self.is_used(val):
					self.fu_dict[target_c]['val'] += 1
				else:
					self.set_val_with_chr(target_c, val)
					if self.is_valid():
						idx += 1
						if idx < len(self.chrs):
							self.fu_dict[self.chrs[idx]]['val'] = 0
					else:
						self.reset_val_with_chr(target_c)
						self.fu_dict[target_c]['val'] += 1


import tweepy
import logging
import time
from config import create_api, download_media
import os
import glob

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger()

def check_mentions(api, since_id):
    logger.info("Retrieving mentions")
    new_since_id = since_id
    # fetch items (tweets) from mentions. Use cursor for pagination (aka can do more than request 1 page)
    for tweet in tweepy.Cursor(api.mentions_timeline, since_id=since_id, tweet_mode="extended").items():
        # set new since_id to the highest tweet id (most recent).
        new_since_id = max(tweet.id, new_since_id)

        '''
        Im still trying to figure out what the below code does exactly...

        if tweet.in_reply_to_status_id is not None:
            logger.info("in_reply_to_status_id is not none... restart loop")
            logger.info(tweet.in_reply_to_status_id)
            continue
        logger.info("Detected mention...")
        '''

        # if not following the person who mentioned you, follow them
        if not tweet.user.following:
            tweet.user.follow()

        # download media
        if 'media' in api.get_status(tweet.in_reply_to_status_id).entities:
            logger.info("I found media!")
            media_ids = download_media(api, api.get_status(tweet.in_reply_to_status_id))
            print(media_ids)
            """# tweets the status argument as a reply, to the specified tweet id
            logger.info(f"Answering to {tweet.user.name} and posting pic...")

            api.update_status(status=f"Hey {tweet.user.name}. "
                                     f"I tried to find some faces/eyes in the tweet you showed me.",
                              in_reply_to_status_id=tweet.id,
                              auto_populate_reply_metadata=True,
                              media_ids=media_ids
                              )"""

            # delete downloaded media
            if os.path.exists('C:\\PythonLearning\\TwitterBot\\media'):
                files = glob.glob('.\\media\\*.jpg')
                for f in files:
                    os.remove(f)
                logger.info("Deleted downloaded photos...")
            else:
                logger.info("Could not delete downloaded photo...")
        else:
            logger.info("Sorry could not find media..")
            api.update_status(status=f"Hey {tweet.user.name}, sorry I could not find a photo in the tweet you tagged"
                                     f" me in...",
                              in_reply_to_status_id=tweet.id,
                              auto_populate_reply_metadata=True)
    return new_since_id

def main():
    # Creates Tweepy API object
    api = create_api()
    # since_id is used return only statuses with an ID greater than (more recent than) the specified ID.
    since_id = 1
    while True:
        since_id = check_mentions(api, since_id)
        logger.info("Waiting...")
        time.sleep(60)

if __name__ == "__main__":
    main()


from __future__ import absolute_import, division, print_function

import paayes

TEST_RESOURCE_ID = "promo_123"

class TestPromotionCode(object):
    def test_is_listable(self, request_mock):
        resources = paayes.PromotionCode.list()
        request_mock.assert_requested("get", "/api/v1/promotion_codes")
        assert isinstance(resources.data, list)
        assert isinstance(resources.data[0], paayes.PromotionCode)

    def test_is_retrievable(self, request_mock):
        resource = paayes.PromotionCode.retrieve(TEST_RESOURCE_ID)
        request_mock.assert_requested(
            "get", "/api/v1/promotion_codes/%s" % TEST_RESOURCE_ID
        )
        assert isinstance(resource, paayes.PromotionCode)

    def test_is_creatable(self, request_mock):
        resource = paayes.PromotionCode.create(coupon="co_123", code="MYCODE")
        request_mock.assert_requested("post", "/api/v1/promotion_codes")
        assert isinstance(resource, paayes.PromotionCode)

    def test_is_saveable(self, request_mock):
        resource = paayes.PromotionCode.retrieve(TEST_RESOURCE_ID)
        resource.metadata["key"] = "value"
        resource.save()
        request_mock.assert_requested(
            "post", "/api/v1/promotion_codes/%s" % TEST_RESOURCE_ID
        )

    def test_is_modifiable(self, request_mock):
        resource = paayes.PromotionCode.modify(
            TEST_RESOURCE_ID, metadata={"key": "value"}
        )
        request_mock.assert_requested(
            "post", "/api/v1/promotion_codes/%s" % TEST_RESOURCE_ID
        )
        assert isinstance(resource, paayes.PromotionCode)


#
# Your previous Plain Text content is preserved below:
#
# This is just a simple shared plaintext pad, with no execution capabilities.
#
# When you know what language you'd like to use for your interview,
# simply choose it from the dropdown in the top bar.
#
# You can also change the default language your pads are created with
# in your account settings: https://coderpad.io/settings
#
# Enjoy your interview!
#

# Symbol  I  V  X  L    C    D    M
# Value  1  5  10  50  100  500  1,000

numerals = {
  1: 'I',
  # 4: 'IV',
  5: 'V',
  # 9: 'IX',
  10: 'X',
  # 40: 'XL',
  50: 'L',
  # 90: 'XC',
  100: 'C',
  # 400: 'CD',
  500: 'D',
  # 900: 'CM',
  1000: 'M'
}

import unittest

def get_roman_numeral(arabic_numeral):
    #Recorrer numerals
    roman_numeral = ''
    numerals_arr = numerals.keys()
    #numerals_arr = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    numerals_arr = sorted(numerals_arr, reverse = True)
    # enumerate(list_a) -> el, idx

    for i in numerals_arr: # 1000, 900, ...
        if arabic_numeral - i < 0:
            continue
        while arabic_numeral - i >= 0 :
            arabic_numeral -= i
            roman_numeral += numerals[i]

        if arabic_numeral == 0:
            return roman_numeral

    ###################################################
    roman_numeral = ''
    numerals_arr = numerals.keys()
    numerals_arr = sorted(numerals_arr, reverse = True)

    while arabic_numeral > 0:
      for n in numerals_arr:
        if arabic_numeral - n >= 0: # We can substract this
          arabic_numeral = arabic_numeral - n
          roman_numeral += numerals[n]
          break

    return roman_numeral
    ###################################################

class TestRomanNumeral(unittest.TestCase):

  def test_roman_numeral(self):
    tests = [
      (1, 'I'),
      (4, 'IV'),
      (14, 'XIV'),
      (16, 'XVI'), # 10 + 5 + 1 -> 16 - 10 - 5 - 1 = 0
      (255, 'CCLV'),
      (490, 'CDXC'),
      (1094, 'MXCIV'),
    ]
    for test in tests:
      self.assertEqual(get_roman_numeral(test[0]), test[1])

unittest.main()


from django.urls import path
from .views import licence_list, licence_details, ask_licence, buy_licences, release_licence

urlpatterns = [
    path('/', licence_list),
    path('/details/<int:pk>', licence_details),
    path('/get/<int:pk>', ask_licence),
    path('/buy/<str:company_name>/<int:quantity>', buy_licences),
    path('/release/<int:pk>', release_licence)
]


"""
预测年收入是否超过 5W 美元
参考: https://github.com/tensorflow/models/blob/r1.8.1/official/wide_deep/wide_deep.py
python -m tutorials.wide_deep --help
"""
import os.path as osp
import shutil
import sys
from dataclasses import dataclass

import pandas as pd
from absl import app
from tensorflow import keras

from utils import logger, tf_settings

_CSV_COLUMNS = [
    'age', 'workclass', 'fnlwgt', 'education', 'education_num',
    'marital_status', 'occupation', 'relationship', 'race', 'gender',
    'capital_gain', 'capital_loss', 'hours_per_week', 'native_country',
    'income_bracket'
]

@dataclass
class Context:
    batch_size: int
    train_epochs: int
    epochs_between_evals: int
    model_type: str
    model_dir: str = '/data/models/census_model'
    base_url: str = 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult'
    train_file: str = 'adult.data'
    test_file: str = 'adult.test'

def parse_args():
    app.define_help_flags()
    app.flags.DEFINE_integer('batch_size', 32, 'Batch size for training and evaluation.')
    app.flags.DEFINE_integer('train_epochs', 40, 'The number of epochs used to train.')
    app.flags.DEFINE_integer('epochs_between_evals', 2, 'The number of training epochs to run between evaluations.')
    app.flags.DEFINE_enum('model_type', 'wide_deep', ['wide', 'deep', 'wide_deep'], 'Select model topology.')
    app.parse_flags_with_usage(sys.argv)
    args = app.FLAGS
    return Context(
        batch_size=args.batch_size,
        train_epochs=args.train_epochs,
        epochs_between_evals=args.epochs_between_evals,
        model_type=args.model_type
    )

def preprocess_data(input_file):
    output_file = input_file + '.md'
    with open(output_file, mode='w', encoding='utf-8') as writer:
        with open(input_file, mode='r', encoding='utf-8') as reader:
            for line in reader:
                line = line.strip().replace(', ', ',')
                if not line or ',' not in line:
                    continue
                if line.endswith('.'):
                    line = line[:-1]
                writer.write(line + '\n')
    return output_file

def maybe_download():
    train_path = keras.utils.get_file(ctx.train_file, osp.join(ctx.base_url, ctx.train_file))
    test_path = keras.utils.get_file(ctx.test_file, osp.join(ctx.base_url, ctx.test_file))
    return preprocess_data(train_path), preprocess_data(test_path)

def load_data(y_name=_CSV_COLUMNS[-1]):
    train_path, test_path = maybe_download()
    train = pd.read_csv(train_path, names=_CSV_COLUMNS)
    train_x = dict(train)
    train_y = train_x.pop(y_name)

    test = pd.read_csv(test_path, names=_CSV_COLUMNS)
    test_x = dict(test)
    test_y = test_x.pop(y_name)
    return (train_x, train_y), (test_x, test_y)

def input_fn(inputs, num_epochs, shuffle, batch_size):
    dataset = tf.data.Dataset.from_tensor_slices(inputs)
    if shuffle:
        dataset = dataset.shuffle(1000)
    dataset = dataset.repeat(num_epochs)
    dataset = dataset.batch(batch_size)
    return dataset

def build_feature_columns():
    age = tf.feature_column.numeric_column('age')
    education_num = tf.feature_column.numeric_column('education_num')
    capital_gain = tf.feature_column.numeric_column('capital_gain')
    capital_loss = tf.feature_column.numeric_column('capital_loss')
    hours_per_week = tf.feature_column.numeric_column('hours_per_week')

    education = tf.feature_column.categorical_column_with_vocabulary_list(
        'education', [
            'Bachelors', 'HS-grad', '11th', 'Masters', '9th', 'Some-college',
            'Assoc-acdm', 'Assoc-voc', '7th-8th', 'Doctorate', 'Prof-school',
            '5th-6th', '10th', '1st-4th', 'Preschool', '12th'])

    marital_status = tf.feature_column.categorical_column_with_vocabulary_list(
        'marital_status', [
            'Married-civ-spouse', 'Divorced', 'Married-spouse-absent',
            'Never-married', 'Separated', 'Married-AF-spouse', 'Widowed'])

    relationship = tf.feature_column.categorical_column_with_vocabulary_list(
        'relationship', [
            'Husband', 'Not-in-family', 'Wife', 'Own-child', 'Unmarried',
            'Other-relative'])

    workclass = tf.feature_column.categorical_column_with_vocabulary_list(
        'workclass', [
            'Self-emp-not-inc', 'Private', 'State-gov', 'Federal-gov',
            'Local-gov', '?', 'Self-emp-inc', 'Without-pay', 'Never-worked'])

    occupation = tf.feature_column.categorical_column_with_hash_bucket(
        'occupation', hash_bucket_size=1000)

    age_buckets = tf.feature_column.bucketized_column(
        age, boundaries=[18, 25, 30, 35, 40, 45, 50, 55, 60, 65])

    base_columns = [
        education, marital_status, relationship, workclass, occupation,
        age_buckets,
    ]

    crossed_columns = [
        tf.feature_column.crossed_column(
            [education, 'occupation'], hash_bucket_size=1000),
        tf.feature_column.crossed_column(
            [age_buckets, education, 'occupation'], hash_bucket_size=1000),
    ]

    wide_columns = base_columns + crossed_columns

    deep_columns = [
        age,
        education_num,
        capital_gain,
        capital_loss,
        hours_per_week,
        tf.feature_column.indicator_column(workclass),
        tf.feature_column.indicator_column(education),
        tf.feature_column.indicator_column(marital_status),
        tf.feature_column.indicator_column(relationship),
        # To show an example of embedding
        tf.feature_column.embedding_column(occupation, dimension=8),
    ]

    return wide_columns, deep_columns

def build_model():
    wide_columns, deep_columns = build_feature_columns()
    hidden_units = [100, 75, 50, 25]
    if ctx.model_type == 'wide':
        return tf.estimator.LinearClassifier(
            feature_columns=wide_columns,
            model_dir=ctx.model_dir)
    elif ctx.model_type == 'deep':
        return tf.estimator.DNNClassifier(
            feature_columns=deep_columns,
            hidden_units=hidden_units,
            model_dir=ctx.model_dir)
    else:
        return tf.estimator.DNNLinearCombinedClassifier(
            linear_feature_columns=wide_columns,
            dnn_feature_columns=deep_columns,
            dnn_hidden_units=hidden_units,
            model_dir=ctx.model_dir)

def main():
    logger.info(ctx)
    shutil.rmtree(ctx.model_dir, ignore_errors=True)
    (train_x, train_y), (test_x, test_y) = load_data()

    def train_input_fn():
        label = tf.equal(train_y, '>50K')
        return input_fn((train_x, label), ctx.epochs_between_evals, True, ctx.batch_size)

    def eval_input_fn():
        label = tf.equal(test_y, '>50K')
        return input_fn((test_x, label), 1, False, ctx.batch_size)

    model = build_model()
    template = 'step: {global_step:d}, accuracy: {accuracy:0.4f}, precision: {precision:0.4f}, recall: {recall:0.4f}, auc: {auc:0.4f}, loss: {loss:0.2f}'
    for n in range(ctx.train_epochs // ctx.epochs_between_evals):
        model.train(input_fn=train_input_fn)
        eval_result = model.evaluate(input_fn=eval_input_fn)
        logger.info(template.format(**eval_result))

if __name__ == '__main__':
    ctx = parse_args()
    tf = tf_settings()
    main()


import random
n = int(input("Maksimal təxmin etmə şansını daxil edin:->"))
number = random.randint(1, 99)
s = n

while n >= s > 0:
    texmin = int(input("Eded daxil edin"))
    s = s - 1
    if texmin == number:
        print("Tebrikler dogru texmin elediniz")
        break

    elif texmin < number and s > 0 :
        print("Daha boyuk daxil edin")

    elif texmin > number and s > 0:
        print("Daha kicik eded daxil edin")

    else:
        print("****************************\nSansiniz bitdi....\nTeessufki uduzdunuz:")


#DriveMan CLI by OxxoCode
#https://github.com/OxxoCode/DriveMan

import argparse

import gdrive

class DriveMan:
    #Parse any DriveMan arguments passed by the user
    def parse_args(self):
        self.parser = argparse.ArgumentParser()
        self.parser.add_argument('-user', '--username',         nargs=1, help="Specify the username/alias for the account you are accessing")
        self.parser.add_argument('-sv', '--service',            nargs=1, help="Specify the service you are using (gdrive, dbox)")
        self.parser.add_argument('-c', '--copy',                nargs=2, help="Copy a file or folder")
        self.parser.add_argument('-d', '--download',            nargs=2, help="Download a file or folder")
        self.parser.add_argument('-u', '--upload',              nargs='+', help="Copy a file or folder")
        self.parser.add_argument('-m', '--move',                nargs=2, help="Move a file a file or folder")
        self.parser.add_argument('-meta', '--metadata',         nargs=1, help="Get the metadata of a file or folder")
        self.parser.add_argument('-l', '--list',                nargs=1, help="List all files and folders in a folder")
        self.parser.add_argument('-r', '--remove',              nargs=1, help="Remove/delete a file or folder")
        self.parser.add_argument('-s', '--size',                nargs=1, help="Get the size a file or folder")
        self.parser.add_argument('-nohash', '--no-hash-check',  nargs=1, help="Skip hash checking when uploading/downloading a file")
        self.args = self.parser.parse_args()

    #Handle authentication for each service, determined by value of --service
    def auth(self):
        s = self.args.service[0].lower()
        if s == "gdrive":
            self.gd = gdrive.GDrive()
            self.gd.auth( self.args.username[0] )
        elif s == "dbox":
            print('Dropbox is not currently supported. Coming soon!')
        else:
            print("ERROR: Must specify the service being used with -sv or --service.")
            print("Available services are: GDrive")

    #Core functionality of DriveMan
    def run(self):
        #Obtain list of all shared drives accessible by user.
        #Necessary for some functions which behave differently if a file is located in a shared drive
        self.gd.listSharedDrives()

        if self.args.copy:
            self.gd.copy( self.gd.cleanInput(self.args.copy[0]) , self.gd.cleanInput(self.args.copy[1]) )

        elif self.args.download: #Has some bugs - getting HTTP Errors on some files for an unknown reason. Also seems to look at files twice?
            self.gd.download( self.gd.cleanInput(self.args.download[0]) , self.gd.cleanInput(self.args.download[1]) )

        elif self.args.upload:
            #Could potentially improve, but it's a lot of additional code that I can just fix with an if-else, so eh.
            #https://stackoverflow.com/questions/4194948/python-argparse-is-there-a-way-to-specify-a-range-in-nargs
            if len(self.args.upload) == 2:
                self.gd.upload( self.gd.cleanInput(self.args.upload[0]) , self.gd.cleanInput(self.args.upload[1]) )
            else:
                self.gd.upload( self.gd.cleanInput(self.args.upload[0]) )

        elif self.args.move:
            self.gd.move( self.gd.cleanInput(self.args.move[0]) , self.gd.cleanInput(self.args.move[1]) )

        elif self.args.list:
            self.gd.list( self.gd.cleanInput(self.args.list[0]) )

        elif self.args.remove:
            self.gd.remove( self.gd.cleanInput(self.args.remove[0]) )

        elif self.args.size:
            self.gd.size( self.gd.cleanInput(self.args.size[0]) )

        elif self.args.metadata:
            meta =  self.gd.getMetadata( self.gd.cleanInput(self.args.metadata[0]))
            for key in meta.keys():
                print('{} : {}'.format(key, meta[key]))

def main():
    driveman = DriveMan()

    driveman.parse_args()
    driveman.auth()
    driveman.run()

if __name__ == '__main__':
    main()


# The game Bot Clean took place in a deterministic environment. In this
# version, the bot is given 200 moves to clean as many dirty cells as possible.
# The grid initially has 1 dirty cell. When the bot cleans this cell, a new
# cell in the grid is made dirty. The new cell can be anywhere in the grid.

# The bot here is positioned at the top left corner of a 5*5 grid. Your task
# is to move the bot to appropriate dirty cell and clean it.

# Link: https://www.hackerrank.com/challenges/botcleanr

def next_move(posr, posc, board):
    dirt_r = dirt_c = 0
    for i in range(5):
        for j in range(5):
            if board[i][j]=='d':
                dirt_r,dirt_c = i, j

    if dirt_c < posc:
        print('LEFT')
    elif dirt_c  > posc:
        print('RIGHT')
    elif dirt_r < posr:
        print('UP')
    elif dirt_r > posr:
        print('DOWN')
    else:
        print('CLEAN')

if __name__ == "__main__":
    pos = [int(i) for i in input().strip().split()]
    board = [[j for j in input().strip()] for i in range(5)]
    next_move(pos[0], pos[1], board)


import requests
import base64
import os

# Obtained from your app dashboard
CLIENT_ID = os.getenv("SPOTIFY_CLIENT_ID")
CLIENT_SECRET = os.getenv("SPOTIFY_CLIENT_SECRET")
# Obtained after the initial user authorization request
CODE = os.getenv("CODE")
STATE = os.getenv("STATE")
# Obtained in the response body when requesting the access token
ACCESS_TOKEN = os.getenv("SPOTIFY_ACCESS_TOKEN")
REFRESH_TOKEN = os.getenv("SPOTIFY_REFRESH_TOKEN")

AUTH_URL = "https://accounts.spotify.com/api/token"

class SpotifyConnector:
    def get_auth_base64(self, id, secret):
        """Used to encode our Client ID and Client Secret when retriving your refresh token"""
        message = f"{id}:{secret}"
        message_bytes = message.encode("ascii")
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode("ascii")
        auth_header = {"Authorization": "Basic" + " " + base64_message}
        return auth_header

    def getToken(self, CLIENT_ID, CLIENT_SECRET):
        """Used to retrieve your access token AFTER the user initially accepts your request"""
        message = f"{CLIENT_ID}:{CLIENT_SECRET}"
        message_bytes = message.encode("ascii")
        base64_bytes = base64.b64encode(message_bytes)
        base64_message = base64_bytes.decode("ascii")
        auth_header = {"Authorization": "Basic" + " " + base64_message}
        auth_data = {
            "grant_type": "authorization_code",
            "code": CODE,
            "redirect_uri": "https://example.com",
        }
        r = requests.post(AUTH_URL, headers=auth_header, data=auth_data)
        response = r.json()

    def get_refresh_token(self):
        """Used to generate a refresh token"""
        refresh_body = {
            "grant_type": "refresh_token",
            "refresh_token": REFRESH_TOKEN,
        }
        headers = self.get_auth_base64(CLIENT_ID, CLIENT_SECRET)
        token = requests.post(AUTH_URL, headers=headers, data=refresh_body).json()
        return token["access_token"]


import os
import sys

from PyQt5 import QtWidgets, QtCore
from pyqtgraph import PlotWidget, plot
import pyqtgraph as pg

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.graphWidget = pg.PlotWidget()
        self.graphWidget.setTitle("Temp over Time")
        self.graphWidget.setStyleSheet("QGraphicsTextItem { color:green;}")
        self.setCentralWidget(self.graphWidget)

        hour = [1,2,3,4,5,6,7,8,9,10]
        temperature = [30, 32, 34, 32, 33, 31, 29, 32, 35, 45]

        self.graphWidget.setBackground('w')
        self.graphWidget.setFontColor = (0,0,0)

        pen = pg.mkPen(color=(0,0,255), width=2,style=QtCore.Qt.DashLine)

        self.graphWidget.plot(hour,        \
                              temperature, \
                              pen=pen,     \
                              symbol='+',  \
                              symbolSize=30)

def main():
    app = QtWidgets.QApplication(sys.argv)
    qssfile="./styles.css"
    with open(qssfile,"r") as fh:
        app.setStyleSheet(fh.read())
    app.setStyleSheet("QGraphicsTextItem { color:green;}")
    window = MainWindow()
    #window.setStyleSheet("border:5px solid blue; padding:10px;")

    window.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


from httprunner.utils import get_platform

def __get_variables_to_list(config_vars):
    variables_list = []
    for k, v in config_vars.items():
        variables_list.append({"key": k, "value": v})
    return variables_list

def get_summary(test_results):
    summary = {
        "success": True,
        "test_success": True,
        "stat": [{
            "test_success": True,
            "total": len(test_results),
            "success": 0,
            "failed": 0,
            "duration": 0,
            "start_time": "",
            "platform": get_platform()
        }],
        "time": {
            "duration": 0,
            "start_time": ""
        },
        "platform": get_platform(),
        "details": test_results
    }
    for test_result in test_results:
        if test_result["test_success"]:
            summary["stat"][0]["success"] += 1
        else:
            summary["stat"][0]["failed"] += 1
        summary["success"] &= test_result["success"]
        summary["test_success"] &= test_result["test_success"]
        summary["stat"][0]["test_success"] = summary["test_success"]
    return summary


#!/usr/bin/env python3

import os

from jmapc import (
    Address,
    Client,
    Email,
    EmailAddress,
    EmailBodyPart,
    EmailBodyValue,
    EmailHeader,
    EmailSubmission,
    Envelope,
    Identity,
    MailboxQueryFilterCondition,
    Ref,
)
from jmapc.methods import (
    EmailSet,
    EmailSubmissionSet,
    EmailSubmissionSetResponse,
    IdentityGet,
    IdentityGetResponse,
    MailboxGet,
    MailboxGetResponse,
    MailboxQuery,
)

TEST_EMAIL_BODY = f"""
Hello from {__file__}!

If you're reading this email in your inbox, the example worked successfully!

This email was created with the JMAP API and sent to yourself using the first
identity's email address in your account.
""".strip()

# Create and configure client
client = Client.create_with_api_token(
    host=os.environ["JMAP_HOST"], api_token=os.environ["JMAP_API_TOKEN"]
)

# Retrieve the Mailbox ID for Drafts
results = client.request(
    [
        MailboxQuery(filter=MailboxQueryFilterCondition(name="Drafts")),
        MailboxGet(ids=Ref("/ids")),
        IdentityGet(),
    ]
)

# From results, second result, MailboxGet instance, retrieve Mailbox data
assert isinstance(
    results[1].response, MailboxGetResponse
), "Error in Mailbox/get method"
mailbox_data = results[1].response.data
if not mailbox_data:
    raise Exception("Drafts not found on the server")

# From the first mailbox result, retrieve the Mailbox ID
drafts_mailbox_id = mailbox_data[0].id
assert drafts_mailbox_id

print(f"Drafts has Mailbox ID {drafts_mailbox_id}")

# From results, third result, IdentityGet instance, retrieve Identity data
assert isinstance(
    results[2].response, IdentityGetResponse
), "Error in Identity/get method"
identity_data = results[2].response.data
if not identity_data:
    raise Exception("No identities found on the server")

# Retrieve the first Identity result
identity = identity_data[0]
assert isinstance(identity, Identity)

print(f"Found identity with email address {identity.email}")

# Create and send an email
results = client.request(
    [
        # Create a draft email in the Drafts mailbox
        EmailSet(
            create=dict(
                draft=Email(
                    mail_from=[
                        EmailAddress(name=identity.name, email=identity.email)
                    ],
                    to=[
                        EmailAddress(name=identity.name, email=identity.email)
                    ],
                    subject=f"Email created with jmapc's {__file__}",
                    keywords={"$draft": True},
                    mailbox_ids={drafts_mailbox_id: True},
                    body_values=dict(
                        body=EmailBodyValue(value=TEST_EMAIL_BODY)
                    ),
                    text_body=[
                        EmailBodyPart(part_id="body", type="text/plain")
                    ],
                    headers=[
                        EmailHeader(name="X-jmapc-example-header", value="yes")
                    ],
                )
            )
        ),
        # Send the created draft email, and delete from the Drafts mailbox on
        # success
        EmailSubmissionSet(
            on_success_destroy_email=["#emailToSend"],
            create=dict(
                emailToSend=EmailSubmission(
                    email_id="#draft",
                    identity_id=identity.id,
                    envelope=Envelope(
                        mail_from=Address(email=identity.email),
                        rcpt_to=[Address(email=identity.email)],
                    ),
                )
            ),
        ),
    ]
)
# Retrieve EmailSubmission/set method response from method responses
email_send_result = results[1].response
assert isinstance(
    email_send_result, EmailSubmissionSetResponse
), f"Error sending test email: f{email_send_result}"

# Retrieve sent email metadata from EmailSubmission/set method response
assert email_send_result.created, "Error retrieving sent test email"
sent_data = email_send_result.created["emailToSend"]
assert sent_data, "Error retrieving sent test email data"

# Print sent email timestamp
print(f"Test email sent to {identity.email} at {sent_data.send_at}")

# Example output:
#
# Found the mailbox named Inbox with ID deadbeef-0000-0000-0000-000000000001
# Found identity with email address ness@onett.example.com
# Test email sent to ness@onett.example.com at 2022-01-01 12:00:00+00:00


import asyncio
import json
from aiohttp import web
from rpc_client import RemoteDictRpcClient
from loguru import logger
import sys

logger.remove()
logger.add(sys.stdout, format="{time:HH:mm:ss} - {level} - {message}", level="INFO")

routes = web.RouteTableDef()

@routes.get('/get_value')
async def get_from_remote_dict(request):
    # make sure 'key' parameter exists
    try:
        key = request.query['key']
        message = {"command": "get", 'key': key}
    except KeyError as ke:
        msg = "Missing query parameter: {}".format(ke)
        response = {"error": msg}
        logger.error(msg)
        return web.json_response(response)

    # use existing rabbit connection
    rpc_client = request.app['rpc_client']

    # send get task to remote server via rabbit and wait for response no longer than 2 secs
    try:
        response = await asyncio.wait_for(rpc_client.call(message), timeout=2.0)
        return web.json_response(json.loads(response))
    except asyncio.TimeoutError:
        msg = "Timeout on waiting for server response"
        response = {"error": msg}
        logger.error(msg)
        return web.json_response(response)
    except Exception as e:
        msg = "An error occurred during request processing"
        response = {"error": msg}
        logger.error(e)
        return web.json_response(response)

@routes.post("/set_value")
async def set_to_remote_dict(request):
    # make sure 'key' and 'value' params are passed, validate value - only floats accepted
    try:
        key = request.query['key']
        value = float(request.query['value'])
        message = {"command": "set", 'key': key, 'value': value}
    except KeyError as ke:
        response = {"error": "Missing query parameter: {}".format(ke)}
        return web.json_response(response)

    except ValueError as e:
        response = {"error": "Incorrect type of value parameter: {}".format(e)}
        return web.json_response(response)

    # use existing rabbit connection
    rpc_client = request.app['rpc_client']

    # send set task to remote server via rabbit and wait for response no longer than 2 secs
    try:
        response = await asyncio.wait_for(rpc_client.call(message), timeout=2.0)
        return web.json_response(json.loads(response))
    except asyncio.TimeoutError:
        msg = "Timeout on waiting for server response"
        response = {"error": msg}
        logger.error(msg)
        return web.json_response(response)
    except Exception as e:
        msg = "An error occurred during request processing"
        response = {"error": msg}
        logger.error(e)
        return web.json_response(response)

async def on_startup(_app):
    logger.info("Application startup...")
    client = await RemoteDictRpcClient().connect()
    _app['rpc_client'] = client

async def on_shutdown(_app):
    logger.info("Gracefully shutting client app down")
    await _app['rpc_client'].disconnect()

if __name__ == "__main__":
    app = web.Application()
    app.on_startup.append(on_startup)
    app.on_shutdown.append(on_shutdown)
    app.add_routes(routes)
    web.run_app(app, port=8080)


import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder

from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score

from sklearn.model_selection import cross_val_score

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix, plot_confusion_matrix

# Load the dataset
column_names = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class']
data = pd.read_csv('data/bezdekIris.data', names=column_names)

# Encode class labels as integers
le = LabelEncoder()
data['class'] = le.fit_transform(data['class'])

# Split the dataset into features (X) and labels (y)
X = data.drop('class', axis=1)
y = data['class']

# Split the dataset into training, validation, and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
X_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5, random_state=42)

# Hyperparameter tuning using GridSearchCV
knn_params = {'n_neighbors': list(range(1, 31))}
dt_params = {'max_depth': list(range(1, 11))}
svm_params = {'C': [0.1, 1, 10, 100], 'kernel': ['linear', 'rbf']}

knn = GridSearchCV(KNeighborsClassifier(), knn_params, cv=5)
dt = GridSearchCV(DecisionTreeClassifier(random_state=42), dt_params, cv=5)
svm = GridSearchCV(SVC(random_state=42), svm_params, cv=5)

# Train the models
knn.fit(X_train, y_train)
dt.fit(X_train, y_train)
svm.fit(X_train, y_train)

# Evaluate the models on the validation set
knn_val_preds = knn.predict(X_val)
dt_val_preds = dt.predict(X_val)
svm_val_preds = svm.predict(X_val)

knn_val_acc = accuracy_score(y_val, knn_val_preds)
dt_val_acc = accuracy_score(y_val, dt_val_preds)
svm_val_acc = accuracy_score(y_val, svm_val_preds)

print(f"k-NN Validation Accuracy: {knn_val_acc}")
print(f"Decision Tree Validation Accuracy: {dt_val_acc}")
print(f"SVM Validation Accuracy: {svm_val_acc}")

# Perform 5-fold cross-validation for each model
knn_cv_scores = cross_val_score(KNeighborsClassifier(**knn.best_params_), X, y, cv=5)
dt_cv_scores = cross_val_score(DecisionTreeClassifier(**dt.best_params_, random_state=42), X, y, cv=5)
svm_cv_scores = cross_val_score(SVC(**svm.best_params_, random_state=42), X, y, cv=5)

# Calculate the mean cross-validation accuracy for each model
knn_cv_mean_acc = knn_cv_scores.mean()
dt_cv_mean_acc = dt_cv_scores.mean()
svm_cv_mean_acc = svm_cv_scores.mean()

print(f"k-NN 5-Fold Cross-Validation Mean Accuracy: {knn_cv_mean_acc}")
print(f"Decision Tree 5-Fold Cross-Validation Mean Accuracy: {dt_cv_mean_acc}")
print(f"SVM 5-Fold Cross-Validation Mean Accuracy: {svm_cv_mean_acc}")

# Calculate metrics for each model using test set
for model, name in [(knn, "k-NN"), (dt, "Decision Tree"), (svm, "SVM")]:
    preds = model.predict(X_test)
    precision = precision_score(y_test, preds, average='macro')
    recall = recall_score(y_test, preds, average='macro')
    f1 = f1_score(y_test, preds, average='macro')

    print(f"{name} Test Precision: {precision}")
    print(f"{name} Test Recall: {recall}")
    print(f"{name} Test F1-score: {f1}")
    print()

    # Plot confusion matrix
    plot_confusion_matrix(model, X_test, y_test)
    plt.title(f"{name} Confusion Matrix")
    plt.show()

# Function to plot decision boundaries for 2D data
def plot_decision_boundary(model, X, y, ax, title):
    h = .02
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    ax.contourf(xx, yy, Z, alpha=0.8)
    scatter = ax.scatter(X[:, 0], X[:, 1], c=y, edgecolors='k', marker='o', s=50)
    ax.set_xlim(X[:, 0].min() - 0.5, X[:, 0].max() + 0.5)
    ax.set_ylim(X[:, 1].min() - 0.5, X[:, 1].max() + 0.5)
    ax.set_xticks(())
    ax.set_yticks(())
    ax.set_title(title)
    ax.legend(*scatter.legend_elements(), title="Classes")

# Select two features for visualization
X_train_2d = X_train.iloc[:, :2].values
X_test_2d = X_test.iloc[:, :2].values

# Train models with 2D data
knn_2d = KNeighborsClassifier(**knn.best_params_).fit(X_train_2d, y_train)
dt_2d = DecisionTreeClassifier(**dt.best_params_, random_state=42).fit(X_train_2d, y_train)
svm_2d = SVC(**svm.best_params_, random_state=42).fit(X_train_2d, y_train)

# Plot decision boundaries
fig, axes = plt.subplots(1, 3, figsize=(18, 5))
plot_decision_boundary(knn_2d, X_test_2d, y_test.values, axes[0], "k-NN Decision Boundary")
plot_decision_boundary(dt_2d, X_test_2d, y_test.values, axes[1], "Decision Tree Decision Boundary")
plot_decision_boundary(svm_2d, X_test_2d, y_test.values, axes[2], "SVM Decision Boundary")

plt.show()


# n명의 사람의 소득이 주어졌을 때 이 중 평균 이하의 소득을 가진 사람들의 수를 출력

T = int(input())
for test_case in range(1, T + 1):
    num = int(input())
    money = list(map(int,input().split(' ')))
    sum = 0
    for el in money:
        sum += el
    avg = sum / num
    res = 0
    for el in money:
        if avg >= el:
            res += 1
    print('#'+str(test_case),res)