# -*- coding: utf-8 -*-
"""The single process processing engine."""

import collections
import logging
import os
import pdb
import time

from dfvfs.resolver import context

from plaso.engine import collector
from plaso.engine import engine
from plaso.engine import queue
from plaso.engine import worker
from plaso.lib import definitions
from plaso.lib import errors
from plaso.parsers import mediator as parsers_mediator

class SingleProcessCollector(collector.Collector):
  """Class that implements a single process collector object."""

  def __init__(self, path_spec_queue, resolver_context=None):
    """Initializes the collector object.

       The collector discovers all the files that need to be processed by
       the workers. Once a file is discovered it is added to the process queue
       as a path specification (instance of dfvfs.PathSpec).

    Args:
      path_spec_queue: the path specification queue (instance of Queue).
                       This queue contains the path specifications (instances
                       of dfvfs.PathSpec) of the file entries that need
                       to be processed.
      resolver_context: optional resolver context (instance of dfvfs.Context).
    """
    super(SingleProcessCollector, self).__init__(
        path_spec_queue, resolver_context=resolver_context)

    self._extraction_worker = None
    self._fs_collector = SingleProcessFileSystemCollector(
        path_spec_queue, resolver_context=resolver_context,
        status_update_callback=self._UpdateStatus)

  def _FlushQueue(self):
    """Flushes the queue callback for the QueueFull exception."""
    self._UpdateStatus()
    while not self._queue.IsEmpty():
      self._extraction_worker.Run()

  def _UpdateStatus(self):
    """Updates the processing status."""
    # Set the collector status to waiting while emptying the queue.
    self._status = definitions.PROCESSING_STATUS_WAITING

  def SetExtractionWorker(self, extraction_worker):
    """Sets the extraction worker.

    Args:
      extraction_worker: the extraction worker object (instance of
                         EventExtractionWorker).
    """
    self._extraction_worker = extraction_worker

    self._fs_collector.SetExtractionWorker(extraction_worker)

class SingleProcessEngine(engine.BaseEngine):
  """Class that defines the single process engine."""

  _STATUS_CHECK_SLEEP = 1.5

  def __init__(self, maximum_number_of_queued_items=0):
    """Initialize the single process engine object.

    Args:
      maximum_number_of_queued_items: the maximum number of queued items.
                                      The default is 0, which represents
                                      no limit.
    """
    path_spec_queue = SingleProcessQueue(
        maximum_number_of_queued_items=maximum_number_of_queued_items)
    event_object_queue = SingleProcessQueue(
        maximum_number_of_queued_items=maximum_number_of_queued_items)
    parse_error_queue = SingleProcessQueue(
        maximum_number_of_queued_items=maximum_number_of_queued_items)

    super(SingleProcessEngine, self).__init__(
        path_spec_queue, event_object_queue, parse_error_queue)

    self._collector = None
    self._extraction_worker = None
    self._event_queue_producer = SingleProcessItemQueueProducer(
        event_object_queue)
    self._last_status_update_timestamp = time.time()
    self._parse_error_queue_producer = SingleProcessItemQueueProducer(
        parse_error_queue)
    self._status_update_callback = None
    self._storage_writer = None

  def _CreateCollector(
      self, filter_find_specs=None, include_directory_stat=True,
      resolver_context=None):
    """Creates a collector object.

       The collector discovers all the files that need to be processed by
       the workers. Once a file is discovered it is added to the process queue
       as a path specification (instance of dfvfs.PathSpec).

    Args:
      filter_find_specs: optional list of filter find specifications (instances
                         of dfvfs.FindSpec).
      include_directory_stat: optional boolean value to indicate whether
                              directory stat information should be collected.
      resolver_context: optional resolver context (instance of dfvfs.Context).

    Returns:
      A collector object (instance of Collector).
    """
    collector_object = SingleProcessCollector(
        self._path_spec_queue, resolver_context=resolver_context)

    collector_object.SetCollectDirectoryMetadata(include_directory_stat)

    if filter_find_specs:
      collector_object.SetFilter(filter_find_specs)

    return collector_object

  def _CreateExtractionWorker(
      self, worker_number, filter_object=None, mount_path=None,
      process_archive_files=False, text_prepend=None):
    """Creates an extraction worker object.

    Args:
      worker_number: a number that identifies the worker.
      filter_object: optional filter object (instance of objectfilter.Filter).
      mount_path: optional string containing the mount path.
      process_archive_files: optional boolean value to indicate if the worker
                             should scan for file entries inside files.
      text_prepend: optional string that contains the text to prepend to every
                    event object.

    Returns:
      An extraction worker (instance of worker.ExtractionWorker).
    """
    parser_mediator = parsers_mediator.ParserMediator(
        self._event_queue_producer, self._parse_error_queue_producer,
        self.knowledge_base)

    resolver_context = context.Context()

    extraction_worker = SingleProcessEventExtractionWorker(
        worker_number, self._path_spec_queue, self._event_queue_producer,
        self._parse_error_queue_producer, parser_mediator,
        resolver_context=resolver_context,
        status_update_callback=self._UpdateStatus)

    # TODO: differentiate between debug output and debug mode.
    extraction_worker.SetEnableDebugMode(self._enable_debug_output)

    extraction_worker.SetEnableProfiling(
        self._enable_profiling,
        profiling_sample_rate=self._profiling_sample_rate,
        profiling_type=self._profiling_type)

    extraction_worker.SetProcessArchiveFiles(process_archive_files)

    if filter_object:
      extraction_worker.SetFilterObject(filter_object)

    if mount_path:
      extraction_worker.SetMountPath(mount_path)

    if text_prepend:
      extraction_worker.SetTextPrepend(text_prepend)

    return extraction_worker

  def _UpdateCollectorStatus(self, processing_completed=False):
    """Updates the collector status.

    Args:
      processing_completed: optional boolean value the processing has been
                            completed.
    """
    status = self._collector.GetStatus()
    status_indicator = status.get(u'processing_status', None)
    produced_number_of_path_specs = status.get(
        u'produced_number_of_path_specs', 0)

    if processing_completed:
      status_indicator = definitions.PROCESSING_STATUS_COMPLETED
    elif status_indicator == definitions.PROCESSING_STATUS_INITIALIZED:
      status_indicator = definitions.PROCESSING_STATUS_RUNNING

    self._processing_status.UpdateCollectorStatus(
        u'Collector', os.getpid(), produced_number_of_path_specs,
        status_indicator, None)

  def _UpdateExtractionWorkerStatus(self, processing_completed=False):
    """Updates the extraction worker status.

    Args:
      processing_completed: optional boolean value the processing has been
                            completed.
    """
    status = self._extraction_worker.GetStatus()
    status_indicator = status.get(u'processing_status', None)
    consumed_number_of_path_specs = status.get(
        u'consumed_number_of_path_specs', 0)
    display_name = status.get(u'display_name', u'')
    number_of_events = status.get(u'number_of_events', 0)
    produced_number_of_path_specs = status.get(
        u'produced_number_of_path_specs', 0)

    if processing_completed:
      status_indicator = definitions.PROCESSING_STATUS_COMPLETED
    elif status_indicator in (
        definitions.PROCESSING_STATUS_COMPLETED,
        definitions.PROCESSING_STATUS_INITIALIZED):
      # If the worker is initialized or completed in single
      # processing mode it is actually waiting for input.
      status_indicator = definitions.PROCESSING_STATUS_WAITING

    self._processing_status.UpdateExtractionWorkerStatus(
        u'Worker', os.getpid(), display_name, number_of_events,
        consumed_number_of_path_specs, produced_number_of_path_specs,
        status_indicator, None)

  def _UpdateStorageWriterStatus(self, processing_completed=False):
    """Updates the storage writer status.

    Args:
      processing_completed: optional boolean value the processing has been
                            completed.
    """
    status = self._storage_writer.GetStatus()
    status_indicator = status.get(u'processing_status', None)
    number_of_events = status.get(u'number_of_events', 0)

    if processing_completed:
      status_indicator = definitions.PROCESSING_STATUS_COMPLETED
    elif status_indicator in (
        definitions.PROCESSING_STATUS_COMPLETED,
        definitions.PROCESSING_STATUS_INITIALIZED):
      # If the storage writer is initialized or completed in single
      # processing mode it is actually waiting for input.
      status_indicator = definitions.PROCESSING_STATUS_WAITING

    self._processing_status.UpdateStorageWriterStatus(
        u'StorageWriter', os.getpid(), number_of_events, status_indicator, None)

  def _UpdateStatus(self, processing_completed=False):
    """Updates the processing status.

    Args:
      processing_completed: optional boolean value the processing has been
                            completed.
    """
    current_timestamp = time.time()
    if current_timestamp < (
        self._last_status_update_timestamp + self._STATUS_CHECK_SLEEP):
      return

    self._UpdateCollectorStatus(processing_completed=processing_completed)
    self._UpdateExtractionWorkerStatus(
        processing_completed=processing_completed)
    self._UpdateStorageWriterStatus(processing_completed=processing_completed)

    if self._status_update_callback:
      self._status_update_callback(self._processing_status)

    self._last_status_update_timestamp = current_timestamp

  def ProcessSources(
      self, source_path_specs, storage_writer, filter_find_specs=None,
      filter_object=None, hasher_names_string=None, include_directory_stat=True,
      mount_path=None, parser_filter_string=None, process_archive_files=False,
      resolver_context=None, status_update_callback=None, text_prepend=None):
    """Processes the sources and extract event objects.

    Args:
      source_path_specs: list of path specifications (instances of
                         dfvfs.PathSpec) to process.
      storage_writer: a storage writer object (instance of BaseStorageWriter).
      filter_find_specs: optional list of filter find specifications (instances
                         of dfvfs.FindSpec).
      filter_object: optional filter object (instance of objectfilter.Filter).
      hasher_names_string: optional comma separated string of names of
                           hashers to enable.
      include_directory_stat: optional boolean value to indicate whether
                              directory stat information should be collected.
      mount_path: optional string containing the mount path.
      parser_filter_string: optional parser filter string.
      process_archive_files: optional boolean value to indicate if the worker
                             should scan for file entries inside files.
      resolver_context: optional resolver context (instance of dfvfs.Context).
      status_update_callback: optional callback function for status updates.
      text_prepend: optional string that contains the text to prepend to every
                    event object.

    Returns:
      The processing status (instance of ProcessingStatus).
    """
    self._collector = self._CreateCollector(
        filter_find_specs=filter_find_specs,
        include_directory_stat=include_directory_stat,
        resolver_context=resolver_context)

    self._extraction_worker = self._CreateExtractionWorker(
        0, filter_object=filter_object, mount_path=mount_path,
        process_archive_files=process_archive_files,
        text_prepend=text_prepend)

    self._storage_writer = storage_writer

    self._status_update_callback = status_update_callback

    if hasher_names_string:
      self._extraction_worker.SetHashers(hasher_names_string)

    self._extraction_worker.InitializeParserObjects(
        parser_filter_string=parser_filter_string)

    # Set the extraction worker and storage writer values so that they
    # can be accessed if the QueueFull exception is raised. This is
    # needed in single process mode to prevent the queue consuming too
    # much memory.
    self._collector.SetExtractionWorker(self._extraction_worker)
    self._event_queue_producer.SetStorageWriter(self._storage_writer)
    self._parse_error_queue_producer.SetStorageWriter(self._storage_writer)

    logging.debug(u'Processing started.')

    self._UpdateStatus()
    self._collector.Collect(source_path_specs)

    self._UpdateStatus()
    self._extraction_worker.Run()

    self._UpdateStatus()
    self._storage_writer.WriteEventObjects()

    self._UpdateStatus(processing_completed=True)

    # Reset the extraction worker and storage writer values to return
    # the objects in their original state. This will prevent access
    # to the extraction worker outside this function and allow it
    # to be garbage collected.
    self._extraction_worker = None
    self._storage_writer = None
    self._status_update_callback = None
    self._event_queue_producer.SetStorageWriter(None)
    self._parse_error_queue_producer.SetStorageWriter(None)
    self._collector = None

    logging.debug(u'Processing completed.')

    return self._processing_status

  def SignalAbort(self):
    """Signals the engine to abort."""
    self._event_queue_producer.SignalAbort()
    self._parse_error_queue_producer.SignalAbort()

    if self._collector:
      self._collector.SignalAbort()

