import copy
from turtle import pos

import torch
import pytorch_lightning as pl
from src.models.layer import *
from src.utils import clones
from pytorch_lightning.callbacks import Callback
import torchmetrics
import torch.nn.functional as F

class periodicTransformer(pl.LightningModule):
    def __init__(self, embedding_size, embedding_sub, num_heads, N, TimeEncoder, n_classes):
        super(periodicTransformer, self).__init__()
    # def __init__(self, n_classes=5, d_model=200, d_ff=128, h=8, N=4, time='discrete'):
    #     super().__init__()
        # self.time = time
        # self.pos_enc_discrete = PositionalEncoding(d_model)
        # self.pos_enc_continuous = TimeFilm(embedding_size=d_model)
        # self.enc_blocks = clones(EncoderBlock(d_model=d_model, d_ff=d_ff, h=h), N)
        # self.proj = nn.Linear(d_model, n_classes)
        # for p in self.parameters():
        #     if p.dim() > 1:
                # nn.init.xavier_uniform(p)

        self.modulation = TimeEncoder
        self.encoders = clones(TransformerEncoder(embedding_size= embedding_size, embedding_sub= embedding_sub, num_heads = num_heads), N)
        self.classifier = nn.Sequential(nn.Linear(in_features=embedding_size, out_features=embedding_size, bias= True),
                                nn.LeakyReLU(0.1),
                                nn.Linear(in_features=embedding_size, out_features=n_classes, bias= True))
        self.N   = N

        # Metrics -----------
        self.val_acc = torchmetrics.Accuracy()
        self.test_f1 = torchmetrics.F1Score(number_classes=n_classes, average="micro")
        self.test_acc = torchmetrics.Accuracy()
        self.test_recall = torchmetrics.Recall(num_classes=n_classes)
        self.test_precision = torchmetrics.Precision(num_classes=n_classes)
        self.test_preds = []
        self.test_targ = []
        self = self.double()

    def forward(self, x, t):

        m = self.modulation(x, t)

        for i in range(self.N):

            m, _ = self.encoders[i](m)

            prob = self.classifier(m)
            prob = prob[:, -1, :]
        return prob

    # def forward(self, x, t):
    #     if self.time == 'continuous':
    #         x = self.pos_enc_continuous(x, t)
    #     else:
    #         x = self.pos_enc_discrete(x)
    #     for enc in self.enc_blocks:
    #         x = enc(x)
    #     # x = self.proj(x)
    #     # F.log_softmax(x, dim=-1)
    #     return self.proj(x)

    def loss_function(self, data, label):
        criterion = torch.nn.CrossEntropyLoss()
        return criterion(data, label)

    def training_step(self, batch, batch_idx):
        x, t, y = batch['mag'], batch['mjd'], batch['label']
        output = self(x.unsqueeze(dim=2), t.unsqueeze(dim=2))
        loss = self.loss_function(output, y)
        self.log('loss',loss)
        return {'loss':loss}

    def validation_step(self, batch, batch_idx):
        x, t, y = batch['mag'], batch['mjd'], batch['label']
        output = self(x.unsqueeze(dim=2), t.unsqueeze(dim=2))
        val_loss = self.loss_function(output, y)
        val_preds = self.predictions(output, y)
        val_acc = self.val_acc(val_preds, y)
        self.log('val_loss', val_loss)
        self.log('val_acc', val_acc)
        return {'val_loss':val_loss, 'val_acc':val_acc}

    def on_save_checkpoint(self, checkpoint):
        self.best_epoch = self.current_epoch

    def configure_optimizers(self):
        return torch.optim.Adam(self.parameters(), lr=1e-4, betas=(0.9, 0.98), eps=1e-9)

    def test_step(self, batch, batch_idx):
        x, t, y = batch['mag'], batch['mjd'], batch['label']
        output = self(x.unsqueeze(dim=2), t.unsqueeze(dim=2))
        test_loss = self.loss_function(output, y)
        test_preds = self.predictions(output, y)
        test_acc = self.test_acc(test_preds, y)
        test_f1 = self.test_f1(test_preds, y)
        test_recalll = self.test_recall(test_preds, y)
        test_precision = self.test_precision(test_preds, y)
        self.test_preds += test_preds.tolist()
        self.test_targ += y.tolist()
        self.log('test_loss', test_loss)
        self.log('test_acc', test_acc)
        self.log('test_recall', test_recalll)
        self.log('test_precision', test_precision)
        self.log('test_f1', test_f1)
        return {'test_loss':test_loss, 'test_acc':test_acc,
                'test_recall':test_recalll, 'test_precision': test_precision,
                'test_f1':test_f1}

    def predictions(self, x, y):
        prediction = F.log_softmax(x, dim=-1)
        prediction = prediction.argmax(axis=1)
        return prediction

class MetricTracker(Callback):
    def __init__(self):
        self.loss_history = []
        self.val_loss_history = []
        self.val_acc_history = []
        self.test_loss_history = []
        self.test_acc_history = []
        self.test_f1_history = []
        self.test_recall_history = []
        self.test_precision_history = []

    def on_validation_epoch_end(self, trainer, module):
        elogs = trainer.logged_metrics['val_loss'].cpu()
        elogs_acc = trainer.logged_metrics['val_acc'].cpu()
        self.val_loss_history.append(elogs)
        self.val_acc_history.append(elogs_acc)

    def on_train_epoch_end(self, trainer, module):
        elogs = trainer.logged_metrics['loss'].cpu()
        self.loss_history.append(elogs)

    def on_test_epoch_end(self, trainer, module):
        elogs = trainer.logged_metrics['test_loss'].cpu()
        elogs_acc = trainer.logged_metrics['test_acc'].cpu()
        elogs_f1 = trainer.logged_metrics['test_f1'].cpu()
        elogs_recall = trainer.logged_metrics['test_recall'].cpu()
        elogs_precision = trainer.logged_metrics['test_precision'].cpu()
        self.test_loss_history.append(elogs)
        self.test_acc_history.append(elogs_acc)
        self.test_f1_history.append(elogs_f1)
        self.test_recall_history.append(elogs_recall)
        self.test_precision_history.append(elogs_precision)

# --------------- NO PL --------------------------
#
# class periodicTransformer(nn.Module):
#     def __init__(self, n_classes=5, d_model=200, d_ff=128, h=8):
#         super().__init__()
#         self.pos_enc = PositionalEncoding(d_model)
#         self.enc = EncoderBlock(d_model=d_model, d_ff=d_ff, h=h)
#         self.proj = nn.Linear(d_model, n_classes)
#         for p in self.parameters():
#             if p.dim() > 1:
#                 nn.init.xavier_uniform(p)

#     def forward(self, x):
#         x = self.pos_enc(x)
#         x = self.enc(x)
#         x = self.proj(x)
#         return F.log_softmax(x, dim=-1)

#     def loss_function(self, data, label):
#         criterion = torch.nn.CrossEntropyLoss()
#         return criterion(data, label)

#     def training_step(self, batch, batch_idx):
#         x, y = batch['mag'], batch['label']
#         output = self(x.unsqueeze(dim=2))
#         loss = self.loss_function(output.mean(axis=1).max(axis=1)[0], y)
#         return loss

#     def validation_step(self, batch, batch_idx):
#         x, y = batch['mag'], batch['label']
#         output = self(x.unsqueeze(dim=2))
#         loss = self.loss_function(output.mean(axis=1).max(axis=1)[0], y)
#         _, acc = self.evaluate(output, y)
#         return loss, acc

#     def configure_optimizers(self):
#         return torch.optim.Adam(self.parameters(), lr=1e-4, betas=(0.9, 0.98), eps=1e-9)

#     def fit(self, train_loader, val_loader, n_epochs):
#         optimizer = self.configure_optimizers()
#         loss_history = []
#         val_loss_history = []
#         save_best_model = SaveBestModel()
#         for epoch in range(n_epochs):
#             for idx, batch in enumerate(train_loader):
#                 optimizer.zero_grad()
#                 loss = self.training_step(batch, idx)
#                 loss.backward()
#                 optimizer.step()
#             for idx, batch in enumerate(val_loader):
#                 val_loss, val_acc = self.validation_step(batch, idx)
#             loss_history.append(loss.detach().item())
#             val_loss_history.append(val_loss.detach().item())
#             print(f'Epoch: {epoch} - Train loss: {loss} - Val loss: {val_loss} - Val acc: {val_acc}')
#             save_best_model(val_loss, epoch, self)
#         self.model = save_best_model.best_model
#         return loss_history, val_loss_history

#     def test(self, test_loader):
#         test_avg_acc = []
#         predictions = []
#         for idx, batch in enumerate(test_loader):
#             x, y = batch['mag'], batch['label']
#             output = self(x)
#             prediction, test_acc = self.evaluate(output, y)
#             test_avg_acc.append(test_acc)
#             predictions += prediction
#             print(f'Test batch acc: {test_acc}')
#         test_avg_acc = sum(test_avg_acc) / len(test_avg_acc)
#         print(f'Test avg acc: {test_avg_acc}')
#         return test_avg_acc, predictions

#     def evaluate(self, x, y):
#         prediction = x.mean(axis=1).argmax(axis=1)
#         accuracy = (prediction == y).sum() / y.shape[0]
#         return list(zip(y.tolist(),prediction.tolist())), accuracy

# -------------------- DEPRECATED -----------
#
# class periodicTransformer:
#     def __init__(self, n_classes, N=6, d_model=512, d_ff=2048, h=8, dropout=0.1):
#         self.model = self.make_model(n_classes, N, d_model, d_ff, h, dropout)

#     def make_model(self, n_classes, N, d_model, d_ff, h, dropout):
#         "Helper: Construct a model from hyperparameters."
#         c = copy.deepcopy
#         attn = torch.nn.MultiheadAttention(d_model, h)
#         ff = PositionwiseFeedForward(d_model, d_ff, dropout)
#         position = PositionalEncoding(d_model, dropout)
#         encoder_layer = EncoderLayer(d_model, c(attn), c(ff), dropout)
#         model = Encoder(position, encoder_layer, N, d_model, n_classes)

#         # This was important from their code.
#         # Initialize parameters with Glorot / fan_avg.
#         for p in model.parameters():
#             if p.dim() > 1:
#                 nn.init.xavier_uniform(p)
#         return model

#     def loss_function(self, data, label):
#         criterion = torch.nn.CrossEntropyLoss()
#         return criterion(data, label)

#     def training_step(self, batch, batch_idx):
#         x, y = batch['mag'], batch['label']
#         output = self.model(x)
#         print(output.shape)
#         loss = self.loss_function(output, y)
#         return loss

#     def validation_step(self, batch, batch_idx):
#         x, y = batch['mag'], batch['label']
#         output = self.model(x)
#         loss = self.loss_function(output, y)
#         _, acc = self.evaluate(output, y)
#         return loss, acc

#     def configure_optimizers(self):
#         return torch.optim.Adam(self.model.parameters(), lr=1e-4, betas=(0.9, 0.98), eps=1e-9)

#     def fit(self, train_loader, val_loader, n_epochs):
#         optimizer = self.configure_optimizers()
#         loss_history = []
#         val_loss_history = []
#         save_best_model = SaveBestModel()
#         for epoch in range(n_epochs):
#             for idx, batch in enumerate(train_loader):
#                 optimizer.zero_grad()
#                 loss = self.training_step(batch, idx)
#                 loss.backward()
#                 optimizer.step()
#             for idx, batch in enumerate(val_loader):
#                 val_loss, val_acc = self.validation_step(batch, idx)
#             loss_history.append(loss.detach().item())
#             val_loss_history.append(val_loss.detach().item())
#             print(f'Epoch: {epoch} - Train loss: {loss} - Val loss: {val_loss} - Val acc: {val_acc}')
#             save_best_model(val_loss, epoch, self.model)
#         self.model = save_best_model.best_model
#         return loss_history, val_loss_history

