import math
import numpy as np

def f1_scores(labels, logits, predictions, label_ids, label_sequences, mode=[0, 0, 0]):
    modified_predictions = np.copy(predictions)
    for i in range(labels.shape[0]):
        if mode[0] == 1:
            modified_predictions[i, :] = remove_isolated(modified_predictions[i, :], logits[i, :], label_ids, label_sequences)
        if mode[0] == 2:
            modified_predictions[i, :] = connect_isolated(modified_predictions[i, :], logits[i, :], label_ids, label_sequences)
        if mode[1] == 1:
            modified_predictions[i, :] = remove_dangling(modified_predictions[i, :], logits[i, :], label_ids, label_sequences)
        if mode[2] == 1:
            modified_predictions[i, :] = select_argmax_su(modified_predictions[i, :], logits[i, :], label_ids, label_sequences)
        if mode[2] == 2:
            modified_predictions[i, :] = select_argmax_path(modified_predictions[i, :], logits[i, :], label_ids, label_sequences)

    true_positive = (labels * (labels == modified_predictions)).sum(0)[labels.sum(0) > 0]
    true_negative = ((1. - labels) * (labels == modified_predictions)).sum(0)[labels.sum(0) > 0]
    false_positive = ((1. - labels) * (labels != modified_predictions)).sum(0)[labels.sum(0) > 0]
    false_negative = (labels * (labels != modified_predictions)).sum(0)[labels.sum(0) > 0]

    micro_precision = true_positive.sum() / (true_positive.sum() + false_positive.sum())
    micro_recall = true_positive.sum() / (true_positive.sum() + false_negative.sum())
    micro_f1 = 2 * micro_precision * micro_recall / (micro_precision + micro_recall)

    precisions = true_positive / (true_positive + false_positive + 1e-8)
    recalls = true_positive / (true_positive + false_negative + 1e-8)

    macro_precision = precisions.mean()
    macro_recall = recalls.mean()
    macro_f1 = 2 * macro_precision * macro_recall / (macro_precision + macro_recall)

    f1s = 2 * precisions * recalls / (precisions + recalls + 1e-8)
    average_f1 = f1s.mean()

    return {'micro-f1': micro_f1, 'macro-f1': macro_f1, 'average-f1':average_f1}

# post-processing for mandatory leaf assumption
def remove_isolated(prediction, logits, label_ids, paths):
    for path in paths:
        if prediction[path[0]]:
            for topic in path[1:]:
                if not prediction[topic]:
                    prediction[path[0]] = False
                    break
    return prediction

def connect_isolated(prediction, logits, label_ids, paths):
    for path in paths:
        if prediction[path[0]]:
            for topic in path[1:]:
                prediction[topic] = True
    return prediction

def remove_dangling(prediction, logits, label_ids, paths):
    dangling = [True for _ in label_ids]
    for path in paths:
        if prediction[path[0]]:
            for topic in path:
                dangling[topic] = False
    for label in range(len(label_ids)):
        if dangling[label]:
            prediction[label] = False
    return prediction

def select_argmax_su(prediction, logits, label_ids, paths):
    flag = True
    best_p = None
    best_path = []
    for path in paths:
        if prediction[path[0]]:
            flag = False
            break
        else:
            p = logits[path[0]]
            if best_p is None or p > best_p:
                best_p = p
                best_path = path
    if flag:
        for topic in best_path:
            prediction[topic] = True
    return prediction

def sigmoid(x):
    return 1 / (1 + math.exp(-x))

def select_argmax_path(prediction, logits, label_ids, paths):
    flag = True
    best_p = None
    best_path = []
    for path in paths:
        p = 1
        if prediction[path[0]]:
            flag = False
            break
        else:
            for topic in path:
                p = p * sigmoid(logits[topic])
            p = p ** (1. / len(path))
        if best_p is None or p > best_p:
            best_p = p
            best_path = path
    if flag:
        for topic in best_path:
            prediction[topic] = True
    return prediction


# https://flask.palletsprojects.com/en/2.2.x/patterns/fileuploads/
# Need to launch the server first

from flask import Flask, g
from flask_cors import CORS
from routes.auth import auth
from routes.scans import scans
from routes.global_data import global_data

app = Flask(__name__)
app.register_blueprint(scans, url_prefix='/api/scans')
app.register_blueprint(auth, url_prefix='/api/auth')
app.register_blueprint(global_data, url_prefix='/api/global_data')

CORS(app)

# Closes the connection to DB if not already done.
@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)

    if db is not None:
        db.close()

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=False)  # Enlever le debug true


import sys

sys.stdin = open('input.txt', 'r')

# solution!!
# 수열 추측하기
def DFS(L, sum):
    if L == n and sum == f:
        for x in p:
            print(x, end=" ")
        # f를 충족하는 값이 여러번 나올 수 있으므로 그냥 처음 나온값 출력후 바로 시스템 종료
        sys.exit(0)
    else:
        # 수열 만든다
        for i in range(1, n+1):
            if ch[i] == 0:
                ch[i] = 1
                p[L] = i
                DFS(L+1, sum+(p[L]*b[L]))
                ch[i] = 0

if __name__ == "__main__":
    n, f = map(int, input().split())
    # 수열 만들어 나감
    p = [0] * n
    # 초기화[1,1,1,1]
    b = [1] * n
    ch = [0] * (n+1)
    # num = [3C0, 3C1, 3C2 , 3C3]
    for i in range(1, n):
        b[i] = b[i-1] * (n-i) // i

    DFS(0, 0)


import os
import numpy as np
import scipy as sp
import scipy.signal as signal
import scipy.fftpack as fft
import scipy.io as io
import scipy.io.wavfile
import matplotlib.pyplot as plt
import rtmidi
from rtmidi import midiconstants
import pyaudio

midiout = rtmidi.MidiOut()
midiout.open_virtual_port('TICS-MIDI')

# Define concert A.
A4_freq = 440
A4_midi = 69
freqs = np.zeros(128, dtype=int)
for i in range(0, 128):
    freqs[i] = round(A4_freq * (2**((i - A4_midi)/12)))

def get_pitch_strengths(fft_data):
    # Try to compensate for rounding the frequencies to ints by including their neighbors.
    return np.abs(fft_data)[freqs-1] + np.abs(fft_data)[freqs] + np.abs(fft_data)[freqs+1]

window_size = 22050
window = signal.hanning(window_size)

pa = pyaudio.PyAudio()

sample_rate = 44100
stream = pa.open(format = pyaudio.paInt16,
                 channels = 1,
                 rate = sample_rate,
                 input = True,
                 output = False,
                 frames_per_buffer = 1024)

data = np.zeros(22050)
last_value = None
i = 0
while stream.is_active():
    raw = stream.read(1024)
    buffer = np.copy(np.frombuffer(raw, dtype=np.int16))
    data[:-1024] = data[1024:]
    data[-1024:] = buffer

    i += 1
    if i >= 10:
        i = 0
    else:
        continue
    out = fft.rfft(window * data)
    out[np.arange(0,80)] = 0
    pitch_strengths = get_pitch_strengths(out)
    value = np.argmax(pitch_strengths)
    if pitch_strengths[value] < 20000:
        value = 0
    if value != last_value:
        onset = i / sample_rate
        if last_value:
            midiout.send_message([midiconstants.NOTE_OFF, last_value, 127])
        if pitch_strengths[value] < 10000000:
            value = 0
        if value:
            midiout.send_message([midiconstants.NOTE_ON, value, 127])
            print(value, pitch_strengths[value], onset)
        last_value = value

stream.close()


from django.contrib.auth.models import User
from django.db import models
from django.utils.text import slugify

Categories = (
    ('HTML', 'HTML'),
    ('CSS', 'CSS'),
    ('JavaScript', 'JavaScript'),
    ('JSON', 'JSON'),
    ('AJAX', 'AJAX'),
    ('Python', 'Python'),
    ('Django', 'Django')
)

class Book(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)
    description = models.TextField()
    url = models.URLField(max_length=200)
    updated_at = models.DateTimeField(auto_now=True)
    created_at = models.DateTimeField(auto_now=True)
    category = models.ForeignKey(
        'Category', on_delete=models.SET_NULL, null=True, blank=True)
    favorite = models.BooleanField(
        'Favorite', null=True, blank=True)

    def __str__(self):
        return f'Book title: {self.title} Author: {self.author} Description: {self.description} URL: {self.url} Category: {self.category} Favorite: {self.favorite}'

    class Meta:
        ordering = ['-created_at']

class Category(models.Model):
    name = models.CharField(max_length=100, choices=Categories)
    slug = models.SlugField(null=False, unique=True)

    def __str__(self):
        return f'{self.name}'

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.name)
        return super().save(*args, **kwargs)

class Favorite(models.Model):
    person = models.ForeignKey(
        User, related_name='+', on_delete=models.CASCADE)
    book = models.ForeignKey(
        Book, related_name='+', on_delete=models.CASCADE)

    def __str__(self):
        return f'Person: {self.person}, Book: {self.book.pk}'

# class User(AbstractUser)


from scapy.all import *
from scapy.layers.inet import IP, UDP, Ether
from scapy.layers.dns import DNS, DNSQR, DNSRR

# Define the DNS server IP address
dns_server_ip = "5.29.14.36"

# Define the domain name to query
domain_name = b"google.com"

# Create the DNS query packet
dns_query = DNSQR(qname=domain_name)

dns_pkt = Ether() / IP(dst=dns_server_ip) / UDP(sport = 9999,dport=53) / DNS(rd=1, qd=dns_query)

# Define the function to handle incoming DNS responses
def handle_dns_response(pkt):
    print("tre")
    if pkt.haslayer(DNSRR) and pkt[DNS].id == dns_pkt[DNS].id:
        ip_address = pkt[DNSRR].rdata
        print(f"The IP address of {domain_name.decode('utf-8')} is {ip_address}")

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


import extra_keras_metrics
from keras.layers import Layer, Dense
from keras.models import Model
from typing import Tuple, List

def head(layer: Layer)->Layer:
    return Dense(1, activation="sigmoid")(layer)

def model(inputs: Tuple[Layer, Layer], output: Layer, metrics:List=None)->Model:
    model = Model(
        inputs=inputs,
        outputs=[head(output)]
    )
    model.compile(
        optimizer="nadam",
        loss="binary_crossentropy",
        metrics=["auprc", "auroc", "accuracy"] if metrics is None else metrics
    )
    return model


import unittest
import warnings

from py2cytoscape.data.cynetwork import CyNetwork
from py2cytoscape.data.cyrest_client import CyRestClient
from py2cytoscape.data.util_network import NetworkUtil

class CheckResponseTests(unittest.TestCase):

    def setUp(self):
        self.client = CyRestClient()
        self.client.network.delete_all()
        locations = [
            'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif'
        ]
        self.network = self.client.network.create_from(locations)
        view_id_list = self.network.get_views()
        self.view = self.network.get_view(view_id_list[0], format='view')

    def test_network_view(self):
        # 'arc' is AssertRaisesContext
        with self.assertRaises(Exception) as arc:
            # Try to request with non-integer values
            self.view.update_network_view(visual_property="NETWORK_CENTER_X_LOCATION",
                                          value="non-integer-value")
        # end of with

        res = arc.exception.response
        self.assertEqual(res.status_code, 500)
        print(arc.exception.args[0]) # HTTP status code information
        print(arc.exception.args[1]) # Error message
    # end of def

    def test_node_views(self):
        d_nodes = self.view.get_node_views_as_dict()
        vals = {}
        for node_id in d_nodes:
            vals[node_id] = "non-integer-value" # Non-integer
        with self.assertRaises(Exception) as arc:
            # Try to request with non-integer values
            self.view.update_node_views(visual_property="NODE_X_LOCATION", values=vals)
        # end of with

        res = arc.exception.response
        self.assertEqual(res.status_code, 500)
        print(arc.exception.args[0]) # HTTP status code information
        print(arc.exception.args[1]) # Error message
    # end of def

    def test_edge_views(self):
        d_edges = self.view.get_edge_views_as_dict()
        vals = {}
        for edge_id in d_edges:
            vals[edge_id] = "non-integer-value`" # Non-integer
        with self.assertRaises(Exception) as arc:
            # Try to request with non-integer values
            self.view.update_edge_views(visual_property="EDGE_LABEL_WIDTH", values=vals)
        # end of with

        res = arc.exception.response
        self.assertEqual(res.status_code, 500)
        print(arc.exception.args[0]) # HTTP status code information
        print(arc.exception.args[1]) # Error message
    # end of def