class SingleProcessEventExtractionWorker(worker.BaseEventExtractionWorker):
  """Class that defines the single process event extraction worker."""

  def __init__(
      self, identifier, path_spec_queue, event_queue_producer,
      parse_error_queue_producer, parser_mediator, resolver_context=None,
      status_update_callback=None):
    """Initializes the event extraction worker object.

    Args:
      identifier: the identifier, usually an incrementing integer.
      path_spec_queue: the path specification queue (instance of Queue).
                       This queue contains the path specifications (instances
                       of dfvfs.PathSpec) of the file entries that need
                       to be processed.
      event_queue_producer: the event object queue producer (instance of
                            ItemQueueProducer).
      parse_error_queue_producer: the parse error queue producer (instance of
                                  ItemQueueProducer).
      parser_mediator: a parser mediator object (instance of ParserMediator).
      resolver_context: optional resolver context (instance of dfvfs.Context).
      status_update_callback: optional callback function for status updates.
    """
    super(SingleProcessEventExtractionWorker, self).__init__(
        identifier, path_spec_queue, event_queue_producer,
        parse_error_queue_producer, parser_mediator,
        resolver_context=resolver_context)

    self._status_update_callback = status_update_callback

  def _ConsumeItem(self, path_spec, **kwargs):
    """Consumes an item callback for ConsumeItems.

    Args:
      path_spec: a path specification (instance of dfvfs.PathSpec).

    Raises:
      QueueFull: If a queue is full.
    """
    if self._status_update_callback:
      self._status_update_callback()

    super(SingleProcessEventExtractionWorker, self)._ConsumeItem(
        path_spec, **kwargs)

  def _DebugProcessPathSpec(self):
    """Callback for debugging path specification processing failures."""
    pdb.post_mortem()

class SingleProcessFileSystemCollector(collector.FileSystemCollector):
  """Class that implements a single process file system collector object."""

  def __init__(
      self, path_spec_queue, resolver_context=None,
      status_update_callback=None):
    """Initializes the collector object.

       The collector discovers all the files that need to be processed by
       the workers. Once a file is discovered it is added to the process queue
       as a path specification (instance of dfvfs.PathSpec).

    Args:
      path_spec_queue: the path specification queue (instance of Queue).
                       This queue contains the path specifications (instances
                       of dfvfs.PathSpec) of the file entries that need
                       to be processed.
      processing_status: the processing status (instance of ProcessingStatus).
      resolver_context: optional resolver context (instance of dfvfs.Context).
      status_update_callback: optional callback function for status updates.
                              This callback is invoked when the collector
                              flushes its queue.
    """
    super(SingleProcessFileSystemCollector, self).__init__(
        path_spec_queue, resolver_context=resolver_context)

    self._extraction_worker = None
    self._status_update_callback = status_update_callback

  def _FlushQueue(self):
    """Flushes the queue callback for the QueueFull exception."""
    if self._status_update_callback:
      self._status_update_callback()

    while not self._queue.IsEmpty():
      self._extraction_worker.Run()

  def SetExtractionWorker(self, extraction_worker):
    """Sets the extraction worker.

    Args:
      extraction_worker: the extraction worker object (instance of
                         EventExtractionWorker).
    """
    self._extraction_worker = extraction_worker

class SingleProcessItemQueueProducer(queue.ItemQueueProducer):
  """Class that implements a single process item queue producer."""

  def __init__(self, queue_object):
    """Initializes the queue producer.

    Args:
      queue_object: the queue object (instance of Queue).
    """
    super(SingleProcessItemQueueProducer, self).__init__(queue_object)

    self._storage_writer = None

  def _FlushQueue(self):
    """Flushes the queue callback for the QueueFull exception."""
    self._storage_writer.WriteEventObjects()

  def SetStorageWriter(self, storage_writer):
    """Sets the storage writer.

    Args:
      storage_writer: the storage writer object (instance of
                      BaseStorageWriter).
    """
    self._storage_writer = storage_writer

class SingleProcessQueue(queue.Queue):
  """Single process queue."""

  def __init__(self, maximum_number_of_queued_items=0):
    """Initializes a single process queue object.

    Args:
      maximum_number_of_queued_items: the maximum number of queued items.
                                      The default is 0, which represents
                                      no limit.
    """
    super(SingleProcessQueue, self).__init__()

    # The Queue interface defines the maximum number of queued items to be
    # 0 if unlimited as does the multi processing queue, but deque uses
    # None to indicate no limit.
    if maximum_number_of_queued_items == 0:
      maximum_number_of_queued_items = None

    # maxlen contains the maximum number of items allowed to be queued,
    # where None represents unlimited.
    self._queue = collections.deque(
        maxlen=maximum_number_of_queued_items)

  def IsEmpty(self):
    """Determines if the queue is empty."""
    return len(self._queue) == 0

  def PushItem(self, item):
    """Pushes an item onto the queue.

    Raises:
      QueueFull: when the queue is full.
    """
    number_of_items = len(self._queue)

    # Deque will drop the first item in the queue when maxlen is exceeded.
    if not self._queue.maxlen or number_of_items < self._queue.maxlen:
      self._queue.append(item)
      number_of_items += 1

    if self._queue.maxlen and number_of_items == self._queue.maxlen:
      raise errors.QueueFull

  def PopItem(self):
    """Pops an item off the queue or None on timeout.

    Raises:
      QueueClose: on user abort.
      QueueEmpty: when the queue is empty.
    """
    try:
      # Using popleft to have FIFO behavior.
      return self._queue.popleft()
    except IndexError:
      raise errors.QueueEmpty
    except KeyboardInterrupt:
      raise errors.QueueClose

  def Close(self):
    """Closes this queue, indicating that no further items will be added to it.

    This method has no effect on for the single process queue, but is included
    for compatibility with the Multiprocessing queue."""
    return

  def Open(self):
    """Opens the queue, ready to enqueue or dequeue items.

    This method has no effect on for the single process queue, but is included
    for compatibility with the Multiprocessing queue."""
    return


from matplotlib import pyplot as plt
import cv2

#In open cv the color of the image is in BGR format
#in matplotlib the color of the image is in RGB format
img = cv2.imread('lena.jpg')
cv2.imshow('image',img)
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.xticks([]),plt.yticks([]) #this will remove the x and y coordinates marker
plt.imshow(img) #this will store the images into the matplotlib eindow
plt.show()   #this will show the matplotlib window
cv2.waitKey(0)
cv2.destroyAllWindows()


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

from torch.nn import Linear
from torch_geometric.nn import GCN2Conv, AGNNConv, FiLMConv
from torch_geometric.nn import SuperGATConv, APPNP
from torch_geometric.nn.conv.gcn_conv import gcn_norm
from torch.nn import Sequential, Linear, BatchNorm1d, ReLU
from torch_geometric.nn import GINConv, global_add_pool
from tqdm import tqdm

def convert(adj_t):
    row, col, edge_attr = adj_t.t().coo()
    edge_index = torch.stack([row, col], dim=0)
    return edge_index, edge_attr

class GCN2Net(torch.nn.Module):
    def __init__(self, in_channels, hidden_channels, out_channels, num_layers, alpha=0.1, theta=0.5, shared_weights=True, dropout=0.0, batchnorm=False):
        super(GCN2Net, self).__init__()

        self.lins = torch.nn.ModuleList()
        self.lins.append(Linear(in_channels, hidden_channels))
        self.lins.append(Linear(hidden_channels, out_channels))
        self.num_layers = num_layers

        self.convs = torch.nn.ModuleList()
        for layer in range(num_layers):
            self.convs.append(GCN2Conv(hidden_channels, alpha, theta, layer + 1, shared_weights, normalize=False))

        self.dropout = dropout

    def forward(self, x, adj_t):
        # print(x.shape)
        # x = x.float()
        x = F.dropout(x, p=0.5, training=self.training)
        x = x_0 = self.lins[0](x).relu()
        # print(x.dtype, x_0.dtype)
        # x = F.dropout(x, self.dropout, training=self.training)
        for i, (adj, _, size) in enumerate(adj_t):
            edge_index, edge_attr = convert(adj)
            x = F.dropout(x, p=0.5, training=self.training)
            # x = x_0 = self.lins[0](x).relu()
            x = self.convs[i](x, x_0, edge_index)
            x = F.relu(x)
            # print(x, x_0)

        x = self.lins[1](x)
        return x.log_softmax(dim=-1)

    def reset_parameters(self):
        for lin in self.lins:
            lin.reset_parameters()
        for conv in self.convs:
            conv.reset_parameters()

    def inference_all(self, data):
        x, adj_t = data.x, data.adj_t
        x = x_0 = self.lins[0](x).relu()
        for i, conv in enumerate(self.convs):
            x = conv(x, x_0, adj_t)
            x = F.relu(x)
            x = F.dropout(x, p=self.dropout, training=self.training)
        # x = self.convs[-1](x, adj_t)
        x = self.lins[1](x)
        return x.log_softmax(dim=-1)

    def inference(self, x_all, layer_loader, device):
        pbar = tqdm(total=x_all.size(0) * self.num_layers, ncols=80)
        pbar.set_description('Evaluating')

        # Compute representations of nodes layer by layer, using *all*
        # available edges. This leads to faster computation in contrast to
        # immediately computing the final representations of each batch.
        xs_ori = []
        for i in range(self.num_layers):
            xs = []
            for idx, (batch_size, n_id, adj) in enumerate(layer_loader):
                # edge_index, _, size = adj.to(device)
                adj_t, _, size = adj.to(device)
                edge_index, edge_attr = convert(adj_t)
                x = x_all[n_id].to(device)
                # x_target = x[:size[1]]
                if i == 0:
                    x = x_0 = self.lins[0](x).relu()
                    xs_ori.append(x_0.detach().cpu())

                x = self.convs[i](x, xs_ori[idx].to(device), edge_index.float())
                x = F.relu(x)
                if i == (self.num_layers - 1):
                    x = self.lins[1](x)
                xs.append(x.detach().cpu())
                pbar.update(batch_size)

            x_all = torch.cat(xs, dim=0)
        # print(x_all.shape)
        pbar.close()
        del xs, xs_ori
        torch.cuda.empty_cache()
        return x_all.log_softmax(dim=-1).to(device)