#     def test(self, test_loader):
#         test_avg_acc = []
#         predictions = []
#         for idx, batch in enumerate(test_loader):
#             x, y = batch['mag'], batch['label']
#             output = self.model(x)
#             prediction, test_acc = self.evaluate(output, y)
#             test_avg_acc.append(test_acc)
#             predictions += prediction
#             print(f'Test batch acc: {test_acc}')
#         test_avg_acc = sum(test_avg_acc) / len(test_avg_acc)
#         print(f'Test avg acc: {test_avg_acc}')
#         return test_avg_acc, predictions

#     def evaluate(self, x, y):
#         prediction = x.argmax(dim=1)
#         accuracy = (prediction == y).sum() / y.shape[0]
#         return list(zip(y.tolist(),prediction.tolist())), accuracy


from mcpi.minecraft import Minecraft
mc = Minecraft.create
x = 10
y = 11
z = 12
gift = mc.getBlock(x,y,z)

if gift == 57:
    mc.postToChat("OMG PLZ BRING A GIFT TO " + str(x) + ", " + str(y) + ", " + str(z))
elif gift == 6:
    mc.postToChat("meh. I mean, you can bring it if you want..." + str(x) + ", " + str(y) + ", " + str(z))
else:
    mc.postToChat("Bring a gift to" + str(x) + ", " + str(y) + ", " + str(z))


# 12_V1
print('cdcdd'[int(input()) - 1])

# 12_V2
import math
class Circle:
    def __init__(self, i, x, y, r):
        self.i, self.x, self.y, self.r = i, x, y, r
    def touch(lhs, rhs):
        return math.hypot(lhs.x - rhs.x, lhs.y - rhs.y) < lhs.r + rhs.r
n = int(input())
cyc = [Circle(*map(int, input().split())) for _ in range(n)]
print(*[c.i for c in cyc if all(not c.touch(t) for t in cyc if c is not t)] or ['Not Found'])

# 12_V3
import math
from collections import namedtuple

class Point(namedtuple('Point', ['x', 'y'])):
	def distance(p1, p2):
		return math.hypot(p1.x - p2.x, p1.y - p2.y)

class Line:
	def __init__(self, x1, y1, x2, y2):
		self.p1 = Point(x1, y1)
		self.p2 = Point(x2, y2)

	def __contains__(cls, rhs):
		if isinstance(rhs, Point):
			x1, y1, x2, y2, px, py = *cls.p1, *cls.p2, *rhs
			if not (min(y1, y2) <= py <= max(y1, y2)): return False
			return abs((y1-py)*(x2-x1)-(y2-y1)*(x1-px)) < 1e-5 if x1 != x2 else px == x1
		raise NotImplemented

class Circle(Point):
	def __new__(cls, idx, x, y, r):
		cls.idx, cls.r = idx, r
		return Point.__new__(cls, x, y)

	def line_intersection(circ, line):
		x1, y1, x2, y2, xc, yc, rc = *line.p1, *line.p2, *circ, circ.r
		if x1 != x2:
			M = (y2-y1)/(x2-x1) # line: y = Mx+B
			B = y1 - M * x1
			a = M**2+1
			b = -2*xc + 2*M*(B-yc)
			c = pow(xc,2) + pow(B-yc,2) - pow(rc,2)
			z = b**2 - 4*a*c # discriminant
			if z > 0:
				ans1 = (-b + math.sqrt(z))/2/a
				ans2 = (-b - math.sqrt(z))/2/a
				return [Point(ans1, M*ans1+B), Point(ans2, M*ans2+B)]
			return   [Point(-b/2/a, M*(-b/2/a)+B)] if z is 0 else[]
		else:
			if rc**2 > (x1-xc)**2:
				rr = math.sqrt(rc**2 - (x1-xc)**2)
				return [Point(x1, rr+yc),Point(x2, rr-yc)]
			return   [Point(x1, yc)] if rc**2 == (x1-xc)**2 else []

	def __contains__(circ, rhs):
		if isinstance(rhs, Point):
			return Point.distance(circ, rhs) <= circ.r
		if isinstance(rhs, Line):
			if rhs.p1 in circ or rhs.p2 in circ: return True
			return any(p in line for p in circ.line_intersection(line))
		raise NotImplemented

if __name__ == '__main__':
	n = int(input().strip())
	line = Line(*map(int, input().split()))
	ans = []
	for i in range(n):
		circle = Circle(*map(int, input().split()))
		if line in circle:
			ans.append(str(circle.idx))
	print(' '.join(map(str, ans)) or 'Not Found')

# 12_V4
import math
import itertools
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])

class Cycle(Point):
	def __new__ (self, x, y, *_): return super(Cycle, self).__new__(self, x, y)
	def __init__(self, x, y, r=0, s=0): self.r, self.s = r, s
	def distance (lhs, rhs): return math.hypot(lhs.x - rhs.x, lhs.y - rhs.y)
	def intersect(lhs, rhs): return lhs.distance(rhs) <= lhs.r + rhs.r
	def area (self): return math.pi * self.r ** 2
	def scale(self): return self.area() * self.s

n = int(input())
p = Cycle(*map(float, input().split()))
grp = []
for _ in range(n):
	tmp = list(map(float, input().split()))
	nw = Cycle(*tmp)
	inc, exc = [[nw]], []
	for ls in grp:
		[exc, inc][any(map(nw.intersect, ls))].append(ls)
	grp = exc + [list(itertools.chain(*inc))]
for ls in grp:
	if any(map(p.intersect, ls)):
		print(sum(map(Cycle.scale, ls)) / sum(map(Cycle.area, ls)))
		break
else:
	print(1.0)