# end of class

if __name__ == '__main__':
    unittest.main(warnings = 'ignore')


from machine import Pin
from homie.node import HomieNode
from homie.property import HomieProperty
from homie.constants import ENUM

class HeatPumpControllerNode(HomieNode):

    pumpPin = Pin(2, Pin.OUT)

    def __init__(self):
        super().__init__(id="HeatPump", name="HeatPump", type="Controller")

        self.heatPumpProperty = HomieProperty(
            id="heatPump",
            name="heatPump",
            datatype=ENUM,
            format="on,off",
            settable=False,
            default="on",
        )
        self.add_property(self.heatPumpProperty)

    def on(self):
        self.pumpPin.on()
        self.heatPumpProperty.value = "on"

    def off(self):
        self.pumpPin.off()
        self.heatPumpProperty.value = "off"


from django.shortcuts import render,HttpResponse
from django.views.generic.list import ListView
import sys
sys.path.append("..")
from ZpModel.models import Zp,CV,CV2Zp,Com
from django.db.models import Q
import re
from functools import reduce
import operator
from django.contrib.auth.models import User

def page_not_found(request):
    return render(request,'404.html')

def loginfo(request):
    user = request.user
    if user != None and user != "" and not user.is_anonymous:
        context = '&nbsp' + str(user) + '' \
                '&nbsp&nbsp&nbsp 注销'
    else:
        context = '&nbsp&nbsp登录'
    return context

def me(request):
    context = {}
    context['user'] = loginfo(request)

    if request.user.is_authenticated:
        u = User.objects.get(username=request.user)
        try:
            cv = CV.objects.get(user_id=u.id)
            context['name'] = u.first_name
            context['sex'] = cv.sex
            context['age'] = cv.age
            context['edu'] = cv.edu
            context['tc'] = cv.super
            context['jn'] = cv.tech
            context['tel'] = cv.tel
            context['email'] = u.email
            context['sal1'] = cv.K1
            context['sal2'] = cv.K2
            context['workingExp']=cv.exp
            context['wantJob']=cv.wantJob
            context['school']=cv.school
            context['gzjl']=cv.gzjl
            context['jybj'] = cv.jybj
            context['zwjs']=cv.zwjs
            for k in context.keys():
                if context[k]==None:
                    context[k]=""
        except:
            if u.last_name == 'pt':
                cv = CV(user_id=u.id)
                cv.save()
            else:
                return ZpListView.as_view()(request)
    else:#如果没有登录就返回注册
        return register(request)
    return render(request,'me.html',context)

def submit_me(request):
    context = {}
    if not request.user.is_authenticated:
        return register(request)

    user = request.GET.get('user')
    sex = request.GET.get('sex')
    edu = request.GET.get('edu')
    age = request.GET.get('age')
    super = request.GET.get('tc')
    tech = request.GET.get('jn')
    tel = request.GET.get('tel')
    email = request.GET.get('email')
    K1 = request.GET.get('sal1')
    K2 = request.GET.get('sal2')
    exp = request.GET.get('workingExp')
    wantJob = request.GET.get('wantJob')
    school= request.GET.get('school')
    gzjl = request.GET.get('gzjl')
    jybj = request.GET.get('jybj')
    zwjs = request.GET.get('zwjs')

    u = User.objects.get(username=request.user)
    cv = CV.objects.get(user_id=u.id)
    cv.age = age if age or None else None

    if exp or None:#None 和 ""都不执行
        cv.exp = exp
    else:
        cv.exp=None
    if K1 or None:
        cv.K1=K1
    else:
        cv.K1=None
    if K2 or None:
        cv.K2 = K2
    else:
        cv.K2=None
    cv.sex = sex
    cv.edu=edu
    cv.super=super
    cv.tech=tech
    cv.tel=tel
    u.email=email
    cv.wantJob=wantJob
    cv.school=school
    cv.gzjl=gzjl
    cv.jybj=jybj
    cv.zwjs=zwjs
    cv.save()

    u.first_name=user
    u.save()
    return me(request)

def register(request):
    context = {}
    context['user'] = loginfo(request)
    return render(request,'register.html',context)

class ZpListView(ListView):
    we=""
    edu=""
    job=""
    salary=""
    path=""
    search=""
    user = "登录"
    model = Zp#数据源
    template_name = "index.html"#网页链接
    paginate_by = 10  # if pagination is desired，分页每页的信息条数

#修改查询数据
    def get_queryset(self):
        d={"edu1":"大专","edu2":"本科","edu3":"硕士","edu4":"博士","edu5":"不限",
           "job1":"教育","job2":"互联网","job3":"管理","job4":"文秘","job5":"电子","job6":"机械","job7":"客服","job8":"销售",
           "job9":"银行","job10":"保险","job11":"汽车","job12":"采购","job13":"化工","job14":"设计",
           "we1":[1,3],"we2":[3,5],"we3":[5,10],"we4":[10,100],
           "sa1":[0,3],"sa2":[3,5],"sa3":[5,10],"sa4":[10,30],"sa5":[30,1000],"sa6":[0,0]}
        r=Zp.objects.all()
        #搜索框
        try:
            self.search=re.match('/list_(.*)',self.path).group(1)
            r = r.filter(jobName__contains=self.search)
        except:
            pass
        #教育等级
        if self.edu!=None and self.edu!="":
            edus=self.edu.split('_')
            eduLevel = [d[x] for x in edus if x in d.keys()]
            if len(eduLevel)==1:
                r = r.filter(eduLevel=eduLevel[0])
            elif len(eduLevel)==0:
                pass
            else:
                r=r.filter(eduLevel__in=eduLevel)
        #工作领域
        if self.job!=None and self.job!="":
            jobs=self.job.split('_')
            jobType = [d[x] for x in jobs if x in d.keys()]
            try:
                r=r.filter(reduce(operator.or_, map(lambda x: Q(jobType__contains=x), jobType)))
            except:
                pass
        #薪资
        if self.salary!=None and self.salary!="":
            k=[]
            for x in self.salary.split('_'):
                if x in d.keys():
                    k.append(d[x])
            r = r.filter(reduce(operator.or_, map(lambda x: Q(K1__gte=x[0]) & Q(K2__lte=x[1]), k)))
        #经验
        if self.we!=None and self.we!="":
            k=[]
            for x in self.we.split('_'):
                if x in d.keys():
                    k.append(d[x])
            r = r.filter(reduce(operator.or_, map(lambda x: Q(W1__gte=x[0]) & Q(W2__lte=x[1]), k)))
        return r

#添加返回数据
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.user!=None and self.user!="" and not self.user.is_anonymous:
            context['user']='&nbsp'+str(self.user)+'' \
                '&nbsp&nbsp&nbsp 注销'
        else:
            context['user'] = '&nbsp&nbsp登录'
        return context

#获取request
    def get(self, request, *args, **kwargs):
        self.we = request.GET.get('we')
        self.edu = request.GET.get('edu')
        self.job = request.GET.get('job')
        self.salary = request.GET.get('salary')
        self.path = request.path
        self.user = request.user
        r=super().get(self, request, *args, **kwargs)
        return r

def CVgo(request):
    user=request.user
    if not user.is_authenticated:
        return HttpResponse(status=403,content='请登录')
    zpId=request.GET.get('zpId')
    com_id=Zp.objects.get(id=zpId).com_id
    jobName = request.GET.get('jobName')
    cv2zp=CV2Zp(zp_id=zpId,user_id=user.id)
    cv2zp.jobName=jobName
    cv2zp.email=user.email
    cv2zp.name=user.first_name
    cv2zp.com_id=com_id
    try:
        CV.objects.get(user_id=user.id)
    except:
        return HttpResponse("请完善简历")
    try:
        cv2zp.save()
    except:
        return HttpResponse(content="不能重复投递")
    return HttpResponse('OK')


import numpy as np
import matplotlib.pyplot as plt
import tkinter as Tk
import gui_stuff as gui
import media as media

gui.set_rcParams()
title = "Reflection and Transmission of a Stack vs. Wavelength"
root = Tk.Tk()
root.title(title)

def m(kfz,z):
    return np.array([[np.cos(kfz*z),np.sin(kfz*z)/kfz],[-np.sin(kfz*z)*kfz,np.cos(kfz*z)]])

def reflection_transmission(epsilon_s,d1,epsilon_f1,d2,epsilon_f2,N,epsilon_c,lambdav): # computing coefficients of reflection and transmission
    ksz = np.sqrt(epsilon_s)*2*np.pi/lambdav
    kf1z = np.sqrt(epsilon_f1)*2*np.pi/lambdav
    kf2z = np.sqrt(epsilon_f2)*2*np.pi/lambdav
    kcz = np.sqrt(epsilon_c)*2*np.pi/lambdav
    m1 = m(kf1z,d1)
    m2 = m(kf2z,d2)
    M = np.linalg.matrix_power(np.matmul(m2,m1),N)
    DENOM = ksz*M[1,1]+kcz*M[0,0]+1j*M[1,0]-1j*ksz*kcz*M[0,1]
    R = (ksz*M[1,1]-kcz*M[0,0]-1j*M[1,0]-1j*ksz*kcz*M[0,1])/DENOM
    tau = np.real(kcz)/np.real(ksz)*np.abs(2*ksz/DENOM)**2

    return R,tau

def plot_subplot_twinx(ax,lambdav,curves,labels,colors):
    axbis = ax.twinx()
    axbis.yaxis.get_major_formatter().set_powerlimits((0, 3))
    lns1 = ax.plot(lambdav,curves[0],colors[0],label=labels[0])
    ax.set_xlabel(r'$\lambda$ [nm]')
    ax.set_ylabel(labels[0])
    lns2 = axbis.plot(lambdav,curves[1],colors[1],label=labels[1])
    axbis.set_ylabel(labels[1])
    ax.legend(lns1+lns2,labels)
    return axbis

def plot_subplot(ax,lambdav,curves,labels,colors):
    for index in range(len(labels)):
        ax.plot(lambdav,curves[index],colors[index],label=labels[index])
    ax.set_xlabel(r'$\lambda$ [nm]')
    ax.set_ylabel(','.join(labels))
    ax.legend()

def epsilon(medium,lambdav):
    if medium == "Vacuum":
        epsilon_medium = (1+0j)*np.ones_like(lambdav)
    elif medium == "Si":
        epsilon_medium = media.Si(lambdav)
    elif medium == "AlAs":
        epsilon_medium = media.AlAs(lambdav)
    elif medium == "GaAs":
        epsilon_medium = media.GaAs(lambdav)
    elif medium == "AlGaAs (70% Al)":
        epsilon_medium = media.AlGaAs70(lambdav)
    elif medium == "AlGaAs (31.5% Al)":
        epsilon_medium = media.AlGaAs31(lambdav)
    elif medium == "TiO2":
        epsilon_medium = media.TiO2(lambdav)
    elif medium == "Ag":
        epsilon_medium = media.Ag(lambdav)
    elif medium == "fused silica":
        epsilon_medium = media.silica(lambdav)
    elif medium == "BaSF":
        epsilon_medium = media.BaSF(lambdav)
    else:
        print("Oops! Medium not known")

    return epsilon_medium

def initialize():
    lambda_min_string.set("400")
    lambda_max_string.set("2400")
    d1_string.set("75")
    d2_string.set("90")
    film1_string.set("GaAs")
    film2_string.set("AlAs")
    N_string.set("10")
    cladding_string.set("GaAs")
    substrate_string.set("Vacuum")

    calculate()