from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('kerb_auth', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='user',
            name='last_connected',
            field=models.DateTimeField(null=True, verbose_name='date last connected to service', blank=True),
        ),
    ]


from PyQt5 import QtCore, QtGui, QtWidgets
from pyqtgraph import PlotWidget , GraphicsLayoutWidget
from scipy import signal
import pyqtgraph
import numpy as np
from lib.FT import fourierTransform,soundfileUtility
import random
import re

class Slider(QtWidgets.QSlider) :
    def __init__(self,objectName,parent) :
        super(Slider,self).__init__()
        self.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        self.setMinimum(0)
        self.setMaximum(5)
        self.setSliderPosition(1)
        self.setOrientation(QtCore.Qt.Vertical)
        self.setTickPosition(QtWidgets.QSlider.TicksAbove)
        self.setTickInterval(1)
        self.setObjectName(objectName)
        self.setParent(parent)

class Tabs(QtWidgets.QTabWidget) :
    def __init__ (self) :
        super(Tabs, self).__init__()
        self.numberOfTabs = 0
    def add_new_viewer(self,timeData,voltsData) :
        self.numberOfTabs += 1
        centralwidget = centralWidget(timeData,voltsData)
        self.addTab(centralwidget, "new tab")
        self.setCurrentWidget(centralwidget)
        self.setCurrentIndex(self.numberOfTabs)
    def tabRemoved(self, index) :
        self.numberOfTabs = self.numberOfTabs - 1