"""empty message

Revision ID: 0d2523c0cb8a
Revises: d278dee35f5a
Create Date: 2017-12-13 19:29:39.010490

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '0d2523c0cb8a'
down_revision = 'd278dee35f5a'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('Post',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('body', sa.TEXT(), nullable=True),
    sa.Column('timestamp', sa.DateTime(), nullable=True),
    sa.Column('auther_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['auther_id'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_Post_timestamp'), 'Post', ['timestamp'], unique=False)
    op.add_column('users', sa.Column('avatar_hash', sa.String(length=64), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('users', 'avatar_hash')
    op.drop_index(op.f('ix_Post_timestamp'), table_name='Post')
    op.drop_table('Post')
    # ### end Alembic commands ###


from django.db.models import Q
from django.forms import ModelForm, ModelChoiceField, CharField, TextInput, Select
from django.contrib.auth.models import Group, Permission
from django.core.validators import RegexValidator

class GroupForm(ModelForm):
    alphanumeric = RegexValidator(r'^[0-9a-zA-Z ]*$', 'Only alphanumeric characters are allowed.')
    permissions = ModelChoiceField(initial=None, required=False,
                    queryset=Permission.objects.filter(~Q(content_type_id__in=[1,4,5])).order_by('content_type_id'),
                    empty_label=None,
                    widget=Select(attrs={
                        'id': 'id_get_groups',
                        'class': 'form-control select2',
                        'style': ' width: 100%;', 'multiple':'multiple'}))

    name = CharField(
        max_length=80,
        error_messages={'required': 'Nama Group tidak boleh kosong'},
        widget=TextInput(attrs={'class': "form-control",
                                'placeholder': "Role name", 'id': 'role_name'}),
        validators=[alphanumeric]
    )

    class Meta:
        model = Group
        fields = ('name', 'permissions')
        widgets = {
            'filter': TextInput(attrs={'class': "form-control", }),
        }


import xml.etree.ElementTree as ET
import XmlObj as XmlTableObj
import XmlKDoMock as XmlKDataObject
from XmlKDoMock import xml2Class as xml2class
from xml2.references import References as xml2ref
from xml2.references import ExtendReferences as xml2extdref
from xml2.references import ExternalReferences as xml2extlref

tree = ET.ElementTree(file='DB.xml')
root = tree.getroot()

kdo_class_list = {}
for class_element in root:
	kdo_class_obj = xml2class(class_element.attrib["Name"])
	kdo_class_list[ class_element.attrib["Name"] ] = kdo_class_obj

for class_element in root:
	#print(class_element.attrib["Name"])
	curr_class_name = class_element.attrib["Name"]
	kdo_class_obj = kdo_class_list[curr_class_name]
	for class_chirld in class_element:
		if class_chirld.tag == 'ExternalReferences':
			for external_reference_element in class_chirld:
				extl_obj = xml2extlref(curr_class_name, external_reference_element.attrib['SourceName'], external_reference_element.attrib['TargetName'], external_reference_element.attrib['ClassName'])
				kdo_class_obj.AddBeforeClass(extl_obj.MyBeforeClass())
				kdo_class_obj.AddReference(extl_obj.MyDotHCode())
				kdo_class_obj.AddCollectionFunction(extl_obj.MyDotHCollectionFunction())
				kdo_class_obj.AddRelListFunction(extl_obj.MyDotCppCollectionFunction())
				kdo_class_obj.AddInitRef(extl_obj.MyInitDotCppCode())

				rel_kdo_class_obj = kdo_class_list[extl_obj.RelClassName()]
				rel_kdo_class_obj.AddBeforeClass(extl_obj.RelBeforeClass())
				rel_kdo_class_obj.AddReference(extl_obj.RelDotHCode())
				rel_kdo_class_obj.AddCollectionFunction(extl_obj.RelDotHCollectionFunction())
				rel_kdo_class_obj.AddRelListFunction(extl_obj.RelDotCppCollectionFunction())
				rel_kdo_class_obj.AddInitRef(extl_obj.RelInitDotCppCode())
				kdo_class_list[extl_obj.RelClassName()] = rel_kdo_class_obj

		if class_chirld.tag == 'ExtendReferences':
			for extend_reference_element in class_chirld:
				extd_obj = xml2extdref(curr_class_name, extend_reference_element.attrib['SourceName'], extend_reference_element.attrib['TargetName'], extend_reference_element.attrib['ClassName'], extend_reference_element.attrib['Relation'])
				kdo_class_obj.AddBeforeClass(extd_obj.MyBeforeClass())
				kdo_class_obj.AddReference(extd_obj.MyDotHCode())
				kdo_class_obj.AddRefField(extd_obj.RelDotHField_Syskey())
				kdo_class_obj.AddInitRefField(extd_obj.RelDotCppField_Syskey())
				kdo_class_obj.AddInitRef(extd_obj.MyInitDotCppCode())

				rel_kdo_class_obj = kdo_class_list[extd_obj.RelClassName()]
				rel_kdo_class_obj.AddBeforeClass(extd_obj.RelBeforeClass())
				rel_kdo_class_obj.AddReference(extd_obj.RelDotHCode())

				rel_kdo_class_obj.AddCollectionFunction(extd_obj.RelDotHCollectionFunction())
				rel_kdo_class_obj.AddRelListFunction(extd_obj.RelDotCppCollectionFunction())
				kdo_class_list[extd_obj.RelClassName()] = rel_kdo_class_obj

		if class_chirld.tag == 'References':
			for reference_element in class_chirld:
				ref_obj = xml2ref(curr_class_name, reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation'])
				kdo_class_obj.AddBeforeClass(ref_obj.MyBeforeClass())
				kdo_class_obj.AddReference(ref_obj.MyDotHCode())
				kdo_class_obj.AddInitRef(ref_obj.MyInitDotCppCode())
				if curr_class_name == 'ManufactureProcess':
					print(ref_obj.my_class_name)
				kdo_class_obj.AddRefField(ref_obj.RelDotHField_Syskey())
				kdo_class_obj.AddInitRefField(ref_obj.RelDotCppField_Syskey())

				rel_kdo_class_obj = kdo_class_list[ref_obj.RelClassName()]
				rel_kdo_class_obj.AddBeforeClass(ref_obj.RelBeforeClass())
				rel_kdo_class_obj.AddReference(ref_obj.RelDotHCode())
				rel_kdo_class_obj.AddCollectionFunction(ref_obj.RelDotHCollectionFunction())
				rel_kdo_class_obj.AddInitRef(ref_obj.RelInitDotCppCode())
				rel_kdo_class_obj.AddRelListFunction(ref_obj.RelDotCppCollectionFunction())
				kdo_class_list[ref_obj.RelClassName()] = rel_kdo_class_obj

		if class_chirld.tag == 'Properties':
			for property_element in class_chirld:
				#print('    ', property_element.attrib["Type"], property_element.attrib["Name"])
				kdo_class_obj.AddMemberVariable(property_element.attrib["Type"], property_element.attrib["Name"])
	kdo_class_list[curr_class_name] = kdo_class_obj

print('--------------------------')
for class_name, stub_obj in kdo_class_list.items():
	#stub_obj.Write2File('KDataObject\\')
	stub_obj.Write2DotHFile('KDataObject\\')
	stub_obj.Write2DotCppFile('KDataObject\\')
	#stub_obj.Write2DotHFile('')
	#stub_obj.Write2DotCppFile('')
print('----------生成TableObj----------')
table_obj_list = []
for class_element in root:
	#print(class_element.attrib["Name"])
	table_obj_class_obj = XmlTableObj.xml2Class(class_element.attrib["Name"])
	for class_chirld in class_element:
		#if class_chirld.tag == 'References':
			#for reference_element in class_chirld:
				##print('    ', reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation'])
				#table_obj_class_obj.AddReference(reference_element.attrib['Name'], reference_element.attrib['Type'], reference_element.attrib['Relation'])
		if class_chirld.tag == 'Properties':
			for property_element in class_chirld:
				#print('    ', property_element.attrib["Type"], property_element.attrib["Name"])
				table_obj_class_obj.AddMemberVariable(property_element.attrib["Type"].lower(), property_element.attrib["Name"])

	table_obj_list.append(table_obj_class_obj);

print('--------------------------')
for obj in table_obj_list:
	#obj.Write2File('KDataObject')
	obj.Write2DotHFile('TableObj')
	obj.Write2DotCppFile('TableObj')
report = '生成' + str(len(table_obj_list)) + '個KDataObject.h檔案\n'
report += '生成' + str(len(table_obj_list)) + '個KDataObject.cpp檔案\n'
report += '生成' + str(len(table_obj_list)) + '個TableObj.h檔案\n'
report += '生成' + str(len(table_obj_list)) + '個TableObj.cpp檔案\n'
print(report)
'''檔案生成，資料夾要保留，才會順利生成。'''


from PyQt5.QtWidgets import QLabel, QPushButton, QApplication, QMainWindow, QFrame, QComboBox, QFileDialog
from PyQt5.QtCore import QRect
from PyQt5.QtGui import QFont
import sys

from concurrent.futures import ThreadPoolExecutor
import time
from license.func import license_func
from func import tracking_func

class myWindow(QMainWindow):

    def __init__(self):
        super(myWindow, self).__init__()
        self.setGeometry(430, 150, 585, 440)
        self.setWindowTitle('Video Selection Tool')
        self.initUI()

    def initUI(self):
        self.path1 = None
        self.path2 = None
        self.path3 = None
        self.path4 = None
        self.checkVideo = 0

        self.line_1 = QFrame(self)
        self.line_1.setGeometry(QRect(30, 10, 521, 20))
        self.line_1.setFrameShape(QFrame.HLine)

        self.line_2 = QFrame(self)
        self.line_2.setGeometry(QRect(20, 20, 20, 391))
        self.line_2.setFrameShape(QFrame.VLine)

        self.line_3 = QFrame(self)
        self.line_3.setGeometry(QRect(540, 20, 20, 391))
        self.line_3.setFrameShape(QFrame.VLine)

        self.line_4 = QFrame(self)
        self.line_4.setGeometry(QRect(30, 400, 521, 20))
        self.line_4.setFrameShape(QFrame.HLine)

        self.label = QLabel(self)
        self.label.setText("Smart Traffic Camera")
        self.label.move(210, 40)
        self.label.setFont(QFont('MS Shell Dlg 2', 12, QFont.Bold))
        self.label.adjustSize()

        self.comboBox = QComboBox(self)
        self.comboBox.setGeometry(QRect(220, 90, 151, 31))
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItem("Select Operation")
        self.comboBox.addItem("Traffic scheduling")
        self.comboBox.addItem("Number Plate Detection")

        self.video_1 = QPushButton(self)
        self.video_1.setText('Video 1')
        self.video_1.setGeometry(QRect(120, 170, 141, 31))
        self.video_1.setStyleSheet("font: 75 10pt \"MS Shell Dlg 2\";")
        self.video_1.clicked.connect(self.getPath1)

        self.video_2 = QPushButton(self)
        self.video_2.setText('Video 2')
        self.video_2.setGeometry(QRect(320, 170, 141, 31))
        self.video_2.setStyleSheet("font: 75 10pt \"MS Shell Dlg 2\";")
        self.video_2.clicked.connect(self.getPath2)

        self.video_3 = QPushButton(self)
        self.video_3.setText('Video 3')
        self.video_3.setGeometry(QRect(120, 240, 141, 31))
        self.video_3.setStyleSheet("font: 75 10pt \"MS Shell Dlg 2\";")
        self.video_3.clicked.connect(self.getPath3)

        self.video_4 = QPushButton(self)
        self.video_4.setText('Video 4')
        self.video_4.setGeometry(QRect(320, 240, 141, 31))
        self.video_4.setStyleSheet("font: 75 10pt \"MS Shell Dlg 2\";")
        self.video_4.clicked.connect(self.getPath4)

        self.runButton = QPushButton(self)
        self.runButton.setText("RUN")
        self.runButton.setGeometry(QRect(220, 320, 151, 31))
        self.runButton.setStyleSheet("font: 75 11pt \"MS Shell Dlg 2\";\n""")
        self.runButton.clicked.connect(self.checkOperation)

        self.errorLabel = QLabel(self)
        self.errorLabel.setText("Either operation or video not selected!!")
        self.errorLabel.move(204, 370)
        self.errorLabel.setStyleSheet('color: red')
        self.errorLabel.adjustSize()
        self.errorLabel.setHidden(True)

    def getPath1(self):
        self.path1 = QFileDialog.getOpenFileName()[0]
        self.checkVideo = self.checkVideo + 1
        print(self.path1)

    def getPath2(self):
        self.path2 = QFileDialog.getOpenFileName()[0]
        self.checkVideo = self.checkVideo + 1
        print(self.path2)

    def getPath3(self):
        self.path3 = QFileDialog.getOpenFileName()[0]
        self.checkVideo = self.checkVideo + 1
        print(self.path3)

    def getPath4(self):
        self.path4 = QFileDialog.getOpenFileName()[0]
        self.checkVideo = self.checkVideo + 1
        print(self.path4)

    def checkOperation(self):

        if (self.comboBox.currentIndex() != 0):
            if(self.checkVideo):
                self.fetchResult()
                self.errorLabel.setHidden(True)
            else:
                self.errorLabel.setHidden(False)
        else:
            self.errorLabel.setHidden(False)

    def fetchResult(self):

        print(
            f'{self.comboBox.currentIndex()}, {self.path1}, {self.path2}, {self.path3}, {self.path4}')
        print("hello")

        if self.comboBox.currentIndex() == 1:
            executors_list = []

            with ThreadPoolExecutor(max_workers=5) as executor:
                executors_list.append(executor.submit(
                    tracking_func, 'tf', './checkpoints/yolov4-tiny-416', 416, True, 'yolov4', self.path1, './outputs/tiny.avi', 'XVID', 0.45, 0.50, False, False, True, 'window1', 'cam1.txt', 'cam2.txt', 'out1.txt', './jumpes/1'))
                executors_list.append(executor.submit(tracking_func, 'tf', './checkpoints/yolov4-tiny-416', 416, True,
                                                      'yolov4', self.path1, './outputs/tiny.avi', 'XVID', 0.45, 0.50, False, False, True, 'window2', 'cam3.txt', 'cam4.txt', 'out2.txt', './jumpes/2'))

            for x in executors_list:
                print(x.result())

        else:
            executors_list = []

            with ThreadPoolExecutor(max_workers=5) as executor:
                executors_list.append(executor.submit(
                    license_func, 'tf', './license/checkpoints/custom-416', 416, False, 'yolov4', self.path1, './license/detections/gui.avi', 'XVID', 0.45, 0.50, False, False, False, False, True))

            for x in executors_list:
                print(x.result())

def window():
    app = QApplication(sys.argv)
    win = myWindow()
    win.show()
    sys.exit(app.exec_())

window()


from Dependencia import Dependencia
from Requisito import Requisito
from Stakeholder import Stakeholder
import csv

RUTA_STAKEHOLDERS_POR_DEFECTO = "stakeholder_data.csv"
RUTA_REQUISITOS_POR_DEFECTO = "requisito_data.csv"
ESFUERZO_POR_DEFECTO = 5
MENSAJE_NO_VALIDO = "Opción no válida."