def calculate():
    try:
        lambda_min = float(lambda_min_string.get())
        lambda_max = float(lambda_max_string.get())
        substrate = substrate_string.get()
        d1 = float(d1_string.get())
        d2 = float(d2_string.get())
        N = int(N_string.get())
        film1 = film1_string.get()
        film2 = film2_string.get()
        cladding = cladding_string.get()

        if d1 <= 0 or d2 < 0 or N <= 0 or lambda_min < 400 or lambda_max > 2400 or lambda_min >= lambda_max:
            gui.input_error(initialize)
        else:
            f.clf()
            lambdav = np.linspace(lambda_min, lambda_max, num=10001, endpoint=False) # vacuum wavelength in nm
            epsilon_s = epsilon(substrate,lambdav)
            epsilon_c = epsilon(cladding,lambdav)
            epsilon_f1 = epsilon(film1,lambdav)
            epsilon_f2 = epsilon(film2,lambdav)
            epsilonp_min = min(np.amin(np.real(epsilon_f1)),np.amin(np.real(epsilon_f2)),np.amin(np.real(epsilon_c)))
            epsilonp_min = epsilonp_min - .1*np.abs(epsilonp_min)
            epsilonp_max = max(np.amax(np.real(epsilon_f1)),np.amax(np.real(epsilon_f2)),np.amax(np.real(epsilon_c)))
            epsilonp_max = epsilonp_max + .1*np.abs(epsilonp_max)
            epsilonpp_max = 1.1*max(np.amax(np.imag(epsilon_f1)),np.amax(np.imag(epsilon_f2)),np.amax(np.imag(epsilon_c)))
            vreflection_transmission = np.vectorize(reflection_transmission)
            R,tau = vreflection_transmission(epsilon_s,d1,epsilon_f1,d2,epsilon_f2,N,epsilon_c,lambdav)
            a1 = f.add_subplot(221)
#            a1 = f.add_subplot(231)
            plot_subplot(a1,lambdav,[np.abs(R)**2,tau,1-np.abs(R)**2-tau],[r'$\rho$',r'$\tau$',r'$a$'],['b','r','g'])
            a1.set_xlim([lambda_min, lambda_max])
            a1.set_ylim([-0.025,1.025])
            a2 = f.add_subplot(222)
#            a2 = f.add_subplot(232)
            a2bis = plot_subplot_twinx(a2,lambdav,[np.real(epsilon_c),np.imag(epsilon_c)],[r'$\varepsilon_{\rm c}^{\prime}$',r'$\varepsilon_{\rm c}^{\prime\prime}$'],['b','r'])
            a2.set_xlim([lambda_min, lambda_max])
            a2.set_ylim([epsilonp_min,epsilonp_max])
            a2bis.set_ylim([0,max(1.e-3,epsilonpp_max)])
            a2.text(0.5, 0.925, r'cladding', verticalalignment='center', horizontalalignment='center', transform=a2.transAxes)
#            a2.text(0.5, 0.925, r'Si cladding', verticalalignment='center', horizontalalignment='center', transform=a2.transAxes)
            a3 = f.add_subplot(223)
            a3bis = plot_subplot_twinx(a3,lambdav,[np.real(epsilon_f1),np.imag(epsilon_f1)],[r'$\varepsilon_{\rm f1}^{\prime}$',r'$\varepsilon_{\rm f1}^{\prime\prime}$'],['b','r'])
            a3.set_xlim([lambda_min, lambda_max])
            a3.set_ylim([epsilonp_min,epsilonp_max])
            a3bis.set_ylim([0,max(1.e-3,epsilonpp_max)])
            a3.text(0.5, 0.925, r'film 1', verticalalignment='center', horizontalalignment='center', transform=a3.transAxes)
            a4 = f.add_subplot(224)
            a4bis = plot_subplot_twinx(a4,lambdav,[np.real(epsilon_f2),np.imag(epsilon_f2)],[r'$\varepsilon_{\rm f2}^{\prime}$',r'$\varepsilon_{\rm f2}^{\prime\prime}$'],['b','r'])
            a4.set_xlim([lambda_min, lambda_max])
            a4.set_ylim([epsilonp_min,epsilonp_max])
            a4bis.set_ylim([0,max(1.e-3,epsilonpp_max)])
            a4.text(0.5, 0.925, r'film 2', verticalalignment='center', horizontalalignment='center', transform=a4.transAxes)

#            a3 = f.add_subplot(233)
#            plot_subplot_twinx(a3,lambdav,[np.real(epsilon_f1),np.imag(epsilon_f1)],[r'$\varepsilon_{\rm f}^{\prime}$',r'$\varepsilon_{\rm f}^{\prime\prime}$'],['b','r'])
#            a3.set_xlim([lambda_min, lambda_max])
#            a3.text(0.5, 0.925, r'BaSF glass film', verticalalignment='center', horizontalalignment='center', transform=a3.transAxes)

            plt.tight_layout()

#            plt.savefig('stack_lambda.pdf',bbox_inches='tight',dpi=300, transparent=True)

            canvas.draw()
    except ValueError: gui.input_error(initialize)

f = plt.figure(1,[8,6])
#f = plt.figure(1,[19,10])
canvas = gui.create_canvas(root,f)
canvas.draw()
mainframe = gui.create_mainframe(root)

lambda_min_string = Tk.StringVar()
lambda_max_string = Tk.StringVar()
d1_string = Tk.StringVar()
film1_string = Tk.StringVar()
d2_string = Tk.StringVar()
film2_string = Tk.StringVar()
N_string = Tk.StringVar()
cladding_string = Tk.StringVar()
substrate_string = Tk.StringVar()

initialize()

row = 1
#row = gui.create_entry(mainframe,u"min. wavelength: \u03bb [nm] =",lambda_min_string,row)
#row = gui.create_entry(mainframe,u"max. wavelength: \u03bb [nm] =",lambda_max_string,row)
#row = gui.create_spacer(mainframe,row)
row = gui.create_radiobutton(mainframe,['substrate medium:','Vacuum','fused silica'],substrate_string,2,row)
#row = gui.create_spacer(mainframe,row)
#row = gui.create_title(mainframe,"stack parameters",row)
row = gui.create_entry(mainframe,u"film 1 thickness: d [nm] =",d1_string,row)
row = gui.create_radiobutton(mainframe,['film 1 medium:','Vacuum','Si','AlGaAs (70% Al)','AlAs','AlGaAs (31.5% Al)','GaAs','TiO2','Ag','fused silica','BaSF'],film1_string,10,row)
row = gui.create_entry(mainframe,u"film 2 thickness: d [nm] =",d2_string,row)
row = gui.create_radiobutton(mainframe,['film 2 medium:','Vacuum','Si','AlGaAs (70% Al)','AlAs','AlGaAs (31.5% Al)','GaAs','TiO2','Ag','fused silica','BaSF'],film2_string,10,row)
row = gui.create_entry(mainframe,u"Number of periods =",N_string,row)
#row = gui.create_spacer(mainframe,row)
row = gui.create_radiobutton(mainframe,['cladding medium:','Vacuum','Si','AlGaAs (70% Al)','AlAs','AlGaAs (31.5% Al)','GaAs','TiO2','Ag','fused silica','BaSF'],cladding_string,10,row)
#row = gui.create_spacer(mainframe,row)
row = gui.create_double_entry(mainframe,u"\u03bb [nm] >",lambda_min_string,u"\u03bb [nm] <",lambda_max_string,row)
row = gui.create_button(mainframe,"Calculate",calculate,row)

gui.mainloop_safe_for_mac(root)


"""
    A module that can help to get max performance of your laptop.
    Of course, if user's machine is a desktop it's pretty useless.
"""

import os

from sys import exit
from modules.logger import logger

class PerformanceHandler:
    """
        A class of machine performance handler.

        Attributes
        ----------
        performance_mode: str
            Current mode of cpu performance

        Methods
        -------
        boost(): void
            Boost system performance.
        powersave(): void
            Set powersave mode.
    """

    def __init__(self):
        with open("/sys/devices/system/cpu/cpu1/cpufreq/scaling_governor") as file:
            self.performance_mode = file.read()
        logger.log("Created an instance of the modules.performance_handler.PerformanceHandler class.")

    def boost(self):
        """ Boost machine performance. """
        os.system("echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor")
        self.performance_mode = "performance"

        print("Set performance mode for your CPU.")
        exit()

    def powersave(self):
        """ Set powersave mode. """
        os.system("echo powersave | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor")
        self.performance_mode = "powersave"

        print("Set powersave mode for your CPU.")
        exit()


'''
The following linear equations

3X + 2 Y + Z = 10
X + Y + Z = 5
can be represented by using three matrices as:

3   2   1
1   1   1
X
Y
Z  and
10
5.
'''

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[1,2],[3,4]])
print(np.linalg.solve(a, b))


from django.core.urlresolvers import reverse

from drop.giftcard.models import GiftCardProduct, Credit
from drop.models import Order, Product
from drop.payment.api import PaymentAPI
from drop.test_utils import DropTestCase, print_order

from decimal import Decimal

class GiftCardTestCase(DropTestCase):
  def test_giftcard_purchase(self):
    gcp = GiftCardProduct.objects.create(name="gift card",unit_price=1,active=True)
    product40 = self.new_product(unit_price=40)
    product20 = self.new_product(unit_price=20)
    user1 = self.new_user()

    # user1 buys a giftcard
    self.login(user1)
    order_id = self.add_to_cart(gcp,50,extra={'to': 'jon','from': 'jan'})
    items = user1.cart.items.all()
    self.assertEqual(items.count(),1)
    self.assertEqual(items[0].extra['to'],'jon')
    self.assertEqual(items[0].extra['from'],'jan')
    order = Order.objects.get(id=order_id)
    #print_order(order)
    PaymentAPI().confirm_payment(order,order.order_total,"fake transaction","fake backend","fake description")
    credit = Credit.objects.get(purchased_by=user1)

    # user2 redeems giftcard
    user2 = self.new_user()
    self.login(user2)
    giftcard = self.client.post(reverse("giftcard_redeem_ajax"),{'code':credit.code}).json()['giftcard']
    self.assertEqual(giftcard['remaining'],'50.00')

    # user2 buys an entire cart using a giftcard
    order2_id = self.add_to_cart(product40)
    payment_url = reverse("drop_payment",args=["giftcard"])
    response = self.client.post(payment_url,{'code': credit.code,'total': 40})
    self.assertTrue(response.json()['next'].startswith('/thank_you/%s/?token='%order2_id))
    order2 = Order.objects.get(pk=order2_id)
    #print_order(order2)
    self.assertTrue(order2.is_paid())

    # gift card now says less money
    giftcard = self.client.post(reverse("giftcard_redeem_ajax"),{'code':credit.code}).json()['giftcard']
    self.assertEqual(giftcard['remaining'],'10.00')

    # user2 partially pays for a cart using a giftcrd
    order3 = Order.objects.get(pk=self.add_to_cart(product20))
    #print_order(order3)

    # Two partial payments work and take order cost down to $10
    response1 = self.client.post(payment_url,{'code': credit.code,'total': 5})
    response2 = self.client.post(payment_url,{'code': credit.code,'total': 5})
    self.assertEqual(len(response2.json()['extra_price_fields']),2)
    order3 = Order.objects.get(pk=order3.id)
    self.assertEqual(order3.amount_paid,Decimal(10))

    # Third fails because balance on gift card is zero
    response3 = self.client.post(payment_url,{'code': credit.code,'total': 5})
    self.assertTrue('Your gift card balance is $0.00' in response3.json()['error'])

    # user2 fully pays with another payment method
    PaymentAPI().confirm_payment(order3,10,"fake transaction","fake backend","fake description")
    self.assertTrue(Order.objects.get(pk=order3.id).is_paid())


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.shortcuts import render, get_object_or_404
from django.shortcuts import render
from django.views.generic import RedirectView, TemplateView
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.http import HttpResponseBadRequest
from libros.models import Libro
from .models import PagoPaypal

import paypalrestsdk

# Create your views here.