# we are going to put all of our widgets inside the tab wrapped by a QWidget
class centralWidget(QtWidgets.QWidget) :
    def __init__(self,timeData,voltsData) :
        super(centralWidget,self).__init__()
        # first generating the widgets of the tab
        self.generateUiWidgets()
        # initializing important variables for plotting
        self.timeData = timeData
        self.originalVoltsData = voltsData
        self.editedVoltsData   = voltsData
        self.plot = None # original Plot
        self.plot1 = None # plot After Editing

        self.xRangeStack = []
        self.yRangeStack = []

        self.sampleTime = timeData[1] - timeData[0]
        yrange = voltsData[len(voltsData) - 1] - voltsData[0]
        self.scrollStep_x = 100 * self.sampleTime
        self.scrollStep_y = yrange / 10

        # sliders values
        for i in range(1,11) :
            setattr(self, "_value"+str(i), 1) # self._value[1-10] = 1

        #Pallete of spectrogram *viridis as deafult
        self.RGB_Pallete_1 = (0, 182, 188, 255)
        self.RGB_Pallete_2 = (246, 111, 0, 255)
        self.RGB_Pallete_3 = (75, 0, 113, 255)

        #set labels text
        ft = fourierTransform(self.originalVoltsData, int(1 / self.sampleTime))
        ranges = ft.rangesOfFrequancy

        for i in range(10) :
            getattr(getattr(self,"label"+str(i+1)),"setText")(str(ranges[i][0] / 1000 ) + " Khz : \n" + str(ranges[i][1] / 1000 ) + " Khz")

        self.HorizontalLabel1.setText("Set Minimun Frequancy")
        self.HorizontalLabel2.setText("Set Maximum Frequancy")

        # values of range of spectrogram
        self.minFreqOfSpectrogram = 0
        self.maxFreqOfSpectrogram = ranges[-1][1]

        self.horizontalSlider1.setMinimum(self.minFreqOfSpectrogram)
        self.horizontalSlider1.setMaximum(self.maxFreqOfSpectrogram)
        self.horizontalSlider1.setTickInterval(self.maxFreqOfSpectrogram / 10 )

        self.horizontalSlider2.setMinimum(self.minFreqOfSpectrogram)
        self.horizontalSlider2.setMaximum(self.maxFreqOfSpectrogram)
        self.horizontalSlider2.setSliderPosition(self.maxFreqOfSpectrogram)
        self.horizontalSlider2.setTickInterval(self.maxFreqOfSpectrogram / 10)

        self.SpectrogramViewer.clear()
        self.drawSpectrogram()

        self.xRangeOfSignal = None # [from , to]
        self.yRangeOfSignal = None

        #start plotting the data
        self.startPlotting()
        # get range of view of the plots
        self.xRangeOfSignal = [0.0,list(self.timeData)[-1]] # [from , to]
        self.yRangeOfSignal = self.plot.viewRange()[1]

    def startPlotting(self) :
        # plot original signal
        self.plot = self.OriginalSignalViewer.addPlot()
        self.plot.plot(self.timeData,self.originalVoltsData)
        # plot data After Editing
        self.plot1 = self.EditedSignalViewer.addPlot()
        self.plot1.plot(self.timeData,self.editedVoltsData)
        # range edit
        self.plot.setXRange(0.0,list(self.timeData)[-1],0)
        self.plot1.setXRange(0.0,list(self.timeData)[-1],0)

    def minSliderOfSpectrogram(self,value) :
        self.minFreqOfSpectrogram = value
        self.SpectrogramViewer.clear()
        self.drawSpectrogram()

    def maxSliderOfSpectrogram(self,value) :
        self.maxFreqOfSpectrogram = value
        self.SpectrogramViewer.clear()
        self.drawSpectrogram()

    def drawSpectrogram(self,minFreq = 1,maxFreq = 1) :
        minFreq_Slider = self.minFreqOfSpectrogram
        maxFreq_Slider = self.maxFreqOfSpectrogram
        freq = 1 / self.sampleTime
        ft = fourierTransform(self.editedVoltsData,int(freq))
        ft.deleteRangeOfFrequancy(0,minFreq_Slider)
        ft.deleteRangeOfFrequancy(maxFreq_Slider,int(freq/2))
        realsAfterEdit = ft.fn_InverceFourier(ft.data_fft)
        frequancyArr, timeArr, Sxx = signal.spectrogram(np.array(realsAfterEdit), freq)
        pyqtgraph.setConfigOptions(imageAxisOrder='row-major')

        win = self.SpectrogramViewer
        p1 = win.addPlot()

        img = pyqtgraph.ImageItem()
        p1.addItem(img)
        hist = pyqtgraph.HistogramLUTItem()
        hist.setImageItem(img)
        win.addItem(hist)
        hist.setLevels(np.min(Sxx), np.max(Sxx))
        hist.gradient.restoreState({
            'mode':
            'rgb',
            'ticks': [(0.5, self.RGB_Pallete_1), (1.0, self.RGB_Pallete_2),
                      (0.0, self.RGB_Pallete_3)]
        })
        img.setImage(Sxx)
        img.scale(timeArr[-1] / np.size(Sxx, axis=1), frequancyArr[-1] / np.size(Sxx, axis=0))
        p1.setLimits(xMin=0, xMax=timeArr[-1], yMin=0, yMax=frequancyArr[-1])
        p1.setLabel('bottom', "Time", units='s')
        p1.setLabel('left', "Frequency", units='Hz')

    def generateUiWidgets(self) :
        font = QtGui.QFont()
        font.setFamily("Arial Unicode MS")
        font.setPointSize(10)
        font.setBold(False)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(50)
        font.setStrikeOut(False)
        font.setKerning(True)
        self.setFont(font)
        self.setTabletTracking(False)
        self.gridLayout_6 = QtWidgets.QGridLayout(self)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.gridLayout_4 = QtWidgets.QGridLayout()
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.SpectrogramGroupBox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setFamily("Arial Unicode MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.SpectrogramGroupBox.setFont(font)
        self.SpectrogramGroupBox.setStyleSheet("border-color: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:0, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(255, 255, 255, 255));")
        self.SpectrogramGroupBox.setObjectName("SpectrogramGroupBox")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.SpectrogramGroupBox)
        self.gridLayout_2.setObjectName("gridLayout_2")

        self.horizontalSlider2 = QtWidgets.QSlider(self.SpectrogramGroupBox)
        font = QtGui.QFont()
        font.setPointSize(7)
        self.horizontalSlider2.setFont(font)
        self.horizontalSlider2.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        self.horizontalSlider2.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider2.setTickPosition(QtWidgets.QSlider.TicksBelow)
        self.horizontalSlider2.setTickInterval(1)
        self.horizontalSlider2.setObjectName("horizontalSlider2")
        self.gridLayout_2.addWidget(self.horizontalSlider2, 3, 0, 1, 1)

        self.SpectrogramViewer = GraphicsLayoutWidget(self.SpectrogramGroupBox)
        self.SpectrogramViewer.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.SpectrogramViewer.setStyleSheet("background-color:rgb(0,0,0)")
        self.SpectrogramViewer.setObjectName("SpectrogramViewer")
        self.gridLayout_2.addWidget(self.SpectrogramViewer, 0, 0, 1, 1)

        self.horizontalSlider1 = QtWidgets.QSlider(self.SpectrogramGroupBox)
        self.horizontalSlider1.setCursor(QtGui.QCursor(QtCore.Qt.ClosedHandCursor))
        self.horizontalSlider1.setOrientation(QtCore.Qt.Horizontal)
        self.horizontalSlider1.setTickPosition(QtWidgets.QSlider.TicksBelow)
        self.horizontalSlider1.setTickInterval(1)
        self.horizontalSlider1.setObjectName("horizontalSlider1")
        self.gridLayout_2.addWidget(self.horizontalSlider1, 1, 0, 1, 1)
        self.HorizontalLabel1 = QtWidgets.QLabel(self.SpectrogramGroupBox)
        font = QtGui.QFont()
        font.setPointSize(7)
        self.HorizontalLabel1.setFont(font)
        self.HorizontalLabel1.setAlignment(QtCore.Qt.AlignCenter)
        self.HorizontalLabel1.setObjectName("HorizontalLabel1")
        self.gridLayout_2.addWidget(self.HorizontalLabel1, 2, 0, 1, 1)
        self.HorizontalLabel2 = QtWidgets.QLabel(self.SpectrogramGroupBox)
        self.HorizontalLabel2.setAlignment(QtCore.Qt.AlignCenter)
        self.HorizontalLabel2.setObjectName("HorizontalLabel2")
        self.gridLayout_2.addWidget(self.HorizontalLabel2, 4, 0, 1, 1)

        self.gridLayout_4.addWidget(self.SpectrogramGroupBox, 0, 1, 3, 1)
        self.OriginalSignalGroupbox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setFamily("Arial Unicode MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.OriginalSignalGroupbox.setFont(font)
        self.OriginalSignalGroupbox.setObjectName("OriginalSignalGroupbox")
        self.gridLayout_5 = QtWidgets.QGridLayout(self.OriginalSignalGroupbox)
        self.gridLayout_5.setObjectName("gridLayout_5")
        self.OriginalSignalViewer = GraphicsLayoutWidget(self.OriginalSignalGroupbox)
        self.OriginalSignalViewer.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.OriginalSignalViewer.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.OriginalSignalViewer.setObjectName("OriginalSignalViewer")
        self.gridLayout_5.addWidget(self.OriginalSignalViewer, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.OriginalSignalGroupbox, 0, 0, 1, 1)
        self.EditedSignalGroupBox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setFamily("Arial Unicode MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.EditedSignalGroupBox.setFont(font)
        self.EditedSignalGroupBox.setObjectName("EditedSignalGroupBox")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.EditedSignalGroupBox)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.EditedSignalViewer = GraphicsLayoutWidget(self.EditedSignalGroupBox)
        self.EditedSignalViewer.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.EditedSignalViewer.setStyleSheet("background-color:rgb(0,0,0)")
        self.EditedSignalViewer.setObjectName("EditedSignalViewer")
        self.gridLayout_3.addWidget(self.EditedSignalViewer, 0, 0, 1, 1)
        self.gridLayout_4.addWidget(self.EditedSignalGroupBox, 2, 0, 1, 1)
        self.SignalEditorGroupBox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setFamily("Arial Unicode MS")
        font.setPointSize(10)
        font.setBold(True)
        font.setWeight(75)
        self.SignalEditorGroupBox.setFont(font)
        self.SignalEditorGroupBox.setObjectName("SignalEditorGroupBox")
        self.gridLayout = QtWidgets.QGridLayout(self.SignalEditorGroupBox)
        self.gridLayout.setObjectName("gridLayout")
        self.gridLayout_7 = QtWidgets.QGridLayout()
        self.gridLayout_7.setObjectName("gridLayout_7")

        # add 10 labels for 10 sliders
        for i in range(10) :
            setattr(self, "label" + str(i+1), QtWidgets.QLabel(self.SignalEditorGroupBox)) # self.label[1-10] = QtWidgets.QLabel(self.SignalEditorGroupBox)
            font = QtGui.QFont()
            font.setPointSize(5)
            font.setBold(False)
            font.setWeight(50)
            getattr(getattr(self,"label" + str(i + 1)),"setFont")(font) #self.label1.setFont(font)
            getattr(getattr(self,"label" + str(i + 1)),"setObjectName")("label"+str(i+1)) #self.label[1-10].setObjectName("label[1-10]")
            getattr(getattr(self,"gridLayout_7"),"addWidget")(getattr(self, "label" + str(i + 1)), 0, i, 1, 1) #self.gridLayout_7.addWidget(self.label1, 0, 0, 1, 1)

        self.gridLayout.addLayout(self.gridLayout_7, 1, 0, 1, 10)

        # add 10 sliders to gui
        for i in range(10) :
            setattr(self, "slider"+str(i+1), Slider(parent=self.SignalEditorGroupBox,objectName="Slider"+str(i+1)))
            Slid = getattr(self, "slider" + str(i + 1))
            getattr(getattr(self,"gridLayout"), "addWidget")(Slid, 0, i, 1, 1)
            # link slider to the trigger function
            Slid.valueChanged.connect(lambda v : self.fn_sliderValue(v))

        self.gridLayout_4.addWidget(self.SignalEditorGroupBox, 1, 0, 1, 1)
        self.gridLayout_6.addLayout(self.gridLayout_4, 0, 0, 1, 1)

        self.horizontalSlider1.valueChanged[int].connect(self.minSliderOfSpectrogram)
        self.horizontalSlider2.valueChanged[int].connect(self.maxSliderOfSpectrogram)
        QtCore.QMetaObject.connectSlotsByName(self)

    def fn_sliderValue(self,value):
        objectName = str(self.sender().objectName())
        sliderNumber = re.search("[0-9]+",objectName).group()
        setattr(self,"_value" + sliderNumber,value)
        self.process()

    def process(self): #(freq,complex_data,reals,time,np.abs(complex_data))
        ft = fourierTransform(list(self.originalVoltsData).copy(), 1 / self.sampleTime)
        complex_data = ft.gain(self._value1,self._value2,self._value3,self._value4,
        self._value5,self._value6,self._value7,self._value8,self._value9,self._value10)
        reals = ft.fn_InverceFourier(complex_data)
        #update Plot
        self.EditedSignalViewer.clear()
        self.plot1 = self.EditedSignalViewer.addPlot()
        self.plot1.plot(self.timeData,reals)
        self.plot1.setXRange(self.xRangeOfSignal[0],self.xRangeOfSignal[1],0)
        self.plot1.setYRange(self.yRangeOfSignal[0],self.yRangeOfSignal[1],0)
        self.editedVoltsData = np.array(reals)
        # update spectrogram
        self.SpectrogramViewer.clear()
        self.drawSpectrogram()

    def playSound(self) :
        ft = fourierTransform(list(self.editedVoltsData).copy(), 1 / self.sampleTime)
        complex_data = ft.gain(self._value1,self._value2,self._value3,self._value4,
        self._value5,self._value6,self._value7,self._value8,self._value9,self._value10)
        reals = ft.fn_InverceFourier(complex_data)
        sound = soundfileUtility()
        sound.fn_CreateSoundFile(list(reals),int(1 / self.sampleTime))
        sound.fn_PlaySoundFile()


from django.db import models
from django.contrib.auth.models import User

class Base(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True

class Employee(Base):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='employees')
    cpf = models.CharField('CPF', max_length=14, unique=True)

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


import json

for i in range(1, 7):
    with open("hsk-"+str(i)+"-including-metadata-update.json", "w", encoding="UTF8") as out_file:
        myjson = json.load(open("hsk-"+str(i)+"-including-metadata.json", encoding="UTF8"))
        for word in myjson['words']:
            try:
                word['translation-data'] = {
                    'english': word['english'],
                    'pinyin-numbered': word['pinyin-numbered'],
                    'pinyin': word['pinyin'],
                    'simplified': word['simplified'],
                    'traditional': word['traditional']
                }
                del word['english']
                del word['pinyin-numbered']
                del word['pinyin']
                del word['simplified']
                del word['traditional']
            except KeyError as exc:
                print('did not have that key')
        out_file.write(
            json.dumps(
                myjson,
                indent=4,
                ensure_ascii=False,
                separators=(',', ': ')))


from aiogram.types import Message

from loader import dp
from utils import MessageBox
from utils.states import States

@dp.message_handler(commands=["start", "help"])
async def start_and_help(message: Message):
    print(f"{message.from_user.first_name}: {message.text}")
    await message.answer(
        "Приветствую!\nДанный бот создан для поиска самых дешевых железнодорожных билетов. 🔍\n"
        "Чтобы воспользоваться поиском, введите команду /find"
    )

@dp.message_handler(commands=["find"], state="*")
async def find_ticket(message: Message):
    print(f"{message.from_user.first_name}: {message.text}")
    message_ = await message.answer(text="Приступим к поиску! 🔍\nВведите название пункта отправления:")
    MessageBox.put(message=message_, user_id=message.from_user.id)
    await States.waiting_for_departure_station.set()


import cv2
import numpy as np
import constants
import mouse

class EyeDetector:
    """
    Eye detection, gaze detection, and mouse pointer movement.
    """

    def __init__(self):

        # The landmarks from face landmark predictor.
        self.landmarks = None

    ###################################################################
    # Eye image processing section
    ###################################################################

    def __get_region(self, landmark_index):
        """
        Get the landmarks based on the index.
        :param landmark_index: find landmarks from 'constants.' like constants.LEFT_PUPIL_LANDMARK.
        :return: an array of [x, y] points of landmarks
        """

        # initialze with zeros and replace them with xy coords
        region = np.zeros(shape=(len(landmark_index), 2), dtype=np.int32)

        for i, point in enumerate(landmark_index):
            region[i] = self.landmarks[point]

        return region

    ###################################################################
    # Gaze detection section
    ###################################################################

    def __get_horizontal_pupil_direction(self):
        """
        Calculate the horizontal gaze direction based on certain horizontal thresholds.
        :return: constants.LEFT, RIGHT, or CENTER
        """

        # get center x between pupils
        left_pupil = self.__get_region(constants.LEFT_PUPIL_LANDMARK)[0]
        right_pupil = self.__get_region(constants.RIGHT_PUPIL_LANDMARK)[0]
        center_x = int((left_pupil[0] + right_pupil[0]) / 2)

        # get the x direction threshold
        # I needed landmarks that will act as x-thresholds to determine left and right.
        # Nose is the part in the body the moves the least, do it will be a good reference point.
        nose_left_x, nose_left_y = self.__get_region(constants.NOSE_TIP_LANDMARK_LEFT)[0]
        nose_right_x, nose_right_y = self.__get_region(constants.NOSE_TIP_LANDMARK_RIGHT)[0]

        # check direction
        if center_x < nose_left_x:
            return constants.LEFT
        elif center_x > nose_right_x:
            return constants.RIGHT
        else:
            return constants.CENTER

    def __get_vertical_pupil_direction(self):
        """
        Calculate the vertical gaze direction based on certain vertical thresholds.
        :return: constants.UP, DOWN, or CENTER
        """
        # get average y between pupils
        left_pupil = self.__get_region(constants.LEFT_EYELID_TOP_LANDMARK)[0]
        right_pupil = self.__get_region(constants.RIGHT_EYELID_TOP_LANDMARK)[0]
        average_y = int((left_pupil[1] + right_pupil[1]) / 2)

        nose_lower_x, nose_lower_y = self.__get_region(constants.NOSE_TIP_LANDMARK_LOW)[0]
        nose_higher_x, nose_higher_y = self.__get_region(constants.NOSE_TIP_LANDMARK_HIGH)[0]

        # Vertical gaze detection is a bit less intuitive than horizontal gaze detection.
        # I cannot use the pupil's relative position against the eye to determine
        # its vertical position. It's due to the limitation of MediaPipe face mesh:
        # the iris landmarks always stay within the eye fissure landmarks.
        # In other words, if the person looks up and the iris moves up,
        # the entire eye landmarks will follow the iris instead of just the iris moving up.
        # So, instead of using the pupil's relative position against the eye fissure as
        # the measure to determine its vertical motion,
        # I measured its distance to the tip of the nose.
        nose2nose = nose_lower_y - nose_higher_y + 1
        nose2iris = nose_lower_y - average_y
        ratio = nose2iris / nose2nose

        # check direction
        if ratio > constants.NOSE2EYE_RATIO_UP_THRESH:
            return constants.UP
        elif ratio < constants.NOSE2EYE_RATIO_DOWN_THRESH:
            return constants.DOWN
        else:
            return constants.CENTER

    def __move_mouse_with_gaze(self):
        """
        Move the mouse pointer based on the gaze.
        :return:
        """
        hor_dir = self.__get_horizontal_pupil_direction()
        ver_dir = self.__get_vertical_pupil_direction()

        mouse.move_mouse_pointer_4dir(hor_dir, ver_dir)

        return hor_dir, ver_dir

    def apply_face_center_mask(self, image):
        """
        Highlight the human outline on the webcam image to
        help the user center their body for better tracking.
        :param image:
        :return:
        """

        head_center_coordinates = (320, 260)
        head_axesLength = (125, 150)

        body_center_coordinates = (320, 500)
        body_axesLength = (225, 100)

        angle = 0
        startAngle = 0
        endAngle = 360
        color = (255, 255, 255)
        thickness = -1

        mask = np.zeros(shape=(480, 640), dtype=np.uint8)

        mask = cv2.ellipse(mask, head_center_coordinates, head_axesLength,
                           angle, startAngle, endAngle, color, thickness)

        mask = cv2.ellipse(mask, body_center_coordinates, body_axesLength,
                           angle, startAngle, endAngle, color, thickness)

        return cv2.bitwise_and(image, image, mask=mask)

    def __show_info_window(self, image, head_rotation, hor_dir, ver_dir):
        """
        Display the window that describes the status of gaze detection.

        :param image:
        :param head_rotation:
        :param hor_dir:
        :param ver_dir:
        :return:
        """

        # blur the rest of face for privacy
        blurred_image = cv2.blur(image, (21, 21))
        blurred_image = cv2.cvtColor(blurred_image, cv2.COLOR_BGR2GRAY)
        blurred_image = cv2.cvtColor(blurred_image, cv2.COLOR_GRAY2BGR)

        # draw iris
        iris_region_l = self.__get_region(constants.LEFT_IRIS_LANDMARKS)
        iris_region_r = self.__get_region(constants.RIGHT_IRIS_LANDMARKS)

        # only reveal the area near eyes
        minx = np.min(iris_region_l[:, 0]) - 15
        maxx = np.max(iris_region_r[:, 0]) + 15
        miny = np.min(iris_region_l[:, 1]) - 5
        maxy = np.max(iris_region_r[:, 1]) + 5

        blur_mask = np.zeros(shape=image.shape, dtype=np.uint8)
        blur_mask = cv2.rectangle(blur_mask, (minx, miny), (maxx, maxy), (255, 255, 255), -1)
        image = np.where(blur_mask == (255, 255, 255), image, blurred_image)

        # apply another mask
        image = self.apply_face_center_mask(image)

        (lx, ly), lr = cv2.minEnclosingCircle(iris_region_l)
        lr = int(lr)
        lx = int(lx)
        ly = int(ly)

        (rx, ry), rr = cv2.minEnclosingCircle(iris_region_r)
        rr = int(rr)
        rx = int(rx)
        ry = int(ry)

        cv2.circle(image, (lx, ly), lr, (0, 0, 255), 2)
        cv2.circle(image, (rx, ry), rr, (0, 0, 255), 2)

        head_rot_color = (255, 255, 255)

        if head_rotation != constants.CENTER:
            head_rot_color = (0, 0, 255)

            cv2.putText(image, 'Align yourself to the outline and', (20, 110),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, head_rot_color, 2)
            cv2.putText(image, 'face the camera for better result.', (20, 140),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.8, head_rot_color, 2)

        cv2.putText(image, f'Head rotation: {head_rotation}', (20, 80), cv2.FONT_HERSHEY_SIMPLEX, 1, head_rot_color, 2)

        return image

    def update(self, landmarks, bgr_img, eye_closed, head_rotation):
        """
        Update the gaze detection and control the mouse.
        """
        self.landmarks = landmarks

        hor_dir = None
        ver_dir = None

        if not eye_closed and head_rotation == constants.CENTER:
            hor_dir, ver_dir = self.__move_mouse_with_gaze()
            bgr_img = self.__show_info_window(bgr_img, head_rotation, hor_dir, ver_dir)
            bgr_img = draw_arrow(bgr_img, hor_dir, ver_dir)
            return bgr_img

        return self.__show_info_window(bgr_img, head_rotation, hor_dir, ver_dir)

def draw_arrow(image, hor_dir, ver_dir):
    """
    Draw the directional arrow on the image

    :param image:
    :param hor_dir:
    :param ver_dir:
    :return:
    """
    radius = 80

    start_point = (270, radius + 20)

    # End coordinate
    end_x = start_point[0]
    end_y = start_point[1]

    if ver_dir == constants.UP:
        end_y -= radius
    elif ver_dir == constants.DOWN:
        end_y += radius

    if hor_dir == constants.LEFT:
        end_x -= radius
    elif hor_dir == constants.RIGHT:
        end_x += radius

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

    # Line thickness
    thickness = 5

    image = cv2.arrowedLine(image, start_point, (end_x, end_y),
                            color, thickness, tipLength=0.2)
    return image


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

# Abrir csv
covid_df = pd.read_csv('COVID-19_Daily_Testing_-_By_Person.csv')

# Borrar filas NaN
covid_df = covid_df.dropna()

# Ordenar el dataframe según la columna 'Date'
covid_df.sort_values(by=['Date'], inplace=True)

# Borrar columna 'Day'
covid_df = covid_df.drop(['Day', 'Date'], axis=1)

# Insertar columna incremental 'Tiempo'
covid_df.insert(0, 'Tiempo', range(len(covid_df)))

# Creación del modelo
x = covid_df[["People Positive - Age 30-30"]]
x = (x-x.min())/(x.max()-x.min())

y = covid_df[['People Positive - Total']]

model = keras.Sequential([
    keras.layers.Dense(
        1,
        input_shape=(x.shape[1],),
        activation=None
    )
])

# Compilar el modelo
model.compile(
    optimizer=keras.optimizers.SGD(lr=0.001),
    loss='mse',
    metrics=[]
)

# Entrenar el modelo
model.fit(x, y, epochs=100, batch_size=16)

# Predecir
y_predictions = model.predict(x)

# Graficar el resultado en azul vs los datos en rojo
plt.plot(covid_df['Tiempo'], covid_df['People Positive - Total'], 'ro')
plt.plot(covid_df['Tiempo'], y_predictions, 'bo')

plt.xlabel('Tiempo')
plt.ylabel('People Positive - Total')

plt.show()


import os
import datetime
#Os Modülü Nedir?
"""
---İşletim sistemleri hakkında bilgiler, klasör işlemleri, dosya işlemleri os modülü ile yapılabilir
---
"""

result = os.name#Hangi işletim sistemi kullandığımızı çıktı olarak veriri
result = os.getcwd()#Dosya hakkında bilgi verir.Bulunduğu konumu çıktı olarak yazdırır -- Etkin dizini gösterme
#os.mkdir("yenidosya")#Aynı dizin altında yeni dosya oluşturur
#os.chdir()#Change the current working directory to the specified path. --Dizin değiştirme
result = os.listdir()
result = os.listdir('C:\\')
result = os.stat("basic_module.py")#Parametreye girilen dosya hakkında bilgileri verir --Boyut --Değiştirme tarihi -- Açma tarihi...
print(datetime.datetime.fromtimestamp(result.st_atime))#Son erişim tarihi
print(datetime.datetime.fromtimestamp(result.st_ctime))#Oluşturma tarihi
print(datetime.datetime.fromtimestamp(result.st_mtime))#Değiştirme tarihi
"""
Klasor Adı değiştirme
os.rename("klasör adı","yeni isim")
"""
"""
os.rmdir()
os.rmdirs()
--Belirtilen dosya içeriklerini veya dosyaları siler
"""
yol = os.path.abspath("basic_module.py")#Dosyanın tam konumunu çıktı olarak verir
yol = os.path.dirname('C:/Users/fb-du\Desktop\python\module/basic_module.py')#Dosya yolu girilen dosyanın dizin ismini verir
result = os.path.dirname(os.path.abspath('basic_module.py'))
result = os.path.exists('C:/Users/fb-du\Desktop\python\module/basic_module.py')#Dosya var mı yok mu ?
result = os.path.isdir('C:/Users/fb-du\Desktop\python\module/basic_module.py')#Dosya mı?
result = os.path.isfile('C:/Users/fb-du\Desktop\python\module/basic_module.py')

print(yol)
print(result)


import os
from common import (
    DECIMALS,
    ROUNDINGS,
    ROUNDING_TO_ZERO,
    FLAG_INEXACT,
    FLAG_INVALID_OPERATION,
    Context,
    Decimal,
    FlagType,
    write_line,
)

DECIMAL_COUNT = 80_000

# Round is important, so it will have multiple files.
# This will also make tests more 'parallel'.
SEEDS: tuple[int, ...] = (
    1191299818,
    68198198,
)

def write(dir: str):
    for ctx in DECIMALS:
        for index, seed in enumerate(SEEDS):
            decimals = ctx.generate(DECIMAL_COUNT, seed=seed)
            _write_round_file(dir, ctx, index, decimals)
            _write_round_exact_file(dir, ctx, index, decimals)

def _write_round_file(
    dir: str,
    ctx: Context,
    file_index: int,
    decimals: list[Decimal],
):
    operation = "round"
    ctx_python = ctx._python_context

    for rounding in ROUNDINGS:
        file_name = (
            f"{operation}_{ctx.file_header}_{rounding.swift_name}_{file_index}.txt"
        )
        path = os.path.join(dir, file_name)
        print(file_name)

        # The most important line:
        ctx_python.rounding = rounding.python

        with open(path, "w") as f:
            for d in decimals:
                ctx.flags.clear_all()
                result = ctx_python.to_integral_exact(d.value)

                excluded_flags: list[FlagType] = [FLAG_INEXACT]

                if ctx_python.is_snan(d.value):
                    excluded_flags.append(FLAG_INVALID_OPERATION)

                ctx.flags.assert_empty(excluding=excluded_flags)

                write_line(
                    f,
                    context=ctx,
                    operation=operation,
                    rounding=rounding,
                    arguments=[d],
                    expected=Decimal(result),
                )

def _write_round_exact_file(
    dir: str,
    ctx: Context,
    file_index: int,
    decimals: list[Decimal],
):
    operation = "round_exact"

    file_name = f"{operation}_{ctx.file_header}_{file_index}.txt"
    path = os.path.join(dir, file_name)
    print(file_name)

    # Rounding does not matter
    rounding = ROUNDING_TO_ZERO
    ctx_python = ctx._python_context
    ctx_python.rounding = rounding.python

    with open(path, "w") as f:
        for d in decimals:
            ctx.flags.clear_all()
            result = ctx_python.to_integral_exact(d.value)

            excluded_flags: list[FlagType] = [FLAG_INEXACT]

            if ctx_python.is_snan(d.value):
                excluded_flags.append(FLAG_INVALID_OPERATION)

            ctx.flags.assert_empty(excluding=excluded_flags)

            compare = ctx_python.compare(d.value, result)
            is_exact = ctx_python.is_zero(compare)

            if not ctx.flags.is_set(FLAG_INEXACT):
                write_line(
                    f,
                    context=ctx,
                    operation=operation,
                    rounding=rounding,
                    arguments=[d],
                    expected=Decimal(result),
                )


# -*- coding: utf-8 -*-
#
from wechat.wrapper import WeChatHandler
from wechat.models import Activity, Ticket, User
import datetime
import json

__author__ = "Epsirom"

class ErrorHandler(WeChatHandler):

    def check(self):
        return True

    def handle(self):
        return self.reply_text('对不起，您输入的信息不规范，请重试')

class DefaultHandler(WeChatHandler):

    def check(self):
        return True

    def handle(self):
        return self.reply_text('对不起，没有找到您需要的信息:(')

class HelpOrSubscribeHandler(WeChatHandler):

    def check(self):
        return self.is_text('帮助', 'help') or self.is_event('scan', 'subscribe') or \
               self.is_event_click(self.view.event_keys['help'])

    def handle(self):
        return self.reply_single_news({
            'Title': self.get_message('help_title'),
            'Description': self.get_message('help_description'),
            'Url': self.url_help(),
        })

class UnbindOrUnsubscribeHandler(WeChatHandler):

    def check(self):
        return self.is_text('解绑') or self.is_event('unsubscribe')

    def handle(self):
        self.user.student_id = ''
        self.user.save()
        return self.reply_text(self.get_message('unbind_account'))

class BindAccountHandler(WeChatHandler):

    def check(self):
        return self.is_text('绑定') or self.is_event_click(self.view.event_keys['account_bind'])

    def handle(self):
        return self.reply_text(self.get_message('bind_account'))

class BookEmptyHandler(WeChatHandler):

    def check(self):
        return self.is_event_click(self.view.event_keys['book_empty'])

    def handle(self):
        return self.reply_text(self.get_message('book_empty'))

class BookWhatHandler(WeChatHandler):

    def check(self):
        return self.is_event_click(self.view.event_keys['book_what'])

    def handle(self):
        acts = Activity.objects.filter(book_end__gte=datetime.datetime.now()).order_by('start_time')
        answer = []
        for index in range(0, len(acts)):
            if index >= 5:
                break
            answer.append({
                'Title': acts[index].name,
                'Description': acts[index].description,
                'Url': self.url_act(acts[index].id),
            })
        return self.reply_news(answer)

class GetTicketHandler(WeChatHandler):

    def check(self):
        return self.is_event_click(self.view.event_keys['get_ticket'])

    def handle(self):
        tic_flag  = False

        tic = []

        for i in Ticket.objects.all():
            if i.student_id == self.user.student_id and i.status == 1:
                    tic_flag = True
                    tic.append(i)
        answer = []
        if len(tic) == 0:
            return self.reply_text("Sorry, you have no tickets now!")
        for index in range(0, len(tic)):
            if index >= 5:
                break
            answer.append({
                'Title': tic[index].activity.name,
                'Description': tic[index].activity.description,
                'Url': self.url_tic(self.user.open_id, tic[index].unique_id),
            })
        return self.reply_news(answer)

class ClickHeaderHandler(WeChatHandler):
    actid = 0
    def check(self):
        for act in Activity.objects.all():
            if self.is_event_click(self.view.event_keys['book_header'] + str(act.id)):
                ClickHeaderHandler.actid = act.id
                return self.is_event_click(self.view.event_keys['book_header']+str(act.id))
    def handle(self):
        act = Activity.objects.get(id = ClickHeaderHandler.actid)
        currentTime = datetime.datetime.now().timestamp()
        if self.user.student_id:
            if act:
                if act.book_start.timestamp() <= currentTime:
                    if act.book_end.timestamp() > currentTime:
                        if act.remain_tickets > 0:
                            tic = Ticket.objects.filter(student_id= User.objects.get(open_id=self.user.open_id).student_id).filter(activity = act).filter(status = 1)
                            if tic:
                                return self.reply_text("您已经拥有该活动的票了。")
                            tic_id = self.get_ticket_id(act, act.total_tickets - act.remain_tickets)
                            temp = Ticket.objects.create(student_id = User.objects.get(open_id=self.user.open_id).student_id, unique_id = tic_id, activity = act, status = 1)
                            temp.save()
                            act.remain_tickets -= 1
                            act.save()
                            return self.reply_single_news({
                                    'Title':act.name,
                                    'Description':act.description,
                                    'Url':self.url_activity(tic_id),
                            })
                        else:
                            return self.reply_text("抱歉，该活动的票已被抢光。")
                    else:
                        return self.reply_text("抱歉，该活动抢票已结束。")
                else:
                    return self.reply_text("抱歉，该活动尚未开始抢票。")
            else:
                return self.reply_text("对不起，您选择的活动不存在。")
        else:
            return self.reply_text("对不起，您还未绑定学号。")

class BookHeaderHandler(WeChatHandler):

    def check(self):
        return self.is_text_command('抢票')

    def handle(self):
        str = self.input['Content'][3:]
        activity = Activity.objects.filter(key = str)
        currentTime = datetime.datetime.now().timestamp()
        if self.user.student_id:
            if activity:
                for act in activity:
                    if act.book_start.timestamp() <= currentTime:
                        if act.book_end.timestamp() > currentTime:
                            if act.remain_tickets > 0:
                                tic = Ticket.objects.filter(student_id= User.objects.get(open_id=self.user.open_id).student_id).filter(activity = act).filter(status = 1)
                                if tic:
                                    return self.reply_text("您已经拥有该活动的票了。")
                                tic_id = self.get_ticket_id(act, act.total_tickets - act.remain_tickets)
                                temp = Ticket.objects.create(student_id = User.objects.get(open_id=self.user.open_id).student_id, unique_id = tic_id, activity = act, status = 1)
                                temp.save()
                                act.remain_tickets -= 1
                                act.save()
                                return self.reply_single_news({
                                    'Title':act.name,
                                    'Description':act.description,
                                    'Url':self.url_activity(tic_id),
                            })
                            else:
                                return self.reply_text("抱歉，该活动的票已被抢光。")
                        else:
                            return self.reply_text("抱歉，该活动抢票已结束。")
                    else:
                        return self.reply_text("抱歉，该活动尚未开始抢票。")
            else:
                return self.reply_text("对不起，您输入的活动不存在。")
        else:
            return self.reply_text("对不起，您还未绑定学号。")

class CancellHeaderHandler(WeChatHandler):

    def check(self):
        return self.is_text_command('退票')

    def handle(self):
        str = self.input['Content'][3:]
        activity = Activity.objects.filter(key = str)
        currentTime = datetime.datetime.now().timestamp()
        if activity:
            for act in activity:
                if act.book_start.timestamp() <= currentTime:
                    tic = Ticket.objects.get(student_id= User.objects.get(open_id=self.user.open_id).student_id, activity = act, status = 1)
                    if tic:
                        tic.delete()
                        act.remain_tickets += 1
                        act.save()
                        return self.reply_text("退票成功。")
                    else:
                        return self.reply_text("您还尚未拥有该活动的票。")
                else:
                    return self.reply_text("抱歉，该活动尚未开始抢票。")
        else:
            return self.reply_text("对不起，您输入的活动不存在。")

class CalHandler(WeChatHandler):

    def check(self):
        return True

    def handle(self):
        return self.reply_text(eval(self.input['Content']))


import ast

from setuptools import find_packages, setup

version = 'unknown'
with open('eventmq/__init__.py') as f:
    for line in f:
        if line.startswith('__version__'):
            version = ast.parse(line).body[0].value.s
            break

setup(
    name='eventmq',
    version=version,
    description='EventMQ job execution and messaging system based on ZeroMQ',
    packages=find_packages(),
    install_requires=[
        'pyzmq==18.1.0',
        'six>=1.14,<2',
        'monotonic==0.4',
        'croniter==0.3.10',
        'future==0.15.2',
        'psutil==5.6.6',
    ],
    extras_require={
          'docs': ['Sphinx==1.5.2', ],
          'testing': [
              'flake8==3.7.8',
              'flake8-import-order==0.18.1',
              'flake8-print==3.1.0',
              'coverage==4.0.3',
              'testfixtures==4.7.0',
              'freezegun==0.3.7',
              'tl.testing==0.5',
              'mock==1.3.0'],
          },
    author='EventMQ Contributors',
    url='https://github.com/eventmq/eventmq/',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 3 - Alpha',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',
        'Topic :: System :: Distributed Computing',

        'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)',  # noqa
        'Operating System :: OS Independent',

        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    scripts=[
        'bin/emq-cli',
        'bin/emq-jobmanager',
        'bin/emq-router',
        'bin/emq-scheduler',
        'bin/emq-pubsub'
    ],
)


import matplotlib.pyplot as plt
import numpy as np

def create_fig(slots, system, fig_name, title):
    fig = plt.figure(fig_name)
    left, right = fig.subplots(nrows=1, ncols=2)
    fig.suptitle(title)

    left.plot(range(0,slots), system.backlogged_by_slot, color='orange')
    left.set_xlabel('Slot')
    left.set_ylabel('Backlogged nodes')
    left.set_xlim(left=0, right=slots)
    left.set_ylim(bottom=0)

    right.plot(range(0,slots), np.cumsum(system.arrivals_by_slot),\
            color='red', label='Total packet arrivals')
    right.plot(range(0,slots), np.cumsum(system.entering_by_slot), \
            color='blue', label='Total packets entering')
    right.plot(range(0,slots), np.cumsum(system.success_in_slot), \
            color='green', label='Total packets leaving')

    right.legend(loc="lower right")
    right.set_xlabel('Slot')
    right.set_ylabel('Packets')
    right.set_xlim(left=0, right=slots)
    right.set_ylim(bottom=0)

    plt.gcf().set_size_inches(16, 8)

def plot_Q3(slots, system):
    fig_name = 'Q3'
    title = 'Plots for Q3, lambda=1/e and qr=0.01'
    create_fig(slots, system, fig_name, title)

def plot_Q5(slots, system):
    fig_name = 'Q5'
    title = 'Plots for Q5, lambda=1/2 and qr=0.01'
    create_fig(slots, system, fig_name, title)

def plot_Q6(slots, system):
    fig_name = 'Q6'
    title = 'Plots for Q6, lambda=1/e and qr=0.1'
    create_fig(slots, system, fig_name, title)

def plot_Q4(m, backlogged_by_slot, mean_ps_empirical, mean_ps_theoretical):
    max_backed = max(backlogged_by_slot)

    fig = plt.figure('Q4_1')
    plot1, plot2 = fig.subplots(2,1)

    plot1.set_title('Frequency of each backlog value for system in Q3')
    freq1 = np.histogram(backlogged_by_slot, range(m+2))[0].tolist()
    plot1.bar(range(m+1), freq1)
    plot1.set_xlim(-1,max_backed+1)

    plot2.set_title('Normalized frequency of each backlog value for system in Q3')
    freq2 = np.histogram(backlogged_by_slot, range(m+2), density=True)[0].tolist()
    plot2.bar(range(m+1), freq2)
    plot2.set_xlim(-1,max_backed+1)
    plt.gcf().set_size_inches(16, 8)

    plt.figure('Q4_2')
    plt.title('Probability of success comparison')
    plt.plot([mean_ps_empirical]*(max_backed+1), linestyle='dashed',\
         label=('Empirical mean: '+ str(mean_ps_empirical)))
    plt.plot([mean_ps_theoretical]*(max_backed+1), linestyle='dashed', \
        label=('Theoretical mean: '+ str(mean_ps_theoretical)))
    plt.xlim(-1,max_backed + 1)
    plt.ylim(0,1)

    plt.legend()
    plt.gcf().set_size_inches(16, 8)

def plot_Q7(slots, system):
    plt.figure('Q7_1')
    plt.title('True vs estimated backlog using Pseudo-Bayesian stabilization')
    plt.plot(system.n_hat_by_slot, label='Estimated n')
    plt.plot(system.backlogged_by_slot, label='True n')

    plt.xlabel('Slot')
    plt.ylabel('n backlogged nodes')
    plt.xlim(0,slots)
    plt.ylim(bottom=0)
    plt.legend()
    plt.gcf().set_size_inches(16, 8)

    plt.figure('Q7_2')
    plt.plot(range(0,slots), np.cumsum(system.arrivals_by_slot),\
            color='red', label='Total packet arrivals')
    plt.plot(range(0,slots), np.cumsum(system.entering_by_slot), \
            color='blue', label='Total packets entering')
    plt.plot(range(0,slots), np.cumsum(system.success_in_slot), \
            color='green', label='Total packets leaving')

    plt.legend(loc="lower right")
    plt.xlabel('Slot')
    plt.ylabel('Packets')
    plt.xlim(left=0, right=slots)
    plt.ylim(bottom=0)

    plt.gcf().set_size_inches(16, 8)

def plot_Q8(arrival_rates, simulated_avg_delay, theoretical_avg_delay):
    plt.figure('Q8')
    plt.title('Average delay for a successful packet transmission')

    plt.plot(arrival_rates, simulated_avg_delay, linestyle='None', marker='o', \
        label='Empirical')
    plt.plot(arrival_rates, theoretical_avg_delay, linestyle='None', marker='x', \
        label='Theoretical')

    plt.xlabel('Arrival rate')
    plt.ylabel('Average delay')
    plt.legend()
    plt.gcf().set_size_inches(16, 8)


from currency_converter import CurrencyConverter

# c = CurrencyConverter()
# print(c.currencies)

import sys

from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow

class MyWidget(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi('design.ui', self)

        self.converter = CurrencyConverter()

        self.current_cur1 = 'RUB'
        self.current_cur2 = 'USD'

        self.update()

        self.calendarWidget.setVisible(False)
        self.hidden_description.setVisible(False)

        self.full_des_btn.clicked.connect(self.show_description)
        self.input.textChanged.connect(self.update)

    def update(self):
        cur1 = self.input.text()

        if cur1.isdigit():
            updated_cur2 = round(self.converter.convert(
                cur1,
                self.current_cur1,
                self.current_cur2
            ), 4)

            self.output.setText(str(updated_cur2))

            cur_for_1_input = round(self.converter.convert(
                1,
                self.current_cur1,
                self.current_cur2
            ), 5)

            self.cur_des.setText('1 {} = {} {}'.format(
                self.current_cur1,
                cur_for_1_input,
                self.current_cur2
            ))

            cur_for_1_output = round(self.converter.convert(
                1,
                self.current_cur2,
                self.current_cur1
            ), 5)

            self.cur_des2.setText('1 {} = {} {}'.format(
                self.current_cur2,
                cur_for_1_output,
                self.current_cur1
            ))

        else:
            self.output.setText('')
            self.cur_des.setText('Можно вводить только числа.')
            self.cur_des2.setText('')

    def show_description(self):
        if not self.hidden_description.isVisible():
            self.hidden_description.setVisible(True)
            self.full_des_btn.move(0, 433)
            self.full_des_btn.setText("Скрыть")
        else:
            self.hidden_description.setVisible(False)
            self.full_des_btn.move(6, 290)
            self.full_des_btn.setText("Развернуть")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MyWidget()
    ex.show()
    sys.exit(app.exec_())


import tensorflow as tf
import numpy as np

from .config import get as tn_config

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
	try:
		# Currently, memory growth needs to be the same across GPUs
		for gpu in gpus:
			tf.config.experimental.set_memory_growth(gpu, True)
		logical_gpus = tf.config.experimental.list_logical_devices('GPU')
		#print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
	except RuntimeError as e:
		# Memory growth must be set before GPUs have been initialized
		print(e)

mdl_yolo = tf.saved_model.load(tn_config('paths.yolo'))
mdl_yolo.trainable = False

def load_image_for_vrd_yolo(data):
	img = tf.cast(tf.image.decode_jpeg(data, channels=3), tf.float32)
	h,w,_ = img.shape
	img = tf.image.resize(img, (320, 320)) / 255.
	return img, w, h

def load_image_from_data(data, preprocess=True):
	img = tf.cast(tf.image.decode_jpeg(data, channels=3), tf.float32)
	img = tf.image.resize(img, (320, 320)) / 255.
	if preprocess:
		img = tf.expand_dims(img, 0)
		img,_ = mdl_yolo(img)
	return img

def load_image(path):
	return load_image_from_data(tf.io.read_file(path))

def resized_range(oldsz, newsz):
	if oldsz == newsz:
		for i in range(newsz):
			yield (i,slice(i,i+1,1))
	elif oldsz < newsz:
		for i in range(newsz):
			j = int(i*oldsz/newsz)
			yield (i,slice(j,j+1,1))
	else: # oldsz > newsz
		nextj = 0
		for i in range(newsz):
			j = nextj
			nextj = int(0.5+(i+1)*oldsz/newsz)
			yield (i,slice(j,nextj,1))

def safe_resize(img, neww, newh):
	out = np.zeros((newh, neww, img.shape[2]))
	for y,oldy in resized_range(img.shape[0], newh):
		for x,oldx in resized_range(img.shape[1], neww):
			out[y,x,:] = np.max(img[oldy,oldx,:],axis=(0,1))
	return out

def bbox_masks(width, height, boxes):
	mask = np.zeros((height, width, len(boxes)))
	for i in range(len(boxes)):
		bb = boxes[i] # 0=xmin 1=xmax 2=ymin 3=ymax
		mask[bb[2]:bb[3],bb[0]:bb[1],i] = 1.0
	return mask

def create_bbox_mask(width, height, *args):
	mask = bbox_masks(width, height, args)
	mask = safe_resize(mask, 64, 64)
	mask = tf.convert_to_tensor(mask)
	mask = tf.expand_dims(mask, 0)
	#mask = tf.image.resize(tf.expand_dims(mask, 0), (64,64), method=tf.image.ResizeMethod.GAUSSIAN, antialias=True)
	return mask

def create_bbox_depth_mask(depthimg, *args):
	mask = depthimg * bbox_masks(depthimg.shape[1], depthimg.shape[0], args)
	mask = safe_resize(mask, 64, 64)
	mask = tf.convert_to_tensor(mask)
	mask = tf.expand_dims(mask, 0)
	return mask

def decode_yolo_bbox(bb,w,h):
	ymin,xmin,ymax,xmax = bb
	return int(.5+xmin*w), int(.5+xmax*w), int(.5+ymin*h), int(.5+ymax*h)

def parse_yolo_results(results, width, height, iou_thr=0.5, score_thr=0.4):
	boxes = results[:,:,0:4]
	scores = results[:,:,4:]
	boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(
		boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),
		scores=tf.reshape(
			scores, (tf.shape(scores)[0], -1, tf.shape(scores)[-1])),
		max_output_size_per_class=50,
		max_total_size=50,
		iou_threshold=iou_thr,
		score_threshold=score_thr
	)
	num_objs = int(valid_detections[0])
	objs = []
	cnt = {}
	for i in range(num_objs):
		box = decode_yolo_bbox(boxes[0,i,:],width,height)
		score = float(scores[0,i])
		clsid = int(classes[0,i])
		cnt[clsid] = cnt.get(clsid, 0) + 1
		objs.append((clsid,cnt[clsid],score,box))
	return objs


import os
import gradio as gr
import numpy as np
from PIL import Image
import argparse
import pathlib
from torch.nn import functional as F

from show import *
from per_segment_anything import sam_model_registry, SamPredictor

parser = argparse.ArgumentParser()
parser.add_argument("-op", "--output-path", type=str, default='default')
args = parser.parse_args()

def point_selection(mask_sim, topk=1):
    # Top-1 point selection
    w, h = mask_sim.shape
    topk_xy = mask_sim.flatten(0).topk(topk)[1]
    topk_x = (topk_xy // h).unsqueeze(0)
    topk_y = (topk_xy - topk_x * h)
    topk_xy = torch.cat((topk_y, topk_x), dim=0).permute(1, 0)
    topk_label = np.array([1] * topk)
    topk_xy = topk_xy.cpu().numpy()

    # Top-last point selection
    last_xy = mask_sim.flatten(0).topk(topk, largest=False)[1]
    last_x = (last_xy // h).unsqueeze(0)
    last_y = (last_xy - last_x * h)
    last_xy = torch.cat((last_y, last_x), dim=0).permute(1, 0)
    last_label = np.array([0] * topk)
    last_xy = last_xy.cpu().numpy()

    return topk_xy, topk_label, last_xy, last_label

def reset_data():
    global cache_data
    cache_data = None

def inference_scribble(image):
    # in context image and mask
    ic_image = image["image"]
    ic_mask = image["mask"]
    ic_image = np.array(ic_image.convert("RGB"))
    ic_mask = np.array(ic_mask.convert("RGB"))

    # sam_type, sam_ckpt = 'vit_h', 'sam_vit_h_4b8939.pth' # SAM Model
    sam_type, sam_ckpt = 'vit_t', 'weights/mobile_sam.pt' # MobileSAM
    # sam = sam_model_registry[sam_type](checkpoint=sam_ckpt).cuda() #SAM loading
    sam = sam_model_registry[sam_type](checkpoint=sam_ckpt) #SAM loading
    # sam = sam_model_registry[sam_type](checkpoint=sam_ckpt) # MObileSAM loading
    predictor = SamPredictor(sam)

    # Image features encoding
    ref_mask = predictor.set_image(ic_image, ic_mask)
    ref_feat = predictor.features.squeeze().permute(1, 2, 0)

    ref_mask = F.interpolate(ref_mask, size=ref_feat.shape[0: 2], mode="bilinear")
    ref_mask = ref_mask.squeeze()[0]

    # Target feature extraction
    print("======> Obtain Location Prior" )
    target_feat = ref_feat[ref_mask > 0]
    target_embedding = target_feat.mean(0).unsqueeze(0)
    target_feat = target_embedding / target_embedding.norm(dim=-1, keepdim=True)
    target_embedding = target_embedding.unsqueeze(0)

    test_image = ic_image
    outputs = []

    print("======> Testing Image")
    # Image feature encoding
    predictor.set_image(test_image)
    test_feat = predictor.features.squeeze()

    # Cosine similarity
    C, h, w = test_feat.shape
    test_feat = test_feat / test_feat.norm(dim=0, keepdim=True)
    test_feat = test_feat.reshape(C, h * w)
    sim = target_feat @ test_feat

    sim = sim.reshape(1, 1, h, w)
    sim = F.interpolate(sim, scale_factor=4, mode="bilinear")
    sim = predictor.model.postprocess_masks(
        sim,
        input_size=predictor.input_size,
        original_size=predictor.original_size).squeeze()

    # Positive-negative location prior
    topk_xy_i, topk_label_i, last_xy_i, last_label_i = point_selection(sim, topk=1)
    topk_xy = np.concatenate([topk_xy_i, last_xy_i], axis=0)
    topk_label = np.concatenate([topk_label_i, last_label_i], axis=0)

    # Obtain the target guidance for cross-attention layers
    sim = (sim - sim.mean()) / torch.std(sim)
    sim = F.interpolate(sim.unsqueeze(0).unsqueeze(0), size=(64, 64), mode="bilinear")
    attn_sim = sim.sigmoid_().unsqueeze(0).flatten(3)

    # First-step prediction
    masks, scores, logits, _ = predictor.predict(
        point_coords=topk_xy,
        point_labels=topk_label,
        multimask_output=True,
        attn_sim=attn_sim,  # Target-guided Attention
        target_embedding=target_embedding  # Target-semantic Prompting
    )
    best_idx = 0

    # Cascaded Post-refinement-1
    masks, scores, logits, _ = predictor.predict(
                point_coords=topk_xy,
                point_labels=topk_label,
                mask_input=logits[best_idx: best_idx + 1, :, :],
                multimask_output=True)
    best_idx = np.argmax(scores)

    # Cascaded Post-refinement-2
    y, x = np.nonzero(masks[best_idx])
    x_min = x.min()
    x_max = x.max()
    y_min = y.min()
    y_max = y.max()
    input_box = np.array([x_min, y_min, x_max, y_max])
    masks, scores, logits, _ = predictor.predict(
        point_coords=topk_xy,
        point_labels=topk_label,
        box=input_box[None, :],
        mask_input=logits[best_idx: best_idx + 1, :, :],
        multimask_output=True)
    best_idx = np.argmax(scores)

    final_mask = masks[best_idx]
    mask_colors = np.zeros((final_mask.shape[0], final_mask.shape[1], 3), dtype=np.uint8)
    mask_colors[final_mask, :] = np.array([[128, 0, 0]])
    # Save annotations

    return [Image.fromarray((mask_colors * 0.6 + test_image * 0.4).astype('uint8'), 'RGB'),
            Image.fromarray((mask_colors ).astype('uint8'), 'RGB')]

with gr.Blocks() as demo:
    gr.Markdown("# Segmentation-Annotator-using-MobileSAM")
    gr.Markdown("To start, input an image, then use the brush to create dots on the object which you want to segment, don't worry if your dots aren't perfect as the code will find the middle of each drawn item. Then press the segment button to create masks for the object that the dots are on.")
    gr.Markdown("## Demo to run Mobile Segment Anything base model")
    gr.Markdown("""This app uses the [MobileSAM](https://github.com/ChaoningZhang/MobileSAM.git) model to get a mask from a points in an image.""")
    gr.Markdown("""Full code can be found here [SourceCode](https://github.com/ChaoningZhang/MobileSAM.git)""")
    with gr.Row():
        image_input = gr.Image(label="[Stroke] Draw on Image", tool='sketch',type='pil')
        image_output1 = gr.Image(type="pil", label="Mask with Image")
    with gr.Row():
        # examples = gr.Examples(examples=["./cardamage_example/0006.JPEG",
        #                                 "./cardamage_example/0008.JPEG",
        #                                 "./cardamage_example/0206.JPEG"],
        #                       inputs=image_input)
        examples = gr.Examples(examples="./cardamage_example", inputs=image_input)
        image_output2 = gr.Image(type="pil", label="Mask")

    image_button = gr.Button("Genarate-Segment-Mask", variant='primary')

    image_button.click(inference_scribble, inputs=image_input, outputs=[image_output1, image_output2])
    image_input.upload(reset_data)

demo.launch()


"""
This module contains the class to find Microsoft IIS configurations
inside a folder structure.
"""

import json
import os
import shutil
import tempfile
import logging
from typing import Dict, List, Optional, Tuple
from coguard_cli.discovery.config_file_finder_abc import ConfigFileFinder
import coguard_cli.discovery.config_file_finders as cff_util
from coguard_cli.print_colors import COLOR_CYAN, COLOR_TERMINATION

class ConfigFileFinderIis(ConfigFileFinder):
    """
    The class to find iis configuration files within a file system.
    """

    def _create_temp_location_and_manifest_entry(
            self,
            path_to_file_system: str,
            file_name: str,
            location_on_current_machine: str) -> Optional[Tuple[Dict, str]]:
        """
        Common helper function which creates a temporary folder location for the
        configuration files, and then analyzes include directives. It returns
        a tuple containing a manifest for a iis service and the path to the
        temporary location.
        """
        temp_location = tempfile.mkdtemp(prefix="coguard-cli-iis")
        to_copy = cff_util.get_path_behind_symlinks(
            path_to_file_system,
            location_on_current_machine
        )
        if not os.path.exists(to_copy):
            logging.error("Could not find the file or resolve the symlink at `%s`",
                          location_on_current_machine)
            return None
        # The reason we added os.sep at the end is because the file location may be
        # at the root of the path_to_file_system. In this case, if there is a separation
        # character at the end of path_to_file_system, the replace may not work.
        # That is why we just add it here.
        loc_within_machine = (os.path.dirname(location_on_current_machine)+os.sep).replace(
            path_to_file_system,
            ''
        )
        loc_within_machine = loc_within_machine[1:] \
            if loc_within_machine.startswith(os.sep) \
               else loc_within_machine
        os.makedirs(os.path.join(temp_location, loc_within_machine), exist_ok=True)
        shutil.copy(to_copy,
                    os.path.join(
                        temp_location,
                        loc_within_machine,
                        os.path.basename(location_on_current_machine)
                    ))
        manifest_entry = {
            "version": "1.0",
            "serviceName": "microsoft_iis",
            "configFileList": [
                {
                    "fileName": file_name,
                    "defaultFileName": file_name,
                    "subPath": f".{os.sep}{loc_within_machine}",
                    "configFileType": "xml"
                }
            ],
            "complimentaryFileList": []
        }
        return (
            manifest_entry,
            temp_location
        )

    def check_for_config_files_in_standard_location(
            self, path_to_file_system: str
    ) -> Optional[Tuple[Dict, str]]:
        """
        See the documentation of ConfigFileFinder for reference.
        """
        logging.debug("There is no standard location for iis files.")

    def check_for_config_files_filesystem_search(
            self,
            path_to_file_system: str
    ) -> List[Tuple[Dict, str]]:
        """
        See the documentation of ConfigFileFinder for reference.
        """
        standard_names = [
            "ApplicationHost.config",
            "administration.config",
            "Redirection.config",
            "machine.config",
            "web.config"
        ]
        result_files = []
        logging.debug("Attempting to find the standard names in the file system")
        for (dir_path, _, file_names) in os.walk(path_to_file_system):
            for standard_name in standard_names:
                logging.debug("Checking if %s is in %s",
                              standard_name,
                              json.dumps(file_names))
                if standard_name in file_names:
                    result_files.append(os.path.join(dir_path, standard_name))
        logging.debug("Found the following files with standard names in the file system: %s",
                      result_files)
        results = []
        for result_file in result_files:
            print(
                f"{COLOR_CYAN}Found file "
                f"{result_file.replace(path_to_file_system, '')}"
                f"{COLOR_TERMINATION}"
            )
            append_candidate = self._create_temp_location_and_manifest_entry(
                path_to_file_system,
                os.path.basename(result_file),
                result_file
            )
            if append_candidate is None:
                continue
            results.append(append_candidate)
        return results

    def check_call_command_in_container(
            self,
            path_to_file_system: str,
            docker_config: Dict
    ) -> List[Tuple[Dict, str]]:
        """
        See the documentation of ConfigFileFinder for reference.
        """
        return []

    def get_service_name(self) -> str:
        """
        See the documentation of ConfigFileFinder for reference.
        """
        return 'iis'

ConfigFileFinder.register(ConfigFileFinderIis)


"""
August 2023
Author: Rambod Azimi

How to use:
1. Enter the numbers you want to convert into barcodes, separated by spaces.
2. Choose the barcode type from the available options (EAN13, EAN8, CODE128, etc.).
3. Click the "Generate Barcodes" button to initiate the barcode generation process.

Features:
Supports multiple barcode types: EAN13, EAN8, CODE128, and more.
Fast and efficient barcode generation for multiple numbers.
Barcodes are automatically saved in the "Downloads" folder for easy access.
"""

import os
import barcode
from barcode import generate
from barcode.writer import ImageWriter
import tkinter as tk
from tkinter import filedialog

# This functions inputs a list of numbers (string type) and the barcode type, and generates the image file (png) in the Downloads folder
def generate_barcode(numbers, barcode_type):
    try:
        barcode_class = barcode.get_barcode_class(barcode_type) # Selecting the barcode type

        downloads_path = os.path.join(os.path.expanduser('~'), 'Downloads')  # Setting the path

        for number in numbers: # iterate over all the list of numbers

            code = barcode_class(number, writer=ImageWriter())

            # Generate the barcode image and save it in the "Downloads" folder
            filename = f'{barcode_type}_{number}'
            full_path = os.path.join(downloads_path, f"{filename}")
            code.save(full_path)

            print(f"Barcode generated: {full_path}")

        tk.messagebox.showinfo("Barcode Generator", "Barcodes generated successfully!")
    except barcode.errors.BarcodeNotFoundError:
        tk.messagebox.showerror("Barcode Generator", "Selected barcode type not supported.")

# Action button function
def generate_button_click():
    numbers_input = numbers_entry.get()
    numbers = numbers_input.split()
    barcode_type = barcode_type_entry.get()

    generate_barcode(numbers, barcode_type)

root = tk.Tk()
root.title("Barcode Generator")

headline_label = tk.Label(root, text="Barcode Generator", font=("Helvetica", 16, "bold"))
headline_label.pack(pady=10)

numbers_label = tk.Label(root, text="Enter the numbers separated by spaces:")
numbers_label.pack()
numbers_entry = tk.Entry(root, width=50)
numbers_entry.pack()

barcode_type_label = tk.Label(root, text="Enter the barcode type (EAN13, EAN8, CODE128, etc.):")
barcode_type_label.pack()
barcode_type_entry = tk.Entry(root, width=50)
barcode_type_entry.pack()

generate_button = tk.Button(root, text="Generate Barcodes", command=generate_button_click)
generate_button.pack(pady=10)

description_label = tk.Label(root, text="Please enter numbers separated by spaces, and select the barcode type. Then, you images are ready in your Downloads folder!")
description_label.pack(pady=10)

developer_label = tk.Label(root, text="Designed and developed by Rambod Azimi")
developer_label.pack(pady=5)

# Main
root.mainloop()


import xlrd
import xlwt
import pysnooper

from excel_reorder import re_order
@pysnooper.snoop()
def excel_read(fil_name):
    data_rd = xlrd.open_workbook(fil_name)
    table_rd = data_rd.sheet_by_index(0)
    nrows = table_rd.nrows
    ncols = table_rd.ncols

    data_write = xlwt.Workbook()
    table_wt = data_write.add_sheet('first',cell_overwrite_ok = True)

    wr_rows = 0
    wl_rows = 0

    change_label = True
    for i_col in range(ncols):
        for i_row in range(nrows):
            if i_col < 3:
                continue
            testdata = table_rd.col(i_col)[i_row].value

            if testdata == "数量合计":
                break

            if testdata is '':
                continue

            if not isinstance(testdata, str):
                label = table_rd.col(1)[i_row].value
                units = table_rd.col(2)[i_row].value
                table_wt.write(wr_rows, 1, label)
                table_wt.write(wr_rows, 2, units)
                table_wt.write(wr_rows, 3, testdata)
            else:
                if wr_rows is not 0:
                    wr_rows += 1
                table_wt.write(wr_rows, 0, testdata)
                table_wt.write(wr_rows, 1, '品名')
                table_wt.write(wr_rows, 2, '单位')
                table_wt.write(wr_rows, 3, '数量')

            wr_rows += 1

    name = "output.xls"
    data_write.save(name)

    name = re_order(name)
    return name

if __name__ == '__main__':
    n = excel_read('干货.xls')
    print(n)