class NRP:

    def __init__(self, limite_esfuerzo: int = ESFUERZO_POR_DEFECTO):
        self._limite_esfuerzo = limite_esfuerzo
        self._requisitos: list[Requisito] = []
        self._stakeholders: list[Stakeholder] = []

    def cargar_stakeholders(self, ruta: str):
        nombres_stakeholders = []
        recomendaciones = {}
        stakeholders = []

        with open(ruta, mode='r') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            line_count = 0
            for row in csv_reader:
                if line_count == 0:
                    print(f'Columnas en CSV para Stakeholder: {row.keys()}')

                nombre_stakeholder = row["nombre"].strip()
                if nombre_stakeholder == "":
                    raise ValueError(f"Debe introducir un nombre para el stakeholder en la línea {line_count+1}.")

                nombres_stakeholders.append(nombre_stakeholder)
                recomendaciones[row["nombre"]] = row["recomendado_por"].split(";")

                line_count += 1

        stakeholders = procesar_stakeholders(nombres_stakeholders, recomendaciones)

        print(f'Cargados {line_count} stakeholders.\n')

        self._stakeholders = stakeholders

    def cargar_requisitos(self, ruta: str):
        if len(self._stakeholders) == 0:
            raise ValueError("Debe cargar los stakeholders antes que los requisitos.")

        requisitos = []
        line_count = 0

        with open(ruta, mode='r') as csv_file:
            csv_reader = csv.DictReader(csv_file)
            dependencias = {}
            for row in csv_reader:
                if line_count == 0:
                    print(f'Columnas en CSV para Requisito: {row.keys()}')

                nombre_requisito = row["nombre"].strip()

                if nombre_requisito == "":
                    raise ValueError(f"Debe introducir un nombre para el requisito en la línea {line_count+1}.")

                recomendado_por = procesar_recomendaciones_requisito(nombre_requisito, row["recomendado_por"].split(";"), self._stakeholders)
                dependencias[nombre_requisito] = row["dependencias"].split(";")

                requisito = Requisito(nombre_requisito, row["descripcion"].strip(), recomendado_por)
                requisitos.append(requisito)

                line_count += 1

        for requisito in requisitos:
            requisito._dependencias = procesar_dependencias_requisito(requisito._nombre, dependencias[requisito._nombre], requisitos)

        print(f'Cargados {line_count} requisitos.\n')

        self._requisitos = requisitos

    def mostrar_requisitos(self):
        print(" --- Requisitos --- ")
        for requisito in self._requisitos:
            print(requisito.to_long_string())
        print()

    def mostrar_stakeholders(self):
        print(" --- Stakeholders --- ")
        for stakeholder in self._stakeholders:
            print(stakeholder)
        print()

    def calcular_solucion(self):
        solucion = {}
        requisitos = sorted(self._requisitos, key=lambda r: r.importancia(), reverse=True)
        esfuerzo = 0
        sprint_actual = []
        for requisito in requisitos:
            if (requisito._coste > self._limite_esfuerzo):
                continue

            if (esfuerzo + requisito._coste <= self._limite_esfuerzo):
                sprint_actual.append(requisito)
                esfuerzo += requisito._coste
            else:
                solucion["Sprint " + str(len(solucion)+1)] = list(sprint_actual)
                sprint_actual = [requisito]
                esfuerzo = requisito._coste
        solucion["Sprint " + str(len(solucion)+1)] = list(sprint_actual)

        print(" --- Solución --- ")
        for sprint in solucion:
            print("- " + sprint)
            for requisito in solucion[sprint]:
                print(requisito)
            print()

        return solucion

    def iniciar_por_consola(self):
        print(" --- NRP --- ")

        self.obtener_esfuerzo_por_consola()

        ruta_stakeholders = input(f"\nIntroduzca la ruta del fichero de stakeholders ({RUTA_STAKEHOLDERS_POR_DEFECTO}): ")
        if ruta_stakeholders == "":
            ruta_stakeholders = RUTA_STAKEHOLDERS_POR_DEFECTO
        self.cargar_stakeholders(ruta_stakeholders)

        ruta_requisitos = input(f"Introduzca la ruta del fichero de requisitos ({RUTA_REQUISITOS_POR_DEFECTO}): ")
        if ruta_requisitos == "":
            ruta_requisitos = RUTA_REQUISITOS_POR_DEFECTO
        self.cargar_requisitos(ruta_requisitos)

        self.mostrar_opciones_menu()

    def mostrar_opciones_menu(self):
        print("\n\n\n\n\n\n\n\n\n\n\n")
        print(" --- Menú --- ")
        print("1. Mostrar requisitos")
        print("2. Mostrar stakeholders")
        print("3. Obtener recomendaciones de stakeholder")
        print("4. Calcular solución")
        print("5. Consultar esfuerzo")
        print("6. Modificar esfuerzo")
        print("7. Salir")
        input_opcion = input("\nIntroduzca una opción: ")
        while not input_opcion.isdigit():
            print(MENSAJE_NO_VALIDO)
            input_opcion = input("\nIntroduzca una opción: ")
        opcion = int(input_opcion)
        print("\n\n\n\n\n\n\n\n\n\n\n")
        if opcion == 1:
            self.mostrar_requisitos()
        elif opcion == 2:
            self.mostrar_stakeholders()
        elif opcion == 3:
            self.obtener_recomendaciones_stakeholder()
        elif opcion == 4:
            self.calcular_solucion()
        elif opcion == 5:
            self.mostrar_esfuerzo()
        elif opcion == 6:
            self.obtener_esfuerzo_por_consola()
        elif opcion == 7:
            return
        else:
            print(MENSAJE_NO_VALIDO)
        input("Presione ENTER para continuar...")
        self.mostrar_opciones_menu()

    def mostrar_esfuerzo(self):
        print(" --- Esfuerzo --- ")
        print(f"Limite de esfuerzo: {self._limite_esfuerzo}")
        print()

    def obtener_esfuerzo_por_consola(self):
        limite_esfuerzo = input("Introduzca el límite de esfuerzo: ")
        while not limite_esfuerzo.isdigit() or int(limite_esfuerzo) <= 0:
            print(MENSAJE_NO_VALIDO)
            limite_esfuerzo = input("Introduzca el límite de esfuerzo: ")
        self._limite_esfuerzo = int(limite_esfuerzo)

    def obtener_recomendaciones_stakeholder(self):
        stakeholder_input = input("Introduzca el nombre del stakeholder: ")

        stakeholder_index  = [index for (index, item) in enumerate(self._stakeholders) if item._nombre == stakeholder_input]

        if len(stakeholder_index) == 0:
            print(f"Stakeholder {stakeholder_input} no encontrado\n")
        else:
            stakeholder = self._stakeholders[stakeholder_index[0]]
            print(stakeholder.mostrar_recomendaciones())
        print()

def procesar_dependencias_requisito(nombre_requisito:str, nombres_dependencias: list[str], requisitos: list[Requisito]) -> list[Dependencia]:
    dependencias = []
    nombres_requisitos = [requisito._nombre for requisito in requisitos]
    for dependencia_name in nombres_dependencias:
        dependencia_name = dependencia_name.strip()
        if dependencia_name == "":
            continue

        dependencia_split = dependencia_name.split(".")

        if len(dependencia_split) != 2:
            raise ValueError(f"El requisito {nombre_requisito} tiene una dependencia mal formada: {dependencia_name}.")

        requisito_asociado, tipo = dependencia_split

        requisito_asociado = requisito_asociado.strip()
        tipo = tipo.strip().upper()

        if requisito_asociado == "" or tipo not in ["I", "J", "X"]:
            raise ValueError(f"El requisito {nombre_requisito} tiene una dependencia mal formada: {dependencia_name}.")

        if requisito_asociado not in nombres_requisitos:
            raise ValueError(f"Requisito {requisito_asociado} no encontrado para el requisito {nombre_requisito}.")

        if requisito_asociado == nombre_requisito:
            raise ValueError(f"El requisito {nombre_requisito} no puede depender de sí mismo.")

        if requisito_asociado in [dependencia._requisito for dependencia in dependencias]:
            raise ValueError(f"El requisito {nombre_requisito} tiene una dependencia duplicada: {requisito_asociado}.")

        dependencia = Dependencia(requisito_asociado, tipo)
        dependencias.append(dependencia)

    return dependencias

def procesar_recomendaciones_requisito(nombre_requisito:str, nombres_stakeholders_recomendadores: list[str], stakeholders: list[Stakeholder]) -> list[Stakeholder]:
    recomendado_por = []
    for stakeholder_name in nombres_stakeholders_recomendadores:
        stakeholder_name = stakeholder_name.strip()
        if stakeholder_name == "":
            continue

        stakeholder_index  = [index for (index, item) in enumerate(stakeholders) if item._nombre == stakeholder_name]

        if len(stakeholder_index) == 0:
            raise ValueError(f"Stakeholder {stakeholder_name} no encontrado para el requisito {nombre_requisito}.")

        stakeholder = stakeholders[stakeholder_index[0]]

        if stakeholder in recomendado_por:
            raise ValueError(f"El requisito {nombre_requisito} no puede ser recomendado varias veces por el stakeholder {stakeholder._nombre}.")

        recomendado_por.append(stakeholder)
    return recomendado_por

def procesar_stakeholders(nombres_stakeholders: list[str], recomendaciones: dict[str, list[str]]) -> list[Stakeholder]:
    stakeholders = []
    for stakeholder_name in nombres_stakeholders:
        stakeholder = Stakeholder(stakeholder_name)

        for recomendador in recomendaciones[stakeholder_name]:
            recomendador = recomendador.strip()
            if recomendador == "":
                continue

            if recomendador == stakeholder_name:
                raise ValueError(f"El stakeholder {stakeholder_name} no puede recomendarse a sí mismo.")

            if recomendador in stakeholder._recomendado_por:
                raise ValueError(f"El stakeholder {stakeholder_name} no puede ser recomendado varias veces por {recomendador}.")

            if recomendador not in nombres_stakeholders:
                raise ValueError(f"Stakeholder {recomendador} no encontrado para el stakeholder {stakeholder_name}.")

            stakeholder.aniadir_recomendacion(recomendador)

        stakeholders.append(stakeholder)
    return stakeholders


import sys, bisect
input = sys.stdin.readline

_ = input()
nums = list(map(int, input().split()))
arr, lis_len = [], []
for num in nums:
    idx = bisect.bisect_left(arr, num)
    lis_len.append(idx+1)
    if idx == len(arr):
        arr.append(num)
    else:
        arr[idx] = num

result = []
length = max(lis_len)
for i in range(len(lis_len)-1, -1, -1):
    if lis_len[i] == length:
        result.append(nums[i])
        length -= 1

print(len(result))
for i in reversed(result):
    print(i, end=' ')

14003(가장 긴 증가하는 부분 수열 5).py


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score

# Load the data
df = pd.read_csv('real_estate_data.csv')

# Explore the data
print(df.head())

# Feature engineering
df['age_years'] = df['age'] / 12

# Split the data into train and test sets
X = df[['house_size', 'age_years', 'num_rooms']].values
y = df['price'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Train the model
model = LinearRegression()
model.fit(X_train, y_train)

# Evaluate the model
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print('MSE:', mse)
print('R2:', r2)

# Predict the price of a new property
new_house = np.array([1500, 5, 3])
new_house = new_house.reshape(1, -1)
new_price = model.predict(new_house)[0]
print('Predicted price:', new_price)


import cv2
import argparse

from ultralytics import YOLO
import supervision as sv
import numpy as np

import pandas as pd

# File path of the Excel file
file_path = r'C:\Users\Администратор\Downloads\Wrenches.xlsx'

# Sheet name to read
sheet_name = 'Лист1'

# Read Excel file
df = pd.read_excel(file_path, sheet_name=sheet_name)

# Display the data in the DataFrame
print(df)

# User input prompt to request information based on ID

ZONE_POLYGON = np.array([
    [0, 0],
    [0.6, 0],
    [0.6, 1],
    [0, 1]
])

def parse_arguments() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="YOLOv8 live")
    parser.add_argument(
        "--webcam-resolution",
        default=[1150, 720],
        nargs=2,
        type=int
    )
    args = parser.parse_args()
    return args

def main():
    args = parse_arguments()
    frame_width, frame_height = args.webcam_resolution

    cap = cv2.VideoCapture(0)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, frame_width)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frame_height)

    model = YOLO("yolov8l.pt")

    box_annotator = sv.BoxAnnotator(
        thickness=2,
        text_thickness=2,
        text_scale=1
    )

    zone_polygon = (ZONE_POLYGON * np.array(args.webcam_resolution)).astype(int)
    zone = sv.PolygonZone(polygon=zone_polygon, frame_resolution_wh=tuple(args.webcam_resolution))
    zone_annotator = sv.PolygonZoneAnnotator(
        zone=zone,
        color=sv.Color.red(),
        thickness=2,
        text_thickness=4,
        text_scale=2
    )

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

        result = model(frame, agnostic_nms=True)[0]
        detections = sv.Detections.from_yolov8(result)
        labels = [
            #f"{model.model.names[class_id]} {confidence:0.2f}"
            "wrenches"
            for _, confidence, class_id, _
            in detections
        ]
        frame = box_annotator.annotate(
            scene=frame,
            detections=detections,
            labels=labels
        )

        zone.trigger(detections=detections)
        frame = zone_annotator.annotate(scene=frame)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        # https://medium.com/analytics-vidhya/gaussian-blurring-with-python-and-opencv-ba8429eb879b
        blur = cv2.GaussianBlur(gray, (41,41), 0)
        thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
        print(cv2.THRESH_BINARY, cv2.THRESH_OTSU)

        # Morphological transformations https://docs.opencv.org/4.x/d9/d61/tutorial_py_morphological_ops.html
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
        opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
        # Find contours https://learnopencv.com/contour-detection-using-opencv-python-c/
        # CHAIN_APPROX_SIMPLE
        # Алгоритм сжимает горизонтальные, вертикальные и диагональные сегменты вдоль контура и оставляет только их конечные точки.
        # Это означает, что любая из точек вдоль прямых путей будет отклонена, и у нас останутся только конечные точки.
        cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cnts = cnts[0] if len(cnts) == 2 else cnts[1]

        i=1
        for c in cnts:
            # Find perimeter of contour
            perimeter = cv2.arcLength(c, True)
            # Perform contour approximation
            approx = cv2.approxPolyDP(c, 0.04 * perimeter, True)
            # print(approx)
            # We assume that if the contour has more than a certain
            # number of verticies, we can make the assumption
            # that the contour shape is a circle
            if len(approx) > 0:

                # Obtain bounding rectangle to get measurements
                x, y, w, h = cv2.boundingRect(c)

                # Find measurements
                diameter = w
                radius = w / 2

                # Find centroid
                M = cv2.moments(c)

                if M["m00"] != 0:
                    cX = int(M["m10"] / M["m00"])
                    cY = int(M["m01"] / M["m00"])
                # print(cX,cY)
                # Draw the contour and center of the shape on the image
                # cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),4)
                cv2.drawContours(frame, [c], 0, (36, 255, 12), 1)
                # cv2.circle(image, (cX, cY), 15, (320, 159, 22), -1)

                # Draw line and diameter information
                # cv2.line(image, (x, y + int(h/2)), (x + w, y + int(h/2)), (156, 188, 24), 3)
                # cv2.putText(image, "Diameter: {}".format(diameter), (cX - 150, cY - 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (156, 188, 24), 3)
                font = cv2.FONT_HERSHEY_SIMPLEX

        # org
                org = (cX, cY)

        # fontScale
                fontScale = 1

        # Blue color in BGR
                color = (255, 0, 0)

        # Line thickness of 2 px
                thickness = 2

        # Using cv2.putText() method
                frame = cv2.putText(frame,str(i), org, font, fontScale, color, thickness, cv2.LINE_AA)
                i=i+1
        # Displaying the image
                cv2.imshow("yolov8", frame)

                if (cv2.waitKey(30) == 27):
                    break
            request = i

            try:
                id = int(request)
                result = df[df['id'] == id]
                if result.empty:
                    print("id not found.")
                else:
                    print(result)
            except ValueError:
                print("Invalid input. Please enter a valid integer id.")