class PaypalView(RedirectView):

    permanent = False

    def _generar_lista_items(self, libro):
        """ """
        items = []
        items.append({
            "name":     str(libro),
            "sku":      str(libro.id),
            "price":    ('%.2f' % libro.precio),
            "currency": "EUR",
            "quantity": 1,
        })
        return items

    def _generar_peticion_pago_paypal(self, libro):
        """Crea el diccionario para genrar el pago paypal de libro"""
        peticion_pago = {
            "intent": "sale",
            "payer": {"payment_method": "paypal"},
            "redirect_urls": {
                "return_url": settings.SITE_URL+reverse('aceptar-pago-paypal'),
                "cancel_url": settings.SITE_URL},

            # Transaction -
            "transactions": [ {
                # ItemList
                "item_list":{
                    "items": self._generar_lista_items(libro)},

                # Amount
                "amount": {
                    "total": ('%.2f' % libro.precio),
                    "currency": 'EUR'},

                #Description
                "description": str(libro),
                }]}

        return peticion_pago

    def _generar_pago_paypal(self, libro):
        """Genera un pago de paypal para libro"""
        paypalrestsdk.configure({
            "mode":         settings.PAYPAL_MODE,
            "client_id":    settings.PAYPAL_CLIENT_ID,
            "client_secret":settings.PAYPAL_CLIENT_SECRET,})

        pago_paypal = paypalrestsdk.Payment(self._generar_peticion_pago_paypal(libro))

        if pago_paypal.create():
            for link in pago_paypal.links:
                if link.method == "REDIRECT":
                    url_pago = link.href
        else:
            raise Exception(pago.error)

        return url_pago, pago_paypal

    def get_redirect_url(self, *args, **kwargs):
        """Extrae el libro que el usuario quiere comprar, genera un pago de
        paypal por el precio del libro, y devuelve la direccion de pago que
        paypal generó"""
        libro = get_object_or_404(Libro, pk=int(kwargs['libro_pk']))
        url_pago, pago_paypal = self._generar_pago_paypal(libro)

        # Se añade el identificador del pago a la sesion para que PaypalExecuteView
        # pueda identificar al ususuario posteriorment
        self.request.session['payment_id'] = pago_paypal.id

        # Por ultimo salvar la informacion del pago para poder determinar que
        # libro le corresponde, al terminar la transaccion.
        PagoPaypal.objects.crear_pago(pago_paypal.id, libro)

        return url_pago

class PaypalExecuteView(TemplateView):

    template_name = 'pagos/paypal_exito.html'

    def _enviar_ebook_email(self, registro_pago):
        """Enviar Email con el libro al cliente """
        #TODO: admjuntar los archivos del modelo libro
        libro = registro_pago.libro
        mensaje = "Gracias por su compra de %s" % libro.titulo
        send_mail('TiendaEbook', mensaje,
	    from_email = settings.DEFAULT_FROM_EMAIL,
            recipient_list=[registro_pago.payer_email,])

    def _aceptar_pago_paypal(self, payment_id, payer_id):
        """Aceptar el pago del cliente, actualiza el registro con los datos
        del cliente proporcionados por paypal"""
        registro_pago = get_object_or_404(PagoPaypal, payment_id=payment_id)
        pago_paypal = paypalrestsdk.Payment.find(payment_id)
        if pago_paypal.execute({'payer_id': payer_id}):
            registro_pago.pagado = True
            registro_pago.payer_id = payer_id
            registro_pago.payer_email = pago_paypal.payer['payer_info']['email']
            registro_pago.save()
        else:
            raise HttpResponseBadRequest

        return registro_pago

    def get(self, request, *args, **kwargs):

        # Extraer identificacion de paypal del cliente, la id del pago,
        # y buscar el registro correspondiente.
        context = self.get_context_data(**kwargs)
        try:
            payer_id = request.GET['PayerID']
            payment_id = request.session['payment_id']
        except Exception:
            raise HttpResponseBadRequest

        registro_pago = self._aceptar_pago_paypal(payment_id, payer_id)
        self._enviar_ebook_email(registro_pago)

        return self.render_to_response(context)


# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
from VideoSpider.items import TvItem

class CctvNewsSpider(scrapy.Spider):
    name = 'CCTV_news'
    allowed_domains = ['news.cctv.com']
    start_urls = ['http://news.cctv.com/']

    def parse(self, response):
        common = response.css('div.top_nav a')
        urls = common.css('::attr(href)').extract()
        urls[0] = 'http://news.cctv.com/'
        del urls[3]
        catalogys = common.css('::text').extract()
        del catalogys[3]
        for (url, cat) in zip(urls, catalogys):
            yield Request(url=url, callback=self.parse_info, meta={'cat': cat}, dont_filter=True)

    def parse_info(self, response):
        urls = response.css('a[href*="news.cctv.com"]::attr(href)').extract()
        if 'jiankang' in response.url:
            urls = response.css('a[href*="jiankang.cctv.com"]::attr(href)').extract()
        if 'sannong' in response.url:
            urls = response.css('a[href*="sannong.cctv.com"]::attr(href)').extract()
        if 'jingji' in response.url:
            urls = response.css('a[href*="jingji.cctv.com"]::attr(href)').extract()
        if 'sports' in response.url:
            urls = response.css('a[href*="sports.cctv.com"]::attr(href)').extract()
            urls.extend(response.css('a[href*="tv.cctv.com"]::attr(href)').extract())
        urls = set(urls)
        urls = [url for url in urls if 'index' not in url and not url.endswith('/') and url.endswith('html')]
        for url in urls:
            yield Request(url=url, callback=self.parse_title, meta={'cat': response.meta['cat']}, dont_filter=True)
        pass

    def parse_title(self, response):
        name = response.css('title::text').extract()[0].partition('_')[0]
        id = response.url[response.url.rfind('/') + 1: response.url.rfind('.')]
        print((name, id))
        item = TvItem()
        item['id'] = id
        item['name'] = name
        item['isFeature'] = 1
        item['upTime'] = ''
        item['area'] = ''
        item['parts'] = 1
        item['updateTime'] = ''
        item['language'] = ''
        item['type_tag'] = response.meta['cat']
        item['playTimes'] = 0
        item['score'] = ''
        item['director'] = ''
        item['actor'] = ''
        item['describe'] = ''
        item['isVip'] = 1
        item['comment'] = 0
        item['recommend'] = ''
        item['platform'] = 'cctv'
        item['sca_app_id'] = 5018
        item['cat1'] = '新闻'
        item['cat2'] = '新闻'
        # yield item


import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from common.config_utils import read_config
from common.log_utils import log_pri

current_path = os.path.dirname(__file__)
driver_path = os.path.join(current_path, '..', read_config.driver_path)

class Browser:
    def __init__(self, driver_name=read_config.driver_name, driver_path=driver_path):
        self.__driver_path = driver_path
        self.__driver_name = driver_name

    def get_driver(self):
        if self.__driver_name.lower()=='chrome':
            return self.__get_chrome_driver()
        elif self.__driver_name.lower()=='firefox':
            return self.__get_firefox_driver()

    def __get_chrome_driver(self):
        chrome_options = Options()
        chrome_options.add_argument('--disable-gpu')  # 谷歌文档提到需要加上这个属性来规避bug
        chrome_options.add_argument('lang=zh_CN.UTF-8')  # 设置默认编码为utf-8
        chrome_options.add_experimental_option('useAutomationExtension', False)  # 取消chrome受自动控制提示
        chrome_options.add_experimental_option("prefs", {"credentials_enable_service": False,
                                                        "profile.password_manager_enabled": False})
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 取消chrome受自动控制提示
        chrome_driver_path = os.path.join(self.__driver_path, 'chromedriver.exe')
        driver = webdriver.Chrome(options=chrome_options, executable_path=chrome_driver_path)
        log_pri.info('初始化并启动谷歌浏览器')
        return driver

    def __get_firefox_driver(self):
        firefox_driver_path = os.path.join(self.__driver_path, 'geckodriver.exe')
        driver = webdriver.Firefox(executable_path=firefox_driver_path)
        log_pri.info('初始化并启动火狐浏览器')
        return driver

if __name__ == '__main__':
    # Browser().get_chrome_driver()
    Browser().get_driver()


crop = {'1':'딸기','2':'토마토','3':'파프리카','4':'오이','5':'고추','6':'시설포도'}
disease = {'1':{'a1':'딸기잿빛곰팡이병','a2':'딸기흰가루병','b1':'냉해피해','b6':'다량원소결핍 (N)','b7':'다량원소결핍 (P)','b8':'다량원소결핍 (K)'},
           '2':{'a5':'토마토흰가루병','a6':'토마토잿빛곰팡이병','b2':'열과','b3':'칼슘결핍','b6':'다량원소결핍 (N)','b7':'다량원소결핍 (P)','b8':'다량원소결핍 (K)'},
           '3':{'a9':'파프리카흰가루병','a10':'파프리카잘록병','b3':'칼슘결핍','b6':'다량원소결핍 (N)','b7':'다량원소결핍 (P)','b8':'다량원소결핍 (K)'},
           '4':{'a3':'오이노균병','a4':'오이흰가루병','b1':'냉해피해','b6':'다량원소결핍 (N)','b7':'다량원소결핍 (P)','b8':'다량원소결핍 (K)'},
           '5':{'a7':'고추탄저병','a8':'고추흰가루병','b3':'칼슘결핍','b6':'다량원소결핍 (N)','b7':'다량원소결핍 (P)','b8':'다량원소결핍 (K)'},
           '6':{'a11':'시설포도탄저병','a12':'시설포도노균병','b4':'일소피해','b5':'축과병'}}
risk = {'1':'초기','2':'중기','3':'말기'}

label_description = {}
for key, value in disease.items():
    label_description[f'{key}_00_0'] = f'{crop[key]}_정상'
    for disease_code in value:
        for risk_code in risk:
            label = f'{key}_{disease_code}_{risk_code}'
            label_description[label] = f'{crop[key]}_{disease[key][disease_code]}_{risk[risk_code]}'

label_encoder = {key:idx for idx, key in enumerate(label_description)}
label_decoder = {val:key for key, val in label_encoder.items()}


from ipinfo import trysites
import rich

def main():
    finaldata = trysites.trysites()
    if not finaldata:
        print("None of the IP sites could return even a valid IP.",
              "Perhaps check your network connection?")
    else:
        rich.print(finaldata)

if __name__ == "__main__":
    main()


from collections import Counter
import time