if __name__ == "__main__":
    main()


def is_one_edit(s1, s2):
    # Difference of two or more characters - instant fail. Can use abs()
    # here, but would rather not for the purposes of this exercise
    if len(s1) - len(s2) >= 2 or len(s2) - len(s1) >= 2:
        return False

    # Find the shorter string - it will only be one char shorter by this point
    shortest = s1 if len(s1) < len(s2) else s2
    mismatched = 1 if len(s1) != len(s2) else 0
    for i in range(len(shortest)):
        if s1[i] != s2[i]:
            mismatched += 1
        if mismatched > 1:
            return False

    return True

if __name__ == '__main__':
    s1 = 'pale'
    s2 = 'pale'
    print(is_one_edit(s1, s2))


# -*- coding: utf-8 -*-
import scrapy
import json
from datetime import datetime

class GeelySpider(scrapy.Spider):
    name = 'geely'
    allowed_domains = ['geely.com']
    start_urls = ['https://www.geely.com/api/geely/official/get/getprovincelist']
    header = {
        'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; ZoomSpider.net bot; .NET CLR 1.1.4322)',
        'Referer': 'ttps://www.geely.com',
    }

    def parse(self, response):
        provinces = json.loads(response.text)
        for p in provinces:
            next_page = 'https://www.geely.com/api/geely/official/get/getcitylist?provinceid={}'.format(p['regionId'])
            yield response.follow(next_page, callback=self.parse_city,
                                  cb_kwargs=dict(province=p))

    def parse_city(self, response, province):
        citys = json.loads(response.text)
        for c in citys:
            next_page = 'https://www.geely.com/api/geely/official/get/' \
                        'GetDealer?seriesCode=&province={}&city={}&keyword='.format(province['regionId'], c['regionId'])
            yield response.follow(next_page, callback=self.parse_dlr,
                                  cb_kwargs=dict(province=province, city=c))

    def parse_dlr(self, response, province, city):
                dealers = json.loads(response.text)
                for dlr in dealers:
                    if dlr['dealerId'] == 16180:
                        dlr['coordinates'] = '116.376747,40.018948'
                    dealer = {
                        '编号': dlr['dealerId'],
                        '省份': province['regionName'],
                        '城市': city['regionName'],
                        '县区': '',
                        '品牌': self.name,
                        '公司名称': dlr['dealerName'],
                        '联系电话': dlr['bizPhone'],
                        '地址': dlr['address'],
                        '经度': dlr['coordinates'][:11] if dlr['coordinates'] else '',
                        '纬度': dlr['coordinates'][11:] if dlr['coordinates'] else '',
                        '坐标': dlr['coordinates'],
                        'crawlTime': datetime.today(),
                    }
                    yield dealer


# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 19:28:15 2021