class TimingCtx:
    def __init__(self, init=None, init_ns=None, first_tic=None):
        self.timings = init if init is not None else Counter()
        self.ns = init_ns if init_ns is not None else Counter()
        self.arg = None
        self.last_clear = time.time()
        self.first_tic = first_tic

    def clear(self):
        self.timings.clear()
        self.last_clear = time.time()

    def start(self, arg):
        if self.arg is not None:
            self.__exit__()
        self.__call__(arg)
        self.__enter__()

    def stop(self):
        self.start(None)

    def __call__(self, arg):
        self.arg = arg
        return self

    def __enter__(self):
        self.tic = time.time()
        if self.first_tic is None:
            self.first_tic = self.tic

    def __exit__(self, *args):
        self.timings[self.arg] += time.time() - self.tic
        self.ns[self.arg] += 1
        self.arg = None

    def __repr__(self):
        return dict(
            total=time.time() - self.last_clear,
            **dict(sorted(self.timings.items(), key=lambda kv: kv[1], reverse=True)),
        ).__repr__()

    def __truediv__(self, other):
        return {k: v / other for k, v in self.timings.items()}

    def __iadd__(self, other):
        if other != 0:
            self.timings += other.timings
            self.ns += other.ns
        return self

    def items(self):
        return self.timings.items()

    @classmethod
    def pprint_multi(cls, timings, log_fn):
        data = []
        for k in timings[0].timings.keys():
            t_mean = sum(t.timings[k] for t in timings) / len(timings)
            t_max = max(t.timings[k] for t in timings)
            n = sum(t.ns[k] for t in timings) / len(timings)
            data.append((t_mean, t_max, k, n))

        log_fn(f"TimingCtx summary of {len(timings)} timings (mean/max shown over this group):")
        ind_log_fn = lambda x: log_fn("  " + x)
        ind_log_fn(
            "{:^24}|{:^8}|{:^18}|{:^18}".format("Key", "N_mean", "t_mean (ms)", "t_max (ms)")
        )
        ind_log_fn("-" * (24 + 8 + 18 + 18))
        for t_mean, t_max, k, n in sorted(data, reverse=True):
            ind_log_fn(
                "{:^24}|{:^8.1f}|{:^18.1f}|{:^18.1f}".format(k, n, t_mean * 1e3, t_max * 1e3)
            )
        ind_log_fn("-" * (24 + 8 + 18 + 18))

        sum_t_mean = sum(t_mean for t_mean, _, _, _ in data)
        ind_log_fn("{:^24}|{:^8}|{:^18.1f}|{:^18}".format("Total", "", sum_t_mean * 1e3, ""))

    def pprint(self, log_fn):
        data = []
        for k in self.timings.keys():
            n = self.ns[k]
            t_total = self.timings[k]
            t_mean = t_total / n
            data.append((t_total, t_mean, k, n))

        log_fn(f"TimingCtx summary:")
        ind_log_fn = lambda x: log_fn("  " + x)
        ind_log_fn("{:^24}|{:^8}|{:^18}|{:^18}".format("Key", "N", "t_total (ms)", "t_mean (ms)"))
        ind_log_fn("-" * (24 + 8 + 18 + 18))
        for t_total, t_mean, k, n in sorted(data, reverse=True):
            ind_log_fn(
                "{:^24}|{:^8.1f}|{:^18.1f}|{:^18.1f}".format(k, n, t_total * 1e3, t_mean * 1e3)
            )
        ind_log_fn("-" * (24 + 8 + 18 + 18))

        elapsed = time.time() - self.first_tic
        sum_t_total = sum(t_total for t_total, _, _, _ in data)
        ind_log_fn(
            "{:^24}|{:^8}|{:^18.1f}|{:^18}".format("Lost", "", (elapsed - sum_t_total) * 1e3, "")
        )
        ind_log_fn("{:^24}|{:^8}|{:^18.1f}|{:^18}".format("Total", "", sum_t_total * 1e3, ""))

class DummyCtx:
    def __enter__(self):
        pass

    def __exit__(self, *args):
        pass

    def __call__(self, *args):
        return self


# coding=utf-8
def weekday_to_int(weekday):
    if weekday == "Понедельник":
        return 1
    if weekday == "Вторник":
        return 2
    if weekday == "Среда":
        return 3
    if weekday == "Четверг":
        return 4
    if weekday == "Пятница":
        return 5
    if weekday == "Суббота":
        return 6

def pair_to_int(pair):
    if pair == "Числитель":
        return 1
    if pair == "Знаменатель":
        return 2
    if pair == "Всегда одинаковые пары":
        return 3

def int_to_weekday(int):
    weekday = {
        0: "Понедельник",
        1: "Вторник",
        2: "Среда",
        3: "Четверг",
        4: "Пятница",
        5: "Суббота",
        6: "Воскресенье"
    }
    return weekday[int]


####
__author__ = 'AM7'

## dataset https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge
####

import os
import cv2
import numpy as np
from random import shuffle
from tqdm import tqdm

import random
from sklearn import preprocessing
from imutils import paths
from sklearn.preprocessing import LabelBinarizer
import imutils
from sklearn.model_selection import train_test_split
from keras.applications import imagenet_utils
import math
import pickle
from model import Build_Model

PATH_ = "Kaggle/Facial_Expression_Recognition/"
LR = 1e-3 # 0.001
EPOCHS = 12
IMG_SIZE = 48

MODEL_NAME = PATH_ + '_Facial-{}-{}.model'.format(LR, 'CNN')
TRAIN_DIR = PATH_ + 'Training'
TEST_DIR = PATH_ + 'PrivateTest'
data = []
labels = []
##  (0=Angry, 1=Disgust, 2=Fear, 3=Happy, 4=Sad, 5=Surprise, 6=Neutral).

imagePaths = sorted(list(paths.list_images(TRAIN_DIR)))
random.seed(9001)
random.shuffle(imagePaths)

def process_image(imagePath):
    img = cv2.imread(imagePath, cv2.IMREAD_GRAYSCALE)
    img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))

    return img

def create_train_data(imagePaths):
    for imagPath in tqdm(imagePaths):
        img = process_image(imagPath)
        data.append(img)

        label =  imagPath.split(os.path.sep)[-2]
        labels.append(label)

    np.save(PATH_ + '_data.npy', data)
    np.save(PATH_ + '_labels.npy', labels)

if os.path.exists(PATH_ + '_data.npy') and os.path.exists(PATH_ + '_labels.npy'):
    data = np.load(PATH_ + '_data.npy')
    labels = np.load(PATH_ + '_labels.npy')
else:
    create_train_data(imagePaths)

data = np.array(data)
labels = np.array(labels,dtype='int')

LB = LabelBinarizer()
labels = LB.fit_transform(labels)
print(LB.classes_)

f = open(PATH_ + 'LB', "wb")
f.write(pickle.dumps(LB))
f.close()

(trainX, testX, trainY, testY) = train_test_split(data, labels, test_size=0.2)

trainX = np.array(trainX).reshape(-1, IMG_SIZE,IMG_SIZE, 1)
testX = np.array(testX).reshape(-1, IMG_SIZE,IMG_SIZE, 1)

model = Build_Model(IMG_SIZE, IMG_SIZE, len(LB.classes_), 1, LR)
print(len(trainX))
if os.path.exists(PATH_ + '_Facial-0.001-CNN.model.meta'):
    model.load(MODEL_NAME)
    mlb = pickle.loads(open(PATH_ + 'LB', "rb").read())
    print('model loaded!')
else:
    print('Building model...')
    model.fit({'input': trainX}, {'targets': trainY}, n_epoch=EPOCHS, validation_set=({'input': testX}, {'targets': testY}),
        snapshot_step=len(trainX) // 32, show_metric=True, run_id=MODEL_NAME)
    model.save(MODEL_NAME)
eva = model.evaluate(testX, testY,len(trainX) // 32)
print(eva)


import random
import string

key = ''
emsg = ''
msg = input("enter the message:")
for i in range(len(msg)):
    if msg[i].isalpha():
        key += chr(random.randrange(26) + 65)
    else:
        key += random.choice(string.punctuation)
msg = msg.upper()
for j in range(len(msg)):
    if key[j].isalpha():
        emsg += chr(((ord(msg[j]) + ord(key[j])) % 26) + 65)
    else:
        emsg += chr((ord(msg[j]) + ord(key[j])) % 256)
print(emsg)
dmsg = ''
for n in range(len(key)):
    if key[n].isalpha():
        dmsg += chr(((ord(emsg[n]) - ord(key[n]) + 26) % 26) + 65)
    else:
        dmsg += chr((ord(emsg[n]) - ord(key[n]) + 256) % 256)
print(dmsg)


import requests
from flask import Flask, render_template, request
from bs4 import BeautifulSoup

"""
When you try to scrape reddit make sure to send the 'headers' on your request.
Reddit blocks scrappers so we have to include these headers to make reddit think
that we are a normal computer and not a python script.
How to use: requests.get(url, headers=headers)
"""

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}

"""
All subreddits have the same url:
i.e : https://reddit.com/r/javascript
You can add more subreddits to the list, just make sure they exist.
To make a request, use this url:
https://www.reddit.com/r/{subreddit}/top/?t=month
This will give you the top posts in per month.
"""

db = {}
reddit_url="https://www.reddit.com"
post_cap=6
subreddits = [
    "javascript",
    "reactjs",
    "reactnative",
    "programming",
    "css",
    "golang",
    "flutter",
    "rust",
    "django",
    "pics"
]

def get_data(subreddit):
  if db.get(subreddit) is None:
    req=requests.get(f"{reddit_url}/r/{subreddit}/top/?t=month", headers=headers)
    soup=BeautifulSoup(req.text,"html.parser")
    reddit_card=soup.find_all("div",{"class":"scrollerItem"},limit=post_cap)
    print(f"extract {subreddit}")
    data_list=[]
    for card in reddit_card:
      #remove ad(promoted post)
      try:
        link=reddit_url+card.find("a",{"data-click-id":"body"})["href"]
      except:
        continue
      ele={
        "upvote":card.find("div").text,
        "title":card.find("h3").text,
        "link":link,
        "keyward":f"r/{subreddit}"
      }
      data_list.append(ele)
    db[subreddit]=data_list
  return db[subreddit]

def number(upvote):
  try:
    vote=int(upvote)
  except:
    if upvote[-1] == 'k':
      vote=int(float(upvote[:-2])*1000)
    elif  upvote[-1] == 'm':
      vote=int(float(upvote[:-2])*1000000)
    else:
      vote=0
  return vote

app = Flask("DayEleven")

@app.route('/')
def home():
  return render_template("home.html",subreddits=subreddits)

@app.route('/read')
def read():
  data_list=[]
  keywards=""
  for subreddit in subreddits:
    is_on=request.args.get(subreddit)
    if is_on == "on":
      data_list.extend(get_data(subreddit))
      keywards+=f" r/{subreddit}"
  data_list=sorted(data_list,reverse=True,key=lambda item:number(item['upvote']))
  return render_template("read.html",keywards=keywards,data_list=data_list)

app.run(host="0.0.0.0")


#!/usr/bin/env python3

import os
import sys

#runPath = os.getcwd() #radni direktorij
runPath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(runPath, "..")) #dodaj parent dir u PATH varijablu

from lib.Config import Configuration
from lib.Toolkit import pad
import lib.DatabaseLayer as db #cve-search lib za rad s bazom

#cpe = db.getCPEs()
from redis import exceptions as redisExceptions
try:
    r = Configuration.getRedisVendorConnection()
except:
    sys.exit(1)

# for key in r.scan_iter():
#        print (key)

#1kxun
#qianxun_yingshi

# Redis db 10 (cpe)
# Redis db 11 (notification)

def vendors(): #vraca sve vendore
    return r.sunion('o', 'a', 'h') #r.sunion('t:/a', 't:/h', 't:/o')

def vendor_products(vendor): #vraca sve proizvode od vendora
    allproduct = []
    products = r.smembers('v:' + vendor)
    for product in products:
        allproduct.append(product)
    return allproduct

#print(vendor_products("muslim_matrimonial_script_project"))

def product_versions(product): #vraca verzije po proizvodu
    allversion = []
    versions = r.smembers('p:' + product)
    for version in versions:
        allversion.append(version)
    return allversion

def get_vendor(product): #vraca vendora po proizvodu
    result = []
    allvendors = r.sunion('t:/a', 't:/h', 't:/o')
    for vendor in allvendors:
        if product in vendor_products(vendor):
            result.append(vendor)
    return result

def sortedVersionsOfProduct(product): #vraca sortirano
  p = r.smembers("p:" + product)
  return sorted(list(p))

def search_vendor(search): #trazi odredenog vendora
    result = []
    for vendor in vendors():
        if search in vendor:
            result.append(vendor)
    return result

def search_product(search): #trazi odreden proizvod
    result = []
    for vendor in vendors():
        for product in vendor_products(vendor):
            if search in product:
                result.append(product)
    return result

def search_vendor_product(search, vendor): #trazi odred proizvod kod odred vendora
    result = []
    for product in vendor_products(vendor):
        if search in product:
            result.append(product)
    return result

def sortedBrowseList(vendor):
  result = {}
  if (vendor is None) or type(vendor) == list:
    v1 = r.smembers("t:/o")
    v2 = r.smembers("t:/a")
    v3 = r.smembers("t:/h")

    vendor = sorted(list(set(list(v1) + list(v2) + list(v3))))

    cpe = None
  else:
    cpenum = r.scard("v:" + vendor)
    if cpenum < 1:
      return None
    p = r.smembers("v:" + vendor)
    cpe = sorted(list(p))

  result["vendor"] = vendor
  result["product"] = cpe

  return result

print(len(list(vendors())))


from Assignment_5_7.domain.Grade import Grade
from Assignment_5_7.domain.ValidatorException import ValidatorException

class GradeValidator:
    '''
    Validation class for Grades
    '''
    def validate(self, grade):
        '''
        :param grade: instance of Grade type
        :return: list of validation errors or an empty list if no error occure
        '''
        if isinstance(grade, Grade) == False:
            raise TypeError("Not a grade.")

        _errors = []

        try:
            int(grade.getStudentId())
        except:
            _errors.append("Student ID has to be integer.")

        try:
            int(grade.getDisciplineId())
        except:
            _errors.append("Discipline ID has to be an integer.")

        try:
            float(grade.getGradeValue())
            if float(grade.getGradeValue()) < 1.0 or float(grade.getGradeValue()) > 10.0:
                _errors.append("The grade value has to be between in [1, 10]. ")
        except:
            _errors.append("Grade value has to be float.")

        if len(_errors) != 0:
            raise ValidatorException(_errors)


import open3d
from open3d import pipelines
import numpy as np
import os
import argparse
import yaml
import sys

parser = argparse.ArgumentParser(description='Run 3D reconstruction on a sequence of RGB-D images.')
parser.add_argument('-c', '--camera', type=str, required=True, help='path to the camera intrinsics yaml file')
parser.add_argument('-p', '--poses', type=str, required=True, help='path to the camera poses yaml file')
parser.add_argument('-r', '--rgb_folder', type=str, required=True, help='path to the folder containing the RGB images')
parser.add_argument('-d', '--depth_folder', type=str, required=True, help='path to the folder containing the depth images')
args = parser.parse_args()

camera_file = args.camera
poses_file = args.poses
rgb_folder = args.rgb_folder
depth_folder = args.depth_folder

if not os.path.exists(camera_file):
    sys.exit(f"The camera file {camera_file} does not exist.")

if not os.path.exists(poses_file):
    sys.exit(f"The poses file {poses_file} does not exist.")

if not os.path.exists(rgb_folder):
    sys.exit(f"The RGB folder {rgb_folder} does not exist.")

if not os.path.exists(depth_folder):
    sys.exit(f"The depth folder {depth_folder} does not exist.")

with open(camera_file, 'r') as f:
    camera_data = yaml.load(f, Loader=yaml.FullLoader)

# Extract the camera intrinsic parameters
fx = camera_data['camera_matrix']['data'][0]
fy = camera_data['camera_matrix']['data'][4]
cx = camera_data['camera_matrix']['data'][2]
cy = camera_data['camera_matrix']['data'][5]
image_width = camera_data['image_width']
image_height = camera_data['image_height']

# Create the PinholeCameraIntrinsic object
intrinsic = open3d.camera.PinholeCameraIntrinsic(image_width, image_height, fx, fy, cx, cy)
intrinsic.intrinsic_matrix = [[fx, 0, cx], [0, fy, cy], [0, 0, 1]]
print(intrinsic.intrinsic_matrix)
cam = open3d.camera.PinholeCameraParameters()
cam.intrinsic = intrinsic

with open(poses_file, 'r') as f:
    poses_data = yaml.load(f, Loader=yaml.FullLoader)

volume = pipelines.integration.ScalableTSDFVolume(voxel_length=0.5 / 512.0, sdf_trunc=0.005,
                                                 color_type=pipelines.integration.TSDFVolumeColorType.RGB8)

for pose_index, pose_info in poses_data.items():
    quaternion = pose_info['camera_to_world']['quaternion']
    translation = pose_info['camera_to_world']['translation']
    M = np.eye(4)

    # Note: You should normalize the quaternion before converting it to a rotation matrix
    quaternion = np.array([quaternion['w'], quaternion['x'], quaternion['y'], quaternion['z']])
    quaternion /= np.linalg.norm(quaternion)

    M[:3, :3] = open3d.geometry.get_rotation_matrix_from_quaternion(quaternion)
    M[:3, 3] = [translation['x'], translation['y'], translation['z']]

    color_path = os.path.join(rgb_folder, f'{pose_index:06d}.png')
    depth_path = os.path.join(depth_folder, f'{pose_index:06d}.png')

    if not os.path.exists(color_path) or not os.path.exists(depth_path):
        print(f"Missing data for pose {pose_index}, skipping.")
        continue

    print(M)
    color = open3d.io.read_image(color_path)
    depth = open3d.io.read_image(depth_path)
    rgbd = open3d.geometry.RGBDImage.create_from_color_and_depth(color, depth, depth_trunc=1.0, convert_rgb_to_intensity=False)

    volume.integrate(rgbd, cam.intrinsic, np.linalg.inv(M))
    print(f"Processed pose {pose_index}")

mesh = volume.extract_triangle_mesh()
mesh.compute_vertex_normals()

pcd = open3d.geometry.PointCloud()
pcd.points = mesh.vertices

output_folder = os.path.dirname(camera_file)
open3d.io.write_triangle_mesh(os.path.join(output_folder, 'fusion_mesh.ply'), mesh, write_ascii=False,
                              compressed=False, write_vertex_normals=True, write_vertex_colors=True,
                              write_triangle_uvs=True, print_progress=True)
open3d.io.write_point_cloud(os.path.join(output_folder, 'fusion_pointcloud.pcd'), pcd, write_ascii=False,
                            compressed=False, print_progress=False)

open3d.visualization.draw_geometries([mesh])


"""Checks if a certain string or number from the user is palindrome or
not and display the last three characters or integer of the palindrome."""

def main() -> dict:
    """main function"""
    print("--- Palindrome ---")
    string_ = input("> ")
    a_palindrome = palindrome(string_)
    last_3 = last_three(string_)
    print("Is palindrome?", a_palindrome)
    print("Last three characters:", last_3)
    return {"Input: ": string_,
            "Is palindrome? ": a_palindrome,
            "Last three characters: ": last_3}

def palindrome(n: str) -> bool:
    """checks if a string or number is palindrome or not"""
    if n.lower() == n[::-1].lower():
        return True
    else:
        return False

def last_three(n: str) -> str:
    """returns the last three characters of a string or number"""
    return n[-3:]


import datetime
from django.contrib import messages
from django.shortcuts import render, redirect
from django.views.decorators.http import require_GET

from MyApp.models.models import Category

# Create your views here.
pathFolder="pages/categorys/"
def index(request):
    if 'search' in request.GET:
        search = request.GET['search']
        category = Category.objects.filter(name__icontains=search)
    else:
        category = Category.objects.all()
    context = {'categorys': category}
    return render(request,pathFolder + "index.html", context)

def create(request):

    return render(request, pathFolder + "add_category.html")

def store(request):
    try:
        category = Category()
        category.name = request.POST["txtName"]
        category.createBy = 1
        messages.success(request, "Category Created")
        category.save()
    except Exception as ex:
        print("Error:" + str(ex))
    return redirect("/category/create")

def destroy(request, id):
    try:
        category = Category.objects.get(pk=id)
        category.delete()
        #messages.success(request, "Category Deleted")
    except Exception as ex:
        print("Error:" + str(ex))
    return redirect("/category")

def edit(request, id):
    try:
        category = Category.objects.get(pk=id)
        context = {"category": category}
    except Exception as ex:
        print("Error:" + str(ex))
    return render(request, pathFolder + "edit.html", context)

def update(request):
    try:
        category = Category()
        category.id = request.POST["txtId"]
        category.name = request.POST["txtName"]
        c1 = Category.objects.get(pk=category.id)
        if c1:
            c1.name = category.name;
            c1.updateAt = datetime.datetime.now()
            c1.updateBy = 1;
            c1.save()
            messages.success(request,"Category Updated")
    except Exception as ex:
        print("Error:" + str(ex))
    return redirect("/category")


# Selenium Web Scraping
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

import time
import logging

def load_more_items(driver):
    status = True
    while status:
        driver.find_element(By.XPATH, '//body').send_keys(Keys.END)
        time.sleep(4)
        try:
            driver.find_elements(By.ID, "masonryViewMore-link")[0].click()
            logging.info("Found more items")
            time.sleep(4)
        except:
            logging.info("No more items found")
            status = False

def get_links_to_items(driver):
    # Fully load all the items
    load_more_items(driver)
    item_links = []
    # Extract the links to the items
    items = driver.find_elements(By.XPATH, "//div[@class='searchVenue card feed-item']")
    for item in items:
        link = item.find_elements(By.TAG_NAME, "a")[0].get_attribute("href")
        item_links.append(link)
    return item_links

def dismiss_ads(driver):
    try:
        logging.info("Trying to dismiss ads...")
        iframe1 = driver.find_elements(By.XPATH, "//div[@id='aswift_1_host']/iframe")[0]
        driver.switch_to.frame(iframe1)
        iframe2 = driver.find_elements(By.XPATH, "//iframe[@id='ad_iframe']")[0]
        driver.switch_to.frame(iframe2)
        driver.find_elements(By.XPATH, "//div[@id='dismiss-button']")[0].click()
    except:
        pass
        logging.info("No ads found...")

class BurpleExtract:

    def __init__(self, driver):
        self.driver = driver

        self.data_dict = dict()
        self.item_links = []

        self.data_dict["title"] = self._get_title()
        self.data_dict["num_reviews"] = self._get_num_reviews()
        self.data_dict["num_wishlisted"] = self._get_num_wishlisted()
        self.data_dict["area"] = self._get_area()
        self.data_dict["price"] = self._get_price()
        self.data_dict["tags"] = self._get_tags()
        self.data_dict["bio"] = self._get_bio()

    def _get_title(self):
        title = self.driver.find_elements(By.CLASS_NAME, "venue-title")[0].text
        return title

    def _get_num_reviews(self):
        num_reviews = self.driver.find_elements(By.CLASS_NAME, "venue-count-reviews")[0].text
        return num_reviews

    def _get_num_wishlisted(self):
        num_wishlisted = self.driver.find_elements(By.CLASS_NAME, "venue-count-wishlisted")[0].text
        return num_wishlisted

    def _get_area(self):
        area = self.driver.find_elements(By.CLASS_NAME, "venue-area")[0].text
        return area

    def _get_price(self):
        price = self.driver.find_elements(By.CLASS_NAME, "venue-price")[0].text
        return price

    def _get_tags(self):
        tags = self.driver.find_elements(By.CLASS_NAME, "venue-tags")[0].text
        return tags

    def _get_bio(self):
        bio = self.driver.find_elements(By.CLASS_NAME, "venue-bio")[0].text
        return bio

    def _load_more_reviews(self):
        status = True
        while status:
            self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(4)
            try:
                self.driver.find_elements(By.ID, "load-more-reviews")[0].click()
                logging.info("Found more reviews")
                time.sleep(4)
            except:
                logging.info("No more reviews found")
                status = False

    def get_reviews(self):
        self.review_title = []
        self.review_desc = []
        self.review_image = []

        BurpleExtract._load_more_reviews(self)
        reviews_card = self.driver.find_elements(By.XPATH, "//div[@id='foodMasonry']/div[@class='food card feed-item']")
        logging.info(f"Number of reviews: {len(reviews_card)}")

        if len(reviews_card) == 0:
            self.review_title.append('NA')
            self.review_desc.append('NA')
            self.review_image.append('NA')

        for index, card in enumerate(reviews_card):
            logging.info(f"Review Item: {index}")
            card_content = card.find_elements(By.XPATH, "//div[@class='card-body']")[index]
            image_content = card.find_elements(By.XPATH, "//div[@class='food-image']")[index]
            try:
                review_title = card_content.find_elements(By.CLASS_NAME, "food-content")[0].find_elements(By.CLASS_NAME, "food-description-title")[0].text
                self.review_title.append(review_title)
                logging.info("Review title extracted")
            except:
                logging.warning("No review title found")
                self.review_title.append('NA')

            try:
                review_desc = card_content.find_elements(By.CLASS_NAME, "food-content")[0].find_elements(By.CLASS_NAME, "food-description-body")[0].text
                self.review_desc.append(review_desc)
                logging.info("Review description extracted")
            except:
                logging.warning("No review description found, appending NA to it")
                self.review_desc.append('NA')

            try:
                review_image = image_content.find_elements(By.TAG_NAME, "img")[0].get_attribute("src")
                self.review_image.append(review_image)
                logging.info("Review image extracted")
            except:
                logging.warning("No review image found, appending NA to it")
                self.review_image.append('NA')

        logging.info(f"Length of review title: {len(self.review_title)}")
        logging.info(f"Length of review description: {len(self.review_desc)}")
        logging.info(f"Length of review image: {len(self.review_image)}")

        if len(self.review_title) == len(self.review_desc) == len(self.review_image):
            self.data_dict["review_title"] = self.review_title
            self.data_dict["review_desc"] = self.review_desc
            self.data_dict["review_image"] = self.review_image
            logging.info("Completed!")
        else:
            raise Exception("Length of review title, description and image does not match!")