@author: mendez
"""

import numpy as np
# Some interpolators

def interp_Space_1D(phi,x_old,x_new,n_B,alpha,l,P):
     # Phi is the spatial basis (old grid)
     # x_old is the old grid
     # x_new is the (given) new grid
     # n_B is the number of RBFs
     # alpha is the penalization parameter
    return phi_new

def interp_Space_2D(phi,x_old,x_new,n_B,alpha,l1,l2,P):
     # Phi is the spatial basis (old grid)
     # x_old is the old grid
     # x_new is the (given) new grid
     # n_B is the number of RBFs
     # alpha is the penalization parameter
     # P is the kind of penalty:
        # 1 is L1 penalty on the weights
        # 2 is L2 penalty on the weights

    return phi_new

def interp_Time(psi_old,t_old,t_new,n_B,sigma,P,alpha):
     # Phi is the spatial basis (old grid)
     # x_old is the old grid
     # x_new is the (given) new grid
     # n_B is the number of RBFs
     # alpha is the penalization parameter
     # P is the kind of penalty:
         # 1 is L1 penalty on the weights
         # 2 is L2 penalty on the weights

     #%% Step 1: Given the X axis, we fix the RBF collocation
     Y_MEAN=psi_old.mean()
     psi_S=psi_old-Y_MEAN
     T_P=np.linspace(t_old.min(),t_old.max(),n_B)
     n_t_o=t_old.shape[0]
     Psi_T_o=np.zeros((n_t_o,n_B)) # Initialize Data Matrix
     for j in range(0,n_B):
       Psi_T_o[:,j]=np.exp(-(T_P[j]-t_old)**2/sigma**2)
    # Solve the regularized regression (for now only L2)
    # min J(w)= ||psi_old-Psi_T_o*w_psi||_2+alpha*||w_psi||_2
     w_psi=np.linalg.inv(Psi_T_o.T.dot(Psi_T_o)+\
          alpha*np.eye(n_B)).dot(Psi_T_o.T).dot(psi_S)
    # Now we prepare the matrix for interpolation
     n_x_n=t_new.shape[0]
     Psi_T_n=np.zeros((n_x_n,n_B)) # Initialize Data Matrix
     for j in range(0,n_B):
       Psi_T_n[:,j]=np.exp(-(T_P[j]-t_new)**2/sigma**2)
    # Finally perform the interpolation
     phi_new=Psi_T_n.dot(w_psi)+Y_MEAN

     return phi_new

def POD(D,R):

    K=np.dot(D.T,D)
    Psi_P,Lambda_P,_=np.linalg.svd(K)
    # The POD has the unique feature of providing the amplitude of the modes
    # with no need of projection. The amplitudes are:
    Sigma_P=(Lambda_P)**0.5;
    # We take R modes
    Sigma_P_t=Sigma_P[0:R]
    Sigma_P_Inv_V=1/Sigma_P_t
    # Accordingly we reduce psi_P
    Psi_P_t=Psi_P[:,0:R]
    # So we have the inverse
    Sigma_P_Inv=np.diag(Sigma_P_Inv_V)
    Phi=np.linalg.multi_dot([D,Psi_P[:,0:R],Sigma_P_Inv])

    return Phi, Sigma_P_t, Psi_P_t


import guassian as g

data = [(2,2),(4,3),(6,1),(8,3),(10,2)]
k = len(data)

'''based on newton lagrange mtehod from page 108. worked on example he did.'''

matrix = []

for i in range(k):
    matrix.append([1])
    prev_entry = 1
    for j in range(1, k):
        if j > i:
            matrix[i].append(0)
        else:
            entry = (data[i][0] - data[j - 1][0]) * prev_entry
            matrix[i].append(entry)
            prev_entry = entry
    matrix[i].append(data[i][1])

for i in matrix:
    print(i)

print(g.gelim(matrix))


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

#!/usr/bin/env python

#スクリプト

#python make_mut_document_2.py test_CosmicNCV.csv hg38.fa

import pandas as pd
from Bio import SeqIO
import re
import sys

mut_file=sys.argv[1]
ref_fasta=sys.argv[2]

df_cosmic=pd.read_table(mut_file)
df_cut=df_cosmic[['ID_SAMPLE', 'ID_tumour','genome position','WT_SEQ', 'MUT_SEQ']]

del df_cosmic

#レファレンスファイルについて

list_id=[]
list_desc=[]
list_seq=[]

#biopythonを用いて、idやdesc、seqを抽出

for record in SeqIO.parse(ref_fasta, 'fasta'):
    id_part = record.id
    desc_part = record.description
    seq = record.seq

    list_id.append(id_part)
    list_desc.append(desc_part)
    list_seq.append(seq)

#mutについて、genome positiionから、chrとsingle positionに分ける
list_cut_chr=[]
list_cut_pos=[]
for i in range(len(df_cut)):
    list_cut_chr.append((re.split('[:-]',df_cut['genome position'][i]))[0])
    list_cut_pos.append((re.split('[:-]',df_cut['genome position'][i]))[1])
df_cut['chr']=pd.Series(list_cut_chr)
df_cut['single position']=pd.Series(list_cut_pos)

#mutのdfからchr23、24、MUT_SEQのnanを除く

df_cut_chr=df_cut[(df_cut['chr'] != '23') & (df_cut['chr'] != '24') & (df_cut['chr'] != '25')]
df_cut_chr.dropna(subset=['MUT_SEQ'],inplace=True)
df_cut_chr.dropna(subset=['WT_SEQ'],inplace=True)

#indexを振り直す
df_cut_chr_i=df_cut_chr.reset_index()

del df_cut_chr

#refから変異位置の前後の配列を抽出
seq_before=[]
seq_after=[]
for i in range(len(df_cut_chr_i)):
    seq_before.append(list_seq[list_id.index('chr'+df_cut_chr_i['chr'][i])][int(df_cut_chr_i['single position'][i])-2])
    seq_after.append(list_seq[list_id.index('chr'+df_cut_chr_i['chr'][i])][int(df_cut_chr_i['single position'][i])])

#df_cut_chr_iにつなげる
df_cut_chr_i['seq_before']=pd.Series(seq_before)
df_cut_chr_i['seq_after']=pd.Series(seq_after)

#大文字に変更
df_cut_chr_i['seq_before']=df_cut_chr_i['seq_before'].str.upper()
df_cut_chr_i['seq_after']=df_cut_chr_i['seq_after'].str.upper()

#3文字の配列にする（seq_forwardが鋳型）
df_cut_chr_i['seq_forward']=df_cut_chr_i['seq_before']+df_cut_chr_i['MUT_SEQ']+df_cut_chr_i['seq_after']
df_cut_chr_i['seq_forward_r']=df_cut_chr_i['seq_after']+df_cut_chr_i['MUT_SEQ']+df_cut_chr_i['seq_before']

#辞書型で相補鎖に変換
dict_base={"A":"T","G":"C","C":"G","T":"A"}

list_seq_reverse=[]
list_wt_seq_reverse=[]
for i in range(len(df_cut_chr_i)):
    list_seq_reverse.append((df_cut_chr_i['seq_forward_r'][i]).translate(str.maketrans(dict_base)))
    list_wt_seq_reverse.append((str(df_cut_chr_i['WT_SEQ'][i])).translate(str.maketrans(dict_base)))
df_cut_chr_i['seq_reverse']=pd.Series(list_seq_reverse)
df_cut_chr_i['WT_seq_reverse']=pd.Series(list_wt_seq_reverse)

#ID_tumorのカウント
dict_tumor_id=df_cut_chr_i['ID_tumour'].value_counts().to_dict()
list_tumor_id = list(dict_tumor_id.keys())

#以下、ID_tumorごとに取り出し変異をテキストに書き込む
df_index_for_id=pd.DataFrame()
for i in list_tumor_id:
    df_index_for_id['index_{}'.format(i)]=pd.Series((df_cut_chr_i[df_cut_chr_i['ID_tumour']==i]).index)
    for j in df_index_for_id['index_{}'.format(i)]:
        if pd.isnull(j)==True:
            continue
        else:
            with open("text_2/{}.txt".format(i), "a") as f:
                if (df_cut_chr_i.iloc[int(j)])['WT_SEQ']=='C'or (df_cut_chr_i.iloc[int(j)])['WT_SEQ']=='T':
                    f.write((df_cut_chr_i.iloc[int(j)])['WT_SEQ']+'>'+(df_cut_chr_i.iloc[int(j)])['MUT_SEQ']+\
                    '_'+(df_cut_chr_i.iloc[int(j)])['seq_forward'][0:1]+\
                    (df_cut_chr_i.iloc[int(j)])['seq_forward'][2:3]+' ')
                elif(df_cut_chr_i.iloc[int(j)])['WT_SEQ']=='A'or (df_cut_chr_i.iloc[int(j)])['WT_SEQ']=='G':
                    f.write((df_cut_chr_i.iloc[int(j)])['WT_seq_reverse']+'>'+(df_cut_chr_i.iloc[int(j)])['seq_reverse'][1:2]+\
                    '_'+(df_cut_chr_i.iloc[int(j)])['seq_reverse'][0:1]+\
                    (df_cut_chr_i.iloc[int(j)])['seq_reverse'][2:3]+' ')
                else:
                    continue


#!/usr/bin/python3

# Author: Ethan Boswell
# NLP implementation of MBTI personality predictions using dominant and auxiliary cognitive functions

# Judging functions:
# Te (extroverted thinking); Ti (introverted thinking)
# Fe (extroverted feeling); Fi (introverted feeling)

# Perceiving functions:
# Se (extroverted sensing); Si (introverted sensing)
# Ne (extroverted intuition); Ni (introverted intuition)

alphabetical_list = ["FeNi", "FeSi", "FiNe", "FiSe", "NeFi", "NeTi", "NiFe", "NiTe", "SeFi", "SeTi", "SiFe", "SiTe", "TeNi", "TeSi", "TiNe", "TiSe"]

# Make MBTI predictions on a set of posts.
# Using the current random forest classifier to predict on a test list
# Since the classifier sorts the labels in alphabetical order, the predictions
# will occur in the following order via predict_proba:

# FeNi, FeSi, FiNe, FiSe,
# NeFi, NeTi, NiFe, NiTe,
# SeFi, SeTi, SiFe, SiTe,
# TeNi, TeSi, TiNe, TiSe
def predict_sets(classifier, test_list):
    standard_predictions = classifier.predict(test_list)
    my_predictions = classifier.predict_proba(test_list)
    my_labels = []

    # Based on the order described above, looks through the list of
    # predicted values and averages them. For the primary cognitive function,
    # the highest average value is determined to be the primary function.
    for pred in my_predictions:
        primary_index = primary(pred)
        secondary_index = secondary(pred, primary_index)

        my_pred = make_prediction(primary_index, secondary_index)
        my_labels.append(my_pred)

    return standard_predictions, my_labels

# Get the average of each primary cognitive function prediction value and
# return the highest value and its index
def primary(prediction):
    primary_pred_value = 0.0
    tmp_value = 0.0
    index_found = 0

    for i in range(len(prediction)):
        if i % 2 == 1:
            continue
        tmp_value = (prediction[i] + prediction[i + 1]) / 2

        if tmp_value > primary_pred_value:
            primary_pred_value = tmp_value
            index_found = i

    return index_found

def secondary(prediction, primary_index):
    secondary_pred_value = 0.0
    secondary_index = 0

    if primary_index < 8:
        if primary_index < 4:
            secondary_index = primary_index + 12
        else:
            secondary_index = primary_index + 4
    else:
        if primary_index < 12:
            secondary_index = primary_index - 4
        else:
            secondary_index = primary_index - 12

    if prediction[secondary_index] > prediction[secondary_index + 1]:
        secondary_index += 1
    secondary_pred_value = prediction[secondary_index]

    return secondary_index

def make_prediction(primary_index, secondary_index):
    if secondary_index % 2 == 1:
        if primary_index % 2 == 0:
            primary_index += 1
    else:
        if primary_index % 2 == 1:
            primary_index -= 1

    return alphabetical_list[primary_index]


from futon.instruments import Crypto
from futon.data.providers import Binance
import datetime as dt
import pandas as pd
import unittest

class Methods(unittest.TestCase):
    def test_unsupported_pair(self):
        # Add your developer API keys here
        test_data = pd.read_csv(
            "tests/test_data.csv",
            parse_dates=["timestamp"],
            index_col=["timestamp"],
        )
        today = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        try:
            Crypto(
                "DOGE",
                "INR",
                data_df=test_data,
                interval="8-hour",
                start_date=today,
            )
        except Exception as e:
            self.assertTrue(isinstance(e, ValueError))
            self.assertEqual(
                str(e), "No valid symbols exist for the pair (DOGE/INR)"
            )

if __name__ == "__main__":
    unittest.main()


import socket

host = socket.gethostname()
port = 8080

#create a socket object
sock_ = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sock_.bind((host,port))
sock_.listen(1)

print("\nServer started ...\n")
#accepting the information once connection is established
conn,addr = sock_.accept()
message = "\nThank you for connecting" + str(addr)
conn.send(message.encode("ascii"))
conn.close()


from PIL import ImageTk, Image
import tkinter as tk
import numpy as np
import face_recognition
import os
#librerías para PCA
from sklearn.decomposition import PCA
# Libreria para la búsqueda de vecinos más cercanos
from sklearn.neighbors import NearestNeighbors
import time
import pickle

window = tk.Tk()
window.geometry("920x600")
title_label = tk.Label(window, text="Servicio Web de Reconocimiento Facial", font=("Arial", 16))
title_label.pack(pady=10)

name_label = tk.Label(window, text="Personaje de consulta:")
name_label.pack()
name_entry = tk.Entry(window)
name_entry.pack()

tok = tk.Label(window, text="Top-k de los personajes más parecidos:")
tok.pack()
topk_entry = tk.Entry(window)
topk_entry.pack()

canvas = tk.Canvas(window)
frame = tk.Frame(canvas)

image_tk_list = []

def search(face_encondings,image_path ,n_components=0.95, N=5):
    # extraer los vectores de codificación facial de la lista de tuplas
    face_encodings = [face_encoding[0] for face_encoding in face_encondings]

    # crear una matriz numpy de los vectores de codificación facial
    X = np.array(face_encodings)

    # crear un objeto PCA
    pca = PCA(n_components=n_components)

    # ajustar el objeto PCA a los vectores de codificación facial
    X_transformed = pca.fit_transform(X)

    # crear un objeto NearestNeighbors

    nbrs = NearestNeighbors(n_neighbors=N, algorithm='ball_tree').fit(X_transformed)

    # extraer el vector de codificación facial de la imagen de consulta
    image = face_recognition.load_image_file(image_path)
    face_locations = face_recognition.face_locations(image)

    # Verifica si se detectó al menos una cara en la imagen
    if len(face_locations) > 0:
        query = face_recognition.face_encodings(image, face_locations)[0]

        # transformar el vector de codificación facial de la imagen de consulta
        query = pca.transform([query])

        # encontrar los N vecinos más cercanos de la imagen de consulta
        inicio = time.time()
        distances, indices = nbrs.kneighbors(query)
        fin = time.time()
        duracion = fin-inicio

        topk = []
        # imprimir los N vecinos más cercanos
        for rank, index in enumerate(indices[0][:N], start=1):
            topk.append(face_encondings[index][1])
            # print(f"Rank {rank}\t{face_encondings[index][1]}")

        # print("Duración de búsqueda con PCA:",duracion,"segundos")

        return topk

def load_encodings(file_path):
    with open(file_path, 'rb') as file:
        face_encodings = pickle.load(file)
    return face_encodings

def update_image_paths(image_paths):
    name_count = {}
    updated_paths = []

    for path in image_paths:
        parts = path.split('/')
        name = parts[-2]  # Obtener el nombre de la carpeta padre

        if name in name_count:
            name_count[name] += 1
        else:
            name_count[name] = 1

        filename = parts[-1]
        filename_parts = filename.split('_')
        filename_parts[-1] = "{:04d}.jpg".format(name_count[name])
        updated_filename = "_".join(filename_parts)
        parts[-1] = updated_filename

        updated_path = "/".join(parts)
        updated_paths.append(updated_path)

    return updated_paths

def perform_search(name_entry, N_entry):
    name = name_entry.get()
    N = int(N_entry.get())

    dataset = "lfw"
    image_path = f"./{dataset}/{name}/{name}_0001.jpg"
    face_encodings = load_encodings("face_encodings.pkl")

    topk = search(face_encodings, image_path, 0.95, N)

    image_paths = [f"./{dataset}/{name}/{name}_0001.jpg" for name in topk]

    image_paths = update_image_paths(image_paths)

    print("Display")
    global image_tk_list  # Access the global variable

    padding = 10  # Padding between images
    label_width = 200  # Width of the labels
    num_columns = 4  # Number of columns in the grid layout

    num_images = len(image_paths)
    num_rows = (num_images + num_columns - 1) // num_columns  # Calculate the number of rows

    # Remove previous images
    image_tk_list.clear()

    for i, image_path in enumerate(image_paths):
        image = Image.open(image_path)
        image = image.resize((200, 200))
        image_tk = ImageTk.PhotoImage(image)
        image_tk_list.append(image_tk)  # Store the reference to avoid garbage collection

        # Calculate the row and column index
        row = i // num_columns
        column = i % num_columns

        # Create a frame for each image with padding
        image_frame = tk.Frame(frame, padx=padding, pady=padding)
        image_frame.grid(row=row, column=column)

        # Add the image label to the frame
        label_image = tk.Label(image_frame, image=image_tk)
        label_image.pack()

        # Add the name label to the frame
        label_name = tk.Label(image_frame, text="Top {} ({})".format(i + 1, topk[i]))
        label_name.pack()

        # Configure the frame width
        image_frame.configure(width=label_width)

    canvas.update_idletasks()  # Update the canvas to calculate the scrollable region
    canvas.configure(scrollregion=canvas.bbox("all"))

buscar_button = tk.Button(window, text="Buscar", command=lambda: perform_search(name_entry, topk_entry))
buscar_button.pack(pady=10)

canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

scrollbar = tk.Scrollbar(window, orient=tk.VERTICAL, command=canvas.yview)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

canvas.configure(yscrollcommand=scrollbar.set)
canvas.bind("<Configure>", lambda e: canvas.configure(scrollregion=canvas.bbox("all")))
canvas.create_window((0, 0), window=frame, anchor=tk.NW)

window.mainloop()


"""
Utils for URLs (to avoid circular imports)
"""

DASHBOARD_URL = '/dashboard/'
PROFILE_URL = '/profile/'
PROFILE_PERSONAL_URL = '{}personal/?'.format(PROFILE_URL)
PROFILE_EDUCATION_URL = '{}education/?'.format(PROFILE_URL)
PROFILE_EMPLOYMENT_URL = '{}professional/?'.format(PROFILE_URL)
SETTINGS_URL = "/settings/"
SEARCH_URL = "/learners/"
ORDER_SUMMARY = "/order_summary/"
EMAIL_URL = "/automaticemails/"
PAYMENT_CALL_BACK_URL = "/payment-callback/"

DASHBOARD_URLS = [
    DASHBOARD_URL,
    PROFILE_URL,
    PROFILE_PERSONAL_URL,
    PROFILE_EDUCATION_URL,
    PROFILE_EMPLOYMENT_URL,
    SETTINGS_URL,
    SEARCH_URL,
    ORDER_SUMMARY,
    EMAIL_URL,
]


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""Small script to parse URL (intended to use from Terraform)."""

import json
import re
import sys

URL_REGEX = re.compile('^(?:(?P<scheme>\\w+):\\/\\/)?(?P<host>[^:\\/]+)(?::(?P<port>\\d+))?(?P<path>[^\\?#]*)(?:\\?(?P<query>[^#]*))?(?:#(?P<hash>.*))?$')

def parse_url(url):
    """Parse URL and returns its parts as dict."""
    try:
        return URL_REGEX.search(url).groupdict(default='')
    except AttributeError:  # If regex did not match
        raise ValueError('invalid url')

def main():
    """Read URL from stdin, parse it, and write result into stdout."""
    input_data = json.load(sys.stdin)

    url = input_data['url']
    result = parse_url(url)

    json.dump(result, sys.stdout)

if __name__ == '__main__':
    main()


import numpy
import pandas
import openpyxl
from neo4j import GraphDatabase

def loadDataSet():  #加载数据集
    wb = openpyxl.load_workbook('Company_relationship.xlsx')
    # 读取工作表
    ws = wb['Sheet1']
    Company = []
    Ticker = []
    Primary_Industry = []
    Industry_category = []
    for col in ws['A']:
        Company.append(col.value)
    Company.remove('Company Name')
    for col in ws['B']:
        Ticker.append(col.value)
    Ticker.remove('Ticker')
    for col in ws['C']:
        Primary_Industry.append(col.value)
    Primary_Industry.remove('Primary Industry')
    for col in ws['D']:
        Industry_category.append(col.value)
    Industry_category.remove('Industry category')

    print("Company", Company)
    print("Ticker", Ticker)
    print("Primary_Industry", Primary_Industry)
    print("Industry_category", Industry_category)

    return Company, Ticker, Primary_Industry, Industry_category

class Example(object):

    def __init__(self, uri, user, password):
        self._driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):
        self._driver.close()
    #创建实体节点
    def create_Company(cls, tx, Name):
        tx.run("CREATE (:Company {Name: $Name})", Name=Name)

    def create_Ticker(cls, tx, Ticker):
        tx.run("CREATE (:Ticker {Name: $Ticker})", Ticker = Ticker)

    def create_Industry(cls, tx, Industry):
        tx.run("CREATE (:Industry {Name: $Industry})", Industry = Industry)

    def create_Industry_Category(cls, tx, Industry_Category):
        tx.run("CREATE (:Industry_Category {Name: $Industry_Category})", Industry_Category = Industry_Category)

    #创建关系
    def Company_Ticker(cls, tx, node_name1, node_name2):
        tx.run("MATCH (node1: Company {Name: $node_name1}) "
               "MATCH (node2: Ticker {Name: $node_name2}) "
               "CREATE (node1)-[:issue]->(node2)",
               node_name1=node_name1, node_name2=node_name2)

    def Company_Industry(cls, tx, node_name1, node_name2):
        print(node_name1, node_name2)
        tx.run("MATCH (node1: Company {Name: $node_name1}) "
               "MATCH (node2: Industry {Name: $node_name2}) "
               "CREATE (node1)-[:engage]->(node2)",
               node_name1=node_name1, node_name2=node_name2)

    def Industry_Classify(cls, tx, node_name1, node_name2):
        print(node_name1, node_name2)
        tx.run("MATCH (node1: Industry {Name: $node_name1}) "
               "MATCH (node2: Industry_Category {Name: $node_name2}) "
               "CREATE (node1)-[:belong_to]->(node2)",
               node_name1=node_name1, node_name2=node_name2)

    #创建Driver
    def create_Company_driver(self, message):
        with self._driver.session() as session:
            session.write_transaction(self.create_Company, message)

    def create_Ticker_driver(self, message):
        with self._driver.session() as session:
            session.write_transaction(self.create_Ticker, message)

    def create_Industry_driver(self, message):
        with self._driver.session() as session:
            session.write_transaction(self.create_Industry, message)

    def create_Industry_Category_driver(self, message):
        with self._driver.session() as session:
            session.write_transaction(self.create_Industry_Category, message)

    def create_Company_Ticker_driver(self, message1, message2):
        with self._driver.session() as session:
            session.write_transaction(self.Company_Ticker, message1, message2)

    def create_Company_Industry_driver(self, message1, message2):
        with self._driver.session() as session:
            session.write_transaction(self.Company_Industry, message1, message2)

    def create_Industry_Classify_driver(self, message1, message2):
        with self._driver.session() as session:
            session.write_transaction(self.Industry_Classify, message1, message2)

exam=Example("bolt://localhost:7687","neo4j","myneo4j")

Company, Ticker, Primary_Industry, Industry_Category = loadDataSet()
Company1 = set(Company)
Ticker1 = set(Ticker)
Primary_Industry1 = set(Primary_Industry)
Industry_Category1 = set(Industry_Category)

#导入节点
for each in Company1:
    exam.create_Company_driver(each)
for each in Ticker1:
    exam.create_Ticker_driver(each)
for each in Primary_Industry1:
    exam.create_Industry_driver(each)
for each in Industry_Category1:
    exam.create_Industry_Category_driver(each)

#导入公司和股票的关系
for i in range(0, len(Company)):
    exam.create_Company_Ticker_driver(Company[i], Ticker[i])

#导入公司和行业的关系
exam.create_Company_Industry_driver(Company[0], Primary_Industry[0])
for i in range(1, len(Company)):
    if(Company[i] != Company[i-1]):
        exam.create_Company_Industry_driver(Company[i], Primary_Industry[i])

#行业分类
s = []
for i in range(0, len(Primary_Industry)):
    if(Primary_Industry[i] not in s):
        exam.create_Industry_Classify_driver(Primary_Industry[i], Industry_Category[i])
        s.append(Primary_Industry[i])


import re

from lxml import etree

from collaborative_platform.settings import NS_MAP, XML_NAMESPACES

def get_first_xpath_match(root, xpath, namespaces):
    matches = root.xpath(xpath, namespaces=namespaces)

    if matches:
        match = matches[0]

        return match
    else:
        return None

def add_property_to_element(root, property_xpath, value):
    target_element_xpath = '/'.join(property_xpath.split('/')[:-1]) or '.'
    target_property = property_xpath.split('/')[-1]

    target_element = get_first_xpath_match(root, target_element_xpath, XML_NAMESPACES)

    if target_element is None:
        create_elements_from_xpath(root, target_element_xpath, XML_NAMESPACES)
        target_element = get_first_xpath_match(root, target_element_xpath, XML_NAMESPACES)

    if '@' in target_property:
        key = target_property.replace('@', '')
        target_element.set(key, value)

    elif 'text()' in target_property:
        target_element.text = value

    else:
        raise ValueError("Xpath for this property not pointing to attribute(@) or text (text())")

def get_or_create_element_from_xpath(root, xpath, namespaces):
    element = get_first_xpath_match(root, xpath, namespaces)

    if element is None:
        create_elements_from_xpath(root, xpath, namespaces)
        element = get_first_xpath_match(root, xpath, namespaces)

    return element

def create_elements_from_xpath(root, xpath, namespaces):
    if xpath == '.':
        return

    child_xpath = __get_child_xpath(xpath)
    child = get_first_xpath_match(root, child_xpath, namespaces)

    if child is None:
        child = __create_child_element(child_xpath)

        root.append(child)

    xpath = xpath.replace(child_xpath, '.', 1)

    return create_elements_from_xpath(child, xpath, namespaces)

def __get_child_xpath(xpath):
    """Function created to properly handle splitting xpath with URLs in elements attributes"""

    element_with_attributes_regex = r'^\.\/[^\/]+\[.+?]'
    element_without_attributes_regex = r'^\.\/[^\[\]\/]+'

    match_with_attributes = re.search(element_with_attributes_regex, xpath)
    match_without_attributes = re.search(element_without_attributes_regex, xpath)

    if match_with_attributes:
        child_xpath = match_with_attributes.group()

    elif match_without_attributes:
        child_xpath = match_without_attributes.group()

    else:
        raise ValueError(f"Xpath to element is incorrect: {xpath}")

    return child_xpath

def __create_child_element(child_xpath):
    name = __get_element_name(child_xpath)
    attributes = __get_element_attributes(child_xpath)

    if ':' in name:
        prefix = name.split(':')[0]
        name = name.split(':')[1]
        namespace = '{%s}' % XML_NAMESPACES[prefix]
        name = namespace + name

    child = etree.Element(name, nsmap=NS_MAP)

    if attributes:
        for key, value in attributes.items():
            child.set(key, value)

    return child

def __get_element_name(child_xpath):
    name = child_xpath.replace('./', '')
    name = name.split('[')[0]

    return name

def __get_element_attributes(child_xpath):
    attributes_regex = r'\[.*?\]'
    match = re.search(attributes_regex, child_xpath)

    attributes = {}

    if match:
        attributes_part = match.group()
        attributes = __parse_attributes(attributes_part)

    return attributes

def __parse_attributes(attributes_part):
    parsed_attributes = {}

    attribute_regex = r'@\S*?=[\'"].*?[\'"]'
    attributes = re.findall(attribute_regex, attributes_part)

    for attribute in attributes:
        key = attribute.split('=')[0]
        key = key.replace('@', '')

        value = attribute.split('=')[1]
        value = re.sub(r'[\'"]', '', value)

        parsed_attributes.update({key: value})

    return parsed_attributes


import sys
from argparse import ArgumentParser
from itertools import tee

from gmail_deleter import GmailHandler

def run(args):
    gmail = GmailHandler(
        credentials_filepath=args.credentials_file, token_filepath=args.token_file
    )

    while True:
        print(
            "\n1. Print authenticated user's email address and total number of messages in the mailbox."
            "\n2. Print a list of all labels associated with the authenticated user's mailbox."
            "\n3. Delete messages with a specified label."
            "\n4. Delete messages with a specified Gmail search filter (e.g. 'from:user@domain.com')"
            "\n5. Delete all messages in Trash."
            "\n6. Delete all messages in Spam."
            "\n7. Quit."
            "\n"
        )

        try:
            choice = int(input("Choose from the listed options: "))
            if choice == 1:
                profile = gmail.get_user_profile(user_id="me")
                print(
                    f"\n[*] You are authenticated as {profile['emailAddress']}"
                    f"\n[+] Found {profile['messagesTotal']} messages in the mailbox"
                )
            elif choice == 2:
                labels = gmail.get_labels(user_id="me")
                print(
                    f"\n[+] Found the following labels in the mailbox:\n"
                    f"{[i['id'] for i in labels]}\n"
                )
            elif choice == 3:
                labels = input(
                    "\nPlease specify which label(s) you want to delete (comma separated if more than one): "
                )
                labels = labels.upper().split(",")
                messages = gmail.list_messages_with_label(
                    user_id="me", label_ids=labels
                )
                delete_type = str(
                    input("\nSoft (move to Trash) or Hard (permanent) Delete: ")
                )
                try:
                    if "soft" in delete_type.lower():
                        for message in messages:
                            delete = gmail.delete_message(
                                user_id="me", msg_id=message["id"], soft_delete=True
                            )
                        print(
                            f"\n[!] Soft deleted messages that were labeled with the following labels: {labels}"
                        )
                    elif "hard" in delete_type.lower():
                        message_ids, message_ids_2 = tee(i["id"] for i in messages)
                        if sum(1 for _ in message_ids) < 1000:
                            batch_delete = gmail.batch_delete_messages(
                                user_id="me", msg_ids=list(message_ids_2)
                            )
                        else:
                            for id in message_ids_2:
                                delete = gmail.delete_message(
                                    user_id="me", msg_id=id, soft_delete=False
                                )

                        print(
                            f"\n[!] Hard deleted messages that were labeled with the following labels: {labels}"
                        )
                except ValueError:
                    print("Invalid input! Try again.")
            elif choice == 4:
                query = input(
                    "\nPlease specify a Gmail search filter for messages you want to delete: "
                )
                query_messages = gmail.list_messages_matching_query(
                    user_id="me", query=query
                )
                delete_type = str(
                    input("\nSoft (move to Trash) or Hard (permanent) Delete: ")
                )
                try:
                    if "soft" in delete_type.lower():
                        for message in query_messages:
                            delete = gmail.delete_message(
                                user_id="me", msg_id=message["id"], soft_delete=True
                            )
                        print(
                            f"\n[!] Soft deleted messages that matched query: {query}"
                        )
                    elif "hard" in delete_type.lower():
                        query_msg_ids, query_msg_ids_2 = tee(
                            i["id"] for i in query_messages
                        )
                        if sum(1 for _ in query_msg_ids) < 1000:
                            batch_delete = gmail.batch_delete_messages(
                                user_id="me", msg_ids=list(query_msg_ids_2)
                            )
                        else:
                            for id in query_msg_ids_2:
                                delete = gmail.delete_message(
                                    user_id="me", msg_id=id, soft_delete=False
                                )
                        print(
                            f"\n[!] Hard deleted messages that matched query: {query}"
                        )
                except ValueError:
                    print("Invalid input! Try again.")
            elif choice == 5:
                trash = gmail.list_messages_with_label(
                    user_id="me", label_ids=["TRASH"]
                )
                trash_ids, trash_ids_2 = tee(i["id"] for i in trash)
                if sum(1 for _ in trash_ids) < 1000:
                    batch_delete = gmail.batch_delete_messages(
                        user_id="me", msg_ids=list(trash_ids_2)
                    )
                else:
                    for id in trash_ids_2:
                        delete = gmail.delete_message(
                            user_id="me", msg_id=id, soft_delete=False
                        )
                print("\n[!] Trash has been emptied!")
            elif choice == 6:
                spam = gmail.list_messages_with_label(user_id="me", label_ids=["SPAM"])
                spam_ids, spam_ids_2 = tee(i["id"] for i in spam)
                if sum(1 for _ in spam_ids) < 1000:
                    batch_delete = gmail.batch_delete_messages(
                        user_id="me", msg_ids=list(spam_ids_2)
                    )
                else:
                    for id in spam_ids_2:
                        delete = gmail.delete_message(
                            user_id="me", msg_id=id, soft_delete=False
                        )
                print("\n[!] Spam has been emptied!")
            elif choice == 7:
                sys.exit(1)
            else:
                print("\n[*] Invalid choice! Please try again...")

        except ValueError:
            print("\n[*] Invalid input! Please select from the following options...")