from dash import dcc
from dash import html
import dash_bootstrap_components as dbc

from .components.sidebar import SIDEBAR
from .components.tab1 import TAB1
from .components.tab2 import TAB2

LAYOUT = dbc.Container(
    fluid=True,
    children=dbc.Row(
        children=[
            SIDEBAR,
            dbc.Col(
                width={"size": 9, "offset": 3},
                children=dbc.Tabs(
                    children=[TAB1, TAB2], id="tab_selection", active_tab="tab-0"
                ),
            ),
        ]
    ),
)


import sys
from setuptools import setup

dependencies = [
    'netaddr',
    'netifaces',
]

if sys.version_info[:2] < (2, 7):
    dependencies.append('argparse')

setup(
    name='cidrchk',
    version='1.0.0',
    author='Joseph Hunkeler',
    author_email='jhunkeler@gmail.com',
    description=('A simple "Is my computer on this subnet?" detection script.'),
    license='BSD',
    keywords='cidrchk detect network interface ethernet',
    zip_safe=True,
    scripts=[
        'cidrchk',
    ],
    install_requires=dependencies,
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Topic :: Utilities',
        'License :: OSI Approved :: BSD License',
    ]
)


import time
import find_remove_find5
import sort_then_find3
import walk_through7

from typing import Callable, List, Any

def time_find_two_smallest(find_func: Callable[[List[float]], Any],
                           lst: List[float]) -> float:
    """find_func(lst)를 실행하는 데 몇 초가 걸렸는지 반환한다.
    """

    t1 = time.perf_counter()
    find_func(lst)
    t2 = time.perf_counter()
    return (t2 - t1) * 1000.0

if __name__ == '__main__':
    # 해면 기압을 읽는다.
    sea_levels = []
    sea_levels_file = open('sea_levels.txt', 'r')
    for line in sea_levels_file:
        sea_levels.append(float(line))
    sea_levels_file.close()

    # 각 방법의 시간을 측정한다.
    find_remove_find_time = time_find_two_smallest(
        find_remove_find5.find_two_smallest, sea_levels)

    sort_get_minimums_time = time_find_two_smallest(
        sort_then_find3.find_two_smallest, sea_levels)

    walk_through_time = time_find_two_smallest(
        walk_through7.find_two_smallest, sea_levels)

    print('"찾고 삭제하고 찾기"는 {:.2f}ms가 걸렸습니다.'.format(find_remove_find_time))
    print('"정렬하고 최솟값 얻기"는 {:.2f}ms가 걸렸습니다.'.format(
        sort_get_minimums_time))
    print('"리스트 전체 훑기"는 {:.2f}ms가 걸렸습니다.'.format(walk_through_time))


import os
from pathlib import Path
import sys

sys.setrecursionlimit(3000)

# Default Directory Paths
home_dir = str(Path.home())
PROJECT_DIR = os.path.join(home_dir, ".project03")
CACHE_PATH = os.path.join(PROJECT_DIR, "cache")
LOG_DIR = os.path.join(PROJECT_DIR, "logs")

os.makedirs(CACHE_PATH, exist_ok=True)
os.makedirs(LOG_DIR, exist_ok=True)


import datetime
import random
import string

from daddypunmaster3000.models import GameSession

def create_session():

    while True:
        random_id = ''.join(
            random.choice(string.ascii_lowercase + string.digits)
            for _ in range(4)
        )
        try:
            GameSession.objects.get(session_id=random_id)
        except GameSession.DoesNotExist:
            game_status = GameSession(session_id=random_id)
            game_status.save()

            return random_id

def delete_old_sessions():

    sessions = GameSession.objects.all()
    for session in sessions:
        session_delta_date = session.updated + datetime.timedelta(days=1)
        session_naive = session_delta_date.replace(tzinfo=None)
        if session_naive < datetime.datetime.now().replace(tzinfo=None):
            session.delete()


class Solution:
    def check(self, val, x):
        return "{:b}".format(val).count("1") <= x <= val

    def makeTheIntegerZero(self, num1: int, num2: int) -> int:
        res = -1
        x = 1
        while x < 65:
            if num1 - x * num2 > 0 and self.check(num1 - x * num2, x):
                return x
            x += 1
        return res


import matplotlib.pyplot as plt
import numpy as np

def check(B, y, x):
    #если мы в пределах картинки и в соседе объект, то возвращаем True
    if not 0 <= x < B.shape[1]:
        return False
    if not 0 <= y < B.shape[0]:
        return False
    if B[y, x] != 0:
        return True
    return False

def neighbors2(B, y, x):
    left = y, x-1 #сосед слева
    top = y - 1, x #сосед сверху

    #присваиваем None если не прошли проверку на наличие объекта
    if not check(B, *left):
        left = None
    if not check(B, *top):
        top = None
    return left, top #возвращаем соседа

def exists(neighbors):
    return not all([n is None for n in neighbors])

def find(label, linked):
    j = label
    # print(linked, linked[j], j)
    while linked[j] != 0:
        j = linked[j]

    # print(j)
    return j

def union(label1, label2, linked):
    j = find(label1, linked)
    k = find(label2, linked)
    if j != k:
        # print(linked[k], j)
        linked[k] = j

def two_pass_labeling(B):
    B = (B.copy() * - 1).astype("int") #изображение, где объекты помечены как -1
    linked = np.zeros(len(B), dtype="uint") #связи объектов
    #print(linked, len(B))
    labels = np.zeros_like(B) #выходной результат
    label = 1 #метка

    #первый проход
    for row in range(B.shape[0]):
        for col in range(B.shape[1]):
            if B[row, col] != 0: #если находим объект
                n = neighbors2(B, row, col) #получаем соседей сверху и слева
                if not exists(n): #если соседей нет, значит, мы нашли начало нового объекта
                    m = label #присваиваем label временной переменной
                    label += 1 #увеличиваем метку на единицу
                else:
                    lbs = [labels[i] for i in n if i is not None] #получаем существующих соседей
                    #print(lbs)
                    m = min(lbs) #получаем минимальную метку
                labels[row, col] = m #присваиваем точке минимальную метку
                for i in n: #идем по соседям
                    if i is not None: #если сосед существует
                        lb = labels[i] #берем соседа
                        if lb != m: #если его метка не является минимальной, то ищем родительскую метку и соединяем
                            union(m, lb, linked)
                            # print(m, lb, linked)
    #print(linked)
    new_linked = np.zeros(label, dtype='int')
    new_label = 1

    # for row in range(B.shape[0]):
    #     for col in range(B.shape[1]):
    #         if B[row, col] != 0:
    #             new_label = find(labels[row, col], linked)
    #             if new_label != labels[row, col]:
    #                 labels[row, col] = new_label

    for lb in range(1, label):
        if (linked[lb] == 0):
            new_linked[lb] = new_label
            new_label += 1
        else:
            new_linked[lb] = new_linked[linked[lb]]

    #print(new_linked)

    for y in range(B.shape[0]):
        for x in range(B.shape[1]):
            if (B[y, x] != 0):
                labels[y, x] = new_linked[labels[y][x]]

    return labels

if __name__ == "__main__":
    image = np.zeros((20, 20), dtype='int32')

    image[1:-1, -2] = 1

    image[1, 1:5] = 1
    image[1, 7:12] = 1
    image[2, 1:3] = 1
    image[2, 6:8] = 1
    image[3:4, 1:7] = 1

    image[7:11, 11] = 1
    image[7:11, 14] = 1
    image[10:15, 10:15] = 1

    image[5:10, 5] = 1
    image[5:10, 6] = 1

    labeled_image = two_pass_labeling(image)

    plt.figure(figsize=(12, 5))
    plt.subplot(121)
    plt.imshow(image)
    plt.subplot(122)
    plt.imshow(labeled_image.astype("uint8"))
    plt.show()


def count_methods_and_fields(class_arg):
    methods, fields = [], []
    for elem in dir(class_arg):
        if callable(getattr(class_arg, elem)) and elem[0:1] != "_":
            methods.append(elem)
        elif elem[0:1] != "_":
            fields.append(elem)
    return methods, fields

def fcounter(class_name, *args, **kwargs):
    class_object = class_name(*args, **kwargs)
    c_methods, c_fields = count_methods_and_fields(class_name)
    o_methods, o_fields = count_methods_and_fields(class_object)
    return (c_methods, c_fields, sorted(list(set(o_methods) - set(c_methods))),
            sorted(list(set(o_fields) - set(c_fields))))


from ytmusicapi import YTMusic
import csv
import time

ytmusic = YTMusic('./src/headers_auth.json')
playlists = ytmusic.get_library_playlists()
lib_playlists = {}
playlist_ids = []

for i in playlists:
    playlist_ids.append(i['playlistId'])
    lib_playlists[i['title']] = i

# print(playlist_ids)
playlist = ytmusic.get_playlist(playlist_ids[2])
# print(playlist)

new_playlist = ytmusic.create_playlist('Imported Songs','Youtube API Test!!')

filename = "songs.csv"
rows = []
# reading csv file
with open(filename, 'r') as csvfile:
    # creating a csv reader object
    csvreader = csv.reader(csvfile)

    # extracting field names through first row
    fields = next(csvreader)

    # extracting each data row one by one
    for row in csvreader:
        rows.append(row[0])

failed = []
file = open("failed_songs.txt","w")
count = 0

for i in rows:
    count+=1
    print(count)
    # time.sleep(0.5)
    # print("sleeping")
    song_result = ytmusic.search(i,'songs')

    # print(len(song_result))
    if len(song_result) > 0:
        if i != song_result[0]['title']:
            video_result = ytmusic.search(i,'videos')
            if len(video_result) > 0:
                # print(video_result[0]['videoId'])
                ytmusic.add_playlist_items(new_playlist,[video_result[0]['videoId']])
            else:
                print("Failed Plus ONEEEEE")
                file.write(i + ' \n')
        else:
            # print(song_result[0]['videoId'])
            ytmusic.add_playlist_items(new_playlist,[song_result[0]['videoId']])
    else:
        print("Failed Plus ONEEEEE")
        file.write(i + ' \n')

file.close()


import math

import torch
import torch.nn as nn
import torch.nn.functional as F