def main():
    parser = ArgumentParser(
        prog="Gmail Message Deleter",
        description="No longer is there a need to manually delete your Gmail messages page by page! Programmatically clean your Gmail inbox and delete messages en masse by specific labels or Gmail search filter syntax!",
    )
    parser.add_argument(
        "-c",
        "--credentials",
        dest="credentials_file",
        help="location of credentials.json file (required for first run!)",
        type=str,
    )
    parser.add_argument(
        "-t",
        "--token",
        dest="token_file",
        help="location of token.json file (once obtained, can be used to authenticate without supplying credentials.json)",
        type=str,
    )
    args = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    run(args)

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import os

os.system("apt-get install figlet")
os.system("clear")
os.system("figlet BHECY")
os.system("figlet PORT TARAMA")

print("""
1) Hızlı Port Tarama
2) Servis ve Versiyon bilgisi
3) Isletim Sistemi Bilgisi
""")

islemno=input("Islem Numarası giriniz : ")

if islemno=="1":
	hedefip=input("Hedef ip giriniz : ")
	os.system("nmap "+hedefip)
elif islemno=="2":
	hedefip=input("Hedef ip giriniz : ")
	os.system("nmap -sS -sV "+hedefip)
elif islemno=="3":
	hedefip=input("Hedef ip giriniz : ")
	os.system("nmap -0 "+hedefip)
else:
	print("Yanlış tuşa bastınız...")


#!/usr/bin/env python
"""
P0 Experiment 1: System baseline overhead under load.

Purpose: Measure system overhead using a canister that does
essentially nothing for typical application subnetworks. Do so for a
canister in Rust and Motoko.

For request type t in { Query, Update }
  For canister c in { Rust nop, Motoko nop }

    Topology A: 13 node subnet, 1 machine NNS
    Topology B: 34 machine NNS, 1 machine subnet
    Deploy one instance of canister c
    Run workload generators on 13 machines, increasing requests of request type t until > ~100% HTTP errors on client side
      Measure and determine (over time, probably grouped by experiment iteration):
      Requests / second
      Error rate
      Request latency
      Flamegraph (suggest one per experiment iteration, so we can also compare them)
      Maximum capacity max_cap (maximum number of successful requests per second)
      Statesync metrics (e.g. duration)
      Workload generator metrics

Suggested success criteria (Queries):
Maximum number of queries not be below yyy queries per second with less than 20% failure and a maximum latency of 5000ms

Suggested success criteria (Updates):
Maximum number of queries not be below xxx queries per second with less than 20% failure and a maximum latency of 10000ms
"""
import os
import sys
import time

import gflags
from termcolor import colored

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import common.misc as misc  # noqa
import common.workload_experiment as workload_experiment  # noqa

FLAGS = gflags.FLAGS
gflags.DEFINE_integer("num_workload_generators", -1, "Number of workload generators to run")
gflags.DEFINE_integer("initial_rps", 100, "Starting number for requests per second.")
gflags.DEFINE_integer("increment_rps", 50, "Increment of requests per second per round.")
gflags.DEFINE_integer(
    "max_rps", 40000, "Maximum requests per second to be sent. Experiment will wrap up beyond this number."
)
gflags.DEFINE_integer("num_canisters", 1, "Number of canisters to run against.")
gflags.DEFINE_boolean("use_random_payload", False, "Add random payload to queries to avoid caching.")
gflags.DEFINE_string("payload_size", "",
                     "Size of the payload. Has to be >0 in order for use_random_payload to work. Example: 42KiB")

class BaselineExperiment(workload_experiment.WorkloadExperiment):
    """Logic for experiment 1."""

    def __init__(self):
        """Construct experiment 1."""
        super().__init__(
            num_workload_gen=FLAGS.num_workload_generators,
            request_type="call" if FLAGS.use_updates else "query",
        )
        for _ in range(FLAGS.num_canisters):
            self.install_canister(self.target_nodes[0])

    def get_payload_size():
        if len(FLAGS.payload_size) > 0:
            return FLAGS.payload_size
        else:
            if FLAGS.use_random_payload:
                return "1KiB"
            else:
                return "0KiB"

    def run_experiment_internal(self, config):
        """Run workload generator with the load specified in config."""
        arguments = config["arguments"] if "arguments" in config else []
        if self.use_updates:
            arguments.append("-u")
        duration = config["duration"] if "duration" in config else 300

        if self.use_updates and len(self.target_nodes) < 2:
            print(
                colored("тЪая╕П  Update requests have to be targeted at all subnet nodes when stressing the system.", "red")
            )

        return self.run_workload_generator(
            self.machines,
            self.target_nodes,
            config["load_total"],
            arguments=arguments,
            duration=duration,
        )

    def run_iterations(self, iterations=None):
        """Exercise the experiment with specified iterations."""
        if iterations is None:
            iterations = []

        run = True
        iteration = 0
        rps_max = 0
        rps_max_in = None
        rps_max_iter = []
        num_succ_per_iteration = []
        rps = []
        failure_rate = 0.0
        t_median = 0.0
        duration = []
        t_average = 0.0
        t_max = 0.0
        t_min = 0.0
        total_requests = 0
        num_success = 0
        num_failure = 0

        while run:

            load_total = iterations[iteration]
            iteration += 1

            rps.append(load_total)
            print(f"ЁЯЪА Testing with load: {load_total} and updates={self.use_updates}")

            iter_duration = FLAGS.iter_duration
            t_start = int(time.time())
            config = {
                "load_total": load_total,
                "duration": iter_duration,
            }
            if FLAGS.use_random_payload:
                config["arguments"] = [
                    "--random-query-payload",
                    f"--payload-size={BaselineExperiment.get_payload_size()}"
                ]
            evaluated_summaries = super().run_experiment(config)
            (
                failure_rate,
                t_median_list,
                t_average_list,
                t_max_list,
                t_min_list,
                _,
                total_requests,
                num_success,
                num_failure,
            ) = evaluated_summaries.convert_tuple()
            duration_in_iteration = int(time.time()) - t_start

            t_median, t_average, t_max, t_min, p99 = evaluated_summaries.get_latencies()

            num_succ_per_iteration.append(num_success)
            avg_succ_rate = evaluated_summaries.get_avg_success_rate(iter_duration)

            print(
                f"ЁЯЪА  ... failure rate for {load_total} rps was {failure_rate} p99 latency is {p99} (median: {t_median} from {t_median_list}, {avg_succ_rate})"
            )

            duration.append(duration_in_iteration)

            if len(iterations) == 1:
                rps_max = num_success / duration_in_iteration
                rps_max_iter.append(rps_max)
                rps_max_in = load_total
                run = False

            else:
                rps_max_iter.append(rps_max)
                if (
                    failure_rate < workload_experiment.ALLOWABLE_FAILURE_RATE
                    and t_median < workload_experiment.ALLOWABLE_LATENCY
                ):
                    if avg_succ_rate > rps_max:
                        rps_max = avg_succ_rate
                        rps_max_in = load_total

                run = (
                    failure_rate < workload_experiment.STOP_FAILURE_RATE
                    and t_median < workload_experiment.STOP_T_MEDIAN
                    and iteration < len(iterations)
                )

            # Write summary file in each iteration including experiment specific data.
            self.write_summary_file(
                "run_system_baseline_experiment" if FLAGS.use_random_payload else "run_system_baseline_experiment_cached",
                {
                    "is_update": FLAGS.use_updates,
                    "total_requests": total_requests,
                    "rps": rps,
                    "rps_max": rps_max,
                    "rps_max_in": rps_max_in,
                    "rps_max_iter": rps_max_iter,
                    "num_succ_per_iteration": num_succ_per_iteration,
                    "success_rate": (num_success / total_requests) * 100,
                    "failure_rate": failure_rate * 100,
                    "failure_rate_color": "green" if failure_rate < 0.01 else "red",
                    "t_median": t_median,
                    "t_average": t_average,
                    "t_max": t_max,
                    "t_min": t_min,
                    "duration": duration,
                    "iter_duration": iter_duration,
                    "target_load": load_total,
                    "allowable_failure_rate": workload_experiment.ALLOWABLE_FAILURE_RATE
                    if len(iterations) > 1
                    else "n.a.",
                    "allowable_latency": workload_experiment.ALLOWABLE_LATENCY if len(iterations) > 1 else "n.a.",
                },
                rps,
                "requests / s",
                rtype="update" if self.use_updates else "query",
                state="running" if run else "done",
            )

            print(f"ЁЯЪА  ... measured capacity so far is {rps_max}")

        self.end_experiment()
        return (failure_rate, t_median, t_average, t_max, t_min, total_requests, num_success, num_failure, rps_max)

if __name__ == "__main__":
    misc.parse_command_line_args()
    iterations = BaselineExperiment.get_datapoints(
        misc.get_iterations(FLAGS.target_rps, FLAGS.initial_rps, FLAGS.max_rps, FLAGS.increment_rps, 2)
    )
    exp = BaselineExperiment()
    exp.run_iterations(iterations)


import os
import sqlite3

connection = sqlite3.connect("database.db", check_same_thread=False)
connection.row_factory = sqlite3.Row

def get_database_connection(testing=False):
    if testing:
        testconnection = sqlite3.connect("testdatabase.db", check_same_thread=False)
        testconnection.row_factory = sqlite3.Row
        return testconnection
    return connection

def remove_test_database(testconnection):
    testconnection.close()
    os.remove("testdatabase.db")


from setuptools import setup, Extension

module = Extension("bytesop", sources=["bytesop.cpp"])
setup(
    name="BytesOp",
    author="Jan Brohl",
    author_email="janbrohl@t-online.de",
    url="https://github.com/janbrohl/BytesOp",
    version="0.10",
    description="Bitwise operations on bytestrings.",
    ext_modules=[module],
    test_suite="test_bytesop.TestOps",
    classifiers=[
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: BSD License",
        "Programming Language :: Python",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 2",
        "Programming Language :: C++",
        "Operating System :: OS Independent",
        "License :: OSI Approved"
    ]
)