class SingleDirectGNN(nn.Module):
    def __init__(self, hidden_size, pos_emb, step=1):
        super(SingleDirectGNN, self).__init__()
        self.pos_emb = pos_emb
        self.step = step
        self.hidden_size = hidden_size

        self.b_iah = nn.Parameter(torch.Tensor(self.hidden_size))
        self.b_oah = nn.Parameter(torch.Tensor(self.hidden_size))
        self.linear_edge_in = nn.Linear(self.hidden_size, 1 * self.hidden_size, bias=False)
        # self.linear_gate_i = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)
        # self.linear_gate_o = nn.Linear(self.hidden_size, 3 * self.hidden_size, bias=False)

        self.reset_parameters()

    def GNNCell(self, A_in, hidden):
        '''
        A: b x t x t
        '''
        h_n = self.linear_edge_in(hidden)
        # h_n = hidden
        # inputs_out = torch.matmul(A_out, h_n) + self.b_iah
        inputs_in = torch.matmul(A_in.transpose(1, 2), h_n) + self.b_oah
        return inputs_in

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.hidden_size)
        for weight in self.parameters():
            weight.data.uniform_(-stdv, stdv)

    def get_pos_emb(self, seq_mask):
        length = seq_mask.sum(1, keepdim=True)
        coo = torch.arange(seq_mask.size(1), device=seq_mask.device).unsqueeze(0).expand(seq_mask.size(0), -1)
        coo = coo * seq_mask
        pos_index = (length - coo) * seq_mask
        # pos_index = (coo + 1) * seq_mask
        return self.pos_emb(pos_index)

    def pos_graph(self, seq_inputs):
        seq_inputs = seq_inputs.unsqueeze(-1)  # b x t x 1
        seq_mask = seq_inputs.bool()  # b x t x 1

        relation_matrix = seq_inputs - seq_inputs.transpose(1, 2)  # b x t x t
        relation_matrix = relation_matrix.bool()  # b x t x t
        relation_matrix = (~relation_matrix).float().tril(diagonal=0)
        relation_matrix = relation_matrix * seq_mask * seq_mask.transpose(1, 2)

        # norm = relation_matrix.sum(-1, keepdim=True)  # b x t x 1
        # norm[torch.where(norm == 0)] = 1.
        # A_out = relation_matrix / norm

        norm = relation_matrix.sum(-2, keepdim=True)  # b x t x 1
        norm[torch.where(norm == 0)] = 1.
        A_in = relation_matrix / norm
        return A_in  # b x t x t

    def pos_dis(self, seq_mask):
        seq_mask = seq_mask.unsqueeze(-1).long()
        coo = torch.arange(seq_mask.size(-2), device=seq_mask.device).unsqueeze(0).unsqueeze(-1)  # 1 x t x 1
        res = coo - coo.transpose(1, 2)  # 1 x t x t
        res = res.tril(diagonal=0)
        return res.expand(seq_mask.size(0), -1, -1)

    def forward(self, seq_inputs, seq_ori_hidden=None):
        seq_mask = seq_inputs.bool()
        A_in = self.pos_graph(seq_inputs)

        pos_emb = self.get_pos_emb(seq_mask)
        pos_emb = F.normalize(pos_emb)  # b x t x h

        for i in range(self.step):
            pos_emb = self.GNNCell(A_in, pos_emb)

        return pos_emb  # b x t x h


from .jgo import _jgo_main as main
from .jgo import resolve_dependencies
from .util import (
    add_jvm_args_as_necessary,
    main_from_endpoint,
    maven_scijava_repository,
)

__all__ = (
    "add_jvm_args_as_necessary",
    "main_from_endpoint",
    "main",
    "maven_scijava_repository",
    "resolve_dependencies",
)


class Solution:
    def mctFromLeafValues(self, A: List[int]) -> int:
        stack = [float('inf')]
        res = 0

        for leaf in A:
            while stack and stack[-1] <= leaf:
                firstLeaf = stack.pop()
                res = res + (firstLeaf * min(stack[-1], leaf))

            stack.append(leaf)

        while len(stack) > 2:
            res = res + (stack.pop() * stack[-1])

        return res


class Solution:
    def getpos(self, grid, i, j, m, n):
        if i == m:
            return j
        nj = j - 1
        if grid[i][j] == 1:
            nj = j + 1
        if 0 <= nj < n and grid[i][j] == grid[i][nj]:
            return self.getpos(grid, i + 1, nj, m, n)
        return -1

    def findBall(self, grid: List[List[int]]) -> List[int]:
        m = len(grid)
        n = len(grid[0])
        return [self.getpos(grid, 0, j, m, n) for j in range(n)]


import folium
from app.tools import convert_adress_to_coordinates

def create_bars_map(current_location, bars_geo, path='app/templates/_map.html'):
    current_coordinates = convert_adress_to_coordinates(current_location)

    map = folium.Map(
        location=current_coordinates,
        zoom_start=12,
    )
    folium.Marker(
    location=current_coordinates,
    popup='Here I am',
    icon=folium.Icon(color='red', icon='check')
    ).add_to(map)

    tooltip = "Let's drink!"
    for bar in bars_geo:
        name = bar['title']
        folium.Marker(bar['coordinates'], popup=f'<i>{name}</i>', tooltip=tooltip).add_to(map)
    map.save(path)


import socket
import selectors
import argparse

def recv_data(conn):
    data = conn.recv(1024)
    if data:
        print(data.decode())
    else:
        e_poll.unregister(conn)
        conn.close()

def acc_conn(p_server):
    conn, addr = p_server.accept()
    print("[*] Acception connection from %s:%d" % (addr[0], addr[1]))
    e_poll.register(conn, selectors.EVENT_READ, recv_data)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='tcp server options')
    parser.add_argument('-p', '--port', default='22222',help='listen to port', dest='port')
    args = parser.parse_args()
    CONN_ADDR = ("127.0.0.1", int(args.port))
    server = socket.socket()
    server.bind(CONN_ADDR)
    server.listen(6)
    e_poll = selectors.DefaultSelector()
    e_poll.register(server, selectors.EVENT_READ, acc_conn)
    print("port: {}  wating for connect...".format(int(args.port)))
    while True:
        # 事件循环不断地调用select获取被激活的socket
        events = e_poll.select()
        # print(events)
        for key, mask in events:
            call_back = key.data
            # print(key.data)
            call_back(key.fileobj)


#player stats
#wizard or warrior (defines move set)
#health - speed - attack bonus (out of 7, player can distribute 7 stat points in whatever way they like)
#one health pot, refills after each boss

#basic enemies
#can use only attacking/defense moves - no stat moves
#no attack bonus, health and speed are split randomly with 7 stat points

#boss enemies
#every 5 fight is against a boss
#each boss is unique and has some random gimmick that makes it strong
#while boss order can be random, no boss should be repeated and

#fight scenario
#both sides choose one move between a predetermined set of three
#the party with the higher speed stat goes first, ties cannot happen since player speed always be a whole number while opponent speed will always be some whole number +- 0.5
#fight will continue as long as both sides have health > 0
#if player wins, they move onto the next fight with the exact same health and stats, with a chance to use a health pot to heal themselves
#all stats will be increased by +1 after each boss (undecided)

import random

def cleave():
    return 20

def eschew():
    return 25 + random.randrange(3)

def ruleta():
    return 15 + random.randrange(10)

def rage():
    return 0

def move(isEnemy):

    if isEnemy == True:
        move = random.choice([0, 1, 2, 3])
        user = 'Enemy'
    else:
        move = int(input('What will you do? '))
        user = 'You'

    if move == 0:
        print('{} used cleave!'.format(user))
        effect = cleave()
        modifier = 0
        type = 0

    if move == 1:
        print('{} used eschew!'.format(user))
        effect = eschew()
        modifier = -0.6
        type = 1

    if move == 2:
        print('{} used ruleta!'.format(user))
        effect = ruleta()
        modifier = 0
        type = 0

    if move == 3:
        print('{} used rage!'.format(user))
        effect = rage()
        modifier = 1.5
        type = 2

    return [effect, modifier, type]

#while True:
#    outcome = move(False)

#    if outcome[2] == 0:
#        calcDamage = outcome[0] * attkBoost
#        print('You did {} damage'.format(calcDamage))
#        attkBoost = attkBoost * outcome[1]
#        print('Attack modifier is {}'.format(attkBoost))

#    if outcome[2] == 1:
#        print('You healed {} hit points'.format(outcome[0]))
#        attkBoost = attkBoost * outcome[1]
#        print('Attack modifier is {}'.format(attkBoost))

#    if outcome[2] == 2:
#        print('You boosted attack')
#        attkBoost = attkBoost * outcome[1]
#        print('Attack modifier is {}'.format(attkBoost))

playerHealth = 500
enemiesDefeated = 0
playerSpeed = random.randrange(5)

while True:

    print('Enemies defeated: {}'.format(enemiesDefeated))

    attkBoost = 1
    eAttkBoost = 1

    enemyHealth = 100 + (20 * enemiesDefeated)

    enemySpeed = random.randrange(5) - 0.5

    print('Your speed stat: {}'.format(playerSpeed))
    print('Enemy speed stat: {}'.format(enemySpeed))
    input()

    print('Entering combat...')

    while True:
        print('Your health: {}'.format(playerHealth))
        print('Enemy health: {}'.format(enemyHealth))

        print('')

        playerMove = move(False)

        enemyMove = move(True)

        if playerSpeed > enemySpeed:

            if playerMove[2] == 0:
                calcDamage = playerMove[0] * attkBoost
                enemyHealth = enemyHealth - calcDamage
                print('You did {} damage'.format(calcDamage))
                attkBoost = attkBoost + playerMove[1]
                print('Attack modifier is {}'.format(attkBoost))

            if playerMove[2] == 1:
                playerHealth = playerHealth + playerMove[0]
                print('You healed {} hit points'.format(playerMove[0]))
                attkBoost = attkBoost + playerMove[1]
                print('Attack modifier is {}'.format(attkBoost))

            if playerMove[2] == 2:
                print('You boosted attack')
                attkBoost = attkBoost + playerMove[1]
                print('Attack modifier is {}'.format(attkBoost))

            if enemyHealth < 1:
                print('You win!')
                print('Onto the next enemy!')

            else:
                if enemyMove[2] == 0:
                    calcDamage = enemyMove[0] * eAttkBoost
                    playerHealth = playerHealth - calcDamage
                    print('Enemy did {} damage'.format(calcDamage))
                    eAttkBoost = eAttkBoost + enemyMove[1]
                    print('Attack modifier is {}'.format(eAttkBoost))

                if enemyMove[2] == 1:
                    enemyHealth = enemyHealth + enemyMove[0]
                    print('Enemy healed {} hit points'.format(enemyMove[0]))
                    eAttkBoost = eAttkBoost + enemyMove[1]
                    print('Attack modifier is {}'.format(eAttkBoost))

                if enemyMove[2] == 2:
                    print('Enemy boosted attack')
                    eAttkBoost = eAttkBoost + enemyMove[1]
                    print('Attack modifier is {}'.format(eAttkBoost))

                if playerHealth < 1:
                    print('Enemy Wins T-T')
                    exit()
        else:
            if enemyMove[2] == 0:
                calcDamage = enemyMove[0] * eAttkBoost
                playerHealth = playerHealth - calcDamage
                print('Enemy did {} damage'.format(calcDamage))
                eAttkBoost = eAttkBoost + enemyMove[1]
                print('Attack modifier is {}'.format(eAttkBoost))

            if enemyMove[2] == 1:
                enemyHealth = enemyHealth + enemyMove[0]
                print('Enemy healed {} hit points'.format(enemyMove[0]))
                eAttkBoost = eAttkBoost + enemyMove[1]
                print('Attack modifier is {}'.format(eAttkBoost))

            if enemyMove[2] == 2:
                print('Enemy boosted attack')
                eAttkBoost = eAttkBoost + enemyMove[1]
                print('Attack modifier is {}'.format(eAttkBoost))

            if playerHealth < 1:
                print('Enemy Wins T-T')
                exit()

            else:
                if playerMove[2] == 0:
                    calcDamage = playerMove[0] * attkBoost
                    enemyHealth = enemyHealth - calcDamage
                    print('You did {} damage'.format(calcDamage))
                    attkBoost = attkBoost + playerMove[1]
                    print('Attack modifier is {}'.format(attkBoost))

                if playerMove[2] == 1:
                    playerHealth = playerHealth + playerMove[0]
                    print('You healed {} hit points'.format(playerMove[0]))
                    attkBoost = attkBoost + playerMove[1]
                    print('Attack modifier is {}'.format(attkBoost))

                if playerMove[2] == 2:
                    print('You boosted attack')
                    attkBoost = attkBoost + playerMove[1]
                    print('Attack modifier is {}'.format(attkBoost))

                if enemyHealth < 1:
                    print('You win!')
                    print('Onto the next enemy!')
                    #exit()

    enemiesDefeated = enemiesDefeated + 1


students = ["Hakan"]

# student ekleme
nameSoy = input("Adınızı ve Soyadınızı giriniz: ")
students.append(nameSoy)

# student silme
students.pop(3)
print(students)

#birden fazla student ekleme
students.extend(nameSoy)
print(students)

# tek tek ekrana yazdırma
for i in range(len(students)):
    print(students[i])

# İndex öğrenme
print(students.index("Hakan"))